

//Pesquisa do filme
function searchMovie() {
	//jQuery("#formAddMovieName").unautocomplete();
	setTimeout("jQuery('.ac_results').hide();",300);
	setTimeout("jQuery('.ac_results').hide();",1000);
	setTimeout("jQuery('.ac_results').hide();",5000);
	jQuery('#formAddMovieName').val(jQuery.trim(jQuery('#formAddMovieName').val()));
	if (jQuery('#formAddMovieName').val().length>=2) {
		jQuery('#moviesSearchResult').html('<div class="center"><div><img src="/images/template/ajax-loader.gif" width="16" height="16"/></div><div class="xsmall">Searching the database. This may take a while...</div></div>');
		jQuery('#moviesSearchResult').show();
		jQuery.ajax({
			type: "GET",
			url: "/ajax/searchmovies.php",
			data: "addtype="+jQuery('#formAddMovie input:radio:checked').val()+"&q="+jQuery('#formAddMovieName').val()+"&searchExact="+jQuery('#searchExact').val(),
			contentType: "text/html;charsetUTF-8",
			success: function(msg) {
				jQuery('#formAddMovie #searchMovie').val('Search again');
				if (jQuery.trim(msg)=='') {
					if (jQuery('#formAddMovie input:radio:checked').val()=='movie') {
						jQuery('#moviesSearchResult').html('<div class="center">No movies were found on themoviedb.org database. Please try again.</div>');
					} else {
						jQuery('#moviesSearchResult').html('<div class="center">No movies were found on TheTVDB.com database. Please try again.</div>');
					}
				} else {
					jQuery('#moviesSearchResult').html(msg);
				}
			}
		});
	}
}
function searchMovieExact() {
	jQuery('#searchExact').val("1");
	searchMovie();
}

//Escolha de filme
function chooseMovie(id_movie) {
	jQuery('#formAddMovie #id_movie').val(id_movie);
	jQuery("#moviebutton"+id_movie).remove();
	jQuery('#movieSearch').html('<div class="searchMoviesListMovie searchMoviesListMovieChoosen">'+jQuery("#movie"+id_movie).html()+'</div>');
	jQuery('#movieOptions').html('<div class="center"><div><img src="/images/template/ajax-loader.gif" width="16" height="16"/></div><div class="xsmall">Fetching movie details...</div></div>');
	jQuery('#movieOptions').show();
	jQuery.ajax({
		type: "GET",
		url: "/ajax/searchmovies_options.php",
		data: "id_movie="+id_movie,
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				jQuery('#movieOptions').html('<div class="center">Error fetching movie details.</div>');
			} else {
				jQuery('#movieOptions').html(msg);
				setTimeout("window.location='#movieaddstart'",200);
				//Evento no destino
				jQuery('#formAddMovieDestination').change(function() {
					if (jQuery('#formAddMovieDestination').val()==1) {
						//Wishlist
						$('.wishlistHide').each(function() {
							jQuery("#"+this.id).hide();
						});
					} else {
						//Normal
						$('.wishlistHide').each(function() {
							jQuery("#"+this.id).show();
						});
					}
				});
				//Evento no formato - Resolução
				jQuery('#formAddMovieFormat').change(function() {
					if (jQuery('#formAddMovieFormat').val()==2 || jQuery('#formAddMovieFormat').val()==3) {
						jQuery('#formAddMovieResolution').val('hd');
					} else {
						jQuery('#formAddMovieResolution').val('sd');
					}
					//Actualizar ref
					updateFref(jQuery('#formAddMovieFormat').val());
				});
				updateFref(jQuery('#formAddMovieFormat').val());
				//Esconder mais opções
				hideMoreDetails();
				jQuery('#formAddMovie').validate({
					rules: {
						id_movie: {
							required: true
						},
						season: {
							required: true
						},
						id_format: {
							required: true
						}
					},
					submitHandler: function(form) {
						jQuery("#addMovieDiv").html('<img src="/images/template/ajax-loader.gif" width="16" height="16"/>');
						jQuery.ajax({
							type: "GET",
							url: "/ajax/addmovie.php",
							data: jQuery('#formAddMovie').serialize(),
							success: function(msg) {
								if (jQuery.trim(msg)=='') {
									jQuery('#formAddMovieContainer').html('<div class="center">Error adding movie to your collection.</div>');
								} else {
									jQuery('#formAddMovieContainer').html(msg);
									UpdateMovieCounters();
									initAddMovieForm();
									jQuery('#google_ads_frame1').attr('src', google_ad_url + '&' + new Date().getTime());
									//setTimeout("addMovieRedirect(10)", 1000);
								}
							}
						});
					}
				});
			}
		}
	});
}

