/** 
 * @projectDescription Frame Factory main script file
 *
 * @author 	Sébastien Dussaut sebastien.dussaut@mediagong.tv
 * @version 	0.1 
 */


// Global variables
var skin = "";			// for skin persisting features. Takes two values: "day" or "night". Filled by php.
var errors = new Array();
var ErrorMsgArray = {
	"job":"error job",
	"name":"error name",
	"firstname":"error firstname",
	"company":"error company",
	"birth":"error birth",
	"phone":"error phone",
	"email":"error email",
	"url":"error url",
	"availability":"error availability",
	"letter":"error letter",
	"cv":"error cv",
	"portfolio":"error portfolio",
	"message":"error message",
	"generic":"Merci de vérifier les champs en rouge."
};
var navStatus = "";

/**
 * @classDescription Frame Factory main Javascript Class
 */
var FrameFactory = {
	alterForm: function(){
		
		
		var Actions = {
			init: function(){
				
				// sets initial states for inputs to alter
				jQuery("select").hide()
								//.find("option:first").attr("selected", "selected");
				jQuery("input[type=file]").addClass("file")
										  .val("");
				
				// creating elements needed
				jQuery("#fAvailability label").after("<span />");
				jQuery(".message p").append("<span class=\"addFile\"></span><span>Votre fichier <strong></strong></span>");
				
			},
			manageInputs: function(){
				
				jQuery("input[type=file]").bind("change", function(){
					var fileValue = jQuery(this).val();
					
					// IE trick for normalizing file url
					if(jQuery.support.hrefNormalized == false) {
						// variables
						var str = "\\";
						var temp = fileValue.lastIndexOf(str);
						
						fileValue = fileValue.substr(temp).split("\\")[1];
												
					}
					// end IE trick
					jQuery(this).nextAll("span").find("strong").html("&laquo;&nbsp;"+ fileValue +"&nbsp;&raquo");
				});
				
			},
			manageSelect: function(){
				
				jQuery("#fAvailability").find("select").after("<a href=\"#availabilityBlock\" class=\"btAvailability\"><span>Options</span></a>").end()
									   .after("<ul></ul>");
				//jQuery("#fAvailability label").css("width", "230px");
				
				// converting options to li
				var listItems = ""; 
				var optionsItems = jQuery("#fAvailability option");
				
				// creating items
				for(var i=0; i < optionsItems.length; i++) {
					if(optionsItems[i].value != "") {
						listItems += "<li class=\"avail"+ optionsItems[i].value +"\"><a href=\"#\" rel=\""+ optionsItems[i].value +"\"><span>"+ optionsItems[i].innerHTML +"</span></a></li>";	
					}
				}
				
				// appending items
				jQuery("#fAvailability").next().attr("id", "availabilityBlock")
											  .append(listItems);
				
				// binding open/close button
				jQuery(".btAvailability").bind("click", function(event){
					
					// prevents default behaviour
					event.preventDefault();
					
					jQuery(this.hash).stop(true,true).slideToggle(350);
					
					// removes focus
					jQuery(this).blur();
				});
				
				// binding list items
				jQuery("#availabilityBlock a").bind("click", function(event){
					
					var linkValue = jQuery(this).attr("rel");
					
					// prevents default behaviour
					event.preventDefault();
					
					// change select state
					jQuery("#fAvailability option[value="+ linkValue +"]").attr("selected", "selected");
					jQuery("#fAvailability label + span").text(jQuery(this).text());
					
					// closing menu
					jQuery(".btAvailability").triggerHandler("click");
					
					// removes focus
					jQuery(this).blur();
				});
			}
		}	
		
		// init (hides and create needed DOM elements, resets inputs)
		Actions.init();
		
		// manage select and file inputs
		Actions.manageSelect();
		Actions.manageInputs();
		
	},
	/**
	 * Altering navigation to show current categorie
	 * @method
	 * @param {Object}	link	jQuery object containing carousel clicked link (inherited)
	 */
	alterNavigation: function(link){
		
		// disabling navigation
		FrameFactory.disableNav();
		
		// set marker on main nav link (preventing imageView close button to toggle weird behaviours)
		jQuery("h1 a").addClass("altered");
		
		// gets carousel opened items
		var toggledItems = jQuery(".carousel li:visible");
		
		// getting elements
		var category = jQuery(link).prevAll("h3").clone();
		var menuItems = jQuery(link).parents("li").siblings(":visible");
		var carousel = jQuery(link).parents(".carousel");
		
		jQuery(link).parents("li").addClass("current");
		jQuery(menuItems).fadeOut(350);
		jQuery(carousel).fadeOut(350, function(){
			jQuery(category).insertBefore(jQuery(this)).fadeIn(350);
		});
		
		// altering nav main link
		jQuery("h1 a").bind("mouseenter", function(event){
			
			// preventing anchors default behaviour
			event.preventDefault();
			jQuery(link).parents("li:eq(1)").removeClass("active current")
											.find("h2").siblings("h3").fadeOut(350, function(){
												jQuery(this).remove();
												
												// shows overlay
												//FrameFactory.showOverlay(1, 350);
												
												// shows navigation
												jQuery(jQuery(menuItems), jQuery(carousel)).fadeIn(350);
												
												// reseting carousel
												jQuery(".carousel li").hide();
												jQuery(toggledItems).show();
												
												// sets default behaviour for navigation links
												FrameFactory.toggleItem(jQuery("#navigation h2 .subMenu"),650);
												
												// reopens submenu
												jQuery(carousel).prev().find("a").triggerHandler("click");
												
												// hides news block
												jQuery("#news").hide();
											});
			// removing focus
			jQuery(this).blur();
			
			// resets main nav link to default
			jQuery(this).unbind("click").removeClass("altered");
			//FrameFactory.toggleItem(jQuery(this),650);
		});
	},
	/**
	 * Building images sets
	 * @method
	 * @param {Object}	obj		jQuery object composed of pictures
	 * @param {Object}	link	jQuery object containing carousel clicked link (inherited)
	 */
	buildImageSet: function(obj, link){
		/**
		 * @classDescription Image set manipulation class
		 */
		var ImageSet = {
			/**
			 * Build new image set and make first item visible
			 * @param {Object}	obj		jQuery object composed of pictures
			 * @param {Object}	link	jQuery object containing carousel clicked link (inherited)
			 * @method
			 */
			build: function(obj, link){
				// appending new items
				/*for(var i = 0; i < obj.length; i++) {
					jQuery("#imageViewer").append(obj[i]);
				}*/
				jQuery(obj).appendTo("body");
				
				
				// launching product area
				//FrameFactory.initProductArea();
				
				// Alter nav and make first item visible
				/*jQuery("#imageViewer img:eq(0)").fadeIn(400, function(){
					//jQuery("h1 a").triggerHandler("click");
					FrameFactory.alterNavigation(link);
					jQuery("#imageViewer > a").fadeIn(1000);
				});*/
				jQuery("#gallery a").lightBox({
					overlayOpacity: 0.6,
					imageLoading: 'img/css/loading.gif',
					imageBtnClose: 'img/css/close.gif',
					imageBtnPrev: 'img/css/prev.png',
					imageBtnNext: 'img/css/next.png',
					imageBlank: 'img/css/blank.gif',
					fixedNavigation:true,
					//containerBorderSize:0,
					containerResizeSpeed: 350,
					txtImage: 'Image',
					txtOf: 'sur'
				});
				jQuery("#gallery a:first").triggerHandler("click");

			},
			/**
			 * Cleans previous images set
			 * @method
			 */
			clean: function(){
				jQuery("#gallery").remove();
			}
		}
		
		// cleaning previous images set
		if (jQuery("#gallery").length) {
			//jQuery("#imageViewer > a").fadeOut(400);
			/*jQuery("#imageViewer").find("img:visible").fadeOut(400, function(){
				
				// cleaning previous set
				ImageSet.clean();
				// appending new images set from ajax request
				ImageSet.build(obj, link);
			});*/
			// cleaning previous set
			ImageSet.clean();
			// appending new images set from ajax request
			ImageSet.build(obj, link);
		} else {
			// appending new images set from ajax request
			ImageSet.build(obj, link);
		}
	},
	/**
	 * Building the product area
	 * @method
	 * @param {Object}	obj		jQuery collection
	 */
	buildProductArea: function(obj){
		
		// creating image container
		//jQuery("#main").append("<div id=\"imageViewer\"><a class=\"close\" href=\"#\"><span>Fermer</span></a><a href=\"#\" class=\"prev\"><span>Image précédente</span></a><a href=\"#\" class=\"next\"><span>Image suivante</span></a><div id=\"overlay\"></div></div>");
		for (var i = 0; i < obj.length; i++) {
			jQuery(obj[i]).bind("click", function(){
				
				// getting images
				FrameFactory.getImages(jQuery(this).find("a"));
				
				// reseting viewer state
				//jQuery("#imageViewer .prev").addClass("disabled");
				//jQuery("#imageViewer .next").removeClass("disabled");
				// removing focus
				//jQuery(this).find("a").blur();
				// disabling anchors
				return false;
			});
		}
		
		//var currentPict;
		/**
		 * @classDescription Image viewer controllers actions class
		 */
		//var ImageViewerControllers = {
			/**
			 * Hiding current image and showing previous one
			 * @method
			 * @param {Object}	obj		jQuery object (clicked link)
			 */
			/*goBackward: function(obj){		
				
				// gets current visible image
				currentPict = jQuery(obj).parent().find("img:visible");
				
				
				// removes disable state for next pic link
				jQuery("#imageViewer .next").removeClass("disabled");
				
				if (jQuery("#imageViewer img").index(currentPict) > 0) {
					jQuery(currentPict).prev().css("z-index", "2")
									   .fadeIn(350, function(){
											jQuery(currentPict).hide()
															   .prev().css("z-index", "1");
											if (jQuery("#imageViewer img").index(jQuery(currentPict).prev()) == 0) {
												jQuery(obj).addClass("disabled");
											}
									   });
				}
				
				// removing focus
				jQuery(obj).blur();
				
			},*/
			/**
			 * Hiding current image and showing next one
			 * @method
			 * @param {Object}	obj		jQuery object (clicked link)
			 */
			/*goForward: function(obj){		
				
				// gets current visible image
				currentPict = jQuery(obj).parent().find("img:visible");
				
				// removes disable state for next pic link
				jQuery("#imageViewer .prev").removeClass("disabled");
				
				jQuery(currentPict).next().css("z-index", "2")
								   .fadeIn(350, function(){
										jQuery(currentPict).hide()
								   						   .next().css("z-index", "1");
										if (jQuery("#imageViewer img").index(jQuery(currentPict).next()) == jQuery("#imageViewer img").length-1) {
											jQuery(obj).addClass("disabled");
										}
								   });
								   
				// removing focus
				jQuery(obj).blur();
			},*/
			/**
			 * Closing Image viewer
			 * @method
			 */
			/*close: function(){
				jQuery("#imageViewer > a").fadeOut(250);
				jQuery("#imageViewer").find("img").fadeOut(400, function(){
					jQuery(this).remove();
					jQuery("h1 a.altered").trigger("click");
				});
				// removing focus
				//jQuery(obj).blur();
			}
		}
		jQuery("#imageViewer a").bind("click", function(event){
			
			// preventing anchors default behaviour
			event.preventDefault();
			
			var elmtClass = jQuery(this).attr("class").split(" ")[0];
			switch (elmtClass) {
				case "prev":
					ImageViewerControllers.goBackward(jQuery(this));
					break;
				case "next":
					ImageViewerControllers.goForward(jQuery(this));
					break;
				case "close":
					ImageViewerControllers.close();
					break;
			}
			
		});*/
		
		
	},
	/**
	 * Creates skin controls
	 * @method
	 */
	createControls: function(){
		jQuery("#main").append("<ul id=\"skins\"><li id=\"day\"><a href=\"#\" rel=\"day\"><span>Jour</span></a></li><li id=\"night\"><a href=\"#\" rel=\"night\"><span>Nuit</span></a></li></ul>");
	},
	/**
	 * Debug function
	 * Prints out debug trace
	 * @method
	 * @param {String, Object}	obj		String or Object to print out
	 */
	debug: function(obj){
		jQuery("#debugBox").append("<p>" + obj + "</p>");
	},
	/**
	 * Disables navigation default behaviour
	 * @method
	 */
	disableNav: function(){
		jQuery("h1 a, #navigation h2 .subMenu").unbind("click");		
	},
	getClick: function(obj){
		// targeting IE only
		if (!jQuery.support.hrefNormalized) {
			jQuery("#"+obj).parent().triggerHandler("click");
		}		
	},
	/**
	 * Function to get asynchronously corresponding images
	 * @method
	 * @param {Object}	link	jQuery object containing carousel clicked link
	 */
	getImages: function(link){
		
		var link = link;
		var pictures;
		
		jQuery.ajax({
			type: "GET",
			url: jQuery(link).attr("href"),
			error: function(XMLHttpRequest, textStatus, errorThrown){},
			success: function(data, textStatus){},
			dataFilter: function(data){
				pictures = jQuery(data).find("#gallery");
			},
			complete: function(XMLHttpRequest, textStatus){
				FrameFactory.buildImageSet(pictures, link);
			}
		});
	},
	/**
	 * Gets user's viewport width and height
	 * @method
	 */
	getViewportDim: function(){
		
		// dimension array : width/height
		var dimensions = [];
		dimensions.push(jQuery("html").outerWidth());
		dimensions.push(jQuery("html").outerHeight());
		
		return dimensions;
	},
	/**
	 * Initialization of FrameFactory class
	 * All calls of other methods go in there
	 * @method
	 */
	init: function(){
		
		// inits navigation
		FrameFactory.toggleNav();
		// sets up carousel
		FrameFactory.initCarousel(650);
		// sets up news block
		FrameFactory.initNews(["#4D4D4D","#999"],["#666","#999"],["#808080","#fff"],["#787878","#333"],["#787878","#333"],["#333","#010101"],800);
		// skins
		FrameFactory.createControls();		
		jQuery("#skins a").bind("click", function(event){
			
			// preventing default behaviour
			event.preventDefault();
			FrameFactory.toggleSkin(jQuery(this).attr("rel"));
		});
		FrameFactory.setSkin("7","19");
		
		// misc stuff
		//jQuery("#overlay").css("opacity", "0");
		//jQuery(".carousel h3").hide();
		//jQuery(".subMenu").parent().next().hide();
		jQuery(".carousel ul").css("overflow", "hidden").css("visibility", "hidden");
		
	},
	/**
	 * Method for settling carousel for sub menu items
	 * @method
	 * @param {Object}	obj			jQuery collection of DOM elements
	 * @param {Number}	speed		Speed value (a milliseconds value)
	 */
	initCarousel: function(speed){
		
		// building links
		jQuery(".carousel > div").prepend("<a href=\"#\" class=\"prev\"><span>Précédent</span></a><a href=\"#\" class=\"back\">Aller au premier élément</a>");
		jQuery(".carousel > div").append("<a href=\"#\" class=\"next\"><span>Suivant</span></a>");
		
		
		// reseting link states
		jQuery(".carousel .prev").addClass("disabled");
		jQuery(".carousel .next").removeClass("disabled");
		
		
		// hiding unwanted items
		jQuery(".carousel li:nth-child(3)").nextAll().hide();

		// variables
		var currentItem;
		var carouselItems = jQuery(".carousel li");
		
		
		/**
		 * @classDescription Carousel set up class
		 */
		var Carousel = {
			
			/**
			 * Hiding current set of images and showing previous one
			 * @method
			 * @param {Object}	obj		jQuery object (clicked link)
			 */
			goBackward: function(obj){
				
				// current first visible item
				currentItem = jQuery(".carousel li:visible:first");
				
				// removes disable state for next pic set link
				jQuery(".carousel .next").removeClass("disabled");
				

				if (jQuery(carouselItems).index(jQuery(currentItem)) > 0) {
					
					// selects the three previous items
					var prevItems = jQuery(currentItem).prevAll().slice(0,3);
					// marks currentItem
					jQuery(currentItem).addClass("first");
					
					// moves from actual items to previous items
					jQuery(".carousel li:visible").fadeOut(speed, function(){
						if (jQuery(this).is(".first")) {
							jQuery(prevItems).fadeIn(speed);
							jQuery(this).removeClass("first");
						}
					});
					
					
					if (jQuery(".carousel li").index(jQuery(currentItem).prevAll(":first")) == 2) { // last item from first set
						jQuery(obj).addClass("disabled");
					}
				}
				
			},
			/**
			 * Hiding current set of images and showing previous one
			 * @method
			 * @param {Object}	obj		jQuery object (clicked link)
			 */
			goForward: function(obj){
				
				// current last visible item
				currentItem = jQuery(".carousel li:visible:last");
				
				// removes disable state for previous pic set link
				jQuery(".carousel .prev").removeClass("disabled");

				if (jQuery(carouselItems).index(jQuery(currentItem)) < carouselItems.length-1) {
					
					// selects the three next items
					var nextItems = jQuery(currentItem).nextAll().slice(0,3);
					// marks currentItem
					jQuery(currentItem).addClass("last");
					
					// moves from actual items to next items
					jQuery(".carousel li:visible").fadeOut(speed, function(){
						if (jQuery(this).is(".last")) {
							jQuery(nextItems).fadeIn(speed);
							jQuery(this).removeClass("last");
						}
					});
					
					if (jQuery(carouselItems).index(jQuery(currentItem).next()) == carouselItems.length-1) {
						jQuery(obj).addClass("disabled");
					}
				}
			}
		}
		
		jQuery(".carousel .prev, .carousel .next").bind("click", function(event){
			
			// preventing anchors default behaviour
			event.preventDefault();
			
			var elmtClass = jQuery(this).attr("class").split(" ")[0];
			switch (elmtClass) {
				case "prev":
					Carousel.goBackward(jQuery(this));
					break;
				case "next":
					Carousel.goForward(jQuery(this));
					break;
			}
			
			// removing focus
			jQuery(this).blur();
		});
		
		
		
	},
	/**
	 * Triggers hover effect on news block
	 * @method
	 * @param {Array}			nTextColor	Night styles : text color - [colorfrom,colorTo]
	 * @param {Array}			nLinkColor	Night styles : link color - [colorfrom,colorTo]
	 * @param {Array}			nDateColor	Night styles : date color - [colorfrom,colorTo]
	 * @param {Array}			dTextColor	Day styles : text color - [colorfrom,colorTo]
	 * @param {Array}			dLinkColor	Day styles : link color - [colorfrom,colorTo]
	 * @param {Array}			dDateColor	Day styles : date color - [colorfrom,colorTo]
	 * @param {Number, String}	speed		Speed value (can be either a milliseconds value or one of jQuery speed values : "slow", "normal", "fast"). 
	 */	
	initNews: function(nTextColor,nLinkColor,nDateColor,dTextColor,dLinkColor,dDateColor,speed){
		
		jQuery("#news li").bind("mouseenter", function(){
			switch(jQuery("#main").attr("class")) {
				case "night":
					jQuery(this).stop(true, true).animate({color: nTextColor[1]}, speed)
								.find("a").stop(true, true).animate({color: nLinkColor[1]}, speed).end()
								.find("strong > span").stop(true, true).animate({color: nDateColor[1]}, speed);
					break;
				case "day":
					jQuery(this).stop(true, true).animate({color: dTextColor[1]}, speed)
								.find("a").stop(true, true).animate({color: dLinkColor[1]}, speed).end()
								.find("strong > span").stop(true, true).animate({color: dDateColor[1]}, speed);
					break;
			}			
		});
		jQuery("#news li").bind("mouseleave", function(){
			switch(jQuery("#main").attr("class")) {
				case "night":
					jQuery(this).stop(true, true).animate({color: nTextColor[0]}, speed)
								.find("a").stop(true, true).animate({color: nLinkColor[0]}, speed).end()
								.find("strong > span").stop(true, true).animate({color: nDateColor[0]}, speed);
					break;
				case "day":
					jQuery(this).stop(true, true).animate({color: dTextColor[0]}, speed)
								.find("a").stop(true, true).animate({color: dLinkColor[0]}, speed).end()
								.find("strong > span").stop(true, true).animate({color: dDateColor[0]}, speed);
					break;
			}
		});
	},
	/**
	 * Method for setting up product area
	 * @method
	 */
	initProductArea: function(){
		// gets viewport dimensions
		var viewportDim = FrameFactory.getViewportDim();
		
		// inits needed CSS properties
		jQuery("html, #imageViewer").css({ // html is for IE to behave like every other browser
			overflow: "hidden"
		});
		
		/**
		 * @classDescription Size manipulation class
		 */
		var HandleResize = {
			/**
			 * Handle pictures container resizing
			 * @method
			 */
			resizeContainer: function(){
				jQuery("#main, #imageViewer").css({
					width: viewportDim[0],
					height: viewportDim[1]
				});
			},
			/**
			 * Handle pictures resizing
			 * @method
			 */
			resizePicture: function(){
				jQuery("#imageViewer img").css("width",viewportDim[0]);
			}
		}
		
		
		// resizes image container and picture
		HandleResize.resizeContainer();
		HandleResize.resizePicture();
		
		// triggers dynamic resizing
		jQuery(window).bind("resize", function(){
			
			// viewport values before resizing
			var origWidth = viewportDim[0];
			var origHeight = viewportDim[1];
			
			viewportDim = FrameFactory.getViewportDim();
			
			// test for IE that fires the resize event multiple times (grr)
			if (origWidth != viewportDim[0] || origHeight != viewportDim[1]) {
					// resizes image container and picture
					HandleResize.resizeContainer();
					HandleResize.resizePicture();
			}
			
		});
	},
	/**
	 * Replace font with custom embed font
	 * @method
	 * @param {String}		obj		jQuery-like CSS selector for items to be replaced
	 * @param {String}		font	Name of the font (font file).
	 */
	replaceFont: function(obj, font){
		Cufon.replace(obj, { fontFamily: font });
	},
	/**
	 * Sets general skin
	 * @method
	 * @param {String}		start		Day start (hour). Ex: "7" for seven o'clock.
	 * @param {String}		end			Day end (hour). Ex: "24" for midnight or "22" for 10pm.
	 */
	setSkin: function(start, end){
		
		if (skin == "") {
			var now = new Date();
			var hours = now.getHours();
			
			if (hours >= start && hours < end) {
				FrameFactory.toggleSkin("day");
			} else {
				FrameFactory.toggleSkin("night");
			}
		} else {
			FrameFactory.toggleSkin(skin);
		}
		
		
		
	},
	/**
	 * Toggles overlay
	 * @method
	 * @param {Number}			opacity		Velue between 0 and 1.
	 * @param {Number, String}	speed		Speed value (can be either a milliseconds value or one of jQuery speed values : "slow", "normal", "fast").
	 */
	showOverlay: function(opacity, speed){
		jQuery("#overlay").show()
						  .animate({
						  	opacity: opacity
						  }, speed);
	},
	/**
	 * Method for activating nav behaviours (open/close)
	 * Concerns main nav effect and nav items.
	 * @method
	 * @param {Object}			obj			jQuery collection of DOM elements
	 * @param {Number, String}	speed		Speed value (can be either a milliseconds value or one of jQuery speed values : "slow", "normal", "fast").
	 */
	toggleItem: function(obj, speed){
		
		/**
		 * @classDescription News block manipulation
		 */
		var News = {
			/**
			 * Hides news block by fade
			 * @method
			 * @param {Number, String}	speed		Speed value (can be either a milliseconds value or one of jQuery speed values : "slow", "normal", "fast").
			 */
			hide: function(speed){
				jQuery("html").css("overflow","hidden");
				jQuery("#news").fadeOut(speed, function(){
					jQuery("html").css("overflow","auto");
				});
			},
			/**
			 * Shows news block by fade
			 * @method
			 * @param {Number, String}	speed		Speed value (can be either a milliseconds value or one of jQuery speed values : "slow", "normal", "fast").
			 */
			show: function(speed){
				jQuery("html").css("overflow","hidden");
				jQuery("#news").fadeIn(speed, function(){
					jQuery("html").css("overflow","auto");
				});
			}
		}
		var carouselStatus = "hidden";
		
		for (var i = 0; i < obj.length; i++) {
		
			jQuery(obj[i]).bind("click", function(event){
			
				//prevents default behaviour
				event.preventDefault();
				
				// hides other opened menu items
				jQuery(this.hash).parents("li").siblings("li.active").find("h2 a").triggerHandler("click");
				

				// toggling news block				
				/*if (jQuery("#news").is(":hidden") && jQuery(this).attr("href").split("#")[1] == "navigation") {
					News.show(450);
				}
					
				if (jQuery(this).is(".subMenu") && jQuery("#news").is(":visible")) {
					News.hide(750);	
				}
				if (jQuery(this).is(".subMenu") && jQuery("#news").is(":hidden")) {
					News.show(450);
				}*/
								
				var clickedLink = jQuery(this);
				
				//resets all menu carousels
				//jQuery(".carousel .back").trigger("click");
				
				// toggling active class
				if (jQuery(this).parents("li").is(".active")) {
					jQuery(this).parents("li").removeClass("active");
				} else {
					jQuery(this).parents("li").addClass("active");
				}
				
				
				// enables effect
				jQuery(this.hash).stop(true, true).slideToggle(speed, function(){
					
					
					/* little trick for IE, to remove hasLayout (ghost) bug in carousel */
					if (!jQuery.support.hrefNormalized) { // to target IE only
						jQuery("#navigation:hidden > li.active").find(".carousel div").addClass("appear");
						jQuery("#navigation:hidden > li.active").find(".carousel div").removeClass("appear");
						jQuery("#navigation:hidden > li.active").find(".carousel .prev").addClass("appear");
						jQuery("#navigation:hidden > li.active").find(".carousel .prev").removeClass("appear");
					}
					/* end trick */
					jQuery("#navigation:hidden > li.active").removeClass("active")
															.find("h2").nextAll("div").hide();
					
					if (carouselStatus == "hidden") {
						jQuery(".carousel ul").css("visibility", "visible");
						carouselStatus = "visible";
					} else {
						jQuery(".carousel ul").css("visibility", "hidden");
						carouselStatus = "hidden";
					}
					
															
				});
				
				// removing focus
				jQuery(this).blur();
			});
		}
	},
	toggleJobList: function() {
		//jQuery("#content dl, #content #centre .apply").hide();
		jQuery("#content h5").css("cursor", "pointer");
		FrameFactory.toggleScroll();
		jQuery("#content h5").bind("click", function(){
			jQuery(this).toggleClass("active");
			jQuery(this).siblings(".active").removeClass("active")
									   		.next(".description").slideUp(350);
											//.nextAll(":eq(0),:eq(1)").slideUp(350);
			
			//jQuery(this).nextAll(":eq(0),:eq(1)").stop(true,true).slideToggle(350, function(){
			jQuery(this).next(".description").stop(true,true).slideToggle(350, function(){
				FrameFactory.toggleScroll();
			});
			Cufon.refresh("#content h5");
		});
	},
	/**
	 * Nav settlement
	 * @method
	 */
	toggleNav: function(){
		
		// hides nav to prevent flicker
		jQuery("#navigation").hide();
		
		/**
		 * @classDescription Navigation management between pages
		 */
		var Navigation = {
			/**
			 * Bind events to restore default navigation status
			 * @method
			 * @param	obj		jQuery collection : current nav list item
			 */
			rebuildNav: function(obj){
				jQuery("#navContainer").bind("mouseenter", function(event){
					
					// preventing default behaviour
					//event.preventDefault();
					
					if (navStatus != "open") {
					
						jQuery("#navigation").fadeOut(350, function(){
							// restores main nav items
							jQuery("#navContainer > ul > li").removeClass("active current disappear").hide().slice(0, 4).show();
							
							// shows navigation
							jQuery("#navigation").fadeIn(350);
						});
					navStatus = "open";	
					//jQuery(this).blur();
					return false;
					}
				});
				jQuery("#navContainer").bind("mouseleave", function(event){
					navStatus = "";
					jQuery("#navigation").fadeOut(350, function(){
						Navigation.triggerItem(obj);	
					});
					return false;
				});
			},
			/**
			 * Bind nav default behaviours
			 * @method
			 */
			setDefault: function(){
				// restores default behaviours
				FrameFactory.toggleItem(jQuery("#navigation h2 .subMenu"),650);
				FrameFactory.buildProductArea(jQuery(".carousel li"));
				
				// shows navigation
				jQuery("#navigation").fadeIn(350);
			},
			/**
			 * Nav for intro page
			 * @method
			 */
			setIntro: function(){
				// hiding stuff
				//jQuery("h1, #footer").hide();
				
				// shows logo and footer
				jQuery("h1, #footer").fadeIn(1500);
			},
			/**
			 * Generic nav active menu
			 * @method
			 * @param	obj		jQuery collection : current nav list item
			 */
			triggerItem: function(obj){
				jQuery(obj).siblings().addClass("disappear").end()
						   .show()
						   .addClass("active current");
				jQuery("#navigation").fadeIn(750);
			}
		}
		
		
		
		// variables
		var myUrl = document.location.href;		
		var temp = myUrl.lastIndexOf("/");
		myUrl = myUrl.substr(temp+1).split(".")[0];
		
		if (myUrl.length) {
		
			// gets nav configuration
			jQuery.getJSON("./pageStatus.php", function(data, textStatus){
				myUrl = eval("data." + myUrl);
				
				// defines differents action for different page
				switch (myUrl) {
					case "intro":
						Navigation.setIntro();
						break;
					case "index":
						// default behaviour
						jQuery("#navigation").fadeIn(350);
						break;
					case "about":
						// show current item
						Navigation.triggerItem(jQuery("#approche"));
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#approche"));
						break;
					case "references":
						// default behaviour
						Navigation.setDefault();
						
						// opens carousel if coming from an other page				
						if (document.location.href.split("#")[1] == "referenceContent") {
							jQuery("#references .subMenu").triggerHandler("click");
						}
						break;
					case "recruitment":
						// show current item
						Navigation.triggerItem(jQuery("#recrutement"));
						
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						
						// toggles scroll
						FrameFactory.toggleScroll();
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#recrutement"));
						
						// inits job list behaviour
						FrameFactory.toggleJobList();
						jQuery("#content h5:first").triggerHandler("click");
						
						break;
					case "recruitmentForm":
						// show current item
						Navigation.triggerItem(jQuery("#recrutement"));
						
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#recrutement"));
						
						// inits form modification
						FrameFactory.alterForm();
						
						// inits form validation
						ManageForm.init();
						
						break;
					case "recruitmentConfirm":
						// show current item
						Navigation.triggerItem(jQuery("#recrutement"));
						
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#recrutement"));
						
						break;
					case "contact":
						// show current item
						Navigation.triggerItem(jQuery("#contact"));
						
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#contact"));
						
						// inits form validation
						ManageForm.init();
						
						break;
					case "legal":
						// show current item
						Navigation.triggerItem(jQuery("#mentions"));
						
						// replaces fonts
						FrameFactory.replaceFont("#content h5", "HelveticaNeueBlkCn");
						//FrameFactory.replaceFont("#left a", "HelveticaNeueLTStd-MdCn");
						
						// toggles scroll
						FrameFactory.toggleScroll();
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#mentions"));
						break;
					case "siteMap":
						// show current item
						Navigation.triggerItem(jQuery("#planSite"));
						
						// restores default nav
						Navigation.rebuildNav(jQuery("#planSite"));
						break;
				}
			});
			
		// myUrl is empty
		// applying default
		} else {
			Navigation.setIntro();
		}
	},
	/**
	 * Inits scroll bar theming
	 * @method
	 */
	toggleScroll: function(){
		jQuery("#centre").css("padding-left", "20px");
		jQuery(".jscrollpane").css({
			paddingLeft: "40px",
			paddingRight: "25px"
		})
							  .jScrollPane({
							  	dragMinHeight:40,
								dragMaxHeight:40,
								scrollbarWidth:12
							  });
	},
	/**
	 * Binds skin controls
	 * @method
	 * @param	{String}	obj		Skin string
	 */
	toggleSkin: function(obj){
		// posting skin value to webservice
		// for persisting feature between pages
		jQuery.post("skin.php", { skinValue: obj });
		
		jQuery("link[title]").attr("disabled", "disabled");
		jQuery("link[title="+ obj +"]").attr("disabled", "");
		jQuery("#main").attr("class",obj);
		FrameFactory.replaceFont("h5", "HelveticaNeueBlkCn");
	}
};


