/**
 * Alcaraz
 * -----------------------------------------------------------------
 *
 * author:					Alcaraz & Estevez Consultores
 * projectId:				
 * version:					0.2
 * creation date:			30-03-2009
 * last modification date:	01-04-2009
 * description:				generic js lib
 * notes:
 *
 */


var ALCARAZ =
{
	/**
	 * utilitats xhtml
	 */
	htmlUtils : 
	{
		/**
		 * en xhtml estricte no existeix l'atribut target
		 */
		initExternalLinks : function()
		{
			$('a')
				.filter(function(){ return this.hostname && this.hostname !== location.hostname; })
				.add('a[href$=.pdf], a.external, a[rel=external], ')
				.filter(function()
				{
					return !$(this).hasClass("full");
				})
				.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();
					}
				}
			}
		}
		
	},
	
	
	
	
	/**
	 * utilitats cookies
	 * basat en els scripts de Peter-Paul Koch, basats en els de Scott Andrew
	 * http://www.quirksmode.org/js/cookies.html
	 */
	cookies :
	{
		create : function(name,value,days)
		{
			if (days)
			{
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},

		read : function(name)
		{
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++)
			{
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},

		erase : function(name)
		{
			ALCARAZ.cookies.create(name,"",-1);
		}
	},
	
	
	
	/**
	 * utilitats formularis
	 */
	forms :
	{
		/**
		 * valor per defecte dels camps de formulari:
		 * segons les WCAG tots els camps editables (inputs i textareas)
		 * han de tenir un valor per defecte (checkpoint 10.4)
		 * la funció elimina el contingut per defecte quan rep el focus i el
		 * restaura quan el perd si el camp està buit
		 */
		initDefaultValues : function()
		{
			$.each($("input[type=text], input[type=password], textarea"), function(i, n)
			{
				$(n).data("val", (($(n).attr("id") !== "") && ( !$(n).is("textarea") )) ? document.getElementById($(n).attr("id")).getAttribute("value") : $(n).val() );
				$(n).focus( function()
				{
					if($(this).val() == $(this).data("val")){ $(this).val(""); }
				});
				$(n).blur( function()
				{
					if($(this).val() === ""){ $(this).val($(this).data("val")); }
				});
				
				
			});
		},


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

		}// end validator

	},// end forms
	
	
	
	
	/**
	 * css fixes:
	 * solucions a diferents problemes relacionats amb css, especialment en explorer
	 * la major part de problemes en explorer estan solucionats en fulles d'estil adicionals
	 * vinculades amb comentaris condicionals, però alguns problemes o no es poden solucionar
	 * únicament amb css o seria massa complicat (per exemple selectors no soportats, etc)
	 */
	cssFixes :
	{
		fixLegends : function()
		{
			$("legend").each(function(i)
			{
				$(this).after("<p class='legend'>" + $(this).html() + "</p>").remove();
			});
		},
		
		fixIESelectors : function()
		{
			$("input[type=submit]").addClass("submit");
			$("input[type=text]").addClass("text");
			$("input[type=password]").addClass("password");
			$("input[type=radiobutton]").addClass("radiobutton");
			$("input[type=checkbox]").addClass("checkbox");
			$("*:first-child").addClass("first");
			$("*:last-child").addClass("last");
			$("label[for=loginBtn]").addClass("loginBtn");
		}
	},
	
	
	
	
	/**
	 * altres
	 */
	misc : 
	{
		addShadow : function(element, params)
		{
			if(element.hasClass("shadow")){ return; }
			
			if( $.browser.msie && ($.browser.version < 7) ){ return; }
			
			var defaults = 
			{
				left:	 3,
				top:	 3,
				blur:	 2,
				opacity: 0.4,
				color:	 "#444444",
				swap:	 false
			};
			
			var getVal = function(prop)
			{
				var returnVal = defaults[prop];
				
				if(params)
				{
					if( params[prop] !== undefined )
					{
						returnVal = params[prop];
					}
				}
				
				return returnVal;
			};
			
			element.addClass("shadow").dropShadow({
				left:	 getVal('left'),
				top:	 getVal('top'),
				blur:	 getVal('blur'),
				opacity: getVal('opacity'),
				color:	 getVal('color'),
				swap:	 getVal('swap')
			});
		},
		
		
		removeShadow : function(element)
		{
			element.removeClass("shadow").removeShadow();
		},
		
		
		launchMagazine : function(url)
		{
			window.open(url, "_blank", "resizable=yes, scrollbars=yes, menubar=no, width=1024, height=768");
		},
		
		
		initFullLinks : function()
		{
			$("a.full").bind("click", function()
			{
				ALCARAZ.misc.launchMagazine( $(this).attr("href") );
				return false;
			});
		}
	}

};



function ALCARAZ_imgPreloader()
{
	this.elements = [];
	this.active	  = false;
	this.callback = null;
	
	this.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();
			}
		}
		
		// security timeout, handy if the image loading stalls
		var _this = this;
		if(typeof this.callback == "function")
		{
			setTimeout( function(){ _this.callback(); }, 10000 );
		}
	};
	
	this.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();
			}
		}
	};
};