function showMoreDetails() {
	jQuery('#moredetails').show();
	jQuery('#wishhide9').html('<a href="javascript:hideMoreDetails();">Show less details...</a>');
	
	//Autocomplete - título alternativo
	jQuery("#formEditMovieTitleAlt").autocomplete("/ajax/movies_alt_title_autocomplete.php", {
		minChars: 2,
		max: 10,
		width: 496,
		matchContains: 0,
		cacheLength: 1,
		delay: 200,
		selectFirst: false,
		extraParams: {
			id_movie: function () { return jQuery('#id_movie').val(); }
		}
	});
}
function hideMoreDetails() {
	jQuery('#moredetails').hide();
	jQuery('#wishhide9').html('<a href="javascript:showMoreDetails();">Show more details...</a>');
}

function updateFref(id_format) {
	if (id_format>0) {
		jQuery.ajaxSetup ({
			cache: false
		}); 
		jQuery("#frefspan").html('').load('/ajax/fref.php?id_format='+id_format);  
	}
}

function addMovieRedirect(seconds) {
	if (seconds==0) {
		alert('redirect');
	} else {
		seconds=seconds-1;
		jQuery('#redirectCount').html(seconds);
		setTimeout("addMovieRedirect("+seconds+")", 1000);
	}
}

function markUnseen(id_user_movie) {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/movie_mark_unseen.php",
		data: 'id_user_movie='+id_user_movie,
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				//ERRO
			} else {
				jQuery('#seen'+id_user_movie).html(msg);
				//UPDATE counters
				UpdateMovieCounters();
			}
		}
	});
}

function markSeen(id_user_movie) {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/movie_mark_seen.php",
		data: 'id_user_movie='+id_user_movie,
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				//ERRO
			} else {
				jQuery('#seen'+id_user_movie).html(msg);
				//UPDATE counters
				UpdateMovieCounters();
			}
		}
	});
}


function removeMovie(id_user_movie) {
	if (confirm('Are you sure you want to remove this movie from your collection?')) {
		jQuery.ajax({
			type: "GET",
			url: "/ajax/movie_remove.php",
			data: 'id_user_movie='+id_user_movie,
			success: function(msg) {
				if (jQuery.trim(msg)=='ok') {
					//DELETE ROW
					jQuery('#movie'+id_user_movie).remove();
					//UPDATE counters
					UpdateMovieCounters();
				} else {
					//ERRO
					alert(msg);
				}
			}
		});
	}
}
function removeMovieWishlist(id_user_wishlist) {
	if (confirm('Are you sure you want to remove this movie from your wishlist?')) {
		jQuery.ajax({
			type: "GET",
			url: "/ajax/movie_remove_wishlist.php",
			data: 'id_user_wishlist='+id_user_wishlist,
			success: function(msg) {
				if (jQuery.trim(msg)=='ok') {
					//DELETE ROW
					jQuery('#movie'+id_user_wishlist).remove();
					//UPDATE counters
					UpdateMovieCounters();
				} else {
					//ERRO
					alert(msg);
				}
			}
		});
	}
}

function UpdateMovieCounters() {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/update_movie_counters.php?rand="+Math.random(),
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				//ERRO
			} else {
				var temp=msg.split("|");
				jQuery('#count_all').html(temp[0]);
				jQuery('#count_unseen').html(temp[1]);
				jQuery('#count_wishlist').html(temp[2]);
			}
		}
	});
	jQuery.ajax({
		type: "GET",
		url: "/ajax/update_movie_counters_top.php?rand="+Math.random(),
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				//ERRO
			} else {
				jQuery('#counter_top').html(msg);
			}
		}
	});
}

