

//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();
									//alert(jQuery('#movieNameLink').html());
									_gaq.push(['_trackEvent', 'Movies', 'Add', jQuery('#movieNameLink').html()]);
									//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 switchFav(id_user_movie) {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/movie_switch_fav.php",
		data: 'id_user_movie='+id_user_movie+'&tv=1',
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				//ERRO
			} else {
				jQuery('#fav'+id_user_movie).html(msg);
			}
		}
	});
}


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('#count_tvseries').html(temp[3]);
				jQuery('#count_tvseries_all').html(temp[3]); //Just in case...
				jQuery('#count_tvseries_unseen').html(temp[4]);
				jQuery('#count_tvseries_new').html(temp[5]);
			}
		}
	});
	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 Show 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();
											//alert(jQuery('#movieNameLink').html());
											_gaq.push(['_trackEvent', 'Movies', 'Add', jQuery('#movieNameLink').html()]);
											//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;
			}
		});
		
		jQuery('#accountRemove').click(function() {
			if (confirm('Are you sure you want to remove your My Movies Collection account? All data will be lost and the process is irreversible!')) {
				jQuery.ajax({
					type: "GET",
					url: "/ajax/terminate.php",
					success: function(msg) {
						if (jQuery.trim(msg)=='1') {
							alert('A message has been sent to your email address. Please click the link on it to complete the account removal process.');
						} else {
							//Erro?
						}
					}
				});
				return false;
			} 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();
		//});
		jQuery('#allMoviesFilter SELECT').change(function() {
			jQuery("#allMoviesFilterForm").submit();
		});
		jQuery('.allMoviesFilterLetterLinks').each(function() {
			jQuery("#"+this.id).click(function() {
				jQuery("#filterPage").val("0");
				jQuery("#allMoviesFilterForm").attr("action","/movies/all/"+this.id.replace("letter", "")+"/");
				jQuery("#allMoviesFilterForm").submit();
				return false;
			});
		});
		jQuery('P.pageList A').each(function() {
			jQuery("#"+this.id).click(function() {
				jQuery("#filterPage").val(this.id.replace("page", ""));
				jQuery("#allMoviesFilterForm").submit();
				return false;
			});
		});
		
		//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');
			}
		});   
		
		//Formulário de adição de amigo
		if (jQuery('#formFriendAdd').length!=0) {			
			jQuery('#formFriendAdd').validate({
				rules: {
					email: {
						required: true,
						email: true
					}
				},
				submitHandler: function(form) {
					jQuery("#friendSearchResult").html('<div class="center"><img src="/images/template/ajax-loader.gif" width="16" height="16"/></div>');
					searchFriend();
				}
			});
		}
		
		//Lista de amigos
		jQuery('.friendsList .friend').each(function() {
			jQuery("#"+this.id).click(function() {
				if (jQuery("#link"+this.id).attr('target')=='_blank') {
					//Não fazemos nada
				} else {
					window.location=jQuery("#link"+this.id).attr('href');
				}
			});
			jQuery("#"+this.id).mouseover(function() {
				jQuery("#"+this.id).addClass("friendHover");
			});
			jQuery("#"+this.id).mouseout(function() {
				jQuery("#"+this.id).removeClass("friendHover");
			});
		});
		jQuery('.friendsList').hide();
		jQuery('.friendsListH2').each(function() {
			jQuery("#"+this.id).click(function() {
				showFriendsList(this.id);
				return false;
			});
		});
		showFriendsList('friendsList_mmc');
		
		
		//Lista de séries
		jQuery('.tvSeriesList .tvSeriesItem').each(function() {
			jQuery("#"+this.id).mouseover(function() {
				jQuery("#"+this.id).addClass("tvSeriesItemHover");
			});
			jQuery("#"+this.id).mouseout(function() {
				jQuery("#"+this.id).removeClass("tvSeriesItemHover");
			});
		});
		
		
		//Seasons
		jQuery('.seasonList').hide();
		jQuery('.seasonLink').each(function() {
			jQuery("#"+this.id).click(function() {
				showEpisodesList(this.id);
				return false;
			});
		});
		showEpisodesList('seasonLink_1');
		
		//Privacy
		jQuery('#formPreferencesMoviesListPrivacy').change(function() {
			toogleMoviesListUrl();
		});
		
		//Lista de episódios na gestão de séries
		jQuery('.episodeMoreInfo').hide();
		jQuery('.moreInfoLink').each(function() {
			jQuery("#"+this.id).click(function() {
				//Esconde todos
				jQuery('.episodeMoreInfo').hide();
				if (jQuery("#"+this.id).html()=='less info') {
					//É para esconder...
					jQuery(".moreInfoLink").html('more info');
				} else {
					//Mostra Este
					jQuery(".moreInfoLink").html('more info');
					jQuery("#"+this.id).html('less info');
					jQuery("#"+this.id.replace("Link", "")).show();
				}
				return false;
			});
		});
		jQuery('#onlyOneSeason .episodeOwned').each(function() {
			if (jQuery("#"+this.id).is(':checked')) {
				//está checked
			} else {
				jQuery("#"+this.id.replace("Owned","Subtitle")).attr('checked', false);
				jQuery("#"+this.id.replace("Owned","Subtitle")).hide();
				jQuery("#"+this.id.replace("Owned","Seen")).attr('checked', false);
				jQuery("#"+this.id.replace("Owned","Seen")).hide();
			}
			jQuery("#"+this.id).click(function() {
				if(jQuery("#"+this.id).is(':checked')) {
					jQuery("#"+this.id.replace("Owned","Subtitle")).show();
					jQuery("#"+this.id.replace("Owned","Seen")).show();
				} else {
					jQuery("#"+this.id.replace("Owned","Subtitle")).attr('checked', false);
					jQuery("#"+this.id.replace("Owned","Subtitle")).hide();
					jQuery("#"+this.id.replace("Owned","Seen")).attr('checked', false);
					jQuery("#"+this.id.replace("Owned","Seen")).hide();
				}
				updateEpisodeState(jQuery('#id_user_movie').val(), this.id.replace("episodeOwned",""), "owned");
			});
		});
		jQuery('#onlyOneSeason .episodeSeen').each(function() {
			jQuery("#"+this.id).click(function() {
				if(jQuery("#"+this.id).is(':checked')) {
					//visto
				} else {
					jQuery("#"+this.id.replace("Seen","Owned")).attr('checked', true);
				}
				updateEpisodeState(jQuery('#id_user_movie').val(), this.id.replace("episodeSeen",""), "seen");
			});
		});
		jQuery('#onlyOneSeason .episodeSubtitle').each(function() {
			jQuery("#"+this.id).click(function() {
				if(jQuery("#"+this.id).is(':checked')) {
					//visto
				} else {
					jQuery("#"+this.id.replace("Subtitle","Owned")).attr('checked', true);
				}
				updateEpisodeState(jQuery('#id_user_movie').val(), this.id.replace("episodeSubtitle",""), "subtitle");
			});
		});
		jQuery('#tvSeriesNewEpisodesList .episodeOwned').each(function() {
			jQuery("#"+this.id).click(function() {
				//alert(this.id.replace("episodeOwned",""));
				updateEpisodeState(jQuery('#episodeIdUserMovie'+this.id.replace("episodeOwned","")).val(), this.id.replace("episodeOwned",""), "owned");
			});
		});
		
		//Preferences - Episodes
		if (jQuery('#formPreferencesEpisodesManagment')) {
			switchEpisodesManagment();
			jQuery('#formPreferencesEpisodesManagment').change(function() {
				switchEpisodesManagment();
			});
		}
		
		
		
		initRecoverPassword();
		
		//IE9 adicionar Pinned Site  
		if (jQuery('#divPinSite').length!=0) {
			try {
					if (window.external.msIsSiteMode()) {
						// Continue intialization
					} else {
						setTimeout('document.getElementById("divPinSite").style.display = "block";', 1000);
						setTimeout('document.getElementById("divPinSite").style.display = "none";', 7000);
					}
    	} catch (e) {
    		// Fail silently. Pinned Site API not supported.
    	}
    }

		
		
		setTimeout("jQuery('#errMsg').remove();jQuery('#okMsg').remove();", 10000);

}

