$(document).ready(function() {
	initPage();
});

function initPage() {
	
	//Esconder fotos
	jQuery(".toHide").hide();
	
	//Mensagens
	if (jQuery('#errorMsg').length) {
		setTimeout('jQuery("#errorMsg").fadeOut();', 5000);
	}
	if (jQuery('#okMsg').length) {
		setTimeout('jQuery("#okMsg").fadeOut();', 5000);
	}
	//Esconder info da foto grande da homepage
	jQuery(".bigpicpichomeinfo").hide();
	jQuery("#bigpic").mouseover(function(){
		jQuery(".bigpicpichomeinfo").show();
	});
	jQuery("#bigpic").mouseout(function(){
		jQuery(".bigpicpichomeinfo").hide();
	});
	
	//Navegação no topo
	jQuery("#distrito_selector").change(function(){
		if (jQuery.trim(jQuery("#distrito_selector").val())!='') {
			window.location='/'+jQuery.trim(jQuery("#pageLang").val())+'/d/'+jQuery.trim(jQuery("#distrito_selector").val())+'/';
		}
	});
	jQuery("#concelho_selector").change(function(){
		if (jQuery.trim(jQuery("#concelho_selector").val())!='') {
			window.location='/'+jQuery.trim(jQuery("#pageLang").val())+'/c/'+jQuery.trim(jQuery("#concelho_selector").val())+'/';
		}
	});
	
	//Adição do método de validação para extensões
	jQuery.validator.addMethod("jpegOnly", function(value, element) {
		var ext = value.split('.').pop().toLowerCase();
		var allow = new Array('jpg','jpeg');
  	if(jQuery.inArray(ext, allow) == -1) {
    	return false;
    } else {
    	return true;
    }
	}, "Invalid image format");
	
	//Adição do método de validação para nickname
	jQuery.validator.addMethod("letterNumbersDashesSpaces", function(value, element) {
		return this.optional(element) || /^[a-z0-9\- ]+$/i.test(value);
	}, "Apenas letras, números, hifens e espaços.<br/>Only letters, numbers, dashes and spaces");
	
	//Adição do método de validação para tags
	jQuery.validator.addClassRules({
		tagsField : {
			minlength: 3
		}
	});


	
	//Opacidade da seta da foto grande da homepage
	jQuery('.bigpicpichomeinfo_right').css('opacity', 0.5);
	jQuery(".bigpicpichomeinfo_right").mouseover(function(){
		jQuery('.bigpicpichomeinfo_right').css('opacity', 1);
	});
	jQuery(".bigpicpichomeinfo_right").mouseout(function(){
		jQuery('.bigpicpichomeinfo_right').css('opacity', 0.5);
	});
	
	//Contadores de textareas
	jQuery(".textareaCounter").each(function () {
		var counterID=String(this.id);
		var textareaID=String(counterID.replace(/-counter/i,""));
		var maxChars=parseInt(String(jQuery("#"+counterID).attr('class').split(' ').slice(-1)).replace(/max-/i,""))+0;
		updateTextareaCount(textareaID, maxChars);
		jQuery("#"+textareaID).keyup(function() {
			updateTextareaCount(textareaID, maxChars);
		});
		jQuery("#"+textareaID).blur(function() {
			updateTextareaCount(textareaID, maxChars);
		});
	});
	
	//Validação do form de registo
	jQuery("#formRegisto").validate({
		rules: {
			nickname: {
				required: true,
				letterNumbersDashesSpaces: true,
				minlength: 3,
				maxlength: 30
			},
			email: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 5,
				maxlength: 15
			},
			aceito: {
				required: true
			}
		}
	});
	jQuery("#submitFormRegisto").click(function(){
		jQuery("#formRegisto").submit();
	});
	
	//Esconder campos do form de registo
	jQuery("#formRegisto .formHide1, #formRegisto .formHide2, #formRegisto #verifNicknameError, #formRegisto #verifEmailError").hide();
	
	//Verificação de nickname do form de registo
	jQuery("#formRegisto #nickname").keyup(function () {
		if (jQuery("#formRegisto").validate().element("#nickname")) {
			var nickname_url=jQuery.trim(jQuery("#nickname").val());
			jQuery("#formRegisto #url_td").html(String(jQuery("#formRegisto #url").val())+nickname_url.replace(/ /gi,"-")+'/');
		} else {
			jQuery("#formRegisto #url_td").html(String(jQuery("#formRegisto #url").val()));
		}
	});
	jQuery("#formRegisto #verifNickname").mouseover(function () {
		jQuery("#formRegisto").validate().element("#nickname");
	});
	jQuery("#formRegisto #verifNickname").click(function () {
		jQuery("#formRegisto #verifNicknameError").hide();
		jQuery("#nickname").val(jQuery.trim(jQuery("#nickname").val()));
		if (jQuery("#formRegisto").validate().element("#nickname")) {
			jQuery.ajax({
   			type: "GET",
   			url: "/ajax_verif_nickname.php",
   			data: "nickname="+jQuery("#nickname").val(),
   			success: function(msg){
   				msg=jQuery.trim(msg);
     			if(msg=='0' || msg=='') {
						jQuery("#formRegisto #verifNicknameError").show();
     			} else {
						jQuery("#formRegisto #verifNicknameError").hide();
						jQuery("#formRegisto #nickname_verif_tr").hide();
						jQuery("#formRegisto #url_td").html(String(jQuery("#formRegisto #url").val())+msg+'/');
						jQuery("#formRegisto #nickname_td").html(jQuery("#nickname").val()+'<input type="hidden" name="nickname" id="nickname" value="'+jQuery("#nickname").val()+'"/>');
						jQuery("#formRegisto .formHide1").show();
						
     			}
   			}
 			});
		}
	});
	jQuery("#formRegisto #nickname").keyup(function() {
		jQuery("#formRegisto #verifNicknameError").hide();
	});
	jQuery("#formRegisto #email").keyup(function() {
		jQuery("#formRegisto #verifEmailError").hide();
	});
	
	//Verificação de email do form de registo
	jQuery("#formRegisto #verifEmail").mouseover(function () {
		jQuery("#formRegisto").validate().element("#email");
	});
	jQuery("#formRegisto #verifEmail").click(function () {
		jQuery("#formRegisto #verifEmailError").hide();
		jQuery("#email").val(jQuery.trim(jQuery("#email").val()));
		if (jQuery("#formRegisto").validate().element("#email")) {
			jQuery.ajax({
   			type: "GET",
   			url: "/ajax_verif_email.php",
   			data: "email="+jQuery("#email").val(),
   			success: function(msg){
   				msg=jQuery.trim(msg);
     			if(msg=='0' || msg=='') {
						jQuery("#formRegisto #verifEmailError").show();
     			} else {
						jQuery("#formRegisto #verifEmailError").hide();
						jQuery("#formRegisto #email_verif_tr").hide();
						jQuery("#formRegisto #email_td").html(jQuery("#email").val()+'<input type="hidden" name="email" id="email" value="'+jQuery("#email").val()+'"/>');
						jQuery("#formRegisto .formHide2").show();
						
     			}
   			}
 			});
		}
	});
	jQuery("#formRegisto #nickname").keyup(function() {
		jQuery("#formRegisto #verifNicknameError").hide();
	});
	
	//Login
	jQuery("#submitFormLogin").click(function(){
		jQuery("#formLogin").submit();
	});
	
	//Items do perfil
	jQuery("#perfilItems .item").mouseover(function(){
		jQuery("#"+this.id).addClass("itemHover");
	});
	jQuery("#perfilItems .item").mouseout(function(){
		jQuery("#"+this.id).removeClass("itemHover");
	});
	jQuery("#perfilItems .item").click(function(){
		window.location=jQuery("#"+this.id+"link").attr("href");
	});
	
	//Validação do form de perfil - dados pessoais
	jQuery("#formPerfilPessoal").validate({
		rules: {
			nickname: {
				required: true,
				minlength: 3,
				maxlength: 30
			},
			email: {
				required: true,
				email: true
			},
			website: {
				url: true
			}
		}
	});
	jQuery("#submitFormPerfilPessoal").click(function(){
		jQuery("#formPerfilPessoal").submit();
	});
	
	//Validação do form de perfil - presença na web
	//jQuery("#formPerfilPessoal").validate({
		//No validation required
	//});
	jQuery("#submitformPerfilWeb").click(function(){
		jQuery("#formPerfilWeb").submit();
	});
	
	//Validação do form de perfil - password
	jQuery("#formPerfilPassword").validate({
		rules: {
			oldpassword: {
				required: true
			},
			newpassword: {
				required: true,
				minlength: 5,
				maxlength: 15
			}
		}
	});
	jQuery("#submitFormPerfilPassword").click(function(){
		jQuery("#formPerfilPassword").submit();
	});
	
	
	//Adição de foto - aviso
	jQuery("#divformadicionarfoto").hide();
	jQuery("#linkMostraUploadForm").click(function(){
		jQuery("#divinfoadicionarfoto").hide();
		jQuery("#divformadicionarfoto").show();
	});
	//Validação do form de adição de foto
	validateAddPhoto();
	jQuery("#submitFormAdicionarFoto").click(function(){
		jQuery("#formAdicionarFoto").submit();
	});
	//adição de foto - distrito / concelho
	jQuery("#formAdicionarFoto #id_distrito").change(function() {
		jQuery("#formAdicionarFoto").validate().element("#id_distrito");
		if(jQuery("#formAdicionarFoto #id_distrito").val()>0) {
			jQuery("#formAdicionarFoto #concelho_td").load("/ajax_select_concelhos.php?lang="+jQuery("#pageLang").val()+"&id_distrito="+jQuery("#formAdicionarFoto #id_distrito").val(), function() {
				validateAddPhoto();
				jQuery("#formAdicionarFoto #id_concelho").change(function() {
					jQuery("#formAdicionarFoto").validate().element("#id_concelho");
					if(jQuery("#formAdicionarFoto #id_concelho").val()>0) {
						jQuery("#formAdicionarFoto #freguesia_td").load("/ajax_select_freguesias.php?lang="+jQuery("#pageLang").val()+"&id_concelho="+jQuery("#formAdicionarFoto #id_concelho").val(), function() {
							validateAddPhoto();
						});
					} else {
						jQuery("#formAdicionarFoto #freguesia_td").html("");
					}
				});
			});
		} else {
			jQuery("#formAdicionarFoto #concelho_td").html("");
			jQuery("#formAdicionarFoto #freguesia_td").html("");
		}
	});
	
	//Edição de foto - Validação
	jQuery("#formEditarFoto").validate({
		rules: {
			descricao: {
				required: true,
				minlength: 10
			},
			id_categoria: {
				required: true
			},
			id_categoria: {
				required: true
			},
		}
	});
	jQuery("#submitFormEditarFoto").click(function(){
		jQuery("#formEditarFoto").submit();
	});
	
	//Edição de foto - Google Maps
	initGMap();
	
	//Edição de foto - Licença
	jQuery("#formEditarFoto #id_licenca").change(function() {
		jQuery("#formEditarFoto #id_licenca_img").attr('src','/images/licencas/'+jQuery("#formEditarFoto #id_licenca").val()+'.png');
	});
	
	//Edição de foto - Tags
	jQuery(".tagsField").autocomplete('/ajax_tags.php', {
		width: 132,
		delay: 150
	});
	
	
	//Esconder info da foto grande na página da foto
	jQuery(".foto_overinfo").hide();
	jQuery(".foto_overnav").hide();
	jQuery("#foto_bigpic").mouseover(function(){
		jQuery(".foto_overinfo").show();
		jQuery(".foto_overnav").show();
	});
	jQuery("#foto_bigpic").mouseout(function(){
		jQuery(".foto_overinfo").hide();
		jQuery(".foto_overnav").hide();
	});
	
	//Opacidade de icons na página da foto
	jQuery('#foto_bigpic #foto_bigpicpic .foto_overinfo IMG, #foto_bigpic #foto_bigpicpic .foto_overnav IMG').css('opacity', 0.5);
	jQuery("#foto_bigpic #foto_bigpicpic .foto_overinfo IMG, #foto_bigpic #foto_bigpicpic .foto_overnav IMG").mouseover(function(){
		var itemID=String(this.id);
		jQuery("#"+itemID).css('opacity', 1);
	});
	jQuery("#foto_bigpic #foto_bigpicpic .foto_overinfo IMG, #foto_bigpic #foto_bigpicpic .foto_overnav IMG").mouseout(function(){
		var itemID=String(this.id);
		jQuery("#"+itemID).css('opacity', 0.5);
	});
	
	//Form de votação na página de foto
	jQuery("#submitFormFotoVotar").click(function(){
		jQuery("#formFotoVotar").submit();
	});
	
	//Share da foto
	jQuery("#shortlink").click(function(){
		jQuery("#shortlink").focus();
		jQuery("#shortlink").select();
	});
	jQuery("#embedHtml").click(function(){
		jQuery("#embedHtml").focus();
		jQuery("#embedHtml").select();
	});
	
	
	//Validação do form de pesquisa
	jQuery("#submitFormPesquisa").click(function(){
		var string=jQuery.trim(jQuery("#formPesquisa #string").val());
		jQuery("#formPesquisa #string").val(string);
		if (string.length>=3) {
			jQuery("#formPesquisa").submit();
		} else {
			alert(jQuery("#formPesquisa #string").attr("title"));
			jQuery("#formPesquisa #string").focus();
		}
	});
	
	//Lightbox
	$("A.lightbox").lightBox();
	
	//Validação do form de contacto
	jQuery("#formContacto").validate({
		rules: {
			nome: {
				required: true
			},
			email: {
				required: true,
				email: true
			},
			assunto: {
				required: true
			},
			mensagem: {
				required: true
			}
		}
	});
	jQuery("#submitFormContacto").click(function(){
		jQuery("#formContacto").submit();
	});
	
	
	
	//Form de aprovação em backoffice
	jQuery("#bo_aprovar").click(function(){
		jQuery("#aprovar").val("1");
		jQuery("#formAprov").submit();
	});
	jQuery("#bo_naoaprovar").click(function(){
		jQuery("#aprovar").val("0");
		jQuery("#razao").val(prompt("Razão para não aprovação?","Foto com pouca qualidade"));
		jQuery("#formAprov").submit();
	});

}

