/**
 * La Escandella
 * -----------------------------------------------------------------
 *
 * author:               Alcaraz & Estevez Consultores
 * projectId:            
 * version:              0.96
 * creation date:        10-12-2008
 * description:          
 * notes:
 *
 */


$(document).ready(function()
{
	// en xhtml estricte no existeix l'atribut target
	$('a[href$=.pdf], a.external, a[rel=external], a.full').bind("click", function()
	{
		window.open($(this).attr("href"));
		return false;
	});
	
	
	
	/**
	 * 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
	 */
	$.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")); }
		});
	});
	
	
	
	
	/**
	 *  Menús:
	 * ------------------------------------
	 *  inicialització, efectes, etc
	 *  dels menús del site
	 *
	 ***********************************************************************************************************************************/
	
	/**
	 * menu superior secundari
	 */
	if(!$("body").hasClass("home"))
	{
		$("#secondaryNav")
			.css("height", "20px")
			.data("collapsedH", "20px")
			.data("uncollapsedH", "81px")
			.data("collapsed", true)
			.addClass("collapsable");
	}
	
	
	
	/**
	 * inicialització per als menús colapsables genèrics
	 * de moment només hi ha el superior secundari
	 */
	$('.collapsable').each(function(i)
	{
		var delayTimer   = null;
		var delayTimeOut = 200;
		var speed        = 200;
		var animating    = false;
		var _this        = $(this);
		
		_this.mouseover(function()
		{
			if(delayTimer){ clearTimeout(delayTimer); }
		
			if( !animating && $(this).data("collapsed") )
			{
				animating = true;
				
				_this.animate(
					{height: _this.data("uncollapsedH")},
					speed,
					"swing",
					function()
					{
						animating = false;
						_this.data("collapsed", false);
					}
				);
			}
		})
		.mouseout(function()
		{
			if(delayTimer){ clearTimeout(delayTimer); }
			
			delayTimer = setTimeout(function()
			{
				delayTimer = null;
				animating  = true;
				
				_this.animate(
					{height: _this.data("collapsedH")},
					speed,
					"swing",
					function()
					{
						animating = false;
						_this.data("collapsed", true);
					}
				);
			}, delayTimeOut);
		});
	});
	
	
	
	
	/**
	 * menú lateral genèric:
	 * destaca la opció del menú que coincideixi amb el
	 * títol de la pàgina (el que està en #contents h2)
	 */
	var genericMenu = {
		
		/**
		 * overrides:
		 * per si alguna pàgina té un títol diferent de
		 * la opció corresponent del menú
		 * 
		 * params:
		 * lang          : idioma de la pàgina
		 * pageClassName : atribut class del node body que identifica
		 *                 de forma única (o no) la pàgina
		 * navText       : text que apareix en la opció del menú
		 */
		overrides : [
			{
				lang          : 'es',
				pageClassName : 'localizacion',
				navText       : 'Localización'
			},
			{
				lang          : 'es',
				pageClassName : 'noticias',
				navText       : 'Noticias'
			},
			{
				lang          : 'es',
				pageClassName : 'links',
				navText       : 'Links'
			},
			{
				lang          : 'es',
				pageClassName : 'descargas',
				navText       : 'Descargas'
			},
			{
				lang          : 'es',
				pageClassName : 'faq',
				navText       : 'FAQ'
			},
			{
				lang          : 'es',
				pageClassName : 'galeria-autocad',
				navText       : 'Galería autocad'
			},
			{
				lang          : 'es',
				pageClassName : 'guias-instalacion',
				navText       : 'Guías instalación'
			},
			{
				lang          : 'es',
				pageClassName : 'fabricacion',
				navText       : 'Fabricación'
			},
			{
				lang          : 'es',
				pageClassName : 'bardo-liso',
				navText       : 'Bardo liso'
			},
			{
				lang          : 'en',
				pageClassName : 'carta-director',
				navText       : 'Letter from the CEO'
			},
			{
				lang          : 'en',
				pageClassName : 'descargas',
				navText       : 'Downloads'
			},
			{
				lang          : 'en',
				pageClassName : 'links',
				navText       : 'Links'
			},
			{
				lang          : 'en',
				pageClassName : 'fabricacion',
				navText       : 'Manufacture'
			},
			{
				lang          : 'en',
				pageClassName : 'guias-instalacion',
				navText       : 'Installation guide'
			},
			{
				lang          : 'en',
				pageClassName : 'contacto',
				navText       : 'Contact'
			},
			{
				lang          : 'fr',
				pageClassName : 'links',
				navText       : 'Liens'
			},
			{
				lang          : 'fr',
				pageClassName : 'descargas',
				navText       : 'Téléchargement'
			},
			{
				lang          : 'fr',
				pageClassName : 'trabaja-con-nosotros',
				navText       : 'Travailler avec nous'
			},
			{
				lang          : 'fr',
				pageClassName : 'contacto',
				navText       : 'Contactez-nous'
			},
			{
				lang          : 'fr',
				pageClassName : 'guias-instalacion',
				navText       : "Guide d'installation"
			}
		],
		
		
		init : function()
		{
			var hasCustomPageTitle = false;
			var pageTitle          = "";
			var overrideIndex      = null;
			
			for(var i = 0; i < this.overrides.length; i++)
			{
				var strClassName = this.overrides[i].pageClassName;
				var strLang      = this.overrides[i].lang;
								
				if( $("body").hasClass(strClassName) && ($("html").attr("lang") == strLang) )
				{
					hasCustomPageTitle = true;
					overrideIndex      = i;
					break;
				}
			}
			
			pageTitle = (hasCustomPageTitle) ? this.overrides[overrideIndex].navText : this.getPageTitle();
			
			this.highlightElement( pageTitle );
		},
		
		
		/**
		 * destaca la opció del menú que contingui el text passat com a paràmetre
		 */
		highlightElement : function(str)
		{
			var navNode = $("#sectionNav > ul > li a").filter(function(i)
			{
				return String( $(this).text() ).toLowerCase() == str.toLowerCase();
			});
			
			if( (str !== "") && (str !== null) )
			{
				//navNode.parent("li").addClass("current");
				
				/**
				 * 'hack' necesari per a les seccions que tenen seccions
				 * aniuades (nested -> no se si la traducció es molt correcta)
				 * i alguna d'aquestes subseccions té el mateix nom que la secció 
				 */
				navNode.eq(navNode.length-1).parent("li").addClass("current");
			}
		},
		
		
		/**
		 * retorna el títol de la pàgina (el que està en #contents h2) net,
		 * es a dir, eliminant qualsevol node fill (strongs / ems / spans / ...)
		 * que poqués contenir el heading i eliminant l'espai en blanc del
		 * principi i el final
		 * 
		 * no he trobat la forma de fer-ho amb jQuery, així que està implementat
		 * utilitzant únicament mètodes estàndard del DOM
		 */
		getPageTitle : function()
		{
			var titleStr     = "";
			var contentsNode = document.getElementById("contents");

			if(!contentsNode){ return; }

			var titleNode    = contentsNode.getElementsByTagName("h2")[0];

			if(!titleNode){ return; }

			for(var i = 0; i < titleNode.childNodes.length; i++)
			{
				if( titleNode.childNodes[i].nodeType == 3 )    // nodeType 3: textNode
				{
					titleStr += titleNode.childNodes[i].nodeValue;
				}
			}

			return jQuery.trim( titleStr );
		}
		
	};
	
	if( !$("body").hasClass("productos") && !$("body").hasClass("home") )
	{
		genericMenu.init();
	}
	
	
	
	
	/**
	 * menu lateral productes:
	 * el de la home i la secció de productes són el mateix
	 * però en la home les animacions estan desactivades
	 */
	var productsMenu = 
	{
		inited       : false,
		menu         : $("#sectionNav.productos ul.nav"),
		menuElements : $("#sectionNav.productos ul.nav > li"),
		
		
		init : function()
		{
			if(this.inited){ return false; }
			
			this.inited = true;
			
			this.menu.addClass("jsfied");
			
			this.expandLinksToImgs();
			
			if( !$("body").hasClass("home") )
			{
				this.highlightCurrentElement();
				
				// this.initRollovers(); //--> desactivat pq l'efecte mareja bastant
			}
		},
		
		
		expandLinksToImgs : function()
		{
			this.menuElements.each(function(i)
			{
				$(this).find("img").eq(0)
					.css("cursor", "pointer")
					.bind("click", function()
					{
						window.location = $(this).parent("li").find("a").eq(0).attr("href");
					});
			});
		},
		
		
		initRollovers : function()
		{
			this.menuElements.each(function(i)
			{
				if( $(this).hasClass("current") ) return;
				
				$(this)
					.data("collapsed",    true)
					.data("delayTimer",   null)
					.data("delayTimeOut", 5)
					.data("speed",        200)
					.data("animating",    false)
					.mouseover(function()
					{
						productsMenu.highlightElement( $(this) );
					})
					.mouseout(function()
					{
						productsMenu.restoreElement( $(this) );
					});
			});
		},
		
		
		highlightElement : function(element)
		{
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }

			if( !element.data("animating") && element.data("collapsed") )
			{
				element
					.data("animating", true)
					.addClass("active")
					.animate(
						{ backgroundColor : "#ccc6bd" },
						element.data("speed") * 1.5,
						function()
						{
							element
								.data("animating", true)
								.data("collapsed", false);
						}
					)
					.find("img")
						.animate(
						{
							top:            "10px",
							left:           "10px",
							"margin-right": "-145px"
						},
						element.data("speed")
					);
			}
		},
		
		
		restoreElement : function(element)
		{
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }
			
			element.data(
				"delayTimer",
				setTimeout(
					function()
					{
						element
							.data("delayTimer", null)
							.data("animating", true)
							.removeClass("active")
							.animate(
								{ backgroundColor : "#eeedec" },
								element.data("speed") * 1.5,
								function()
								{
									element
										.data("animating", false)
										.data("collapsed", true);
								}
							)
							.find("img").animate(
								{
									top:            "-20px",
									left:           "10px",
									"margin-right": "-130px"
								},
								element.data("speed")
							);
					},
					element.data("delayTimeOut")
				)
			);
		},
		
		
		// destaca l'element del menú corresponent a la pagina actual
		highlightCurrentElement : function()
		{
			var productName = $("#productName").text();
			var productNode = $("#sectionNav.productos > ul > li strong > a").filter(function(i)
			{
				return String( $(this).text() ).toLowerCase() == productName.toLowerCase();
			}).parent("strong").parent("li");
			
			if( (productName !== "") && (productName !== null) )
			{
				productNode.addClass("current");
			}
		}
		
	};
	
	productsMenu.init();
	
	
	
	
	/**
	 * menu tipus teules amb animacions en els rollovers
	 */
	var productTypesMenu = 
	{
		inited            : false,
		menu              : $("#productTypes"),
		menuElements      : $("#productTypes a"),
		menuType          : null,
		animationSettings : 
		{
			regular : 
			{
				over : 
				{
					width:    "70px",
					height:   "40px",
					top:      "2px",
					left:     "4px"
				},
				
				out :
				{
					width:    "65px",
					height:   "37px",
					top:      "3px",
					left:     "7px"
				}
			},
			
			big :
			{
				over : 
				{
					width:    "180px",
					height:   "105px",
					top:      "2px",
					left:     "4px"
				},
				
				out :
				{
					width:    "130px",
					height:   "76px",
					top:      "12px",
					left:     "28px"
				}
			}
		},
		
		
		init: function()
		{
			if(this.inited){ return false; }
			
			this.inited = true;
			
			this.menuType = $("body").hasClass("caracteristicas") ? "big" : "regular";
			
			this.menu.addClass("jsFixed");
			this.initRollovers();
		},
		
		
		initRollovers : function()
		{
			this.menuElements.each(function()
			{
				if( $(this).hasClass("current") ){ return; }
				
				$(this)
					.data("collapsed",    true)
					.data("delayTimer",   null)
					.data("delayTimeOut", 10)
					.data("animating",    false)
					.data("speed",        300)
					.mouseover(function()
					{
						productTypesMenu.highlightElement( $(this) );
						
					})
					.mouseout(function()
					{
						productTypesMenu.restoreElement( $(this) );
					});
			});
		},
		
		
		highlightElement : function(element)
		{
			var _this = this;
			
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }
			
			if( !element.data("animating") && element.data("collapsed") )
			{
				element
					.data("animating", true)
					.addClass("active")
					.find("img").animate(
						_this.animationSettings[_this.menuType].over,
						element.data("speed"),
						function()
						{
							element
								.data("animating", false)
								.data("collapsed", false);
						}
				);
				
				_this.addShadow(element);
			}
		},
		
		
		restoreElement : function(element)
		{
			var _this = this;
			
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }
			
			element.data(
				"delayTimer",
				setTimeout(
					function()
					{
						element
							.data("delayTimer", null)
							.data("animating", true)
							.removeClass("active")
							.find("img").animate(
								_this.animationSettings[_this.menuType].out,
								element.data("speed"),
								function()
								{
									element
										.data("animating", false)
										.data("collapsed", true);
									_this.removeShadow(element);
								}
							);
					},
					element.data("delayTimeOut")
				)
			);
		},
		
		
		addShadow : function(element)
		{
			if(element.hasClass("shadow")){ return; }
			if(this.menuType == "big"){ return; }
			if($.browser.msie){ return; }
			
			element.addClass("shadow").dropShadow({
				left: 0,
				top: 3,
				blur: 4,
				opacity: 0.4,
				color: "#544837",
				swap: false
			});
		},
		
		
		removeShadow : function(element)
		{
			if(this.menuType == "big"){ return; }
			element.removeClass("shadow").removeShadow();
		}
		
	};
	
	productTypesMenu.init();
	
	
	
	
	/**
	 *  Altres seccions:
	 * ------------------------------------
	 *  
	 *
	 ***********************************************************************************************************************************/
	
	
	/**
	 * banners capçalera:
	 * slideshow banners
	 */
	var bannersTop = {
		banners       : $("#bannersTop li"),
		totalBanners  : 0,
		currentBanner : 0,
		intervalId    : null,
		speed         : 5000,
		staticPages   :
		[
			{
				pageClassName : 'promoVisum3',
				bannerId      : 'bt_visum3'
			},
			
			{
				pageClassName : 'quienes-somos',
				bannerId      : 'bt_cercaDeTi'
			},
			
			{
				pageClassName : 'galeria',
				bannerId      : 'bt_creaTuMundo'
			},
			
			{
				pageClassName : 'certificaciones',
				bannerId      : 'bt_maximaCalidad'
			},
			
			{
				pageClassName : 'medio-ambiente',
				bannerId      : 'bt_cuidandoTuEntorno'
			},
			
			{
				pageClassName : 'localizacion',
				bannerId      : 'bt_venAConocernos'
			},
			
			{
				pageClassName : 'quienes-somos',
				bannerId      : 'bt_cercaDeTi'
			},
			
			{
				pageClassName : 'quienes-somos',
				bannerId      : 'bt_cercaDeTi'
			},
			
			{
				pageClassName : 'profesionales',
				bannerId      : 'bt_disenoCreacion'
			}
		],
		
		
		init : function()
		{
			var staticPage      = false;
			var staticPageIndex = null;
			
			// desactivat pq en realitat el carrussel només està en la home
			
			/*
			for(var i = 0; i < this.staticPages.length; i++)
			{
				var strClassName = this.staticPages[i].pageClassName;
				
				if( $("body").hasClass(strClassName) )
				{
					staticPage      = true;
					staticPageIndex = i;
					break;
				}
			}
			*/
			
			if(staticPage)
			{
				this.initStaticBanner(staticPageIndex);
			}
			else
			{
				this.prepareSlideshow();
			}
		},
		
		
		/**
		 * inicialització del banner
		 * en el cas que la pàgina no tingui slideshow
		 * (el llistat ara s'està filtrant per php. així que això provablement es innecesari...)
		 */
		initStaticBanner : function(staticBannerNum)
		{
			var bannerId = this.staticPages[staticBannerNum].bannerId;
			
			for(var i = 0; i < this.banners.length; i++)
			{
				if( this.banners.eq(i).attr("id") != bannerId )
				{
					this.banners.eq(i).hide();
				}
			}
		},
		
		
		prepareSlideshow : function()
		{
			this.totalBanners  = this.banners.length;
			this.currentBanner = this.banners.length - 1;
			
			for(var i = 0; i < this.currentBanner; i++)
			{
				this.banners.eq(i).hide();
			}
			
			this.buildNav();
			this.startSlideshow();
		},
		
		
		crossfade : function(banner1, banner2)
		{
			bannersTop.banners.eq(banner2).fadeIn("slow");
			
			this.banners.eq(banner1).fadeOut("slow", function()
			{
				bannersTop.currentBanner = banner2;
			});
		},
		
		
		/**
		 * menú per a seleccionar el banner a visualitzar
		 */
		buildNav : function()
		{
			
		},
		
		
		startSlideshow : function()
		{
			this.intervalId = setInterval(
				function()
				{
					var banner1 = bannersTop.currentBanner;
					var banner2 = (bannersTop.currentBanner < bannersTop.totalBanners -1) ? (bannersTop.currentBanner + 1) : 0;
					
					bannersTop.crossfade(banner1, banner2);
				},
				this.speed );
		},
		
		
		stopSlideshow : function()
		{
			clearInterval(this.intervalId);
		}
		
	};
	
	bannersTop.init();
	
	
	
	
	/**
	 * pàgina colors teules
	 */
	var productColors =
	{
		inited        : false,
		menu          : $("#productColors"),
		menuElements  : $("#productColors a"),
		
		
		init : function()
		{
			if( !$("body").hasClass("gama-colores") ){ return; }
			
			if(this.inited){ return false; }
			
			this.inited = true;
			
			this.initRollovers();
			this.assignLinksClickHandlers();
		},
		
		
		/**
		 * 'hijacking' dels enllaços del llistat d'imatges
		 * per a que es carreguin les noves imatges sense
		 * recarregar la pàgina
		 */
		assignLinksClickHandlers : function()
		{
			this.menuElements.each(function()
			{
				$(this).bind("click", function()
				{
					$.getJSON($(this).attr("href"), function(data)
					{
						if(data)
						{
							var _target = ($("#productColorsPicsWrapper").length > 0) ? $("#productColorsPicsWrapper") : $("#productColorsPics");
							
							_target.fadeOut("slow", function()
							{
								if(data.productColorDetail)
								{
									if( $("#productColorDetail").length < 1 ){ $("#productColorsPics").prepend('<li><img id="productColorDetail" src="" alt="" /></li>'); }
									
									$("#productColorDetail")
										.show()
										.attr("src", data.productColorDetail)
										.attr("alt", data.productName + " - " + data.productType + " : " + data.productColorName);;
								}
								else
								{
									$("#productColorDetail").hide();
								}
								
								
								if(data.productColorPhoto)
								{
									if( $("#productColorPhoto").length < 1 ){ $("#productColorsPics").append('<li><img id="productColorPhoto" src="" alt="" /></li>'); }
									
									$("#productColorPhoto")
										.show()
										.attr("src", data.productColorPhoto)
										.attr("alt", data.productName + " - " + data.productType + " : " + data.productColorName);
								}
								else
								{
									$("#productColorPhoto").hide();
								}
								
								$(this).fadeIn("slow");
							});
							
							
							$("#productColorName").fadeOut("slow", function()
							{
								$(this).text(data.productColorName).fadeIn("slow");
							});
						}
					});
					
					return false;
				});
			});
		},
		
		
		initRollovers : function()
		{
			this.menuElements.each(function()
			{
				$(this)
					.mouseover(function()
					{
						productColors.addShadow( $(this) );
					})
					.mouseout(function()
					{
						productColors.removeShadow( $(this) );
						
						$(this).css("position", "static");
					});
			});
		},
		
		
		addShadow : function(element)
		{
			if($.browser.msie){ return; }
			
			if(element.hasClass("shadow")){ return; }
			
			element.addClass("shadow").dropShadow({
				left: -3,
				top: 5,
				blur: 2,
				opacity: 0.2,
				color: "#544837",
				swap: false
			});
		},
		
		
		removeShadow : function(element)
		{
			element.removeClass("shadow").removeShadow();
		}
	};
	
	productColors.init();
	
	
	
	
	/**
	 * peces especials
	 */
	var specialPieces =
	{
		data : {},
		
		
		init : function()
		{
			if(!$("body").hasClass("piezas-especiales")){ return; }
			
			$("#piezas-especiales").before("<div id='flash-piezas-especiales'></div>");
			
			this.parseSpecialPieces();
		},
		
		
		initSWF : function()
		{
			var __data     = $.browser.msie ? this.urlencode($.toJSON(this.data)) : $.toJSON(this.data);
			var flashvars  = { data : __data };
			var params     = {};
			var attributes = {};
			var basePath   = '/assets/flash/';
			var swfPath    = basePath + 'piezas-especiales.' + $("html").attr("lang") + '.swf';
            
			params.scale             = "exactfit";
			params.wmode             = "transparent";
			params.bgcolor           = "#ffffff";
			params.allowfullscreen   = "false";
			params.allowscriptaccess = "sameDomain";
			
			attributes.id = this.swfId;
			
			swfobject.embedSWF(
				swfPath,
				"flash-piezas-especiales",
				"590",
				"204",
				"10.0.0",
				basePath + "expressInstall.swf",
				flashvars,
				params,
				attributes
			);
		},
		
		
		parseSpecialPieces : function()
		{
			var _this = this;
			
			$("#piezas-especiales li").each(function()
			{
				var classes   = String($(this).attr("class")).split(" ");
				var regExp    = /^C[0-9]*$/;
				
				for(var i = 0; i < classes.length; i++)
				{
					if( regExp.test(classes[i]) )
					{						
						var className = String(regExp.exec(classes[i])[0]).toLowerCase();
						
						if(!_this.data[className]){ _this.data[className] = []; }
						
						_this.data[className].push({
							title: $(this).find("strong").text(),
							img  : $(this).find("img").eq(0).attr("src"),
							href : $(this).find("a").eq(0).attr("href")
						});
						
						break;
					}
				}
				
				$(this).bind("click", function()
				{
					var productId = null;
					var anchors   = $(this).find("a");
					
					if(anchors.length > 0)
					{
						var anchorHref = anchors.eq(0).attr("href");
						
						productId = (function(url)
						{
							var regexS  = "[\\?&]id=([^&#]*)";
							var regex   = new RegExp(regexS);
							var results = regex.exec(url);
							return (results === null) ? null : results[1];
						})(anchorHref);
						
						if(productId !== null)
						{
							var lang   = $("html").attr("lang");
							var titles = {
								"es" : "Piezas especiales",
								"en" : "Accessories",
								"fr" : "Accessoires"
							};
							tb_show(titles[lang], "piezas-especiales-ficha.php" + "?id=" + productId + "&keepThis=true&TB_iframe=true&height=500&width=470", false);
						}
					}
					
					return false;
				});
			});
			
			this.initSWF();
		},
		
		
		/**
		 * mètode auxiliar per a codificar les dades abans de passar-les al flash
		 * només es necessari en el p**o Explorer, per variar...
		 */
		urlencode : function( str )
		{
		    // http://kevin.vanzonneveld.net
		    // +   original by: Philip Peterson
		    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +      input by: AJ
		    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
		    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +      input by: travc
		    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
		    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: Lars Fischer
		    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
		    // *     example 1: urlencode('Kevin van Zonneveld!');
		    // *     returns 1: 'Kevin+van+Zonneveld%21'
		    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
		    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
		    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
		    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

		    var histogram = {}, unicodeStr='', hexEscStr='';
		    var ret = (str+'').toString();

		    var replacer = function(search, replace, str) {
		        var tmp_arr = [];
		        tmp_arr = str.split(search);
		        return tmp_arr.join(replace);
		    };

		    // The histogram is identical to the one in urldecode.
		    histogram["'"]   = '%27';
		    histogram['(']   = '%28';
		    histogram[')']   = '%29';
		    histogram['*']   = '%2A';
		    histogram['~']   = '%7E';
		    histogram['!']   = '%21';
		    histogram['%20'] = '+';
		    histogram['\u00DC'] = '%DC';
		    histogram['\u00FC'] = '%FC';
		    histogram['\u00C4'] = '%D4';
		    histogram['\u00E4'] = '%E4';
		    histogram['\u00D6'] = '%D6';
		    histogram['\u00F6'] = '%F6';
		    histogram['\u00DF'] = '%DF';
		    histogram['\u20AC'] = '%80';
		    histogram['\u0081'] = '%81';
		    histogram['\u201A'] = '%82';
		    histogram['\u0192'] = '%83';
		    histogram['\u201E'] = '%84';
		    histogram['\u2026'] = '%85';
		    histogram['\u2020'] = '%86';
		    histogram['\u2021'] = '%87';
		    histogram['\u02C6'] = '%88';
		    histogram['\u2030'] = '%89';
		    histogram['\u0160'] = '%8A';
		    histogram['\u2039'] = '%8B';
		    histogram['\u0152'] = '%8C';
		    histogram['\u008D'] = '%8D';
		    histogram['\u017D'] = '%8E';
		    histogram['\u008F'] = '%8F';
		    histogram['\u0090'] = '%90';
		    histogram['\u2018'] = '%91';
		    histogram['\u2019'] = '%92';
		    histogram['\u201C'] = '%93';
		    histogram['\u201D'] = '%94';
		    histogram['\u2022'] = '%95';
		    histogram['\u2013'] = '%96';
		    histogram['\u2014'] = '%97';
		    histogram['\u02DC'] = '%98';
		    histogram['\u2122'] = '%99';
		    histogram['\u0161'] = '%9A';
		    histogram['\u203A'] = '%9B';
		    histogram['\u0153'] = '%9C';
		    histogram['\u009D'] = '%9D';
		    histogram['\u017E'] = '%9E';
		    histogram['\u0178'] = '%9F';

		    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
		    ret = encodeURIComponent(ret);

		    for (unicodeStr in histogram) {
		        hexEscStr = histogram[unicodeStr];
		        ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
		    }

		    // Uppercase for full PHP compatibility
		    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
		        return "%"+m2.toUpperCase();
		    });
		}
	};
	
	specialPieces.init();
	
	
	
	
	/**
	 * galeria fotos
	 */
	var productPicsGallery =
	{
		inited            : false,
		menu              : $("#galleryPicsList"),
		menuElements      : $("#galleryPicsList a"),
		currentImg        : null,
		animating         : false,
		animationInterval : null,
		
		
		init : function()
		{
			if( !$("body").hasClass("galeria") ){ return; }
			
			if(this.inited){ return false; }
			
			this.inited     = true;
			this.currentImg = 0;
			
			this.menu.addClass("jsFixed");
			this.addReflections();
			this.initRollovers();
			
			this.menuElements.each(function(i)
			{
				$(this).find("img").eq(0).data("index", i);
			});
			
			if( this.menuElements.length > 1)
			{
				this.buildNav();
				this.buildPagination();
			}
			
			this.initialiseLinks();
			// this.initScroller();  //--> desactivat, substituit per un altre sistema de navegació (buildPagination)
			
			if($("body").hasClass("productos")){ this.initTooltips(); }
		},
		
		
		/**
		 * inicialització links imatges per a que la imatge ampliada
		 * es carregui sense actualitzar la pàgina
		 */
		initialiseLinks : function()
		{
			this.menuElements.each(function()
			{
				$(this).bind("click", function()
				{
					var imgSrc   = $(this).attr("href");
					var imgTitle = $(this).find("img").eq(0).attr("alt");
					var imgIndex = $(this).find("img").eq(0).data("index");
					
					productPicsGallery.zoomImage( imgSrc, imgTitle, imgIndex );
					return false;
				});
			});
		},
		
		
		initRollovers : function()
		{
			this.menuElements.each(function()
			{
				if( $(this).hasClass("current") ){ return; }

				$(this)
					.data("collapsed",    true)
					.data("delayTimer",   null)
					.data("delayTimeOut", 20)
					.data("animating",    false)
					.data("speed",        300)
					.mouseover(function()
					{
						productPicsGallery.highlightElement( $(this) );
					})
					.mouseout(function()
					{
						productPicsGallery.restoreElement( $(this) );
					});
			});
		},
		
		
		highlightElement : function(element)
		{
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }

			if( !element.data("animating") && element.data("collapsed") )
			{
				element
					.data("animating", true)
					.addClass("active")
					.find("img").animate(
						{ width: "95px", height: "63px" },
						element.data("speed"),
						function()
						{
							element
								.data("animating", false)
								.data("collapsed", false);
						});
				
				if(element.hasClass("reflectionInitialised"))
				{
					element.find("div").animate( { width: "95px" }, element.data("speed") );
					element.find("canvas").animate( { width: "95px" }, element.data("speed") );
				}
			}
		},
		
		
		restoreElement : function(element)
		{
			if( element.data("delayTimer") ){ clearTimeout( element.data("delayTimer") ); }
			
			element.parent("li").find(".shadow").fadeOut( element.data("speed")/2 );
			
			element.data( "delayTimer", setTimeout(
				function()
				{
					element
						.data("delayTimer", null)
						.data("animating", true)
						.removeClass("active")
						.find("img")
						.animate(
							{ width: "74px", height: "50px" },
							element.data("speed"),
							function()
							{
								element
									.data("animating", false)
									.data("collapsed", true);
							}
						);
						
					if(element.hasClass("reflectionInitialised"))
					{
						element.find("div").animate( { width: "74px" }, element.data("speed") );
						element.find("canvas").animate( { width: "74px" }, element.data("speed") );
					}
				},
				element.data("delayTimeOut") )
			);
		},
		
		
		addReflections : function()
		{
			this.menu.find("img").each(function()
			{
				$(this).load(function()
				{
					$(this).parent("a").addClass("reflectionInitialised");
					$(this).reflect({height: 0.6, opacity: 0.4});
				});
			});
		},
		
		
		buildNav : function()
		{
			/**** btns anterior/seguent foto ****/
			$("#galleryPic")
				.append("<img id='galleryPic_prev' src='/assets/images/ui/gallery_prev.png' alt='anterior' />")
				.append("<img id='galleryPic_next' src='/assets/images/ui/gallery_next.png' alt='siguiente' />");
			
			$("#galleryPic_prev").bind("click", function()
			{
				var _this        = productPicsGallery;
				var prevImgIndex = ( _this.currentImg > 0 ) ? (_this.currentImg - 1) : (_this.menuElements.length - 1);
				
				var prevNode     = _this.menuElements.eq(prevImgIndex);
				var imgSrc       = prevNode.attr("href");
				var imgTitle     = prevNode.find("img").eq(0).attr("alt");
				var imgIndex     = prevNode.find("img").eq(0).data("index");

				_this.zoomImage( imgSrc, imgTitle, imgIndex );
			});

			$("#galleryPic_next").bind("click", function()
			{
				var _this        = productPicsGallery;
				var nextImgIndex = ( _this.currentImg < _this.menuElements.length -1 ) ? (_this.currentImg + 1) : 0;
			
				var nextNode     = _this.menuElements.eq(nextImgIndex);
				var imgSrc       = nextNode.attr("href");
				var imgTitle     = nextNode.find("img").eq(0).attr("alt");
				var imgIndex     = nextNode.find("img").eq(0).data("index");

				_this.zoomImage( imgSrc, imgTitle, imgIndex );
			});
		},
		
		
		zoomImage : function(imgHref, imgDesc, imgIndex)
		{
			clearInterval(this.animationInterval);
			
			if(this.animating){ return false; }
			
			this.animating = true;
			
			productPicsGallery.currentImg = imgIndex;
			
			$("#galleryPic img").eq(0).fadeOut("slow", function()
			{
				$("#galleryPic").append("<div id='loadingAnimation'></div>");
				
				var callback = function()
				{
					$("#loadingAnimation").fadeOut("fast", function()
					{
						$(this).remove();
						productPicsGallery.animating = false;
					});
				};
				
				$(this)
					.data("inited", false)
					.load(function()
					{
						if( $(this).data("inited") ){ return; } else { $(this).data("inited", true); }
						$(this).fadeIn("slow");
						callback();
					})
					.error(function(){ callback(); })
					.attr("alt", imgDesc)
					// es necesari resetejar l'atribut src pq si no en safari i en opera
					// podria no produirse l'esdeveniment load en determinades circumstancies
					.attr("src", "")
					.attr("src", imgHref);
			});
		},
		
		
		/**
		 * autoscroll dels thumbs al fer rollover
		 */
		initScroller : function()
		{
			var _this       = this;
			var _itemsWidth = 0;
			var _availWidth = $("#galleryPicsList").outerWidth();
			
			$("#galleryPicsList li").each(function(){ _itemsWidth += $(this).outerWidth(); });
			
			if( $("#galleryPicsList li").length <= 6 ){ return; }
			
			var inc = ($.browser.msie && ($.browser.version < 7)) ? 600 : 200;
			
			$("#galleryPicsList")
				.css("width", (_itemsWidth + inc) + "px")
				.wrap('<div id="galleryPicsListWrapper"></div>');
			
			if($.browser.msie && ($.browser.version < 7)){ return; }
			
			$("#galleryPicsListWrapper")
				.mouseover(function(e)
				{
					clearInterval(_this.animationInterval);
					
					_this.animationInterval = setInterval(function()
					{
						var _el = $("#galleryPicsListWrapper");
						
						xCoordIncrement = ((_el.outerWidth() / 2) < (e.clientX - _el.offset().left)) ? 2 : -2;
						
						_el.scrollLeft( _el.scrollLeft() + xCoordIncrement);
					}, 5);
				})
				.mouseout(function(){ clearInterval(_this.animationInterval); });
		},
		
		
		/**
		 * pseudopaginació miniatures
		 */
		buildPagination : function()
		{
			var _this       = this;
			var _itemsWidth = 0;
			var _availWidth = $("#galleryPicsList").outerWidth();

			$("#galleryPicsList li").each(function(){ _itemsWidth += $(this).outerWidth(); });

			if( $("#galleryPicsList li").length <= 6 ){ return; }

			var inc = ($.browser.msie && ($.browser.version < 7)) ? 600 : 200;

			$("#galleryPicsList")
				.css("width", (_itemsWidth + inc) + "px")
				.wrap('<div id="galleryPicsListWrapper"></div>');

			if($.browser.msie && ($.browser.version < 7)){ return; }
			
			$("#contents").append("<img id='picsList_prev' src='/assets/images/ui/gallery_prev.png' alt='anterior' />");
			$("#contents").append("<img id='picsList_next' src='/assets/images/ui/gallery_next.png' alt='siguiente' />");
			
			$("#picsList_prev").bind("click", function()
			{
				$("#galleryPicsListWrapper").scrollTo(
					"-=582px",
					{
						axis     : "x",
						duration : 400,
						easing   : 'swing',
						onAfter  : function(){}
					}
				);
			});
			
			$("#picsList_next").bind("click", function()
			{
				$("#galleryPicsListWrapper").scrollTo(
					"+=582px",
					{
						axis     : "x",
						duration : 400,
						easing   : 'swing',
						onAfter  : function(){}
					}
				);
			});	
		},
		
		
		initTooltips : function()
		{
			$("#galleryPic img")
				.not("#galleryPic_prev")
				.not("#galleryPic_next")
				.tooltip({
					bodyHandler: function()
					{
						var val      = $(this).attr("src").replace(/\.[^\.]*$/, '');
						var chunks   = val.split("_");
						
						chunks.shift();
						return chunks.join(" ");
					},
					showURL: false
				});
			
		}
	};
	
	productPicsGallery.init();
	
	
	
	
	/**
	 * noticies
	 */
	var news = 
	{
		init : function()
		{
			$("#news li")
				.append('<a class="more-info" href="#">+<abbr title="información">info</abbr></a>')
				.not(".initial")
				.addClass("collapsed");
			
			this.initHandlers();
		},
		
		
		toggleNew : function(newElementRef)
		{
			newElementRef
				.toggleClass("collapsed")
				.siblings()
				.addClass("collapsed");
		},
		
		
		initHandlers : function()
		{
			var _this = this;
			
			$("#news h3")
				.css("cursor", "pointer")
				.add("a.more-info")
				.bind("click", function()
				{
					_this.toggleNew( $(this).parent("li") );
					return false;
				});
		}
	};
	
	news.init();
	
	// just for fun: tot l'objecte news en una sola línea encadenant mètodes a sac
	// $("#news li").addClass("collapsed").append('<a class="more-info" href="#">+<abbr title="información">info</abbr></a>').find("h3").css("cursor", "pointer").add("a.more-info").bind("click", function(){ $(this).parent("li").toggleClass("collapsed").siblings().addClass("collapsed"); return false; });
	
	
	
	
	/**
	 * carrussel certificats
	 */
	$('#certs').Fisheye(
	{
		itemWidth: 40,
		maxWidth: 60,
		items: 'li',
		itemsText: 'p',
		container: '.certs-container',
		proximity: 80,
		valign: 'bottom',
		halign : 'center'
	});
	
	
	
	
	/**
	 * faq
	 */
	$("#faq dt")
		.css("cursor", "pointer")
		.bind("click", function()
		{
	    	$(this).next("dd").slideToggle();
		})
		.next("dd").hide();
	
	
	
	
	/**
	 * icones descarregues
	 */
	$('#downloads-list > li')
		.css("cursor", "pointer")
		.bind("click", function()
		{
			window.location = $(this).find("a").eq(0).attr("href");
		})
		.append('<span class="icon" />');
	
	
	
	
	/**
	 * autocad
	 */
	$("#autocad")
		.wrap('<div id="autocad-wrapper"></div>')
		.find("li").each(function()
		{
			$(this)
				.data("href", $("a", this).attr("href"))
				.data("img", $("img", this).attr("src"))
				.find("img").remove().end()
				.find("a").bind("click", function()
				{
					$(this).parent("li").addClass("current").siblings().removeClass("current");
					
					if($("#autocad-info").length === 0)
					{
						$("#autocad-wrapper").append('<div id="autocad-info"></div>');
						$("#autocad-info").append('<img id="autocad-pic" />');
						$("#autocad-info").append('<a id="autocad-dl">descargar</a>');
					}
					
					var _this = this;
					
					$("#autocad-info").fadeOut("fast", function()
					{
						$("#autocad-pic").attr("src", $(_this).parent("li").data("img"));
						$("#autocad-dl").attr("href", $(_this).parent("li").data("href"));
						$("#autocad-info").fadeIn("slow");
					});
					return false;
				});
		});
	
	
	
	
	/**
	 * video
	 */
	// css adicional thickbox
	var style = document.createElement("link");
	style.setAttribute("type", "text/css");
	style.setAttribute("media", "screen");
	style.setAttribute("rel", "stylesheet");
	style.setAttribute("href", "/assets/css/thickbox.css");
	document.getElementsByTagName("head")[0].appendChild(style);
	
	$("#videoCorporativo a.video").bind("click", function()
	{
		tb_show("", $(this).attr("href") + "?keepThis=true&TB_iframe=true&height=210&width=400", false);
		return false;
	});
	
	if($("body").hasClass("video") && ($(".video-corporativo").length > 0) )
	{
		var flashParams =
		{
			path       : "/assets/flash/video-corporativo/",
			file       : "player." + $("html").attr("lang") + ".swf",
			width      : "400",
			height     : "219",
			flashvars  : {},
			params     : {},
			attributes : { id : "contents" }
		};
		
		swfobject.embedSWF(
			flashParams.path + flashParams.file,
			flashParams.attributes.id,
			flashParams.width,
			flashParams.height,
			"10.0.0",
			"/assets/flash/expressInstall.swf",
			flashParams.flashvars,
			flashParams.params,
			flashParams.attributes);
	}
	
	
	
	
	/**
 	 *  Efectes:
 	 * ------------------------------------
 	 *  rounded corners, dropshadows, ...
 	 *
 	 ***********************************************************************************************************************************/	
	
	/**
	 *  rounded corners
	 * ------------------------------------
	 */
	if( !($.browser.msie && ($.browser.version < 7)) )
	{
		$("#productNav a").corner("round 8px");
	}
	
	
	// colors
	if(!$.browser.msie)
	{
		$("#productColors").wrap("<div id='productColorsWrapper'></div>");
		$("#productColorsPics").wrap("<div id='productColorsPicsWrapper'></div>");

		$("#productColors, #productColorsPics")
			.addClass("roundedCorners")
			.corner("round 10px");

		$("#productColorsWrapper, #productColorsPicsWrapper").corner("round 10px");
	}
	
	
	// menú tipus producte en pàgina característiques
	if( $("body").hasClass("caracteristicas") && (!$.browser.msie) )
	{
		$("#productTypes").wrap("<div id='productTypesWrapper'></div>");
		
		$("#productTypes")
			.addClass("roundedCorners")
			.corner("round 12px");

		$("#productTypesWrapper").corner("round 10px");
	}
	
	
	// galeria
	$("#galleryPic").wrap("<div id='galleryPicWrapper'></div>");
	
	$("#galleryPic")
		.addClass("roundedCorners")
		.corner("round 10px");
	
	$("#galleryPicWrapper").corner("round 10px");
	
	
	// peces especials
	$("#piezas-especiales")
		.addClass("roundedCorners")
		.corner("round 10px")
		.wrapInner( "<div class='innerWrapper'></div>" );
			
	$(".innerWrapper").corner("round 6px");
	
	
	// forms downloads/contacte
	$("#fDownloads input[type=text], #fDownloads input[type=password]")
		.addClass("roundedCorners")
		.wrap("<div class='inputWrapper'></div>");
		
	$("#fContacto input[type=text], #fSolicitudTrabajo input[type=text]")
		.addClass("roundedCorners")
		.wrap("<div class='inputWrapper'></div>");
	
	$("#fContacto textarea, #fSolicitudTrabajo textarea")
		.addClass("roundedCorners")
		.wrap("<div class='textareaWrapper'></div>");
	
	if(!$.browser.msie)
	{
		$("#fContacto #fSubmit, #fSolicitudTrabajo #fSubmit").wrap("<div class='submitWrapper'></div>");
	}
	
	$(".submitWrapper").corner("round 10px");
	
	$(".inputWrapper, .textareaWrapper").append("<div class='rightBorder'></div>");
	
	
	// guies instalacio
	if(!($.browser.msie && ($.browser.version < 7)))
	{
		$("#guias-instalacion li")
			.css("border", "none")
			.css("background-color", "#e0e0e0")
			.css("padding", "1px")
			.css("margin-left", "-2px")
			.wrapInner( "<div class='innerWrapper'></div>" )
			.addClass("roundedCorners")
			.corner("round 3px");
	}
	
	
	
	
	/**
	 *  dropshadows
	 * ------------------------------------
	 *
	 */
	if( !$.browser.safari && !$.browser.msie )	// desactivat en Safari pq fa coses rares de vegades
	{
		$("#secondaryNav").dropShadow({
			left: 0,
			top: 16,
			blur: 4,
			opacity: 0.3,
			color: "#544837",
			swap: false
		});
	}
	
	
	
	
	/**
	 *  reflex menú secundari
	 * ------------------------------------
	 *
	 *  desactivat perque interfereix
	 *  amb el menu colapsable
	 * 
	 */
	
	//	$("#secondaryNav > li").each(function(i)
	//	{
	//		$(this)
	//			.data("img", String($(this).css("background-image")).replace("url(", "").replace(")", "") )
	//			.css("background-image", "none")
	//			.append("<div class='btnPic'><img src=" + $(this).data("img") + " /></div>");
	//	});
	//	
	//	$('.btnPic img').load(function()
	//	{
	//		$(this).reflect({height: 0.3, opacity: 0.4});
	//	});
	
	
	
	
	/**
	 * 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)
	 *
	 ***********************************************************************************************************************************/
	
	if( $.browser.msie )
	{
		$("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");
		$("html[lang=en]").addClass("en");
		$("html[lang=fr]").addClass("fr");
		
		$("#secondaryNav  > li").css("height", "100%");

		$("legend").each(function(i)
		{
			$(this).after("<p class='legend'>" + $(this).text() + "</p>").remove();
		});
		
		$("label[for$='ubmit']").css("display", "none");
		
		if($.browser.version < 8)
		{
			$("body.links #contents dd").after('<span class="clear" />');
			
			$("#presencia-en-el-mundo dd").each(function()
			{
				var countries = [];
				
				$("li", $(this)).each(function()
				{
					countries.push( $.trim($(this).text()) );
				});
				
				$(this).html( "<span/>" + countries.join(", ") );
			});
		}
		
		if($.browser.version < 7)
		{
			$("#secondaryNav > li").addClass("child");
			
			$("#faq dt").each(function(i)
			{
				$(this).prepend((i+1) + "- ").wrapInner("<p></p>");
			});
			
			$("#sectionNav ul.nav > li").addClass("child");
			
			$("#piezas-especiales > li").addClass("category");
		}
	}
	
	
	if( $.browser.mozilla )
	{
		$("legend").each(function(i)
		{
			$(this).after("<p class='legend'>" + $(this).text() + "</p>").remove();
		});
		
		$("#fDownloads legend").css("display", "none");
	}
	
});


