$(function(){

	autoCloseLayer();
	
    if (typeof $('#photo-list').imageGallery == "function" ) {
        $('#photo-list').imageGallery();
    }

	// AbreFecha	
	$("#showRegulation").click(function(){
		$("#contText").slideToggle("slow");
	});

	// DETALHE DA FOTO
	$("#sendPhotoComment").click(function(){
		if($("#formName").val() == "" || $("#formName").val() == $('#formName').attr("title")){
			$(".errorMessage").html("Nome é Obrigatório.");
		}else if ($("#formEmail").val() == "" || $("#formEmail").val() == $("#formEmail").attr("title")){
		    $(".errorMessage").html("Email é Obrigatório.");
		}else if($("#formComment").val() == "" || $("#formComment").val() == $('#formName').attr("title")){
			$(".errorMessage").html("Digite seu comentário.");
		}else{
			$.post(			 
				rootUrl+"challengeComment/insert/",
				{ name: $("#formName").val(), email: $("#formEmail").val() , photoComment: $("#formComment").val(), challengePhotoId: $("#idChallengePhoto").html() },
				function(data){
					$(".comentarios").prepend(data);
				}
			);
			if(!$("#formName").attr("disabled")){
				$("#formName").val("Nome");
			}
			if(!$("#formEmail").attr("disabled")){
                $("#formEmail").val($("#formEmail").attr("title"));
            }
			$("#formComment").val("Comentário");
		}
	});
	
	$("#sendProductComment").click(function(){
		if($("#formName").val() == "" || $("#formName").val() == "Nome"){
			$(".errorMessage").html("Nome é Obrigatório.");
		}else if($("#formComment").val() == "" || $("#formComment").val() == "Comentário"){
			$(".errorMessage").html("Digite seu comentário.");
		}else{
			$.post(
				rootUrl+"product/comment/",
				{ name: $("#formName").val() , photoComment: $("#formComment").val(), productId: $("#idProduct").val() },
				function(data){
					$(".comentarios").prepend(data);
				}
			);
			if(!$("#formName").attr("disabled")){
				$("#formName").val("Nome");
			}
			$("#formComment").val("Comentário");
		}
	});
	
	$("#reloadImage").click(function(){
		$(".imagemValida").attr("src",rootUrl + "challengePhoto/generateCaptcha/?a="+Math.random(12));
	});
	
	$(".btnAmeiFoto").click(function(){
		$(".boxFavorito").hide();
		$(".boxValidacao").show();
	});
	
	$(".remove-comment").click(function(){
	   if (!confirm('Deseja realmente remover o comentário? O comentário será removido permanentemente.')){
	       return false;
	   }
	});
	
	$("#sendVote").click(function(){
		$.post(
				rootUrl+"challengeVote/vote/",
				{ captchaCode: $("#captchaCode").val(), challengePhotoId: $("#idChallengePhoto").html() },
				function(data){
					if(data == "success=0"){
						$(".imagemValida").attr("src",rootUrl + "challengePhoto/generateCaptcha/?a="+Math.random(12));
						$("#captchaCode").val("");
					}else{
						$(".boxValidacao").hide();
						$(".boxFavorito").show().html(data);
					}
				}
			);
	});
	
	// LOGIN TODO O SITE
	$("#btnLogin").click(function(){
		$("#btnLogin").hide();
		$("#btn_Voltar2").show();
		$(".boxLogar").slideDown();
		$("#btnSouQueen").hide();
		$("#boxBusca").slideUp();
		$("#btnEsqueci").show();
		$("#logAs").val("normal");
	});
	$("#btn_Voltar2").click(function(){
		$("#btnLogin").show();
		$("#btn_Voltar2").hide();
		$(".boxLogar").slideUp();
		$("#btnSouQueen").show();
		$("#boxBusca").slideDown();
		$("#btnEsqueci").hide();
		$("#logAs").val("normal");
		$('#boxRetorno').html('');
	});
	
	$("#btnSouQueen").click(function(){
		$("#btnLogin").hide();
		$(".boxLogar").slideDown();
		$("#btnSouQueen").hide();
		$("#btn_Voltar3").show();
		$("#boxBusca").slideUp();
		$("#btnEsqueci").show();
		$("#logAs").val("queen");
	});
	$("#btn_Voltar3").click(function(){
		$("#btnLogin").show();
		$("#btn_Voltar3").hide();
		$("#btnSouQueen").show();
		$(".boxLogar").slideUp();
		$("#boxBusca").slideDown();
		$("#btnEsqueci").hide();
		$("#logAs").val("normal");
		$('#boxRetorno').html('');
	});
	
	$("#btnEsqueci").click(function(){
		$("#btnLogin").hide();
		$("#btn_Voltar3").hide();
		$("#btn_Voltar2").hide();
		$("#btn_Voltar4").show();
		$("#btnSouQueen").hide();
		$(".boxLogar").slideUp();
		$("#boxEsqueci").slideDown();
		$("#boxBusca").slideUp();
		$("#btnEsqueci").hide();
	});
	
	$("#btn_Voltar4").click(function(){
		$("#btnLogin").show();
		$("#btn_Voltar4").hide();
		$("#btnSouQueen").show();
		$("#boxEsqueci").slideUp();
		$("#boxBusca").slideDown();
		$("#btnEsqueci").hide();
		$("#logAs").val("normal");
		$('#boxRetorno').html('');
	});
	
	$('#btnForgotPass').click(function() {
		$('#boxRetorno').html('Enviando...');
		$('#boxRetorno').load(
			rootUrl + "user/forgotPassword",
			{email: $('#forgotEmail').val()}
		);
	});
	
	$("#btnLogOk").click(function(){
		$('#boxRetorno').html('Enviando...');
		$.post(
			rootUrl+"userSession/login/",
			{ email: $("#logEmail").val(), password: $("#logPassword").val() },
			function(data){
				if(data == "success=0"){
					$("#logPassword").val("");
					$('#boxRetorno').html('E-mail e/ou senha incorretos.');
				}else{
					$('#boxRetorno').html('');
					$(".boxLogar").slideUp();
					$("#boxBusca").slideDown();					
					$(".boxLinksLogar").html(data);
				}
			}
		);
	});
	
	// UPLOAD DA FOTO
	if ($("#txtDescription").length) {
		$("#txtDescription").textlimit('span.counter',1000);
	}
	
	$("#goToRegulation").click(function(){
		$("#photoSend").hide();
		$("#challengeRegulation").show();
	});
	$("#backToPhoto").click(function(){
		$("#challengeRegulation").hide();
		$("#photoSend").show();
	});
	
	/*
	$("#btnSendPhotoUpload").click(function(){
		if($("#txtName").val() == "" || $("#txtName").val() =="Título da foto"){
			$(".errorMessage").html("O título da foto é obrigatório.");
		}else if($("#txtDescription").val() == "" || $("#txtDescription").val() =="Descrição"){
			$(".errorMessage").html("A descrição é obrigatória.");		
		}else if(!$('#aceito').attr('checked')){
			$(".errorMessage").html("Você precisa concordar com os termos do regulamento");
		}else{
			$("#btnSendPhotoUpload").hide();
			$(".errorMessage").html("enviando...");
			$("#upload_form").submit();
		}
	});
	*/
	
	$('#upload_form').submit(function(){
		var canSubmit = true;
		
		if($("#txtName").val() == "" || $("#txtName").val() =="Título da foto"){
			$(".errorMessage").html("O título da foto é obrigatório.");
			canSubmit = false;
		}else if($("#txtDescription").val() == "" || $("#txtDescription").val() =="Descrição"){
			$(".errorMessage").html("A descrição é obrigatória.");		
			canSubmit = false;
		}else if(!$('#aceito').attr('checked')){
			$(".errorMessage").html("Você precisa concordar com os termos do regulamento");
			canSubmit = false;
		}else{
			$("#btnSendPhotoUpload").hide();
			$(".errorMessage").html("enviando...");			
		}
		return canSubmit;
	});
	
	//GERAIS
	$('.txtFocus').focus(function(e) {	
		var elm = $(e.target);
		if (elm.val() == elm.attr("title")){  
             elm.val('');
		}
     });
	 
	 $('.txtFocus').blur(function(e) {
		var elm = $(e.target);
		if (elm.val() == ""){  
             elm.val(elm.attr("title"));
		}
     });
	 
	 // CADASTRO NORMAL
	 $('#createUser .colEsq p').hide();
	 $('#createUser .colEsq p:first').show();
	 
	 $("#btnConfirmar1").click(function(){
	 
	    var regex = /\\/;
	    var allowedExtensions = /(.gif|.jpg|.png|.GIF|.JPG|.PNG)/;
	    var fileName = $('#user_file').val();
	    
	    if (fileName.match(regex)){
	       var fileArray = fileName.split("\\");
	       fileName = fileArray[(fileArray.length-1)];
	    }
	 	    
		if($("#user_name").val() == ""){
			$(".errorMessage").html("Nome é obrigatório!");
		}else if($("#user_email").val() == ""){
			$(".errorMessage").html("E-mail é obrigatório!");
		}else if($("#user_msn").val() == ""){
			$(".errorMessage").html("O MSN é obrigatório!");
		}else if($("#user_password").val() == ""){
			$(".errorMessage").html("Senha é obrigatória!");
		}else if($("#user_password").val().length < 4){
			$(".errorMessage").html("Senha de no mínimo 4 caracteres!");
		}else if($("#user_password").val() != $("#user_passawordConfirm").val()){
			$(".errorMessage").html("As senhas precisam ser iguais!");
		}else if(!fileName.match(allowedExtensions)){
		    $(".errorMessage").html("Somente arquivos .JPG, .GIF e .PNG são permitidas na foto do perfil.");
		}else{
			$(".errorMessage").html("");
			$("#passo1").hide();
			$("#passo2").show(); 
			$("#btnLatera2").addClass("on");
			$("#btnLatera1").removeClass("on");
			$('#createUser .colEsq p').hide();
			$("#btnLatera2 p").show();
		}
	 });
	 $("#btnConfirmar2").click(function(){
		if($("#user_adress").val() == ""){
			$(".errorMessage").html("Endereço é obrigatório!");
		}else if($("#user_number").val() == ""){
			$(".errorMessage").html("O número é obrigatório!");		
		}else if($("#user_state").val() == ""){
			$(".errorMessage").html("Selecione um estado!");
		}else if($("#user_city").val() == ""){
			$(".errorMessage").html("Selecione uma cidade!");
		}else if($("#user_cep1").val() == "" || $("#user_cep2").val() == ""){
			$(".errorMessage").html("O CEP é obrigatório!");
		}else{
			$(".errorMessage").html("");
			$("#passo2").hide();
			$("#passo3").show();
			$("#btnLatera3").addClass("on");
			$("#btnLatera2").removeClass("on");
			$('#createUser .colEsq p').hide();
			$("#btnLatera3 p").show();
		}
	 });
	 $("#btnConfirmar3").click(function(){
		if($("#user_accept").attr('checked')){
			$("#form_user").submit();
			return false;
		}else{
			$(".errorMessage").html("Você precisa concordar com o regulamento!");
		}
	 });
	 $("#termosUsoIlha").click(function(){
		
	 });
	 $("#btnVoltar2").click(function(){
		$("#passo2").hide();
		$("#passo1").show();
		$("#btnLatera1").addClass("on");
		$("#btnLatera2").removeClass("on");
		$('#createUser .colEsq p').hide();
		$("#btnLatera1 p").show();
	 });
	 $("#btnVoltar3").click(function(){
		$("#passo3").hide();
		$("#passo2").show();
		$("#btnLatera2").addClass("on");
		$("#btnLatera3").removeClass("on");
		$('#createUser .colEsq p').hide();
		$("#btnLatera2 p").show();
	 });
	$("#user_state").change(function(){
		if($("#user_state").val() > 0){
			$("#user_city").html("Carregando...");
			$.post(
				rootUrl+"city/index/",
				{ stateId: $("#user_state").val()},
				function(data){
					$("#user_city").html(data);
				}
			);
		}
	});
	 
	 //BUSCA
	 $(".btnFiltroBusca").click(function(){
		$("#boxOptions").slideToggle("10");
	 });
	 
	 $('.boxBusca .btnOk').click(function() {
		if($('#search_input').val() != "pesquisar") {
			window.location.href = rootUrl + 'search/result/keyword/' + $('#search_input').val() + '/filter/' + $(this).attr('rel');
		}
		
		return false;
	 });
	 
	 $('#boxOptions a').click(function() {
		if($('#search_input').val() != "pesquisar") {
			window.location.href = rootUrl + 'search/result/keyword/' + $('#search_input').val() + '/filter/' + $(this).attr('rel');
		}
		
		return false;
	 });
	 
	 //FIM BUSCA
	 
	$("#user_state_id").change(function() {
		$('#user_city_id').html("<option value=''>Carregando...</option>");
		$('#user_city_id').load(
			rootUrl + 'city/loadCities',
			{id: $(this).val()}
		);
	});
	
	 $("#queen_create").submit(function(){
		if($("#user_name").val() == ""){
			$(".errorMessage").html("Nome é obrigatório!");
			return false;
		}else if($("#user_email").val() == ""){
			$(".errorMessage").html("E-mail é obrigatório!");
			return false;
		}else if($("#user_password").val() == ""){
			$(".errorMessage").html("Senha é obrigatória!");
			return false;
		}else if($("#user_password").val().length < 4){
			$(".errorMessage").html("Senha de no mínimo 4 caracteres!");
			return false;
		}else if($("#user_password").val() != $("#user_passawordConfirm").val()){
			$(".errorMessage").html("As senhas precisam ser iguais!");
			return false;
		}else if($("#user_address").val() == ""){			
			$(".errorMessage").html("Endereço é obrigatório!");
			return false;
		}else if($("#user_number").val() == ""){
			$(".errorMessage").html("O número é obrigatório!");
			return false;
		}else if($("#user_state_id").val() == ""){
			$(".errorMessage").html("Selecione um estado!");
			return false;
		}else if($("#user_city_id").val() == ""){
			$(".errorMessage").html("Selecione uma cidade!");
			return false;
		}else if($("#user_cep1").val() == "" || $("#user_cep2").val() == ""){
			$(".errorMessage").html("O CEP é obrigatório!");
			return false;
		}else if($('.typeCheck:checked').length == 0 || $('.typeCheck:checked').length > 2){
			$(".errorMessage").html("Você deve marcar no mínimo uma e no máximo duas categorias.");
			return false;
		}else{
			$(".errorMessage").html("");
			return true;
		}
	 });
	 
});

function closeLayer() {	
	$('#overlay').hide();
}

function autoCloseLayer() {	
	setTimeout('closeLayer()',30000);
}