function updateTextareaCount(elID, maxC) {
	el=jQuery("#"+elID);
	var curr=el.val().length;
	if (curr>maxC) {
		el.val(el.val().substring(0,maxC));
	}
	curr=el.val().length;
	jQuery("#"+elID+"-counter").html(curr+"/"+maxC);
}

function validateAddPhoto() {
	jQuery("#formAdicionarFoto").validate({
		rules: {
			ficheiro: {
				required: true,
				jpegOnly: true
			},
			foto: {
				required: true,
				minlength: 3,
				maxlength: 100
			},
			descricao: {
				required: true,
				minlength: 10
			},
			id_distrito: {
				required: true
			},
			id_concelho: {
				required: true
			},
			id_categoria: {
				required: true
			}
		}
	});
}

function initGMap() {
	jQuery("#editgooglemap").each(function() {
		var zoom=14;
		if (GBrowserIsCompatible()) {
  		map = new GMap2(document.getElementById("editgooglemap"));
			map.enableDragging();
  		if (jQuery('#gps_lat').val()!='' && jQuery('#gps_lon').val()!='') {
  			var temppoint=new GLatLng(jQuery('#gps_lat').val(), jQuery('#gps_lon').val());
  			jQuery('#gps_actual').html(temppoint.y.toFixed(6)+','+temppoint.x.toFixed(6));
  			map.setCenter(temppoint, zoom);
  			
  			//marker
  			point=new GLatLng(jQuery('#gps_lat').val(), jQuery('#gps_lon').val());
				marker = new GMarker(point, {draggable: true});
				marker.enableDragging();
				GEvent.addListener(marker, "dragend", function() {
				  var temppoint = marker.getLatLng();
					jQuery('#gps_lat').val(temppoint.y);
					jQuery('#gps_lon').val(temppoint.x);
					jQuery('#gps_actual').html(temppoint.y.toFixed(6)+','+temppoint.x.toFixed(6));
					map.setCenter(temppoint);
				});
				map.addOverlay(marker);
  			map.checkResize();
  			
  			markerSet=true;
  			
  			map.setUIToDefault();
  			map.setMapType(G_HYBRID_MAP);
  			map.checkResize();
  		}
		}
	});
}

function gpsReset(lat,lon) {
	jQuery('#gps_lat').val(lat);
	jQuery('#gps_lon').val(lon);
	initGMap();
}