function initAddMovieForm() {
	
	//Desabilitar submissão
		jQuery('#formAddMovie').submit(function() {
			if (jQuery('#formAddMovie #id_movie').val()=='') {
				return false;
			}
		});
		
		//Tipo
		jQuery('#formAddMovie #formAddMovieAddTypeMovie').click(function() {
			jQuery('#type_text').html('Enter the Movie name or the IMDb id (ttxxxxxxx):');
		});
		jQuery('#formAddMovie #formAddMovieAddTypeTV').click(function() {
			jQuery('#type_text').html('Enter the TV Series name or the IMDb id (ttxxxxxxx):');
		});
		
		
		//Pesquisa do filme
		jQuery('#formAddMovie #searchMovie').click(function() {
			searchMovie();
		});
		jQuery('#formAddMovieName').keypress(function(e) {
			if (e.which == 13) {
				searchMovie();
			}
		});
		jQuery('#formAddMovieName').focus(function() {
			jQuery('#searchExact').val("0");
		});
		
		//Autocomplete - pesquisa do filme
		jQuery("#formAddMovieName").autocomplete("/ajax/movies_search_autocomplete.php", {
			minChars: 2,
			max: 10,
			width: 496,
			matchContains: 0,
			cacheLength: 1,
			delay: 200,
			selectFirst: false,
			onItemSelect: searchMovieExact,
			extraParams: {
				addtype: function () { return jQuery('#formAddMovie input:radio:checked').val(); }
			}
		});
		
		//Focus
		jQuery('#formAddMovieName').focus();
		
		//Formulário para filmes NO-IMDB
		jQuery('#formAddMovie #addMovieNoIMDB').click(function() {
			jQuery.ajax({
				type: "GET",
				url: "/ajax/addmovie_noimdb_options.php",
				data: "name="+jQuery('#formAddMovieName').val(),
				success: function(msg) {
					if (jQuery.trim(msg)=='') {
						jQuery('#moviesSearchResult').html('<div class="center">Error.</div>');
					} else {
						jQuery('#formAddMovieContainer').html(msg);
						setTimeout("window.location='#movieaddstart'",1000);
						//Evento no tipo de filme
						jQuery('#formAddMovieType').change(function() {
							if (jQuery('#formAddMovieType').val()=='TVS') {
								jQuery('#formAddMovieSeasonDiv').show();
								jQuery('#formAddMovieSeason').focus();
							} else {
								jQuery('#formAddMovieSeasonDiv').hide();
							}
						});
						//Evento no formato - Resolução
						jQuery('#formAddMovieFormat').change(function() {
							if (jQuery('#formAddMovieFormat').val()==2 || jQuery('#formAddMovieFormat').val()==3) {
								jQuery('#formAddMovieResolution').val('hd');
							} else {
								jQuery('#formAddMovieResolution').val('sd');
							}
							//Actualizar ref
							updateFref(jQuery('#formAddMovieFormat').val());
						});
						updateFref(jQuery('#formAddMovieFormat').val());
						//Validação
						now = new Date;
						theYear=now.getFullYear();
						jQuery('#formAddMovieNoIMDB').validate({
							rules: {
								name: {
									required: true,
									minlength: 2
								},
								season: {
									required: true
								},
								year: {
									required: true,
									number: true,
									min: 1900,
									max: theYear
								},
								runtime: {
									number: true
								},
								id_format: {
									required: true
								}
							},
							submitHandler: function(form) {
								jQuery("#addMovieDiv").html('<img src="/images/template/ajax-loader.gif" width="16" height="16"/>');
								jQuery.ajax({
									type: "GET",
									url: "/ajax/addmovie_noimdb.php",
									data: jQuery('#formAddMovieNoIMDB').serialize(),
									success: function(msg) {
										if (jQuery.trim(msg)=='') {
											jQuery('#formAddMovieContainer').html('<div class="center">Error adding movie to your collection.</div>');
										} else {
											jQuery('#formAddMovieContainer').html(msg);
											UpdateMovieCounters();
											initAddMovieForm();
											//jQuery('#google_ads_frame1').attr('src', google_ad_url + '&' + new Date().getTime());
											//setTimeout("addMovieRedirect(10)", 1000);
										}
									}
								});
							}
						});
					}
				}
			});
		});
		
		
}

function initAddLocation() {	
	//Formulário de location
	jQuery('#formLocationAdd').validate({
		rules: {
			location: {
				required: true,
				minlength: 2,
				maxlength: 50
			}
		}
	});	
}
function initEditLocation() {	
	//Formulário de location
	jQuery('#formLocationEdit').validate({
		rules: {
			location: {
				required: true,
				minlength: 2,
				maxlength: 50
			}
		}
	});	
}


function initRecoverPassword() {	
	//Formulário de location
	jQuery('#formRecover').validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		}
	});	
}