function switchEpisodesManagment() {
	if (jQuery('#formPreferencesEpisodesManagment').val()==1) {
		//jQuery('#formPreferencesEpisodesShowField').show();
	} else {
		//jQuery('#formPreferencesEpisodesShow').val(0);
		//jQuery('#formPreferencesEpisodesShowField').hide();
	}
}

function updateEpisodeState(id_user_movie, id_episode, theaction) {
	//alert(id_user_movie+' '+id_episode+' '+theaction);
	var owned=0;
	var subtitle=0;
	var seen=0;
	if (jQuery("#episodeOwned"+id_episode).is(':checked')) {
		owned=1;
		if (jQuery("#episodeSubtitle"+id_episode).is(':checked')) subtitle=1;
		if (jQuery("#episodeSeen"+id_episode).is(':checked')) seen=1;
	}
	jQuery('INPUT[type="checkbox"]').attr('disabled', true);
	jQuery.ajax({
		type: "GET",
		url: "/ajax/set_episode_state.php",
		data:  "id_user_movie="+id_user_movie+"&id_episode="+id_episode+"&owned="+owned+"&subtitle="+subtitle+"&seen="+seen+"&action="+theaction,
		success: function(msg) {
			//alert(msg);
			UpdateMovieCounters();
			jQuery('INPUT[type="checkbox"]').removeAttr('disabled');
		}
	});
}

