/**
 * full-interactive
 * ------------------------------------------
 *
 * autor:				Josep (josepramon@alcaraz.com)
 * fitxa:				????
 * data creacio:		05-05-2008
 * ultima modificacio:	
 *
 *
 */


$(document).ready(function()
{
	$("#formContacto label").append(":");
	
	
	$("body.home #product-demo").append("<div id='minifull'></div>");
	$("body.home #product-demo a").remove();
	
	if($("body").hasClass("home"))
	{
		var flashvars     = {};
		var params        = {};
		var attributes    = {};
		var path          = "/revistas/minifull2/";
		params.wmode      = "transparent";
		params.base       = path;
		attributes.id     = "minifull";
		swfobject.embedSWF(path + "fullinteractive.swf", "minifull", "335", "298", "9.0.0", path + "other/expressInstall.swf", flashvars, params, attributes);
	}
	
	
	
	$("#tipoPublicaciones + ul").find("li:eq(9)").append("...");
	$("#tipoPublicaciones + ul").find("li:last").remove();
	
	
	var magazinesList = 
	{
		menu          : $("#product-examples"),
		menuElements  : $(".magazines-container li"),
		animating     : false,
		inited        : false,
		
		init : function()
		{
			if( this.inited ) return;
			
			$("body").addClass("jsfied");
			
			$("#product-examples").append('<img id="loadingAnimation" src="/img/ui/ajax-loader.gif" />');
			
			$(".magazines-container").hide();
			
			var _this = this;
			var magazineCovers = $(".magazines-container img").map(function(){ return $(this).attr("src"); }).get();
			
			ALCARAZ.htmlUtils.imgPreloader.preload(magazineCovers, function()
			{
				if(_this.inited){ return; }
				
				$(".magazines-container").css("width", _this.getMenuWidth() + "px").fadeIn("slow");
				
				$("#loadingAnimation").remove();
				
				_this
					.addReflections()
					.buildNav()
					.assignEventHandlers()
					.inited = true;
			});
		},
		
		
		addReflections : function()
		{
			if($.browser.safari && (navigator.userAgent.indexOf("Version/4") > 0)) // safari 4 suporta css reflections
			{
				$("#product-examples img").css("-webkit-box-reflect", "below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.5, transparent), to(rgba(255,255,255,.50)))");
			}
			else
			{
				/*
				var imgs = document.getElementById("product-examples").getElementsByTagName("img");
				for(var i = 0; i < imgs.length; i++)
				{
					Reflection.add(imgs[i], { height: 1/2, opacity: 1/3 });
				}*/
				
				// puto explorer...
				if(document.getElementById("magazinesInner"))
				{
					var liEls = document.getElementById("magazinesInner").getElementsByTagName("li");
					for(var i = 0; i < liEls.length; i++)
					{
						var img = liEls[i].getElementsByTagName("img")[0];
						Reflection.add(img, { height: 1/2, opacity: 1/3 });
					}
				}
			}
			
			return this;
		},
		
		getMenuWidth : function()
		{
			var inc = ($.browser.msie && (parseFloat($.browser.version) < 8)) ? 150 : 120;
			return (this.menuElements.length * inc);
		},
		
		assignEventHandlers : function()
		{
			this.menu.find("a").each(function()
			{
				$(this).bind("click", function()
				{
					window.open($(this).attr("href"), "_blank", "resizable=yes, scrollbars=yes, menubar=no, width=1024, height=768");
					return false;
				});
			});
			
			$("a", this.menu).mouseover(function()
			{
				$("img", this).stop().animate({"height": "150px"}, 200,'swing');
				$("canvas", this).stop().animate({"width": "120%"}, 200,'swing');
			}).mouseout(function()
			{ 
				$("img", this).stop().animate({"height": "130px"}, 200,'swing');
				$("canvas", this).stop().animate({"width": "100%"}, 200,'swing');
			});
			
			
			$("#magazinesList_prev").bind("click", function()
			{
				$("#magazinesInner").scrollTo(
					"-=920px",
					{
						axis     : "x",
						duration : 600,
						easing   : 'swing',
						onAfter  : function(){}
					}
				);
			});
			
			$("#magazinesList_next").bind("click", function()
			{
				$("#magazinesInner").scrollTo(
					"+=920px",
					{
						axis     : "x",
						duration : 600,
						easing   : 'swing',
						onAfter  : function(){}
					}
				);
			});
			
			return this;
		},
		
		buildNav : function()
		{
			$("#product-examples").append("<span id='magazinesList_prev' />");
			$("#product-examples").append("<span id='magazinesList_next' />");
			
			return this;
		}
	};
	
	magazinesList.init();
	
	
	
	$("#ejemplos a, #ejemplos_otros a, a.revista").bind("click", function()
	{
		window.open($(this).attr("href"), "_blank", "resizable=yes, scrollbars=yes, menubar=no, width=1024, height=768");
		return false;
	});
	
	$("#ejemplos a img").hover(
		function()
		{
			$(this).attr("src", String( $(this).attr("src") ).replace("_a_", "_b_") );
		},
		function()
		{
			$(this).attr("src", String( $(this).attr("src") ).replace("_b_", "_a_") );
		}
	);
	
	$("ul#ejemplos, ul#ejemplos_otros").append("<li class='clearList'></li>");
	
	
	
	
	$.each($("input[type=text], 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")); }
		});
	});
	
	
	
	
	$("#fSubmit").css("cursor", "pointer");
	
	formContacto.init();
	
	
	
	
	if($.browser.msie && (parseFloat($.browser.version) < 7))
	{
		$("#costeCero").css("background-image", "none");
	}

});