function initPage() {
	
	pageInited=true;
	
	
	//Adição do método de validação para nome/nickname
	jQuery.validator.addMethod("letterNumbersDashesSpaces", function(value, element) {
		return this.optional(element) || /^[a-z0-9\- ]+$/i.test(value);
	}, "Only letters, numbers, dashes and spaces");

	
	//Login Form on top
	jQuery('#formLoginEmail').focus(function() {
		if (jQuery.trim(jQuery('#formLoginEmail').val())=='Email') {
			jQuery('#formLoginEmail').val('');
		}
	});
	jQuery('#formLoginEmail').blur(function() {
		if (jQuery.trim(jQuery('#formLoginEmail').val())=='') {
			jQuery('#formLoginEmail').val('Email');
		}
	});
	jQuery('#formLoginPassword').focus(function() {
		if (jQuery.trim(jQuery('#formLoginPassword').val())=='Password') {
			jQuery('#formLoginPassword').val('');
		}
	});
	jQuery('#formLoginPassword').blur(function() {
		if (jQuery.trim(jQuery('#formLoginPassword').val())=='') {
			jQuery('#formLoginPassword').val('Password');
		}
	});
	
	//Mensagem de erro
	jQuery('#closeErrMsg').click(function() {
		jQuery('#errMsg').remove();
		return false;
	})
	//Mensagem de OK
	jQuery('#closeOKMsg').click(function() {
		jQuery('#okMsg').remove();
		return false;
	})
	
	//Formulário de registo
	jQuery('#formRegister').validate({
		rules: {
			name: {
				required: true,
				minlength: 3,
				maxlength: 50,
				letterNumbersDashesSpaces: true
			},
			id_country: {
				required: true
			},
			email: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 5,
				maxlength: 15
			},
			passwordconf: {
				required: true,
				minlength: 5,
				maxlength: 15,
				equalTo: "#formRegisterPassword"
			}
		}
	});
	
	//Formulário de adição de filme
		if (jQuery('#formAddMovie').length!=0) {
			initAddMovieForm();
			var ender=window.location.toString();
			if (ender.indexOf("#") > -1) {
				var id=ender.substring(ender.indexOf("#")+1);
				if (id.substring(0,2)=='tt') {
					jQuery('#formAddMovieName').val(id);
					setTimeout("searchMovie();",1000);
				}
				
			}
		}
		
		//Formulário de contacto
	jQuery('#formContact').validate({
		rules: {
			name: {
				required: true,
				minlength: 3
			},
			email: {
				required: true,
				email: true
			},
			subject: {
				required: true,
				minlength: 3
			},
			message: {
				required: true,
				minlength: 3
			}
		}
	});
		
		//Linhas da lista de filmes
		jQuery('#moviesTable TR').mouseover(function() {
			if (this.id!='') {
				jQuery("#"+this.id).addClass("TROver");
			}
		});
		jQuery('#moviesTable TR').mouseout(function() {
			if (this.id!='') {
				jQuery("#"+this.id).removeClass("TROver");
			}
		});
		
		//Imagens da lista de filmes
		/*jQuery('#moviesTable TD.thumb IMG').mouseover(function() {
			jQuery('#'+this.id).css("width", 100);
		});
		jQuery('#moviesTable TD.thumb IMG').mouseout(function() {
			jQuery('#'+this.id).css("width", 25);
		});*/
		
		//Mostar mudança de password
		jQuery('#formProfile #changePasswordLink A').click(function() {
			jQuery('#formProfile #changePasswordLink').hide();
			jQuery('#formProfile #changePassword').show();
		});
	
	//Formulário de perfil
	jQuery('#formProfile').validate({
		rules: {
			name: {
				required: true,
				minlength: 3,
				maxlength: 50,
				letterNumbersDashesSpaces: true
			},
			id_country: {
				required: true
			},
			email: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 5,
				maxlength: 15
			},
			newpassword: {
				minlength: 5,
				maxlength: 15
			},
			newpasswordconf: {
				minlength: 5,
				maxlength: 15,
				equalTo: "#formRegisterPasswordNew"
			}
		}
	});
	
	initAddLocation();
	
	initEditLocation();
	
	jQuery('#twitterRemove').click(function() {
		if (confirm('Are you sure you want to de-authorize My Movies Collection from posting to your twitter account?')) {
			return true;
		} else {
			return false;
		}
	});
	
	//Edição de filme
	now = new Date;
	theYear=now.getFullYear();
	jQuery('#formEditMovie').validate({
		rules: {
			id_user_movie: {
				required: true
			},
			season: {
				required: true
			},
			loaned_to: {
				required: true
			},
			gref: {
				required: true,
				number: true,
				min: 1
			},
			fref: {
				required: true,
				number: true,
				min: 1
			},
			year: {
				required: true,
				number: true,
				min: 1900,
				max: theYear
			},
			runtime: {
				number: true
			}
		}
	});
	jQuery('#formEditMovieLoaned').click(function() {
		switchLoanedTo();
	});
	switchLoanedTo();
	
	
	jQuery('#formEditMovieType').change(function() {
		switchEditSeason();
	});
	switchEditSeason();
	
	//Autocomplete - título alternativo
	jQuery("#formEditMovieTitleAlt").autocomplete("/ajax/movies_alt_title_autocomplete.php", {
		minChars: 2,
		max: 10,
		width: 496,
		matchContains: 0,
		cacheLength: 1,
		delay: 200,
		selectFirst: false,
		extraParams: {
			id_movie: function () { return jQuery('#id_movie').val(); }
		}
	});
	
	jQuery('.homeFeatures').each(function() {
		jQuery(this).stop().animate({ opacity: 0.7 }, 100);
	});
	jQuery('.homeFeatures').mouseover(function() {
		var thisOne=this;
		jQuery('.homeFeatures').each(function() {
			if (this.id==thisOne.id) {
				jQuery(this).stop().animate({ opacity: 1.0 }, 100);
			} else {
				jQuery(this).stop().animate({ opacity: 0.3 }, 100);
			}
		});
	});
	jQuery('.homeFeatures').mouseout(function() {
		jQuery('.homeFeatures').each(function() {
			jQuery(this).stop().animate({ opacity: 0.7 }, 200);
		});
	});
	jQuery('.homeFeatures').click(function() {
		window.location=jQuery("#"+this.id+"Link").attr('href');
	});
	
	//Filtragem de todos os filmes
	jQuery('#allMoviesFilter SELECT').change(function() {
		filterAllMovies();
	});
	
	//Formato / Resolução nas preferências
	jQuery('#formPreferencesFormat').change(function() {
		if (jQuery('#formPreferencesFormat').val()==2 || jQuery('#formPreferencesFormat').val()==3) {
			jQuery('#formPreferencesResolution').val('hd');
		} else {
			jQuery('#formPreferencesResolution').val('sd');
		}
	});
	
	
	initRecoverPassword();
	
	
	setTimeout("jQuery('#errMsg').remove();jQuery('#okMsg').remove();", 10000);

}




