/**
 * OBS: Legado Jorge Juan
 * -----------------------------------------------------------------
 *
 * author:               Alcaraz & Estevez Consultores
 *                       Josep (josepramon@alcaraz.com)
 * projectId:               
 * version:              0.1
 * creation date:        24-09-2009
 * description:          
 * notes:                
 *
 *
 */




$(document).ready(function()
{
	// en xhtml estricte no existeix l'atribut target
	$('a[@href^="http://"], a[href$=.pdf], a.external').bind("click", function()
	{
		window.open($(this).attr("href"));
		return false;
	});
	
	
	
	
	// valor per defecte de camps de text/textarea
	$.each($("input[type=text], input[type=password], textarea"), function(i, n)
	{
		$(n).attr("rel", (($(n).attr("id") != "") && ( !$(n).is("textarea") )) ? document.getElementById($(n).attr("id")).getAttribute("value") : $(n).val() );
		
		$(n).focus( function()
		{
			if($(this).val() == $(this).attr("rel")){ $(this).val(""); }
		});
		$(n).blur( function()
		{
			if($(this).val() === ""){ $(this).val($(this).attr("rel")); }
		});
	});
	
	
	
	
	// galeries fotos - no compatible amb explorer 6
	if( !($.browser.msie && ($.browser.version < 7)) )
	{
		$("ul.galeria a").fancybox({
			'zoomSpeedIn': 200,
			'zoomSpeedOut': 200,
			'overlayShow': true,
			'hideOnContentClick': false
		});
	}
	else
	{
		$("ul.galeria a").bind("click", function()
		{
			window.open($(this).attr("href"));
			return false;
		});
	}
	
	
	
	
	// continguts secundaris
	if( $("body").hasClass("libros") || $("body").hasClass("noticias")  || $("body").hasClass("biografia") )
	{
		var newH       = 0;
		var mainH      = parseInt( $("#main").outerHeight() );
		var secondaryH = parseInt( $("#secondary").outerHeight() );
		var offset     = parseInt( $("#secondary").css("top") );
		
		var mainVerticalPadding      = parseInt( $("#main").css("padding-top") ) + parseInt( $("#main").css("padding-bottom") );
		var secondaryVerticalPadding = parseInt( $("#secondary").css("padding-top") ) + parseInt( $("#secondary").css("padding-bottom") );
		
		if(mainH > (secondaryH + offset))
		{
			newH = mainH - secondaryVerticalPadding - offset;
			
			$("#secondary").css("height", newH + "px");
		}
		else if(mainH < (secondaryH + offset))
		{
			newH = secondaryH - mainVerticalPadding + offset;
			
			$("#main").css("height", newH + "px");
		}
	}
	
	
	
	
	// llibres
	$("body.libros #secondary").append("<dl></dl>");
	
	$("body.libros #main ul a").bind("click", function()
	{
		var imgPath = $(this).attr("href");
		var imgDesc = $(this).attr("title");
		
		$("#secondary dl").fadeOut("slow", function()
		{
			$("#secondary").empty();
			$("#secondary").append(
				"<dl>" +
					"<dt>" +
						"<img src='" + imgPath + "' alt='" + imgDesc + "' />" +
					"</dt>" +
					"<dd>" + imgDesc + "</dd>" +
				"</dl>"
			).find("dl").hide().fadeIn("slow");
		});
		
		return false;
	});
	
	
	
	
	// formulari contacte
	formContacto.init();
	
	
	
	
	// p**o explorer ...
	if( $.browser.msie )
	{
		$("ul#topNav li:last-child a").css("border-right", "none");
		
		$("#footer li, ul#informacion_accesibilidad li").not($(":first-child")).prepend("- ");
		
		$("q, cite, body.home blockquote p").prepend("'").append("'");
		
		// només per a explorer 6.x
		if( parseFloat($.browser.version) < 7 )
		{
			if( $("body").hasClass("home") )
			{
				var txt = $("body.home blockquote p").html();
				
				$("body.home blockquote p").html( txt.replace(/^'D/, "<span style='font-size: 2em;'>'D</span>") );
			}
		}
	}
	
	
	
});




var formContacto = {
	
	returnVal           : true,
	enabled             : true,
	error               : false,
	strError            : "",
	strErrorReqFields   : "Todos los campos del formulario son obligatorios.",
	strErrorBadEmail    : "La dirección de correo introducida no es válida.",
	
	
	init : function()
	{
		$("#fContacto").submit( function ()
		{
			$("#fContacto input, #fContacto textarea").removeClass("error");
			
			if(!formContacto.validate())
			{
				formContacto.error    = true;
				formContacto.strError = "El formulario contiene algunos datos erróneos:<br />" + formValidator.errors.join("<br />");
			}
			
			if(formContacto.error)
			{
				formContacto.showErrorMsg();
			}
			else
			{
				formContacto.submitForm();
			}
			
			return false;
			
		});
	},
	
	
	validate : function()
	{
		this.returnVal = true;
		
		formValidator.init();
		
		$.each($("#fNombre, #fMail, #fSugerencias"), function(i, n)
		{
			formValidator.checkRequired($(n));
		});
		
		if($("#fMail").val() != $("#fMail").attr("rel"))
		{
			formValidator.checkValidMail($("#fMail"));
		}
		
		if(!formValidator.returnVal){ this.returnVal = false; }
		
		for(var i = 0; i<formValidator.erroneousFields.length; i++)
		{
			formValidator.erroneousFields[i].addClass("error");
		}
		
		return this.returnVal;
	},
	
	
	showErrorMsg : function()
	{
		formContacto.enabled = false;
		
		$("#fContacto").css("position", "relative");
		$("#thanx").remove();
		
		var shakeDist   = 4;
		var shakeDuration = 30;
		
		$("#fContacto").animate( {left: shakeDist}, shakeDuration, function(){
			$("#fContacto").animate( {left: -shakeDist}, shakeDuration, function(){
				$("#fContacto").animate( {left: shakeDist}, shakeDuration, function(){
					$("#fContacto").animate( {left: -shakeDist}, shakeDuration, function(){
						$("#fContacto").animate( {left: shakeDist}, shakeDuration, function(){
							$("#fContacto").animate( {left: -shakeDist}, shakeDuration, function(){
								$("#fContacto").animate( {left: 0}, shakeDuration/2, function(){
									$("#fContacto").animate( {left: 0}, 1000, function(){  //delay trick
										$("#fContacto").append("<div id='thanx'>" + formContacto.strError + "</div>");
										$("#thanx").hide().fadeIn(1000, function(){formContacto.enabled = true;});
									});
								});
							});
						});
					});
				});
			});
		});
	},
	
	
	submitForm : function()
	{
		$("#fContacto div label").before("<img id='loadingImg' src='img/ui/loadingAnimation_small.gif' alt='enviando formulario...'>");
		
		$("#fContacto input, #fContacto textarea").attr("disabled","disabled");
		
		$.post(
			$("#fContacto").attr("action"),
			{ fNombre: $("#fNombre").val(), fMail: $("#fMail").val(), fSugerencias: $("#fSugerencias").val() },
			function(data)
			{
				$("#fContacto input, #fContacto textarea").removeAttr("disabled");
				$("#loadingImg").remove();
				$("#thanx").remove();
				$("#fContacto").append("<div id='thanx'>" + data + "</div>");
				$("#thanx").hide().fadeIn(1500);
				$("#fNombre").val( $("#fNombre").attr("rel") );
				$("#fMail").val( $("#fMail").attr("rel") );
				$("#fSugerencias").val( $("#fSugerencias").attr("rel") );
				formContacto.enabled = true;
			}
		);
	}
	
	
};




var formValidator = {
	
	errors          : Array,
	erroneousFields : Array,
	returnVal       : true,
	
	init : function()
	{
		formValidator.errors          = [];
		formValidator.erroneousFields = [];
		formValidator.returnVal       = true;
	},
	
	checkRequired : function(el)
	{
		if( (el.val() === "") || (el.val() === null) || (el.val() == el.attr("rel")) )
		{
			formValidator.errors.push("El campo " + String(el.attr("id")).replace(/^f/,"") + " es obligatorio");
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	},
	
	checkMaxLength : function(els, length)
	{
		for(var i=0; i<els.length; i++)
		{
			if(String(els[i].val()).length > length)
			{
				formValidator.errors.push("El campo " + String(els[i].attr("id")).replace(/^f/,"") + " no puede contener mas de " + length + " dígitos");
				formValidator.returnVal = false;
				formValidator.erroneousFields.push(els[i]);
			}
		}
	},
	
	checkValidMail : function(el)
	{
		var pattern  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!pattern.test(el.val()))
		{  
			formValidator.errors.push("Debe introducir una direccion de mail correcta en el campo " + String(el.attr("id")).replace(/^f/,""));
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	},
	
	checkNumeric : function(el)
	{
		if(isNaN(el.val()))
		{
			formValidator.errors.push("El campo " + String(el.attr("id")).replace(/^f/,"") + " solo puede contener números");
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}	
	},
	
	checkRange : function(el, minValue, maxValue)
	{
		var val = el.val();
		if(isNaN(val) || !( (val >= minValue) && (val <= maxValue) ) )
		{
			formValidator.errors.push("El campo " + String(el.attr("id")).replace(/^f/,"") + " debe contener un valor numérico emprendido entre " + minValue + " y " + maxValue);
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	},
	
	checkCp : function(el)
	{
		var cp = el.val();
		if( !( !isNaN(cp) && (cp.length = 5) && (parseInt(cp) >= 1001) && (parseInt(cp) <= 52999) && (String(cp).indexOf("000", 2) == -1) ) )
		{
			formValidator.errors.push("El campo " + String(el.attr("id")).replace(/^f/,"") + " debe contener un código postal válido, formado por 5 núneros");
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	},
	
	checkFileInputExtension : function(el, ext)
	{
		if(String(el.val()).toLowerCase().substr(String(el.val()).lastIndexOf('.')) != ext)
		{
			formValidator.errors.push("El campo " + String(el.attr("id")).replace(/^f/,"") + " solo admite archivos con la extensión " + ext);
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	}

};