var formContacto = {

  returnVal : true,
  
  init : function()
  {
	$("#formContacto").submit( function ()
	{
	  $("#formContacto input, #formContacto textarea").removeClass("error");
	  if(!formContacto.validate())
	  {
		alert("Algunos de los datos introducidos en el formulario no son válidos:\n" + formValidator.errors.join("\n"));
		return false;
	  }
	});
  },
  
  validate : function()
  {
	this.returnVal = true;
	
	formValidator.init();
	
	$.each($("#fNombre, #fTelefono, #fEmail"), function(i, n)
	{
	  formValidator.checkRequired($(n));
	});
		
	formValidator.checkNumeric($("#fTelefono"));   
	
	if($("#fEmail").val() != $("#fEmail").attr("rel"))
	{
	  formValidator.checkValidMail($("#fEmail"));
	}
	
	if(!formValidator.returnVal){ this.returnVal = false; }
	
	for(var i = 0; i<formValidator.erroneousFields.length; i++)
	{
	  formValidator.erroneousFields[i].addClass("error");
	}
	
	return this.returnVal;
  
  }
};

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, 10) >= 1001) && (parseInt(cp, 10) <= 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, entre el \"01001\" y el \"52999\" y no puede terminar en \"XX000\"");
	  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);
	}
  }
  
};









var ALCARAZ =
{
	/**
	 * utilitats xhtml
	 */
	htmlUtils : 
	{
		/**
		 * en xhtml estricte no existeix l'atribut target
		 */
		initExternalLinks : function()
		{
			$('a[href$=.pdf], a.external, a[rel=external]').bind("click", function()
			{
				window.open($(this).attr("href"));
				return false;
			});
		},
		
		imgPreloader :
		{
			elements : [],
			active   : false,
			callback : null,
			
			preload : function(imgsArray, callbackFunc)
		    {
				if(this.active)
				{
					for(var i = 0; i < imgsArray.length; i++)
					{
						this.elements.push(imgsArray[i]);
					}
				}
				else
				{
					this.elements = imgsArray;
					this.callback = callbackFunc;
					
					if(this.elements.length > 0)
					{
						if(!document.getElementById("tmpPreloaderImg"))
						{
							$('<img id="tmpPreloaderImg" />').appendTo('body').hide();
						}
						this.loadElement();
					}
				}
				
				// timeout de seguretat per si s'exganxa la càrrega de la imatge
				var _this = this;
				if(typeof this.callback == "function")
				{
					setTimeout( function(){ _this.callback(); }, 10000 );
				}
			},
			
			loadElement : function()
			{
				if(this.elements.length > 0)
				{
					var imgSrc = this.elements.shift();
					var loaded = false;
					var _this  = this;
					
					$("img#tmpPreloaderImg").attr("src", imgSrc).load(function()
					{
						if(!loaded)
						{
							_this.loadElement();
							loaded = true;
						}
					});
				}
				else
				{
					$('img#tmpPreloaderImg').remove();
					
					this.active = false;
					
					if(typeof this.callback == "function")
					{
						this.callback();
					}
				}
			}
		}
		
	}

};