function filterAllMovies() {
	
	jQuery('#moviesTable TR').show();
	
	var counter=parseInt(jQuery('#moviesCounter').val());
	
	if (jQuery('#allMoviesFilter #filterType').val()!='') {
		jQuery('#moviesTable TR.item').each(function() {
			if (!jQuery("#"+this.id).hasClass('type_'+jQuery('#allMoviesFilter #filterType').val())) {
				if (jQuery("#"+this.id).is(':visible')) counter=counter-1;
				jQuery("#"+this.id).hide();
			}
		});
	}
	
	if (jQuery('#allMoviesFilter #filterGenre').val()!='') {
		jQuery('#moviesTable TR.item').each(function() {
			if (!jQuery("#"+this.id).hasClass('genre_'+jQuery('#allMoviesFilter #filterGenre').val())) {
				if (jQuery("#"+this.id).is(':visible')) counter=counter-1;
				jQuery("#"+this.id).hide();
			}
		});
	}
	
	jQuery('#moviesCounterSpan').html(counter);
}




function switchLoanedTo() {
	if ($('#formEditMovieLoaned').attr('checked')) {
		$('#formEditMovieLoanedTo').attr('disabled', '');
		$('#formEditMovieLoanedTo').removeClass("disabled");
		$('#formEditMovieLoanedTo').focus();
	} else {
		$('#formEditMovieLoanedTo').val('');
		$('#formEditMovieLoanedTo').attr('disabled', 'disabled');
		$('#formEditMovieLoanedTo').addClass("disabled");
	}
}

function switchEditSeason() {
	if (jQuery('#formEditMovieType').val()=='TVS') {
		jQuery('#formEditMovieSeasonDiv').show();
		jQuery('#formEditMovieSeason').focus();
	} else {
		jQuery('#formEditMovieSeasonDiv').hide();
	}
}

function setMovieListOrder(order) {
	$('#filterOrder').val(order);
	$('#filterMyMovies').submit();
}


var pageInited=false;

$(document).ready(function() {
	if (!pageInited) {
		initPage();
	}
});