/**
 * Expodec
 * -----------------------------------------------------------------
 *
 * author:               Alcaraz & Estevez Consultores
 * projectId:            
 * version:              0.1
 * creation date:        26-03-2009
 * description:          
 * notes:
 *
 */


$(document).ready(function()
{
	/**
	 * inicialització llibreria generica
	 */
	ALCARAZ.htmlUtils.initExternalLinks();
	ALCARAZ.forms.initDefaultValues();
	ALCARAZ.misc.initFullLinks();
	
	if( $.browser.msie )
	{
		ALCARAZ.cssFixes.fixIESelectors();
		ALCARAZ.cssFixes.fixLegends();
	}
	
	if( $.browser.mozilla )
	{
		ALCARAZ.cssFixes.fixLegends();
	}
	
	
	
	/**
	 * menu
	 */
	$("#siteNav > ul > li")
		.not("#sn4")
		.not("#sn5")
		.after("<img src='/assets/images/ui/menuSeparator.png' class='separator' />");
	
	$("#siteNav li")
		.css("cursor", "pointer")
		.bind("click", function(){ window.location = $(this).find("a").eq(0).attr("href"); });
	
	$("#siteNav ul ul")
		.css("cursor", "default")
		.bind("click", function(){ return false; });
	
	
	
	
	/**
	 * flash
	 */
	var flashParams = 
	{
		path : "/assets/flash/",
		
		// flash principal home
		flashHome : 
		{
			file       : "home.swf",
			width      : "942",
			height     : "370",
			flashvars  : {},
			params     : {},
			attributes : { id : "intro" }
		},
		
		// flash banner ex3 home
		flashBannerEx3 : 
		{
			file       : "promo-ex3.swf",
			width      : "194",
			height     : "268",
			flashvars  : {},
			params     : { wmode : "transparent" },
			attributes : { id : "promo-ex3-banner" }
		},
		
		// flash ex3
		flashEx3 : 
		{
			file       : "ex3.swf",
			width      : "670",
			height     : "485",
			flashvars  : {},
			params     : {},
			attributes : { id : "flash-ex3" }
		}
	};
	
	
	if( $("body").hasClass("home") )
	{
		swfobject.embedSWF(
			flashParams.path + flashParams.flashHome.file,
			flashParams.flashHome.attributes.id,
			flashParams.flashHome.width,
			flashParams.flashHome.height,
			"10.0.0",
			flashParams.path + "expressInstall.swf",
			flashParams.flashHome.flashvars,
			flashParams.flashHome.params,
			flashParams.flashHome.attributes);
			
		if( $.browser.msie ){ $("body.home #intro").css("text-indent", "0"); }
		
		swfobject.embedSWF(
			flashParams.path + flashParams.flashBannerEx3.file,
			flashParams.flashBannerEx3.attributes.id,
			flashParams.flashBannerEx3.width,
			flashParams.flashBannerEx3.height,
			"9.0.0",
			flashParams.path + "expressInstall.swf",
			flashParams.flashBannerEx3.flashvars,
			flashParams.flashBannerEx3.params,
			flashParams.flashBannerEx3.attributes);
	}
	
	if( $("body").hasClass("inicio-ex3") )
	{
		swfobject.embedSWF(
			flashParams.path + flashParams.flashEx3.file,
			flashParams.flashEx3.attributes.id,
			flashParams.flashEx3.width,
			flashParams.flashEx3.height,
			"9.0.0",
			flashParams.path + "expressInstall.swf",
			flashParams.flashEx3.flashvars,
			flashParams.flashEx3.params,
			flashParams.flashEx3.attributes);
	}
	
	
	
	
	/**
	 * galeries
	 * -----------
	 * el constructor de la 'classe' requereix un paràmetre, galleryProperties, un objecte amb les diferents propietats de la galeria
	 * les propietats que ha de tenir aquest objecte son:
	 *   - dataUrl             : string url de la que es carregaran les dades serialitzades en json per ajax
	 *   - thumbsListContainer : obj selector jquery que fa referencia al contenedor de la llista de thumbs
	 *   - galleryNav          : obj selector jquery que fa referencia al llistat numèric de navegació
	 *   - imgs                : array selectors jquery on es carregaran les imatges
	 *   - textfields          : array selectors jquery on es carregaran els textos
	 *   - currentItem         : int element inicial de la galeria
	 * 
	 * tots els mètodes de la classe exceptuant init serien privats en cas de javascript ho soportés
	 * init() sha d'invocar explicitament, no n'hi ha prou en crear una instancia de la classe
	 * 
	 */
	var Gallery = function()
	{
		// propietats de la classe
		this.dataUrl             = null;
		this.thumbsListContainer = null;
		this.galleryNav          = null;
		this.imgs                = null;
		this.textfields          = null;
		this.currentItem         = null;
		this.totalItems          = 0;
		this.loading             = false;
		this.itemWidth           = 0;
		
		
		// constructor
		if( (arguments.length === 0) || !$("body").hasClass("gallery") )
		{
			return;
		}
		else
		{
			this.dataUrl             = arguments[0].dataUrl;
			this.thumbsListContainer = arguments[0].thumbsListContainer;
			this.galleryNav          = arguments[0].galleryNav;
			this.imgs                = arguments[0].imgs;
			this.textfields          = arguments[0].textfields;
			this.currentItem         = arguments[0].currentItem;
			this.totalItems          = $("li", this.thumbsListContainer).length;
			this.itemWidth           = $("li", this.thumbsListContainer).eq(0).outerWidth(true);
		}
		
		
		// inicialització galeria
		this.init = function()
		{
			if( 
				(this.thumbsListContainer === null) ||
				(this.galleryNav          === null) ||
				(this.imgs                === null) ||
				(this.textfields          === null) ||
				(this.totalItems          === 0)
			)
			{
				return;
			}
			
			this.highlightProject(this.currentItem);
			this.preloadHighlightImages();
			this.initBtns();
			this.thumbsListContainer.scrollTo((this.currentItem * this.itemWidth), {axis: "x"});
		};
		
		
		// assignació event hendlers als links dels thumbs i del llistat numèric
		this.initBtns = function()
		{
			var _this = this;
			
			$("a", this.thumbsListContainer).add($("a", this.galleryNav)).each(function(i)
			{
				$(this)
					.data( "itemId", parseInt(String($(this).attr("href")).match(/\d+$/)[0], 10) )
					.bind("click", function()
					{
						_this.loadProject( $(this).data("itemId") );
						return false;
					});
			});
		};
		
		
		// càrrega per ajax de un projecte
		this.loadProject = function(itemId)
		{
			if(this.loading || (this.currentItem == itemId)){ return; }
			
			var _this = this;
			
			this.currentItem = itemId;
			this.loading = true;
			
			$.getJSON(
				_this.dataUrl + "?itemId=" + itemId,
				function(data)
				{
					// actualització texts
					$.each(data.metadata, function(i)
					{
						if( (_this.textfields[i] !== undefined) && (_this.textfields[i] !== null) )
						{
							_this.textfields[i].fadeOut("fast", function()
							{
								$(this).text(data.metadata[i]).fadeIn("fast");
							});
						}
					});
					
					// actualització imatges
					$.each(data.pics, function(i)
					{
						if( (_this.imgs[i] !== undefined) && (_this.imgs[i] !== null) )
						{
							_this.imgs[i].fadeOut("fast", function()
							{
								$(this)
									.attr("alt", data.pics[i].description)
									.attr("src", data.pics[i].src).load(function()
									{
										$(this).fadeIn("fast");
										_this.loading = false;
									});
							});
						}
					});
					
					// timeout de seguretat per si s'exganxa la càrrega de la imatge
					setTimeout( function(){ _this.loading = false; }, 3000 );
				}
			);
			
			this.highlightProject(this.currentItem);
			this.updateNav();
		};
		
		
		// actualització links anterior/següent de la barra dnavegació numèrica
		this.updateNav = function()
		{
			var c    = this.currentItem;
			var t    = this.totalItems;
			
			var prev = (c > 0)    ? (c - 1) : c;
			var next = (c < t -1) ? (c + 1) : c;
			
			$("a.prev", this.galleryNav).data("itemId", prev);
			$("a.next", this.galleryNav).data("itemId", next);
		};
		
		
		// destaca en el menú numèric i en el de thumbs el item que s'està mostrant actualment en la galeria
		this.highlightProject = function(itemId)
		{
			var _this = this;
			
			$("li", this.galleryNav).each(function(i)
			{
				$(this).removeClass("current");
				
				var index = String( $(this).find("a").eq(0).attr("href") ).match(/\d+$/)[0];
				
				if(index == itemId)
				{
					$(this).addClass("current");
				}
			});
			
			$("img", this.thumbsListContainer).each(function(i)
			{
				if( $(this).attr("src").indexOf("/thumbs_highlight/") > -1 )
				{
					var regularImgPath = $(this).attr("src").replace("/thumbs_highlight/", "/thumbs/");
					
					$(this).attr("src", regularImgPath);
				}
				
				var index = String( $(this).parent("a").attr("href") ).match(/\d+$/)[0];
				
				if(index == itemId)
				{
					var highlightImgPath = $(this).attr("src").replace("/thumbs/", "/thumbs_highlight/");
					
					$(this).attr("src", highlightImgPath);
				}
				
			});
			
			if( this.thumbsListContainer.width() <  (this.itemWidth * this.totalItems) )
			{
				this.thumbsListContainer.scrollTo(
					(itemId * _this.itemWidth),
					{
						axis     : "x",
						duration : 600,
						easing   : 'swing',
						onAfter  : function(){}
					}
				);
			}
		};
		
		
		// precarga imatges menú thumbs
		this.preloadHighlightImages = function()
		{
			var highlightImgs = [];
			
			$("img", this.thumbsListContainer).each(function(i)
			{
				highlightImgs.push( $(this).attr("src").replace("/thumbs/", "/thumbs_highlight/") );
			});
			
			ALCARAZ.htmlUtils.imgPreloader.preload(highlightImgs);
		};
		
	};
	
	
	if( $("body").hasClass("portfolio") )
	{
		var portfolioGallery = new Gallery({
			dataUrl             : "/portfolio/getData.php",
			thumbsListContainer : $("#project-pics"),
			galleryNav          : $("#projects-nav"),
			imgs                : [$("#pic img"), $("#pic img")],
			textfields          : [$("#client"), $("#projectName")],
			currentItem         : $("#projectId").text()
		});
		
		portfolioGallery.init();
	}
	
	
	
	if( $("body").hasClass("ejemplos-ex3") )
	{
		var ex3Gallery = new Gallery({
			dataUrl             : "/ex3/getData.php",
			thumbsListContainer : $("#project-pics"),
			galleryNav          : $("#projects-nav"),
			imgs                : [$("#pic img"), $("#diagram img")],
			textfields          : [null, $("#pic p")],
			currentItem         : $("#projectId").text()
		});
		
		ex3Gallery.init();
	}
	
	
	
	
	/**
	 * transicions ajax en ex3
	 */
	if( $("body").hasClass("inicio-ex3") )
	{
		$("#sn4-1, #sn4-2").bind("click", function(){ return false; });
		
		$("#sn4-1 a, #sn4-2 a").bind("click", function()
		{
			var currentLiElement = $(this).parent("li");
			var href             = $(this).attr("href");
			
			$("#sn4-1, #sn4-2").not(currentLiElement).removeClass("current");
			
			currentLiElement.addClass("current");
			
			$("#ex3-contents").fadeOut("slow", function()
			{
				$(this).load(href + " #contents-inner", function()
				{
					$("#ex3-contents").fadeIn("slow");
				});
			});
			
			return false;
		});
	}
	
	
	
	
	/**
	 * formulari contacte
	 */
	var formContacto =
	{
		returnVal : true,
		validator : new ALCARAZ.forms.Validator(),
		
		init : function()
		{
			// referencia a formContacto, pq des de dins dels objectes $ this ja no fa referencia a formContacto
			var _this = this;
			
			$("#contacto").submit( function()
			{
				$("#contacto input, #contacto textarea").removeClass("error");
				
				if(!_this.validate())
				{
					alert("Algunos de los datos introducidos en el formulario no son válidos:\n" + _this.validator.errors.join("\n"));
					return false;
				}
			});
		},
		
		
		validate : function()
		{
			// referencia a formContacto, pq des de dins dels objectes $ this ja no fa referencia a formContacto
			var _this = this;
			
			// reseteig validador
			_this.validator.init();
			_this.returnVal = true;
			
			// camps obligatoris
			$.each($("#fNombre, #fTelefono, #fEmail"), function(i, n)
			{
				_this.validator.checkRequired($(n));
			});
			
			_this.validator.checkNumeric($("#fTelefono"));   
			
			if($("#fEmail").val() != $("#fEmail").attr("rel"))
			{
				_this.validator.checkValidMail($("#fEmail"));
			}
			
			if(!_this.validator.returnVal){	_this.returnVal = false; }
			
			for(var i = 0; i<_this.validator.erroneousFields.length; i++)
			{
				_this.validator.erroneousFields[i].addClass("error");
			}
			
			return _this.returnVal;
		}
	};
	
	formContacto.init();
	
	
	
	
	/**
	 * 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 )
	{
		$("label[for$='ubmit']").css("display", "none");
		$("#contents p + h2").addClass("folliwingP");
		
		if($.browser.version < 8)
		{
			$("#siteNav li strong").each(function(i)
			{
				$(this).prepend("<span class='before'>0" + (i+1) + "</span>");
			});
			
			$("#project-info #info dd").each(function(i)
			{
				$(this).after("<span class='clear'></span>");
			});
			
			$("#copyright address, #copyright address span").each(function(i)
			{
				$(this).before("<span class='before'> | </span>");
			});
			
			$("#legalInfo li:not(:last)").each(function(i)
			{
				$(this).append("<span class='after'> | </span>");
			});
		}
	}
	
	if( $.browser.mozilla )
	{
		$("#banners-home p").css("line-height", "1.3em");
		$("body.aviso-legal #contents ol").css("list-style-position", "outside");
	}
	
	
	/**
	 * el disseny utilitza Arial Narrow que no es una font segura per a web...
	 * així que é necessari ajustar la mida del text en cas que l'usuari no tingui la font
	 */
	fontDetector = new Detector();
	
	if( !fontDetector.test("arial narrow")[3] )
	{
		$("#siteNav li strong a").css("font-size", "1.6em");
	}
	
});