/**
 * @classDescription Frame Factory form validation Javascript Class
 */
var ManageForm = {
	/**
	 * Sets up form validation
	 * @method
	 */
	init: function(){
		
		// variables
		var fields;
		var formStatus;
		var errorStatus;
		
		if (jQuery("#availability option:selected").length) {
			ManageForm.toggleAvailability();
		}
		
		
		jQuery("input[type=submit]").each(function(){
			
			jQuery(this).bind("click", function(event){
				
				// resets states
				errors = [];
				jQuery(".errors ul").empty();
				
				// prevents default behaviour
				event.preventDefault();
				
				fields = jQuery(this).parents("form").find(".mandatory :input");
				
				for(var i = 0; i < fields.length; i++) {
					errorStatus = ManageForm.checkInput(fields[i]);
				}
				
				formStatus = jQuery.grep(errorStatus, function(n,i){
					return n == true;
				});
				
				if(formStatus.length < 1) {
					jQuery(this).parents("form").submit();
				}
			});
		});		
	},
	/**
	 * Method for checking input (input, select, etc) value.
	 * @method
	 * @param	{Object}	jQuery collection: input to be checked
	 * @return	{Array}		Returns "errors" array (boolean values).
	 */
	checkInput: function(obj){
		
		switch(obj.nodeName.toLowerCase()) {
			
			case "select":
				if (jQuery(obj).find("option:selected").val() != "") {
					ManageForm.removeError(obj);
					errors.push(false);
				} else {
					errors.push(true);
					ManageForm.setError(obj);
				}
				break;
			default:
				if (obj.value != "") {
					
					switch(obj.id) {
						case "email":
							// mail check regular expression
							var regexp = new RegExp(/^([a-zA-Z0-9]+(([\.\-\_]?[a-zA-Z0-9]+)+)?)\@(([a-zA-Z0-9]+[\.\-\_])+[a-zA-Z]{2,4})$/);
							
							if (!jQuery(obj).val().match(regexp)) {
								errors.push(true);
								ManageForm.setError(obj);
							} else {
								ManageForm.removeError(obj);
								errors.push(false);
							}
							break;
						default:
							ManageForm.removeError(obj);
							errors.push(false);
							break;
					}				
				} else {
					errors.push(true);
					ManageForm.setError(obj);
				}
				break;	
		}
		return errors;
	},
	/**
	 * Sets error status: displays error message and add error class.
	 * @method
	 * @param	{Object}	jQuery collection: input checked.
	 */
	setError: function(obj) {
		
		//var errorMsg = eval("ErrorMsgArray."+obj.id);
		var errorMsg = ErrorMsgArray.generic;
		
		
		switch(jQuery(obj).attr("type").toLowerCase()) {
			
			case "file":
				jQuery(obj).siblings("label").addClass("error");			
				break;
			default:
				jQuery(obj).parent().addClass("error");
				break;	
		}
		if(!jQuery(".errors").length) {
			jQuery(obj).parents("form").append("<fieldset class=\"errors\"><ul /></fieldset>");
		}
		jQuery(".errors ul").html("<li>" + errorMsg + "</li>");
	},
	/**
	 * Removes error status.
	 * @method
	 * @param	{Object}	jQuery collection: input checked.
	 */
	removeError: function(obj) {
		jQuery(obj).parent().children().andSelf().removeClass("error");
	},
	/**
	 * Toggle selected availability when error from server
	 * @method
	 */
	toggleAvailability: function(){
		jQuery("#fAvailability > span").html(jQuery("#availability option:selected").text());
	}
}



/* launching scripts */

jQuery(document).ready(function(){
	FrameFactory.init();
	//FrameFactory.getClick("references");
});