function toogleMoviesListUrl() {
	if (jQuery('#formPreferencesMoviesListPrivacy').val()==-1) {
		jQuery("#moviesListUrl").hide();	
	} else {
		jQuery("#moviesListUrl").show();	
	}
}

function showFriendsList(id) {
	jQuery('.friendsList').hide();
	jQuery("#"+id+"_list").show();
	jQuery('.friendsListH2').each(function() {
		jQuery("#"+this.id).removeClass("friendsListH2Active");
	});
	jQuery("#"+id).addClass("friendsListH2Active");
}
function showEpisodesList(id) {
	jQuery('.seasonList').hide();
	jQuery("#"+id+"_list").show();
	jQuery('.seasonLink').each(function() {
		jQuery("#"+this.id).removeClass("seasonLinkActive");
	});
	jQuery("#"+id).addClass("seasonLinkActive");
}


/*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').is(':checked')) {
		$('#formEditMovieLoanedTo').removeAttr("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();
}

function searchFriend() {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/friend_search.php",
		data: jQuery('#formFriendAdd').serialize(),
		success: function(msg) {
			if (jQuery.trim(msg)=='') {
				jQuery('#friendSearchResult').html('<div class="center small">Error searching friend. Please try later.</div>');
			} else {
				jQuery('#friendSearchResult').html(msg);
			}
		}
	});
}

function addFriend(id_user) {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/friend_add.php",
		data: 'id_user='+id_user,
		success: function(msg) {
			window.location="/profile/friends/";
		}
	});
}

function removeFriend(id_user) {
	if (confirm('Are you sure you want to remove the friendship with this user?')) {
		jQuery.ajax({
			type: "GET",
			url: "/ajax/friend_remove.php",
			data: 'id_user='+id_user,
			success: function(msg) {
				window.location="/profile/friends/";
			}
		});
	}
}

function acceptFriend(id_user) {
		jQuery.ajax({
			type: "GET",
			url: "/ajax/friend_accept.php",
			data: 'id_user='+id_user,
			success: function(msg) {
				window.location="/profile/friends/";
			}
		});
}

function inviteFriend(email) {
	jQuery.ajax({
		type: "GET",
		url: "/ajax/friend_invite.php",
		data: 'email='+email,
		success: function(msg) {
			alert(msg);
			window.location="/profile/friends/";
		}
	});
}

function performFacebookLogin() {
	//window.location=jQuery('#formAddMovieName').val();
	$('#formLoginFacebook').submit();
}

function addSiteIE9() {
	try {
		window.external.msAddSiteMode();
	} catch (e) {
		alert("This feature is only available in Internet Explorer 9.");
	}
}



var pageInited=false;

$(document).ready(function() {
	if (!pageInited) {
		initPage();
	}
});