/***********************************************************************************************************************************/




/**
 * validador generic per a formularis
 */
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) )
		{
			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 comprendido entre " + minValue + " y " + maxValue);
			formValidator.returnVal = false;
			formValidator.erroneousFields.push(el);
		}
	},
	
	
	checkCp : function(el)
	{
		var cp = el.val();
		if( (cp.length > 5) || (isNaN(cp)) )
		{
			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);
		}
	}
	
};




/***********************************************************************************************************************************/


/**
 * funcions/mètodes que han d'estar en el namespace global
 * pq han de ser accessibles des de flash via ExternalInterface
 */
var laEscandella = 
{
	showCard : function(url)
	{
		var lang   = $("html").attr("lang");
		var titles = {
			"es" : "Piezas especiales",
			"en" : "Accessories",
			"fr" : "Accessoires"
		};
		var productId = (function(url)
		{
			var regexS  = "[\\?&]id=([^&#]*)";
			var regex   = new RegExp(regexS);
			var results = regex.exec(url);
			return (results === null) ? null : results[1];
		})(url);
		
		if(productId !== null)
		{
			tb_show(titles[lang], "piezas-especiales-ficha.php" + "?id=" + productId + "&keepThis=true&TB_iframe=true&height=500&width=470", false);
		}
	}
};