﻿_spBodyOnLoadFunctionNames.push("InitMap");//SP version
function InitMap() {
	if($('#dealer_map').is('div')){gMap.init();}
	
};

/* 
window.onload = function(){//static version
	if($('#dealer_map').is('div')){gMap.init()}
};
 */

//var fiat_respath = 'http://prod2.fiat.it/Resources/';//sharepoint ambienti
//var SPpath = '/Resources/';//useless: printed in page as fiat_respath

$(document).ready(function(){
	//$(function() {
		//$.ajaxSetup ({ cache:false });//disable clientside caching (useful for IE8)
	//});

	/* $('a.ajax_test').click(function(){
		$.ajax({
			type: 'GET',
			//url: gMap.ajaxParam.URL,
			//url: 'http://dealerlocator.fiat.com/geocall/PublicServlet',
			//url: 'http://testdealerlocator.fiat.com/geocalltest/AjaxServlet',
			url: 'http://sitetest.svil.domino.it/transport.php?action=dealerlocator.fiat.com/geocall/PublicServlet?method=get&mkt=1000&brand=00&dlr=1&rad=5&func=finddealerxml&address=milano',
			//contentType: 'text/xml',
			contentType: 'text/html; charset=iso-8859-1',
			dataType: 'xml',//The type of data that you're expecting back from the server
			//data: 'func=finddealerxml&brand=00&mkt='+gMap.ajaxParam.market+'&address='+gMap.ajaxParam.address+'&dlr='+gMap.ajaxParam.dealer,
			//data: 'mkt=1000&brand=00&dlr=1&rad=5&func=finddealerxml&address=torino',
			//data: 'mkt=1000&brand=00&dlr=1&rad=5&func=finddealerxml&address=torino',
			//http://dealerlocator.fiat.com/geocall/PublicServlet?mkt=1000&brand=00&dlr=1&rad=5&func=finddealerxml&address=torino%corso%giovanni%agnelli&x=&y=
			cache: false,
			success: function(msg){
				alert('e vai!');
				var response = msg;
				//cc[callback](response, modelId, versionId, carCode, fn);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//alert('doh!');
				var sStatus = XMLHttpRequest.status;
				var sResponse = XMLHttpRequest.responseText;
				var sXml = XMLHttpRequest.responseXml;
				alert('http status: '+sStatus+', text response entity body: '+sResponse+', document response entity body: '+sXml+', type of error: '+textStatus);
			},
			complete: function(msg){
				alert('done'+msg);
				$.log(msg);
			}
		})
	}); */
	fiatCom.body = $("body");
	if($("div.actions").length){openObj($("div.actions a"))};
	openObj($("a.coa"));
	openObj($("ul.summary a"));
	openObj($("a.change_mvs"));
	//openObj($("a.inspiration"));
	openObj($("a[class*=resolve_conflict]"));
	openObj($("a.conflict"));
	openObj($("a.save_money"));
	openObj($("a.zoom"));
	/* openObj($("a.saved_builds")); */
	//openObj($("a.save"));
	clearInput();
	initObjs();//initialize all objects in one function	
	
	var layerTdriveLanding = new Layer();//trig open test drive layer when landing on page
	layerTdriveLanding.init();
	layerTdriveLanding.trigLanding();
	
	
	var trackClicks = new TrackClicks(); // sophus tracking
	trackClicks.tracking(fiatCom.body);
	
	if( !( $("#layout").hasClass("hp") || $("#layout").hasClass("our_cars") ) ){//showing our cars grid layer everywhere but in hp and in our cars pages
		globalNav.showOurCars();
	};
	
	if(GetUrlParam('contacts') == 'true'){//apertura sezione contatti
		$('div#header div.secondary_nav a.contacts').trigger('click');
	}
	
	//air tech
	if($("div.page_wrapper").length){
		var renderLayout = new RenderLayout();
		renderLayout.init($('div.page_wrapper ul.filters a'));
	};
	
	//stampa delle select per effettuare test su tutti gli mvs
	if($('div.test_mvs').is('div')){testMvs.init();}
	
	/********* UGO *******/
	startPage();
	if($('.model_page').length){loadPage.init()};
	//if($('.model_page').length){handleTab.init()};
});

//creating global variables
var fiatCom = {
	loading: $("<div class='loading'><img src='" + fiat_respath + "img/ajax.gif' alt='"+printMsg('loading', 'content')+"'/></div>"),
	//loadingCC: $("<div class='loading'><img src='" + fiat_respath + "img/configurator/ajaxCC.gif' alt='"+printMsg('loading', 'content')+"'/></div>"),//wide, white loading gif
	loadingCC: $("<div class='loading'><img src='" + fiat_respath + "img/ajax.gif' alt='"+printMsg('loading', 'content')+"'/></div>"),//small, transparent loading gif
	body: "", //init in doc ready
	element: null,
	currentCar: null,
	//filledMvsLayer: false,
	filledPack: false,
	
	filledExt: false,
	filledInt: false,
	
	filledMyPanel: false,
	
	filledModelPanel: false,
	
	filledOthers: false,
	
	filledTechSpec: false,
	
	readyColorExt: false,
	filledColorExt: false,
	
	readyColorInt: false,
	filledColorInt: false,
	
	readyPack: false,
	
	filledPackPanel: false,
		
	removed: [],
	
	added :[],
	
	vincoli: [],
	
	imgCounter: 0,
	
	//filledMpFlags: false,
	catIcon: {
		panel: "",
		flag: ""
	},
	multiple: false,//callback campaigns
	//FIXMS var globale necessaria per orribile hack per evitare invii multipli di contact requests
	lastTimeMessageSent: null
};

function initObjs(){
	/* if($('div.dealer_map').is('div')){
		dealerPanel.init();// init in gmaps. This div never exists
	} */
	//activateDirections.init();//moved to gmap.js
	filterCars.init();
	flipCars.init();
	layerHeader.init();
	globalNav.init();
	//if($('#layout').hasClass('model_page')){
	if($('div.model_outside').is('div')){
		//handleCurrentCar.init();
		//alert( typeof(modelPanel) );
		modelPanel.init();
		//optPanels.init();
		handleOpt.init();
		//changeViewExt.init();
		//changeViewInt.init();
		//handleMpFlags.init();
		//packagePanel.init();
		//var colorPanelExt = new ColorPanel( $('#above div.colorExt_panel') );//moved to configurator.js
		//var colorPanelInt = new ColorPanel( $('#above div.colorInt_panel') );
		//colorPanelExt.init();//moved to configurator.js
		//colorPanelInt.init();
		myPanel.init();
		//configurator.init();
		finitoPage.init();
		statusHandler.init();
		//mvsSelection.init();
		var loadSocialNetworks = new LoadSocialNetworks();
		loadSocialNetworks.loadFB();
		loadSocialNetworks.loadAddThis();
		
		//tableCompareEngines.init();
	};
	
	if($('#layout').hasClass('promotions')){
		var loadSocialNetworks = new LoadSocialNetworks();
		loadSocialNetworks.loadFB();
		loadSocialNetworks.loadAddThis();
		promotionDetail.init();
	};
	if($("#layout").hasClass("fiatpedia")){fiatPedia.init()};
	if($("#layout").hasClass("shopping_tools")){shoppingTools.init()};
	//if($("#layout").hasClass("owner_tools")){
	if($("#layout").is(".owner_tools.landing")){
		ownerTools.init();
		//promises.init();//to activate the accordion
	};
	if($("#layout").is(".owner_tools.promises")){
		//ownerTools.init();
		promises.init();
	};
	if($("#layout").hasClass("hp")){hp.init()};
	if($("#layout").hasClass("end_series")){
		promotionDetail.init();
		endSeries.init();
	}
	if($("div.campaigns").length){campaigns.init();}
};

function removeEmpty(){//removing empty <p> inserted by cms
	fiatCom.body.find("p:empty").remove();
};

function trigBuild(){//scroll the page to top and trig the Configure btn
	$("a[href='#above']").click(function(e){
		var el = ( $.browser.webkit ) ? fiatCom.body : $("html");
		
		el.animate({
			scrollTop: 0
		}, globalNav.speed.A, function(){
			modelPanel.panel.find('a.configure:visible').trigger("click");
		});
		
		e.preventDefault();
	});
}

var privacyHandler = {
	btnOpen: null,
	btnClose: null,
	text: null,
	init: function(el){// the parameter is the DOM obj in which to search the privacy for
		privacyHandler.btnOpen = el.find("a.read_privacy");
		privacyHandler.btnClose = el.find("a.hide_privacy");
		privacyHandler.text = el.find("div.privacy_txt");
		
		privacyHandler.open();
		privacyHandler.close();
	},
	open: function(){
		privacyHandler.btnOpen.click(function(){
			privacyHandler.text.fadeIn();
			return false;
		});
	},
	close: function(){
		privacyHandler.btnClose.click(function(){
			privacyHandler.text.fadeOut();
			return false;
		});
	}
};

function Layer(){
	var _self = this;//storing this in a var to always access the object in the function	
	this.objLayer = $("<div class='layer' />");
	this.layer_inner = $("<div class='layer_inner'/>");
	this.layer_fake = $("<div class='layer_fake'/>");//fake div to trigger COA layer's close
	this.loaderWrapper = $("<div class='loader_wrapper' />");
	this.btnClose = $("<a href='#' class='close'>x</a>");
	this.loader = $("<div class='loader' />");
	this.init = function(){
		this.loaderWrapper.append(this.btnClose, this.loader);
		this.layer_inner.append(this.loaderWrapper);
		this.objLayer.append(this.layer_fake, this.layer_inner);
	};		
	this.openLayer = function(el){//the parameter is the clicked element, needful to calculate its position and assign it to the layer
		fiatCom.body.append(this.objLayer);
		
		var h = $(document).height(),
			w = $(window),
 			name = el.attr('class').split(' ')[0],
			boxParent, prevLoaderWrapper, boxParentWidth, boxParentHeight, layerHeight, layerWidth, offsetTop, offsetLeft, toTop, toLeft, parentPadding, margin;
		
		switch(name){
			case 'coa':
				boxParent = el.parent();
				boxParentWidth = boxParent.width();
				layerHeight = this.loaderWrapper.height();
				layerWidth = this.loaderWrapper.outerWidth();
				offsetTop = el.offset().top;
				offsetLeft = (el.position().left - layerWidth/2) + (boxParentWidth/2);
				//toTop = offsetTop - layerHeight/2;
				parentPadding = parseInt(this.loaderWrapper.css('padding-top'), 10);// parseInt to be sure all browser read it right
				
				if( el.closest("div.box01").offset().top > 400 ){//if the element is in the last row, move up the COA
					toTop = offsetTop - parentPadding - layerHeight/2;
				}else{
					toTop = offsetTop - parentPadding;//opening COA layer on top of the clicked car
				} 
				
				ourCars.container.unbind('mouseleave');//unbinding mouseleave event to keep our cars layer shown
			break;
			case 'tdrive_ca':
				prevLoaderWrapper = el.closest('.layer').find('.loader_wrapper');//getting the previous loader_wrapper to set the current position
				boxParent = el.parent(this.loader);
				boxParentWidth = boxParent.outerWidth();
				boxParentHeight = boxParent.outerHeight();
				layerHeight = this.loaderWrapper.height();
				layerWidth = this.loaderWrapper.outerWidth();
				offsetTop = el.offset().top;
				parentPadding = parseInt(prevLoaderWrapper.css('padding-left'), 10);// parseInt to be sure all browsers read it right
				toLeft = parseInt(prevLoaderWrapper.css('left'), 10);// parseInt to be sure all browsers read it right
				offsetLeft = (toLeft - layerWidth/2) + (boxParentWidth/2) + parentPadding;
				toTop = offsetTop - layerHeight/2 - boxParentHeight;
			break;
			case 'tdrive_netmining'://fall through
			case 'tdrive':
				boxParent = el.parent();
				boxParentWidth = boxParent.outerWidth();
				boxParentHeight = boxParent.outerHeight();
				layerHeight = this.loaderWrapper.height();
				//offsetTop = el.position().top;
				offsetTop = el.offset().top;
				if(boxParent.hasClass("text_wrap")){//if the layer opens inside gmap, it  follows parent's position, else it opens at the center of the page
					offsetLeft = (el.position().left - boxParentWidth/2)
				}else{
					offsetLeft = "50%";
					margin = (_self.loaderWrapper.width())/2;
					_self.loaderWrapper.css({'margin-left':-(margin)});
				}
				//offsetLeft = (el.position().left - boxParentWidth/2);	
				( offsetTop < layerHeight ) ? toTop = 30 : toTop = offsetTop - layerHeight;//if the tdrive is on top of the page, open the layer 30px from top
			break;
			case 'warranty'://it's a fall through: these cases share the same code, so the code to be executed is in the last statement
			case 'share':
			case 'save':
			case 'saved_builds':
			case 'resolve_conflict_ext':
			case 'resolve_conflict_int':
			case 'conflict':
			case 'save_money':
			case 'promo':
			//case 'zoom':
				layerHeight = this.loaderWrapper.height();
				toTop = (w.height() - layerHeight) / 2 + w.scrollTop();
			break;
		};	
		
		this.objLayer.css("height", h);
		this.layer_fake.css("height", h);
		this.layer_inner.css("height", h);
		
		this.loaderWrapper.css({
			"top":toTop,
			"left":offsetLeft
		});
		
		this.callbacks();
	};
	this.loadContent = function(content, el){
		this.loader.html(fiatCom.loading);//inserting the loading.gif before ajax load is completed

		this.openLayer(el);//the parameter is the clicked element useful to calculate the position
		
		//if the content is an external html, then load it; else, write the content inside the container
		if(content.indexOf(".html")!=-1 || content.indexOf(".aspx")!=-1 ){
			this.loader.load(content, function(){
				var formName = _self.loaderWrapper.attr("class").split(" ")[1];// reading the name of the form to be checked
					
				privacyHandler.init(_self.loaderWrapper);
				checkForm(formName, _self.loaderWrapper);//the second parameter is form's container
				
				if( _self.loaderWrapper.hasClass("share") ){
					var loadSocialNetworks = new LoadSocialNetworks();
					loadSocialNetworks.initAddThis();
				}
				if( _self.loaderWrapper.hasClass("warranty") ){
					warrantyTabs = new Tabs( _self.loaderWrapper.find('div.tab_wrap'), false, /* false, */ false );
					warrantyTabs.init();
				}
				if( _self.loaderWrapper.hasClass("save") ){
					//if the user shares the configuration, close the save layer and open the share layer
					var btnShare = _self.loaderWrapper.find("a.share.btn");
					btnShare.click(function(e){
						_self.objLayer.remove();
						e.preventDefault();
					}).trigger(openObj(btnShare));
				}
				if( _self.loaderWrapper.hasClass("saved_builds") ){
					var btnSave = _self.loader.find("a.save");
					btnSave.click(function(e){
						_self.objLayer.remove();
						e.preventDefault();
					}).trigger(openObj(btnSave));
				}
				if( _self.loaderWrapper.hasClass("resolve_conflict_ext" ) || _self.loaderWrapper.hasClass("resolve_conflict_int") ){
					_self.loader.find("a.close").click(function(e){
						_self.btnClose.trigger('click');
						e.preventDefault();
					});
				}
				if( _self.loaderWrapper.hasClass("tdrive_netmining") ){
					_self.loader.find("a.btn_prev").addClass("disabled");
					_self.loader.find("div.carousel").jCarouselLite({
						btnNext: "a.btn_next",
						btnPrev: "a.btn_prev",
						visible: 1,
						circular: false,
						speed: 800
					});
				}

// FIXMS REMOVE THESE LINES
//				if( _self.loaderWrapper.hasClass("tdrive_ca") ){
//					_self.loaderWrapper.find("span[id]").each(function(){//setting input text value according to text put into span
//						var $this = $(this), 
//							txt = $this.text().toUpperCase(),
//							id = $this.attr("id");
//				
//						$this.siblings("input[type=text]").filter( "[name=" + id + "]" ).val(txt);						
//					});
//				}
			});
		}else{
			this.loader.html(content);
			if(_self.loaderWrapper.hasClass("mvs_selection")){
				mvsSelection.init();
			}
			if ( _self.loaderWrapper.hasClass('zoom') ){
				handleZoom.init();
			}
		};
	};
	this.callbacks = function(){
		this.layer_fake.click(function(){
			_self.objLayer.find("a.close").trigger('click');//closing the open layer when clicking on the layer_inner's sibling
		});
		this.btnClose.click(function(){
			_self.loaderWrapper.removeClass().addClass('loader_wrapper');//restoring original classes
			_self.objLayer.remove();
			ourCars.container.bind('mouseleave', ourCars.destroy());//binding the mouseleave event again to our cars layer
			
			cms.type = 1;
			
			return false;
		});
	};
};

Layer.prototype = {
	writeLayer: function(){
		var h = $(document).height(),
			w = $(window),
			path = fiat_respath+"other/loaded/",
			ext = "html",
			content = path + "error_status" + "." + ext;
			
		fiatCom.body.append(this.objLayer);
		this.loader.html(fiatCom.loading);//inserting the loading.gif before ajax load is completed
		this.loader.load(content);
		this.objLayer.css("height", h);
		this.layer_fake.css("height", h);
		this.layer_inner.css("height", h);
		this.callbacks();

		if( $("div.layer").length > 1 ){
			$("div.layer").not(":first").remove();
		}
	}
};

Layer.prototype = {
	trigLanding: function(){
		if(GetUrlParam('tdrive') == 1){
			modelPanel.tDrive.triggerHandler('click');
		} else if(GetUrlParam('tdrivemodel') == 1){
			//apre layer tdrive ma in model page. Trigger finto elemento?
			var path = 'other/loaded/',
				title = 'tdrive_netmining',
				name = title,
				$this = filterCars.boxes.eq(5);//the element in the middle of the page 
			
			fiatCom.body.append(this.objLayer);
			this.init();
			this.loader.html(fiatCom.loading);//inserting the loading.gif before ajax load is completed
			this.loaderWrapper.addClass(name).addClass('tdrivemodel');//setting class for style
			this.loadContent(fiat_respath + path + title + '.html', $this);//the second parameter is the obj clicked
		}
	}
};

/* Layer.prototype = {
	trigNetMining: function(modelID){//parametro input modello
		//this.init();
		var h = $(document).height();
		this.objLayer.css("height", h);
		this.layer_fake.css("height", h);
		this.layer_inner.css("height", h);
		fiatCom.body.append(this.objLayer);
		this.loader.html(fiatCom.loading);//inserting the loading.gif before ajax load is completed
		this.loaderWrapper.addClass('tdrive_netmining');//setting class for style
		var myiframe = $("<iframe id='IFRAMEmaster' width='620px' height='460px' scrolling='no' frameborder='0'/>");
		this.loader.html(myiframe);
		var url = "http://selfcare.fiat.com/nmFiatForm.aspx?BRAND=00&selfclose=yes" + "&MMVS="+modelID;//parametro in input da inserire
		this.loaderWrapper.find("iframe").attr("src", url);				
		this.callbacks();	
	}
}; */

function openObj(trigger){
	var name, title, $this,
		path = fiat_respath+'other/loaded/';
		
	trigger.click(function(e){
		$this = $(this);
		name = $this.attr("class").split(" ")[0];//using the first class's name to style the layer
		title = $this.attr("rel");//using the rel to load the content
		
		/* if( $("#layout").hasClass("hp") ){
			hp.carouselWrapper.fadeOut();//in hp, when clicking on a car of the grid, the carousel and the steering wheel disappear
			hp.wheel.hide();
		} */

		switch(name){
			case 'coa':
				coa.init($this);//new layer for COA created inside coa.init();
				e.preventDefault();//real url inserted for SEO reasons; when js activated should not follow the link
			break;
			case 'warranty'://it's a fall through: these cases share the same code, so the code to be executed is in the last statement
			case 'share':
			case 'save':
			case 'saved_builds':
			case 'promo':
			//case 'mvs_selection':
			case 'resolve_conflict_ext':
			case 'resolve_conflict_int':
			case 'conflict':
			case 'save_money':
			case 'inspiration':
			//case 'tdrive_ca':
			case 'tdrive_netmining':
			//break doesn't apply here
			// FIXMS commento riga sotto
			// case 'tdrive':
				layerTdrive = new Layer();//create a new layer
				layerTdrive.init();
				layerTdrive.loaderWrapper.addClass(name);//setting class for style
				layerTdrive.loadContent(fiat_respath + path + title + '.html', $this);//the second parameter is the obj clicked
				//layerTdrive.loadContent(path+title+'.aspx', $this);//the second parameter is the obj clicked
			break;
			// FIXMS aggiunta case tdrive:
			case 'tdrive':
				layerTdriveA = new Layer();//create a new layer
				layerTdriveA.init();
				layerTdriveA.loaderWrapper.addClass(name);//setting class for style
				var myiframe = $("<iframe width='620px' height='440px' scrolling='no' frameborder='0'/>");
				layerTdriveA.loader.append(myiframe);
				//layerTdriveA.loaderWrapper.find("iframe").attr("src", "http://selfcare.fiat.com/fullFiatForm.aspx");
				fiat_tdfullurl1 = "http://selfcare.fiat.com/fullFiatForm.aspx" + "?MMVS="+modelCar.modelId;
                layerTdriveA.loaderWrapper.find("iframe").attr("src", fiat_tdfullurl1);				
				layerTdriveA.openLayer($this);//the parameter is the clicked element useful to calculate the position
				
				/* if($this.attr("data-tracking")){
					var data = $this.attr("data-tracking");
					s3_log(data);//sending data to sophus
					$.log(data);
				} */
				
				e.preventDefault();
			break;
// FIXMS: sostituisci intero case
			case 'tdrive_ca':
				layerTdriveCoa = new Layer();//create a new layer
				layerTdriveCoa.init();
				layerTdriveCoa.loaderWrapper.addClass(name);//setting class for style
				var modelID = $this.attr("data-model");
				fiat_tdcoaurl1 = fiat_tdcoaurl + "?MMVS="+modelID;
				var myiframe = $("<iframe width='386px' height='385px' scrolling='no' frameborder='0' allowTransparency='true'/>");
				// Set height and remove padding so the CoA TD form stays centered.
				layerTdriveCoa.loader.attr("style", "height:385px; width:386px; padding:0px");
				layerTdriveCoa.loader.append(myiframe);
				layerTdriveCoa.loaderWrapper.find("iframe").attr("src", fiat_tdcoaurl1);
				layerTdriveCoa.openLayer($this);//the parameter is the clicked element useful to calculate the position
				
				if($this.attr("data-tracking")){
					var data = $this.attr("data-tracking");//sophus tracking
					s3_log(data);
					$.log(data);
				}
			break;
			case 'mvs_selection':
				//fiatCom.currentCar = new cc('it','it','150','001','001500C60000','rosso');
				
				layerMvsSelection = new Layer();//create a new layer
				layerMvsSelection.init();
				layerMvsSelection.loaderWrapper.addClass(name);//setting class for style
				layerMvsSelection.loadContent(mvsSelection.layer(), $this);
				mvsSelection.engineCount=0;
				
				mvsSelection.startCall();
				
				var data = $this.attr("data-tracking");//sophus tracking
				s3_log(data);
				$.log(data);
			break;
			case 'zoom':
				layerZoom = new Layer();//create a new layer
				layerZoom.init();
				layerZoom.loaderWrapper.addClass(name);//setting class for style
				layerZoom.loadContent( handleZoom.insertCode(), $this);
				e.preventDefault();
			break;
		};
		e.stopPropagation();//using stopPropagation to make anchor with actual href work
	});
};

function checkForm(formId, container){
	//clearing the input everywhere but in the share layer
	if( !container.hasClass("share") ){
		clearInput();
	}
	
	var btn_send = container.find(".send");
	
	// formId is a string, so I need to make it a jQuery obj
	//formId = $('form.'+formId);	
	formId = $("div.form_wrapper").find("div."+formId+"");
	
	btn_send.click(function(){
		$.log(btn_send);
		var formActive = formId,
			formOk = true,
			formObbl = formActive.find('input[type="text"].required'),
			formDate = formActive.find('input[type="text"].data'),
			formMail = formActive.find('input[type="text"].email'),
			formConfirmMail = formActive.find('input[type="text"].confirm_email'),
			formNum = formActive.find('input[type="text"].num'),
			formSelect = formActive.find('select.required'),
			formTextarea = formActive.find('textarea.required'),
			formPrivacy = formActive.find('input[type="checkbox"]'),
			formErrorMsg = formActive.find('p.error_msg'),
			formCaptcha = formActive.find('input[name="captcha"]'),
			formPwd = formActive.find('input[type="password"]'),
			formDataTreatment = formActive.find('input[type="radio"]');// in test drive form it indicates if the user wants his data to be used for commercial purpose
			//formError = formActive.find('label').children('span');
		
		//reset errors
		/* formError.each(function() {
			$(this).hide();
		}); */
			
		//doing the checks
		formObbl.each(function(){
			var $this = $(this),
				insValue = $this.val();
			
			//if the field is empty or filled with the default value, then throw an error	
			if( insValue === '' ||  insValue === this.defaultValue ){
				$this.addClass("error");
				//$(this).prev('label').children('span').html(stampaMessaggi('form','obbligatorio')).fadeIn();
				formOk = false;
			}
		});
		
		formNum.each(function(){
			var $this = $(this);
			
			//if the text is not a number, throw an error
			if(!validNum.exec($this.val())){
				$this.addClass("error");
				formOk = false;
			}	
		});
		
		if( formDate.length > 0 && !validDate.exec(formDate.val()) ){//date is a dd/mm/yyyy
			formDate.addClass("error");
			//formDate.prev('label').children('span').html(stampaMessaggi('form','data')).fadeIn();
			formOk = false;
		}
		if (!validEmail.exec(formMail.val()) ) {
			formMail.addClass("error");
			//displaying error message only if we are in the "save" layer
			if(container.hasClass("save")){
				formErrorMsg.fadeIn();
			}
			//formMail.prev('label').children('span').html(stampaMessaggi('form','mail')).fadeIn();
			formOk = false;
		}
		if( formConfirmMail.length > 0 && formConfirmMail.val() != formMail.val() ){//if the mail confirmed is different from the first mail, throw an error
			formConfirmMail.addClass("error");
			formOk = false;
		}
		if( formPrivacy.length > 0 && !(formPrivacy.attr('checked')) ){//privacy mandatory
			formPrivacy.parent("div").addClass("error");
			//displaying error message only if we are in the "save" layer
			if(container.hasClass("save")){
				formErrorMsg.fadeIn();
			}
			//formPrivacy.next('label').children('span').html(stampaMessaggi('form','privacy')).fadeIn();
			formOk = false;
		}
		if( formSelect.length > 0 && formSelect.val() == "" ){
			formSelect.addClass("error");
			formOk = false;
		}
		if( formCaptcha.length && formCaptcha.val() == "" ){ //throw an error else if the value is void
			formCaptcha.addClass("error");
			formOk = false;
		}
		if( formPwd.length && formPwd.val() == "" ){ //throw an error else if the value is void
			formPwd.addClass("error");
			formOk = false;
		}
		/* if(formDataTreatment.val()=='ko'){//privacy
			formPrivacy.parent("label").addClass("error");
			formOk = false;
		} */
		
		//removing error messages
		$('div.error').click(function(){
			$(this).removeClass('error');
			//removing error message only if we are in the "save" layer
			if(container.hasClass("save")){
				formErrorMsg.fadeOut();
			}
			//$(this).find("a").children("span").fadeOut();
		});	
		$('.error').keyup(function(){
			$(this).removeClass('error');
			//removing error message only if we are in the "save" layer
			if( container.hasClass("save") ){
				formErrorMsg.fadeOut();
			}
			//$(this).prev("label").children("span").fadeOut();
		});
		$("select.error").change(function(){
			var $this = $(this);
			if( $this.val() != "" ){ $this.removeClass('error'); }
		});
		$(".accept_privacy input").click(function(){
			$(".accept_privacy label").removeClass('error');
			//removing error message only if we are in the "save" layer
			if( container.hasClass("save") ){
				formErrorMsg.fadeOut();
			}
		});
		
		// FIXMS aggiunta invio informazioni del contatto al web service
		if(formOk){

			var isInformationCompany = formActive.hasClass("information_company");
			var isInformationPrivate = formActive.hasClass("information_private");
			var isComplaintCompany = formActive.hasClass("sells_company");
			var isComplaintPrivate = formActive.hasClass("sells_private");
			var isSuggestionsCompany = formActive.hasClass("suggestions_company");
			var isSuggestionsPrivate = formActive.hasClass("suggestions_private");
			
			var name =	formActive.find('input[name="nome"]').val();
			var lastName = formActive.find('input[name="cognome"]').val();
			var email = formActive.find('input[name="email"]').val();
			var phoneNumber = formActive.find('input[name="telefono"]').val();
			var description = formActive.find('textarea[name="descrizione"]').val();
			var checkedConsentPrivacy = $("input[name=accept]:checked").val();
			if(checkedConsentPrivacy != "ok" && checkedConsentPrivacy != "ko") {
				alert(printMsg('form', 'privacy'));
				return;
			}
			
			if(isInformationCompany || isComplaintCompany || isSuggestionsCompany) {
				var ragioneSociale = formActive.find('input[name="ragioneSociale"]').val();
			}

			// INFORMATION REQUEST
			if(isInformationCompany || isInformationPrivate) {
				var productRequested = $("input[name=product]:checked").val();
				
				var dataObject = {
					"serviceType" : "Information",
					"isContactACompany" : isInformationCompany,
					"ragioneSociale" : ragioneSociale,
					"name" : name,
					"lastName" : lastName,
					"email" : email,
					"phoneNumber" : phoneNumber,
					"description" : description,
					"isPrivacyConsentGiven" : checkedConsentPrivacy,
					"productRequested" : productRequested
				};
				var mapData = JSON.stringify(dataObject);
			}
			
			// COMPLAINT
			if(isComplaintCompany || isComplaintPrivate) {
				var complaintReason = $("input[name=complaints]:checked").val();
				var dealer = formActive.find('input[name="dealer"]').val();
				var targa = formActive.find('input[name="targa"]').val();
				var modello = formActive.find('input[name="modello"]').val();
				var typeOfComplaint = formActive.find('select[name="typeOfComplaint"]').val();
				
				var dataObject = {
					"serviceType" : "Complaint",
					"isContactACompany" : isComplaintCompany,
					"ragioneSociale" : ragioneSociale,
					"name" : name,
					"lastName" : lastName,
					"email" : email,
					"phoneNumber" : phoneNumber,
					"description" : description,
					"isPrivacyConsentGiven" : checkedConsentPrivacy,
					"dealer" : dealer,
					"targa" : targa,
					"modello" : modello,
					"typeOfComplaint" : typeOfComplaint,
					"complaintReason" : complaintReason
				};
				var mapData = JSON.stringify(dataObject);
			}
			
			// SUGGESTION
			if(isSuggestionsCompany || isSuggestionsPrivate) {
				
				var dataObject = {
					"serviceType" : "Suggestion",
					"isContactACompany" : isSuggestionsCompany,
					"ragioneSociale" : ragioneSociale,
					"name" : name,
					"lastName" : lastName,
					"email" : email,
					"phoneNumber" : phoneNumber,
					"description" : description,
					"isPrivacyConsentGiven" : checkedConsentPrivacy
				};
				var mapData = JSON.stringify(dataObject);
			}
			//FIXMS PROVA PATH RELATIVO
			//var jspUrl = "http://test2.fiat.com/webservices/sendcontacts.jsp";
			var jspUrl = "/webservices/obs/cgi-bin/pbrand.dll/FIAT_ITALIA/contact/contact_us_fiat2.jsp";
		
			// workaround per evitare invii multipli.  Non dovrebbe essere necessaria e andrebbe rimossa 
			// evitando chiamate multiple a questo metodo ad invii di contatti successivi.
			if(fiatCom.lastTimeMessageSent != null && ((new Date().getTime() - fiatCom.lastTimeMessageSent) < 15000) ) {
				formStep( container, $(this) );
				return;
			}
			
			fiatCom.lastTimeMessageSent = new Date().getTime()
			
			$.ajax({
				type: "POST",
				url: jspUrl,
				data: dataObject,
				success:function(data, textStatus, jqXHR){
					// Solo se tutto e' andato a buon fine, chiudiamo lo step del form
					formStep( container, $(this) );
				},
 			    error: function(jqXHR, textStatus, errorThrown){
					alert(printMsg('form', 'error'));
					$.log(jqXHR.responseText);
					return;
				}

			});			

		}
		return false;
	});
};

function formStep(container, btn_send){
	var stepClass = 'div[class*="step"]',
		steps = container.find(stepClass),
		step1 = container.find('.step1'),
		step2 = container.find('.step2'),
		msgOK = container.find('.book.ok'),
		btnOtherDealer = container.find('.next'),
		keepBuild = $("a.keep_build"),
		warning = $('span.mandatory'),
		search = $('div.input_text');
	
	step1.hide();
	warning.hide();//hiding "mandatory fields" message
	
	if ( $('#above').find('#dealer_map').length > 0 ) { // se mi trovo nella pagina del locator, il layer test drive non deve prevedere il secondo step con la mappa 
		msgOK.fadeIn();
	}else if( container.hasClass('tdrive_ca') ){
		step2.fadeIn();
	}else if( container.hasClass('save') ){
		step2.fadeIn();
		
		//updating car name according to user's choice
		var carName = container.find("input[name=car_name]").val(),
			p = container.find("div.step2").find("p.car_name");
			
		if( carName != "" ){p.text(carName);}
		
		keepBuild.live('click', function(e){
			layerTdrive.btnClose.trigger('click');//closing the layer if the user clicks on keep building
			e.preventDefault();
		});
	}else if( container.hasClass('tdrive_netmining') ){
		if( btn_send.hasClass("info") ){
			container.find("div.info").show();
		}else if( btn_send.hasClass("tdrive") ){
			container.find("div.tdrive").show();
		}
	}else if( container.parents("div.contacts").hasClass("contacts") ){ //global navigation contacts
		//spostare queste 2 funzioni in sendCaptcha();
		container.parents("div.contacts").find("div[class*=step]").hide();
		container.nextAll(".step3").show();
	}else{
		step2.fadeIn(function(){
			gMap.init();
			$('div.result a.book').live('click',function(){
				steps.hide();
				msgOK.fadeIn();
				return false;
			});
		});
		btnOtherDealer.click(function(){
			gMap.clear();
			search.css({'visibility':'visible'});
			btnOtherDealer.hide();
			return false;
		});
	}
};

function SendCaptcha(container){ // this parameter is the div containing the form with the captcha
	var _self = this;

	this.guid = "";
	this.url = "http://www.lancia.it/_vti_bin/_wcf/GetCaptchaImage.jpg"; //the url of the service to be called to build the captcha img
	this.input = container.find("input[name=captcha]");
	this.inputVal = this.input.val(); //the value prompt by the user
	this.captchaImg = container.find("div.captcha").children("img");//the img of the captcha	
	
	this.createCaptcha = function(){//invoked in globalNav.handleLoading()
		$.ajax({
			url: _self.url,
			type: "POST",
			success: function(data){
				_self.guid = data; //the guid will be sent by the service and will be used to be compared with the input value
				_self.captchaImg.attr("src", data); //the src will be the url of the image sent by the service
			},
			error: function(){
			},
			complete: function(){
			}
		});
	};
	
	this.checkCaptcha = function(){//invoked in checkForm()
		$.ajax({
			url: _self.url,
			type: "POST",
			data:  _self.inputVal + _self.guid,
			success: function(data){
				if( data == "ok" ){ // if input value corresponds to the guid, so we can show the other steps
					container.parents("div.contacts").find("div[class*=step]").hide();
					container.next(".step3").show();					
				}else{
					alert("errore");
					//errore
				}
			},
			error: function(){
			},
			complete: function(){
			}
		});
	};
};

function Tabs (wrapper,isAnimated,/* canGrade, */canCloseAll,whichOpen){
	if (typeof whichOpen == "undefined") {
		whichOpen = 0;
	}
	//$.log(canCloseAll);
	var _self = this;
	//this.controlHeight = 0;
	this.tabControls = null;
	this.tabContent = null;
	this.tabOn = null;
	this.init = function(){
		this.tabControls = wrapper.children('ul.tab_controls').children('li');
		this.tabContent = _self.tabControls.parent().next('div.tab_contents').children('div.tab_content');
		
		if (!canCloseAll) {
			this.tabControls.eq(whichOpen).addClass('on');
			this.tabContent.eq(whichOpen).addClass('on');
		}
		/* if (canGrade) {
			this.gradeControls();
		} */
		this.switchTab();
	};
	/* this.gradeControls = function(){//set the same height for each tab control
		_self.controlHeight = 0;//reset
		//$.log( _self.controlHeight );
		_self.tabControls.each(function(){
			//alert( $(this).height() );
			$(this).removeAttr('style');//reset style given via js
			if ( $(this).height() > _self.controlHeight) {
				_self.controlHeight = $(this).height();
			}
		});
		this.tabControls.height( _self.controlHeight );
	}; */
	this.switchTab = function(){
		this.tabControls.click(function(e) {
			//$.log(clicked);
			var _this = $(this);
			if ( !_this.hasClass('on') ) {
				var clicked = _self.tabControls.index( _this );
				if (isAnimated) {
					_self.tabContent.parent().stop(true,true).slideUp(function(){
						_self.tabControls.removeClass('on').eq(clicked).addClass('on');
						_self.tabContent.removeClass('on').removeAttr('style').eq(clicked).addClass('on');
						_self.tabContent.parent().slideDown();
					});
				} else {
					_self.tabControls.removeClass('on').eq(clicked).addClass('on');
					_self.tabContent.removeClass('on').eq(clicked).addClass('on');
				}
			} else {
				if (canCloseAll && isAnimated) {//add option to close all tabs when clicking the opened tab
					_self.tabContent.parent().stop(true,true).slideUp(function(){
						_self.tabControls.removeClass('on').eq(clicked).addClass('on');
						_self.tabContent.removeClass('on').eq(clicked).addClass('on');
						_self.tabContent.parent().slideDown();
					});
				}
			}
			e.preventDefault();
		});
	};
};

var promotionDetail = {
	accordionTitle: null,
	init: function(){
		promotionDetail.accordionTitle = $('div.more_title');
		promotionDetail.handleToggle();
	},
	handleToggle: function(){
		promotionDetail.accordionTitle.click(function(){
			$(this).toggleClass('closed').next('div.more_content').slideToggle();
		});
	}
};

var endSeries = {
	SPEED: 800,
	obj: null,
	cars: null,
	boxes: null,
	back: null,
	more: null,
	init: function(){
		endSeries.obj = $("#layout.end_series");
		endSeries.boxes = endSeries.obj.find("div.box.titles");
		endSeries.cars = endSeries.obj.find("ul.cars").find("a");
		endSeries.back = endSeries.obj.find("a.to_top");
		endSeries.more = endSeries.obj.find("div.baloon").find("a");
		
		endSeries.pageScroll(endSeries.cars);
		endSeries.pageScroll(endSeries.back);
		endSeries.pageScroll(endSeries.more);
	},
	pageScroll: function(el){
		el.click(function(e){
			// if I click on read more, the target boxes become the promotion details
			if( el == endSeries.more ){
				endSeries.boxes = endSeries.obj.find("div.promotion_detail");
				var accordionTitle = $(this).parents("div.container_12").next("div.container_12").find("div.promotion_detail").find("div.more_title");//traversing the DOM to the next accordion title
				accordionTitle.triggerHandler("click");//open up only the first accordion
			}
				
			var thisID = $(this).attr("href").split("#")[1],
				target = endSeries.boxes.filter( "[class*="+thisID+"]" );
			
			if( el == endSeries.back ){
				target = $("div.box.titles.no_stripe.top");
			}
			
			$.scrollTo( target, endSeries.SPEED );
			e.preventDefault();
		});
	}
};

var ourCars = {
	container: $("<div class='grid_container'/>"),
	init: function(url){
		$("#header_inner").after(ourCars.container);
		ourCars.loadContent(url);
		ourCars.destroy();
	},
	loadContent: function(url){
		// if/else used to load the content one time only
		if( ourCars.container.html() === "" ){
			ourCars.container.load(url + " div.grid_wrapper", function(){
				ourCars.container.fadeIn();
				filterCars.init();
				flipCars.init();
				openObj($("a.coa"));
			});
		}else{ ourCars.container.fadeIn(); }//the content is already loaded, so I just need to show it
	},
	destroy: function(){
		ourCars.container.bind('mouseleave', function(){
			ourCars.container.fadeOut();
		});
	}
};

var filterCars = {
	container: null,
	select: null,
	buttons: null,
	li: null,
	boxes: null,
	resetBtn: null,
	init: function(){
		filterCars.container = $('div.our_cars.grid');
		filterCars.select = $("div.grid_wrapper .select");
		filterCars.li = filterCars.select.find("li");
		filterCars.buttons = filterCars.li.find("a");
		filterCars.boxes =  filterCars.container.find(".box01");
		filterCars.resetBtn = filterCars.select.find("a.close_select");
		
		filterCars.reArrangeSelect();
		filterCars.triggerFiltering();
		filterCars.resetFilters();//reset filters when user clicks on the first voice
		filterCars.hideSelect();
		filterCars.resetAll();//reset all select when user clicks on X
	},
	reArrangeSelect: function(){
		filterCars.buttons.click(function(){
			var $this = $(this),
				thisParent = $this.parent("li"),
				adjacents = thisParent.siblings("li"),
				liHeight = filterCars.li.parent("ul").height(),
				ulHeight = filterCars.li.height();
			
			//if the select is closed, open it up
			if(ulHeight === liHeight){
				filterCars.li.show();
			}else{
				thisParent.addClass("on").show();
				adjacents.removeClass("on").hide();			
			}
			
			return false;
		});
	},
	hideSelect: function(){
		$("body").click(function(){
			filterCars.li.hide();
			
			//if exists a LI with class on, show it, else show the first one
			(filterCars.li.hasClass("on")) ? filterCars.select.find("li.on").show() : filterCars.li.eq(0).show();
		});
	},
	triggerFiltering: function(){
		filterCars.li.not(":first").find("a").click(function(){
			var $this = $(this),
				selector = $this.attr("rel");
				
			filterCars.boxes.addClass("filtered");//adding filtered class to all elements
			$(".filtered").find("a.coa").removeClass("coa");//removing calss COA to prevent COA layer opening
			
			$(".box01."+selector).removeClass("filtered");
			$(".box01."+selector).children("a").addClass("coa");//re-adding the class to open COA layer
			
			//filterCars.boxes.find("a.coa").unbind('hover', flipCars.hovering);
			//$(".filtered").find("a.coa").bind('mouseover', flipCars.hovering);			
			
			var data = $this.attr("data-tracking");
			s3_log(data);
			$.log(data);
			return false;
		});
	},
	resetFilters: function(){
		filterCars.li.eq(0).find("a").click(function(){
			filterCars.boxes.removeClass("filtered");
			filterCars.boxes.children("a").addClass("coa");//re-adding the class to open COA layer
		});
	},
	resetAll: function(){
		filterCars.resetBtn.click(function(){
			filterCars.li.removeClass("on").hide();
			filterCars.li.eq(0).show();
			filterCars.boxes.removeClass("filtered");
			filterCars.boxes.children("a").addClass("coa");//re-adding the class to open COA layer
		});
	}
};

var flipCars = {
	SPEED: 300,
	img: "",
	canAnim: true,
	init: function(){
		flipCars.wrapImg();
		flipCars.hovering();
	},
	hovering: function(){
		filterCars.boxes.find("a").hover(
			function(){//mouse in
				if( flipCars.canAnim ){
					flipCars.canAnim = false;
					$(this).find("div.img_wrapper").stop(true, true).fadeOut(flipCars.SPEED, function(){
						$(this).find("img").css("margin-left", "-140px");
					}).fadeIn(flipCars.SPEED, function(){ flipCars.canAnim = true; });
				}
			},
			function(){//mouse out
				flipCars.canAnim = true;
				$(this).find("div.img_wrapper").fadeOut(flipCars.SPEED, function(){
					$(this).find("img").css("margin-left", "0");
				}).fadeIn(flipCars.SPEED, function(){
					//flipCars.canAnim = true;
				});
			}
		);
	},
	wrapImg: function(){//wrappig the image to preserve span's behaviour
		filterCars.boxes.find("img").wrap("<div class='img_wrapper'/>");
	}
};
 
 
function LoadSocialNetworks(){

};

LoadSocialNetworks.prototype = {
	loadFB: function(){
		(function(d, s, id) {
			var js,
				fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) {return;}
			js = d.createElement(s); js.id = id;
			js.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));
	},
	loadAddThis: function(){
		(function(d, s) {
			var js,
				ajs = d.getElementsByTagName(s)[0];
			js = d.createElement(s); 
			js.src = "http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e849d00767f3512&domready=1&async=1";
			ajs.parentNode.insertBefore(js, ajs);
		}(document, 'script'));
        
	},
	initAddThis: function(){
		//addthis.init();
		var tbx = document.getElementById("toolbox"),
			html = "",
			svcs = {facebook: 'Facebook', twitter: 'Twitter', expanded: 'More'};

		for (var s in svcs) {
			html += '<a class="addthis_button_'+s+'">'+svcs[s]+'</a>'; //appending to string
		}
       // alert(html);
		tbx.innerHTML = html; //reflow
		var addthis_config = {
			ui_language: "en",
			ui_use_css: false,
			ui_header_color: "#96172E",
			ui_header_background: "#fff",
			ui_cobrand: "Share your Fiat",//set it dynamically?
			services_expanded: "email, twitter, facebook, reddit, tumblr, print, gmail, linkedin, blogger, stumbleupon, favorites, menu"
		};
		addthis.toolbox("#toolbox", addthis_config);
		//addthis.update('config', 'ui_language', 'en');
	},
	initAddThisFooter : function(){
		//self invoking to force the execution
        if(globalNav.footer.find("#toolbox").length!=0){
		//(function(){
			var tbx = document.getElementById("toolbox"),
				html = "",
				svcs = {facebook: 'Facebook', twitter: 'Twitter', linkedin: 'Linkedin', email: 'Email', google_plusone: 'Google +1', expanded: 'More'};

			for (var s in svcs) {
				html += '<a class="addthis_button_'+s+'">'+svcs[s]+'</a>'; //appending to string
			}	
			tbx.innerHTML = html; //reflow
			var addthis_config = {
				ui_language: "en",
				services_expanded: "email, twitter, facebook, reddit, tumblr, print, gmail, linkedin, blogger, stumbleupon, favorites, menu"
			};
			addthis.toolbox("#toolbox", addthis_config);
			//addthis.update('config', 'ui_language', 'en');
		}
		//}());
	}
};

var fiatPedia = {
	container: null,
	tagWrapper: null,
	tags: null,
	all: null,
	selector: null,
	init: function(){
		fiatPedia.container = $("div.isotope_wrapper");
		fiatPedia.tagWrapper = $("div.tags");
		fiatPedia.tags = fiatPedia.tagWrapper.find("a");
		fiatPedia.all = $("div.paging").find("div.all").children("a");
		
		fiatPedia.doCarousel();
		
		//common function
		fiatPedia.initIsotope();
		fiatPedia.addThisUrl();
		var loadSocialNetworks = new LoadSocialNetworks();
		loadSocialNetworks.loadAddThis();
		
		//layout-specific function
		if(!$("#layout").hasClass("detail")){
			fiatPedia.filtering();
			fiatPedia.triggerFiltering();
		};
		if($("#layout").hasClass("detail")){fiatPedia.buildParam()};
	},
	doCarousel: function(){
		var itemVisible = 7; //num max  di bimestri sempre visibili
		var itemList = [];
		
		if($('div.paging_wrapper div.carousel ul.paging li').length > itemVisible){
			$('div.paging_wrapper a.next, div.paging_wrapper a.last').css({'visibility':'visible'});
		}
		
		for(var i=0, l=$('div.paging_wrapper div.carousel ul.paging li').length; i<l; i++){
			if(i==0){//identifico il primo elemento
				itemList.push('div.paging_wrapper a.first');
			}else if(i==(($('div.paging_wrapper div.carousel ul.paging li').length) - itemVisible)){//identifico il primo elemento dell'ultimo gruppo
				itemList.push('div.paging_wrapper a.last');
			}else{
				itemList.push('');
			}
		}
		//$.log(itemList);
		
		$('div.paging_wrapper div.carousel').jCarouselLite({
			btnNext: 'div.paging_wrapper a.next',
			btnPrev: 'div.paging_wrapper a.prev',
			visible: itemVisible,
			circular: false,
			speed: 500,
			btnGo: itemList,//prevedo comandi che conducano all'inizio (cioe' al primo elemento) o alla fine (cioe' al primo elemento dell'ultimo gruppo) del carosello
			//btnGo: ["div.paging_wrapper a.first","","","","","div.paging_wrapper a.last","","","","","",""],
			afterEnd: function(a){
				if($('div.paging_wrapper a.next').hasClass('disabled')){
					$('div.paging_wrapper a.next, div.paging_wrapper a.last').css({'visibility':'hidden'});
				}else{
					$('div.paging_wrapper a.next, div.paging_wrapper a.last').css({'visibility':'visible'});
				}
				
				if($('div.paging_wrapper a.prev').hasClass('disabled')){
					$('div.paging_wrapper a.prev, div.paging_wrapper a.first').css({'visibility':'hidden'});
				}else{
					$('div.paging_wrapper a.prev, div.paging_wrapper a.first').css({'visibility':'visible'});
				}
			}
		});
	},
	initIsotope: function(){
		fiatPedia.container.isotope({
			itemSelector: '.element',
			masonry: {
				columnWidth: 5
			},
			transformsEnabled: false //necessary to let Add This layer open in the correct position
		});
	},
	filtering: function(){
		fiatPedia.tags.click(function(e){
			var $this = $(this);
			
			fiatPedia.selector = $this.attr('rel');
				
			// don't proceed if already selected
			if($this.hasClass('selected')){ return false };
			
			// a css selector is needed, so add a class notation but not for the ALL element
			if(!$this.hasClass("all")){ fiatPedia.selector = '.'+fiatPedia.selector; };
			
			fiatPedia.tagWrapper.find('.selected').removeClass('selected');
			$this.addClass('selected');			
			
			fiatPedia.container.isotope({ filter: fiatPedia.selector });
			
			e.stopPropagation();
			e.preventDefault();
		});
	},
	buildParam: function(){
		var href, filterName, $this;
		
		//building filtering parameter starting from the href written in the html
		fiatPedia.tags.each(function(){
			$this = $(this);
			
			href = $this.attr("href");			
			filterName = $this.attr("rel");
			href = href + '?filter=1&selector=' + filterName;
			
			$this.attr('href', href);		
		});		
	},
	triggerFiltering: function(){
		if(GetUrlParam('filter') == 1){
			//reading the parameter to trigger the filtering
			fiatPedia.selector = GetUrlParam('selector');
			
			//adding the class selected to the corrisponding tag
			fiatPedia.tags.filter('[rel='+fiatPedia.selector+']').addClass("selected");	
			
			// a css selector is needed, so add a class notation
			fiatPedia.selector = '.'+fiatPedia.selector;			
			
			fiatPedia.container.isotope({ filter: fiatPedia.selector });
		}
	},
	addThisUrl: function(){
		//building url to share
		fiatPedia.container.children("div").each(function(){
			var $this = $(this),
				url = $this.find("a").eq(0).attr("href");
			$this.find("a.addthis_button_compact").attr('addthis:url', url);
		});
	}
};

var shoppingTools = {
	tabbed: null,
	content: null,
	command: null,
	tabs: null,
	init: function(){
		shoppingTools.tabbed = $("div.tabbed_content");
		shoppingTools.content = shoppingTools.tabbed.find("div.content");
		shoppingTools.command = shoppingTools.tabbed.find("a.command");
		
		shoppingTools.tabs = new Tabs( $("#below div.tab_wrap"), false, false );
		shoppingTools.tabs.init();
		
		shoppingTools.specialTab();
	},
	specialTab: function(){
		shoppingTools.command.eq(0).addClass("on");
		shoppingTools.content.eq(0).addClass("on");
		
		shoppingTools.command.click(function(e){
			var $this = $(this),
				toShow = $this.attr("class").split(" ")[0];
				
			shoppingTools.command.removeClass("on");
			$this.addClass("on");
			
			shoppingTools.content.removeClass("on");
			shoppingTools.tabbed.find("div.content." + toShow + " ").addClass("on");
			
			e.preventDefault();
		});
	}
};

var ownerTools = {
	locate: null,
	btnGo: null,
	btnSearch: null,
	input: null,
	init: function(){
		ownerTools.locate = $("div.locate");
		//ownerTools.btnGo = ownerTools.locate.find("a");
		ownerTools.btnSearch = ownerTools.locate.find("a.search");
		ownerTools.input = ownerTools.locate.find("div.input_text input[type=text]");
		
		ownerTools.clickSearch();
		ownerTools.returnSearch();
	},
	clickSearch: function(){
		ownerTools.btnSearch.click(function(e){
			ownerTools.buildUrl();
			e.preventDefault();
		});
	},
	returnSearch: function(){
		ownerTools.input.keypress(function(event) {
			if ( event.which == 13 ) {
				ownerTools.buildUrl();
				return false;
			}
		});
	},
	buildUrl: function(){
		var searchValue = ownerTools.input.val(),
			searchType = ownerTools.locate.find('input[type="radio"]:checked').val(),
			href = ownerTools.btnSearch.attr("href");
			//href = ownerTools.btnGo.attr("href");
		href += '?trigger=' +searchValue+ '&searchType='+searchType;
		location.replace(href);
	},
	triggerMap: function(){//initialized in gMap.initializeMap()
		var inputValue = GetUrlParam("trigger");
		var radioValue = GetUrlParam("searchType");
		if(inputValue.length){
			dealerPanel.input_text.val(inputValue);
			//mapTabs.tab_content.eq(1).find('input[type="radio"]').filter('[value="'+radioValue+'"]').attr("checked", "checked");
			mapTabs.tab_content.eq(1).find('input[type="radio"]').filter('[value="'+radioValue+'"]').trigger('click');
			dealerPanel.search_btn.eq(1).trigger('click');
		}
	}
};

var promises = {
	SPEED: 800,
	flags: null,
	boxes: null,
	$this: null,
	init: function(){
		promises.flags = $("div.promises").find("ul.flags").find("a");
		promises.boxes = $("#below").find("div.tohover");
		promises.filtering();
	},
	filtering: function(){
		promises.flags.click(function(e){//selecting the boxes and scrolling the page
			promises.$this = $(this);
			var thisID = promises.$this.attr("href").split("#")[1],
				target = promises.boxes.filter( "[class*="+thisID+"]" );
			
			promises.flags.parent("li").removeClass("on");
			promises.$this.closest("li").addClass("on");
			promises.boxes.addClass("filtered").removeClass("on");
			target.addClass("on").removeClass("filtered");
			
			$.scrollTo(target, promises.SPEED);
			
			e.preventDefault();
		});
		
		promises.boxes
			.click(function(){//selecting the boxes
				promises.$this = $(this);
				var id = promises.$this.attr("class")[0],
					flag = promises.flags.filter( "[href*=#"+id+"]" );

				promises.flags.parent("li").removeClass("on");
				flag.closest("li").addClass("on");
				promises.boxes.removeClass("on").addClass("filtered");
				promises.$this.removeClass("filtered").addClass("on");
			})
			.hover(function(){
					promises.boxes.filter( "[class~=on]" ).addClass("filtered");
				},
				function(){
					promises.boxes.filter( "[class~=on]" ).removeClass("filtered");
				}
			);
	}
};

var hp = {
	wrapper: null,
	carouselWrapper: null,
	carouselBtns: null,
	carousel: null,
	carouselLi: "",
	nav: null,
	command: "",
	canClick: true,
	canAnim: true,
	SPEED: 1300,
	SPEED2: 500,
	//DISTANCE_BOXES: [500, 600, 700, 800, 900, 1100],
	DISTANCE_BOXES: [50, 100, 150, 200, 250, 300],
	boxesOpt: {
		direction: "right",
		distance: 100,
		times: 1,
		//easing: "easeInOutQuad"
		easing: "easeInOutSine"
	},
	wheel: null,
	btnBack: null,
	init: function(){
		hp.wrapper = $("#above");
		hp.carouselWrapper = hp.wrapper.find("div.carousel_wrapper");
		hp.nav = hp.carouselWrapper.find("div.nav");
		hp.carouselBtns = hp.carouselWrapper.find("a.btn_prev, a.btn_next");
		hp.carousel = hp.carouselWrapper.find("div.carousel");
		//hp.command = hp.carouselLi.find("div.index").find("a");
		hp.wheel = hp.wrapper.find("div.steering_wheel");
		hp.btnBack = hp.wrapper.find("a.back");
		
		hp.loadPages();
		hp.showHp();
		hp.imageRotationIE();
		//hp.bounceBoxes();
	},
	loadPages: function(){
		hp.carouselBtns.hide();
		var url = fiat_respath+"other/loaded/pages_hp.html";
		//var url = hp.carouselWrapper.find("input[type='hidden']").val();
	
		hp.carousel.children("ul").load(url, function(){
			hp.doCarousel();
			hp.carouselBtns.show();
			hp.trackingArrows();
			hp.trigCarousel();
			hp.handleCOA();
			hp.showOurCars();
			var rollingHp = new Rolling();
			//rollingHp.hp();
		});
	},
	doCarousel: function(){
		hp.carouselLi = hp.carousel.children("ul").children("li");
		hp.carouselLi.css('opacity', '0.2').eq(0).css('opacity', '1').addClass("on");
		
		//var data = hp.carouselLi.eq(0).attr("data-trackingHP");//HP sophus tracking when landing: WAITING FOR APPROVAL
		//s3_log(data);
		//$.log(data);
		
		hp.carouselLi.addClass('opaque').eq(0).removeClass('opaque').addClass("on");//ie
		
		
		hp.affordance();
		var loadSocialNetworksCarousel = new LoadSocialNetworks();
		loadSocialNetworksCarousel.loadFB();
		
		hp.carousel.jCarouselLite({
			btnNext: "a.btn_next",
			btnPrev: "a.btn_prev",
			btnGo: hp.command,
			visible: 1,
			speed: hp.SPEED,
			easing: "easeInOutCubic",
			beforeStart: function(){
				hp.carouselLi = hp.carousel.children("ul").children("li");//re-defining the LI to get the cloned ones as well
				hp.carouselLi.removeClass("on").css('opacity', '1');
				hp.carouselLi.removeClass("on opaque");//ie
				
				//hiding buttons to prevent multiple clicks
				//TO DO: finding a better way to do this!
				hp.carouselBtns.fadeOut(200);
				
				hp.canClick = false;
			},
			afterEnd: function(a){
				a.addClass("on");
				//var data = a.attr("data-trackingHP");//HP sophus tracking when changing: WAITING FOR APPROVAL
				//s3_log(data);
				//$.log(data);
				
				hp.carouselLi.not(".on").stop(true, true).animate(
					{
						'opacity':'0.2'
					},
					200, function(){
						//showing again the buttons
						hp.carouselBtns.fadeIn();					
						hp.canClick = true;
					}
				);
				hp.carouselLi.not(".on").addClass('opaque');//ie
				
				hp.affordance();
				
			}
		}).wipetouch({
			preventDefault: false,
			wipeLeft: function(result) {
				hp.nav.find("a.btn_next").trigger('click');
			},
			wipeRight: function(result) {
				hp.nav.find("a.btn_prev").trigger('click');
			}
		});
	},
	trackingArrows: function(){
		hp.carouselBtns.click(function(){
			var data = $(this).attr("data-tracking");
			s3_log(data);//sending data to sophus
			$.log(data);
		});
	},
	trigCarousel: function(){
		hp.wheel.children("a").click(function(e){
			if( hp.canClick ){
				( $(this).hasClass("lft") ) ? hp.nav.find("a.btn_prev").trigger("click") : hp.nav.find("a.btn_next").trigger("click");
			}
			e.preventDefault();
		});
	},
	showOurCars: function(){
		hp.carouselLi.find("div.show_our_cars").click(function(){
			//$(".hp .above_wider > table:first-child").addClass("off");//ie7
			hp.carouselWrapper.fadeOut();
			hp.wheel.hide();
		});
	},
	showHp: function(){
		hp.btnBack.click(function(e){
			$(".hp .above_wider > table:first-child").removeClass("off");//ie7
			hp.carouselWrapper.fadeIn();
			hp.wheel.show();
			e.preventDefault();
			//e.stopPropagation();
		});
	},
	handleCOA: function(){
		hp.carouselLi.find("div.empty").each(function(){
			$(this).find("a.coa_trig").click(function(e){
			
				var rel = $(this).attr("rel").split("_")[1];
				
				$("div.grid_inner").find("div.box01").eq(rel).find("a.coa").trigger("click");//trigger the opening of the COA according to the position of the box of the inner grid
				
				hp.carouselWrapper.fadeOut();
				hp.wheel.hide();
				e.preventDefault();
			});
		});
	},
	bounceBoxes: function(){		
		hp.wrapper.find("a.btn_prev, a.btn_next").click(function(e){			
			// re-defining direction according to button clicked
			( $(this).hasClass("btn_prev") ) ? hp.boxesOpt.direction = "right" : hp.boxesOpt.direction = "left";
			
			// 6 are the classes of the boxes. 
			//TO DO: make the number dynamic.
			for( var i = 1; i <= 6; i++ ){
				hp.animateBoxes(i);
			}
			
			e.preventDefault();
			e.stopPropagation();
		});		
	},
	animateBoxes: function(n){
		// re-defining distances inserting values stored into the array. -1 because the for loop starts from 1
		hp.boxesOpt.distance = hp.DISTANCE_BOXES[n-1]; 
		
		hp.carousel.find("div.box.x_" + n).stop(true, true).effect( "bounce", hp.boxesOpt, hp.SPEED );	
	},
	affordance: function(){
		var li = hp.carousel.find("li.on");
		hp.nav.find("a.btn_prev, a.btn_next").hover(
			function(){
				hp.moving(li, $(this));
			},
			function(){
				li.animate({
					left: '0',
					right: '0'
				}, hp.SPEED2, hp.boxesOpt.easing, function(){ hp.canAnim = true });
			}
		);
	},
	moving: function(li, link){
		if( hp.canAnim ){
			hp.canAnim = false;
			
			hp.carouselLi.css({
				left: 'auto',
				right: 'auto'
			});
			
			if( link.hasClass("btn_prev") ){
				hp.carousel.find("li.on").animate({
					left: '8px'
				}, hp.SPEED2, hp.boxesOpt.easing, function(){ hp.canAnim = true });
			} else {
				hp.carousel.find("li.on").animate({
					right:'8px'
				}, hp.SPEED2, hp.boxesOpt.easing, function(){ hp.canAnim = true });
			}
		}
	},
	imageRotationIE: function(){
		if( $.browser.msie && $.browser.version < 9){
			hp.wheel.find("img").attr("src", fiat_respath+"img/sprite_wheel.png").css("margin-left", "-1342px");
			
			var opt = {
				SPEED: 40,//defining the timing. It's 1 second / fps (1000/25=40)
				FPS: 25,
				step: 122
			};
	
			var animationOn = false;
			var loopCounter = 0;
			var t;
			var $this;
			var _self = this;
			var img = hp.wheel.find("img");
			
			var moveLeft = function(){
				var margin = parseInt(img.css("margin-left"));
				
				opt.FPS = ( img.width()/2 ) / opt.step;//the loop is as long as the img width / the actual step
				
				img.css({
					marginLeft: (margin + opt.step) + "px"
				});
				
				loopCounter ++;

				if( loopCounter > opt.FPS ){
					//_self.reset();
					_self.stop(true);
				}
			};
			
			var moveRight = function(){
				var margin = parseInt(img.css("margin-left"));
				
				opt.FPS = ( img.width()/2 ) / opt.step;//the loop is as long as the img width / the actual step
				
				img.css({
					marginLeft: (margin - opt.step) + "px"
				});
				
				loopCounter ++;

				if( loopCounter > opt.FPS ){
					//_self.reset();
					_self.stop(false);
				}
			};
			
			hp.wheel.find("a.lft").hover(
				function(){
					if (animationOn) {return;}
					animationOn = true;
					$this = $(this);
					t = setInterval(moveLeft, opt.SPEED);
				},
				function(){
					$this = $(this);
					_self.reset();
				}
			);
			hp.wheel.find("a.rgt").hover(
				function(){
					if (animationOn) {return;}
					animationOn = true;
					$this = $(this);
					t = setInterval(moveRight, opt.SPEED);
				},
				function(){
					$this = $(this);
					_self.reset();
				}
			);
			
			this.reset = function(){
				loopCounter = 0;
				animationOn = false;
				window.clearInterval(t);
				img.css({
					marginLeft: '-1342px'
				});
			};
			this.stop = function(isLeft){//stop animation at last step
				var endPoint = isLeft ? 0 : -(img.width()-opt.step);
				animationOn = false;
				window.clearInterval(t);
				img.css({
					marginLeft: endPoint+'px'
				});
			}
		}
	}
};

var layerHeader = {
    a: null,
	t: null,
    div: null,
	SPEED: 800,
    init: function(){
        layerHeader.a = $(".main_nav a.ddown");
        layerHeader.div = $(".dropdown-container div.dropdown");
        
		layerHeader.callbacks();
    },
    callbacks: function(){
		layerHeader.a.closest("li").hover(
			function(){
				var el = $(this).children("a");
				var fn = function(){ layerHeader.showingDDown(el) };
				layerHeader.t = setTimeout(fn, layerHeader.SPEED);//using setTimeout to prevent accidental hover
				
				//hiding our cars layer when showing the dropdown menu
				ourCars.container.css({display: "none"});
			},
			function(){	
				layerHeader.div.hide();
				window.clearInterval(layerHeader.t);
			}
		);
    },
	showingDDown: function(el){
		layerHeader.div.hide();

		var overClass = "." + el.attr("class").split(" ")[1];
	
		layerHeader.div.filter(overClass).appendTo( el.closest("li") ).slideDown(layerHeader.SPEED);
	}
};

var globalNav = { //loadContent
	speed: {
		A: 800,
		B: 500,
		C: 300
	},
	height: {
		H: 365,
		F: 300
	},
	isOpenHeader: false,
	isOpenFooter: false,
	t: null,
	above: null,
	below: null,
	header: null,
	footer: null,
	secondNav: null,
	footerNav: null,
	contacts: null,
	wrapper: null,
	content: null,
	choose: null,
	radio: null,
	myFiat: null,
	search: null,
	searchRes: null,
	path: fiat_respath+"other/loaded/global_nav/",
	init: function(){
		globalNav.above = $("#above");
		globalNav.below = $("#below");
		globalNav.header = $("#header_inner");
		globalNav.footer = $("#footer_inner");
		//globalNav.footerNav = globalNav.footer.find(".nav").children("li");		
        globalNav.footerNav = globalNav.footer.find(".nav li").children("a");

		globalNav.wrapper = $("div.content_wrapper");
		globalNav.content = globalNav.wrapper.find("div.content");
		globalNav.secondNav = globalNav.header.find("div.secondary_nav").find("a[class]");
		globalNav.myFiat = globalNav.header.find("div.myfiat");
		globalNav.contacts = globalNav.header.find("div.contacts");
		globalNav.choose = globalNav.contacts.find("div.choose");
		globalNav.radio = globalNav.contacts.find("div.radio");
		globalNav.search = globalNav.header.find("div.input_text").find("input[type=text]"); 
		globalNav.searchRes = globalNav.header.find("div.search_results");
		
		globalNav.handleLoading();
		globalNav.showSearchRes();
	},
	loadContentHeader: function(content, name, fn){
		if(!globalNav.isOpenHeader){//qnd e ancora chiuso
			//if( content.indexOf(".html") !=-1 ){
			//if( content.indexOf(".") !=-1 ){
			globalNav.wrapper
				.show() //showing the container
				.find("." + name) //filtering the selected
				.html(fiatCom.loading) //ajax loader
				.load(content, function(){ //loading content and executing the callback functions
					for( var i = 0; i < fn.length; i++){
						fn[i]();
					}
				})
				.animate({height: globalNav.height.H}).show();
			/* }else {
				globalNav.wrapper.show().find("." + name).animate({height:globalNav.height.H}).show();
			} */

			globalNav.above.animate({top: '+='+(globalNav.height.H + 20)});//20 is div.content padding-top
			globalNav.below.animate({paddingTop: '+='+(globalNav.height.H + 20)});
			var bgPosTop = ( parseInt(globalNav.below.css("padding-top")) + (globalNav.height.H + 20) );
			$("#content").css("backgroundPosition", "0px "+ bgPosTop +"px");
			if( $("div.page_wrapper").length ){
			$("div.page_wrapper").animate({
					paddingTop: (globalNav.height.H +20)
				});
			}
			globalNav.isOpenHeader = true;
		}else{//quando e gia aperto
			//if( content.indexOf(".") !=-1 ){
				globalNav.wrapper
					.show() //showing the container
					.find("." + name) //filtering the selected
					.html(fiatCom.loading) //ajax loader
					.load(content, function(){ //loading content and executing the callback functions
						for( var i = 0; i < fn.length; i++){
							fn[i]();
						} 
					})
					.height(globalNav.height.H).show();
			/* }else {
				globalNav.wrapper.show().find("." + name).height(globalNav.height.H).show();
			} */
		}	
	},
	loadContentFooter: function(content, name, fn){
		if(!globalNav.isOpenFooter){//qnd e ancora chiuso
			//if( content.indexOf(".html") !=-1 ){
			//if( content.indexOf(".") !=-1 ){
			globalNav.wrapper
				.show() //showing the container
				.find("." + name) //filtering the selected
				.html(fiatCom.loading) //ajax loader
				.load(content, function(){ //loading content and executing the callback functions
					for( var i = 0; i < fn.length; i++){
						fn[i]();
					} 
				})
				.animate({height: globalNav.height.F}).show();
			/*} else {
				globalNav.wrapper.show().find("." + name).animate({height:globalNav.height.F}).show();
			} */
			globalNav.isOpenFooter = true;
		}else{//quando e gia apetrto
			//if( content.indexOf(".") !=-1 ){
				globalNav.wrapper
					.show() //showing the container
					.find("." + name) //filtering the selected
					.html(fiatCom.loading) //ajax loader
					.load(content, function(){ //loading content and executing the callback functions
						for( var i = 0; i < fn.length; i++){
							fn[i]();
						} 
					})
					.height(globalNav.height.F).show();
			/* }else {
				globalNav.wrapper.show().find("." + name).height(globalNav.height.F).show();
			} */
		}
	},
	handleLoading: function(){
		globalNav.secondNav.click(function(e){
			//sendCaptcha = new SendCaptcha(globalNav.contacts);
			
            var _this = $(this);
			//var name = $(this).attr("class").split(" ")[0],
			//var name = _this.siblings("input[type='hidden']").val();
			//fn = [ globalNav.handleMyFiat, sendCaptcha.createCaptcha, globalNav.handleContacts, globalNav.trigCloseHeader ]; //the array is needed for Add This functions in the footer
            
            if ( !_this.attr("rel") ) {return;}
			var name = _this.attr("href");

            //var fn = [ globalNav.handleMyFiat, sendCaptcha.createCaptcha, globalNav.handleContacts, globalNav.trigCloseHeader ]; //the array is needed for Add This functions in the footer
            var fn = [ globalNav.handleMyFiat, globalNav.handleContacts, globalNav.trigCloseHeader ]; //the array is needed for Add This functions in the footer
			
			globalNav.secondNav.removeClass("on");
            var parent = _this.parent();
			_this.addClass("on");
			
			globalNav.content.hide();
			//globalNav.loadContentHeader( fiat_respath + globalNav.path + name + ".html", name, fn);
			globalNav.loadContentHeader(name + " #content-to-load", _this.attr("class").split(" ")[0], fn);
				
			/* var data =_this.attr("data-tracking");
			s3_log(data);
			$.log(data); */
			e.preventDefault();
			//return false;
		});
		
		globalNav.footerNav.click(function(e){
            var _this = $(this);
			//var name = _this.attr("class").split(" ")[0];
			
			//var name = _this.siblings("input[type='hidden']").val();
            if ( !_this.attr("rel") ){return;}
			var name = _this.attr("href");

            var	loadSocialNetworks = new LoadSocialNetworks(),/** da fare: vedere se e' meglio caricarlo da un'altra parte -> infatti genera errore su ie7 **/
				fn = [ globalNav.trigCloseFooter, loadSocialNetworks.loadAddThis, loadSocialNetworks.initAddThisFooter ]; //creating an array with the Add This functions
				
			globalNav.footerNav.removeClass("on");
            //$(this).addClass("on");
            var parent = _this.parent();
			_this.addClass("on");
			
			globalNav.content.hide();
			//globalNav.loadContentFooter( fiat_respath + globalNav.path + name + ".html", name, fn);
			globalNav.loadContentFooter( name + " #content-to-load", _this.attr("class").split(" ")[0], fn);
			globalNav.t = setTimeout("globalNav.pageScroll()", globalNav.speed.C);
			
			e.preventDefault();
            //return false;
		});
	},
	handleContacts: function(){
		//first choice
		globalNav.choose.find("a").live('click', function(e){
			var category = $(this).closest("li").attr("class"),
				type = $(this).attr("class");
			
			globalNav.contacts.find("div.selection_wrapper").hide(); // hiding all
			globalNav.contacts.find("." + category).show().find("." + type).show();	//showing the right one		
			
			if( category === 'suggestions' ){//checkForm for Suggestions				
				var step = $("div.suggestions").children("div:visible").find("div[class*='step']");
				privacyHandler.init(step);
				var formName = $("div.suggestions").children("div:visible").find("div.form").parent("div").attr("class");				
				checkForm( formName, step );	
			}
			
			e.preventDefault();
		});
		
		//second choice
		globalNav.radio.find("input[type=radio]").live('click', function(e){
			var $this = $(this),
				category = $this.parents(".box").children("h3").text(),
				subcategory = $this.next("span").text(),
				step = $this.closest("div[class*=step]").next("div[class*=step]"),
				formName = step.find("div.form").parent("div").attr("class");
			
			step.prev().hide();
			step.find(".category").text(category); 	
			step.find(".subcategory").text(subcategory);	
			step.show();	
			
			privacyHandler.init(step);
			checkForm(formName, step);
			
			e.preventDefault();
		});
	},
	handleMyFiat: function(){
		var formName = globalNav.myFiat.find("div.login_form").attr("class");
		checkForm(formName, globalNav.myFiat);
	},
	showSearchRes: function(){
		globalNav.searchRes.slideUp();
		
		globalNav.search.keyup(function(){
			if( $(this).val().length >= 3 ){
				globalNav.searchRes.slideDown("slow");
			} else {
				globalNav.searchRes.slideUp("slow");
			}
		});
	},
	pageScroll: function(){		
		var pos = globalNav.footerNav.offset().top;
		var el = ( $.browser.webkit ) ? fiatCom.body : $("html");
		
		el.animate({
			scrollTop: pos
		}, globalNav.speed.A);		
	},
	closeHeader: function(){
		globalNav.wrapper.eq(0).find("div.content").animate({
			height: 0
			},	function(){
				$(this).hide();
			});
		globalNav.above.animate({top: '-='+(globalNav.height.H +20)});
		globalNav.below.animate({paddingTop: '-='+(globalNav.height.H +20)});
		var bgPosTop = ( parseInt(globalNav.below.css("padding-top")) - (globalNav.height.H +20) );
		$("#content").css("backgroundPosition", "0px "+ bgPosTop +"px");
		globalNav.isOpenHeader = false;
		globalNav.header.find("div.secondary_nav").find("a.on").removeClass("on");
		if( $("div.page_wrapper").length ){
			$("div.page_wrapper").animate({
				paddingTop: 0
			});
		}
	},
	closeFooter: function(){
		globalNav.wrapper.eq(1).find("div.content").animate({
			height: 0
			},	function(){
				$(this).hide();
			});
		globalNav.isOpenFooter = false;
		globalNav.footer.find(".nav").find("a.on").removeClass("on");
	},
	trigCloseHeader: function(){
		globalNav.header.find("div#content-to-load").find("a.close").eq(0).click(function(e){
			//alert("sd");
			globalNav.closeHeader();
			e.preventDefault();
		});
	},
	trigCloseFooter: function(){
		globalNav.footer.find("div#content-to-load:visible").find("a.close").eq(0).click(function(e){
			globalNav.closeFooter();
			//return false;
			e.preventDefault();
		});
	},
	showOurCars: function(){
		var t;
		globalNav.header.find("a.our_cars").hover(
			function(){
				var url = $(this).attr("href");
				var fn = function(){ ourCars.init(url) };

				t = setTimeout(fn, globalNav.speed.A);
				s3_log("/our-cars/");
				//$.log(data);
			},
			function(){
				window.clearInterval(t);
			}
		);
	}
};

function TrackClicks(){
	/* this.tracking = function(container){ //parameter is necessary to find loaded content. For static content, parameter is $("body")
		container.find("*[data-tracking]").click(function(){
			var data = $(this).attr("data-tracking");
			//$.log(data);
			s3_log(data);
		});	
	};	 */
	this.tracking = function(container){ //parameter is necessary to find loaded content. For static content, parameter is $("body")
		//$.log(container);
		container.delegate("[data-tracking]", "click", function(){
			var data = $(this).attr("data-tracking");
			s3_log(data);
			$.log('TrackClicks: '+data);
			//return false;
		});	
	};	
};

function Rolling(){
	var opt = {
		SPEED: 40,//defining the timing. It's 1 second / fps (1000/25=40)
		FPS: 25,
		step: ""
	};
	
	var animationOn = false;
	var animationEnded = false;
	var loopCounter = 0;
	var t;
	var $this;
	var _self = this;
	this.obj = $("div.cell");
	
	var move = function(){
		var margin = parseInt($this.find("img").css("margin-left"));
		
		opt.step = ( $this.closest("div.row").hasClass("one") ) ? 149 : 300;
		if ( $('#layout').hasClass('hp') ) {
			opt.step = 148;
		}
		opt.FPS = $this.find("img").width() / opt.step;//the loop is as long as the img width / the actual step
		
		$this.find("img").css({
			marginLeft: (margin - opt.step) + "px"
		});
		
		loopCounter ++;
		//$.log('loopCounter: '+loopCounter+'  opt.FPS: '+opt.FPS)
		//if( loopCounter == opt.FPS-1 ){
		if( loopCounter >= opt.FPS-1 ){
			_self.freeze();
			animationEnded = true;
		} else {
			animationEnded = false;
		}
		/* if( loopCounter == opt.FPS ){
			//loopCounter = 0;
			_self.restart();
		} */
	};
	var moveBack = function(){
		var margin = parseInt($this.find("img").css("margin-left"));
		/* 
		opt.step = ( $this.closest("div.row").hasClass("one") ) ? 149 : 300;
		if ( $('#layout').hasClass('hp') ) {
			opt.step = 148;
		}
		opt.FPS = $this.find("img").width() / opt.step;//the loop is as long as the img width / the actual step
		 */
		$this.find("img").css({
			marginLeft: (margin + opt.step) + "px"
		});
		
		loopCounter --;
		//$.log('BACK loopCounter: '+loopCounter+'  opt.FPS: '+opt.FPS)
		if( loopCounter <= 0 ){
			_self.reset();
		}
	};
	
	if ( !$('#layout').hasClass('hp') ) {
		this.obj.hover(
			function(){
				if (animationOn) {return;}
				animationOn = true;
				$this = $(this);
				t = setInterval(move, opt.SPEED);
			}, 
			function(){
				$this = $(this);
				_self.reset();
			}
		);
	} else {//hp: animation rolls back on mouse out
		this.obj.hover(
			function(){
				if (animationOn) {return;}
				animationOn = true;
				$this = $(this);
				t = setInterval(move, opt.SPEED);
			}, 
			function(){
				if (!animationEnded) {
					_self.freeze();
				}
				if (animationOn) {return;}
				animationOn = true;
				$this = $(this);
				t = setInterval(moveBack, opt.SPEED);
			}
		);
	}
	
	this.reset = function(){
		loopCounter = 0;
		animationOn = false;
		window.clearInterval(t);
		$this.find("img").css({
			marginLeft: 0
		});
	},
	this.freeze = function(){
		//loopCounter = 0;
		animationOn = false;
		window.clearInterval(t);
		//$this.find("img").css({
			//marginLeft: 0
		//});
	}/* ,
	this.restart = function(){
		loopCounter = 0;
		//animationOn = false;
		//window.clearInterval(t);
		$this.find("img").css({
			marginLeft: 0
		});
	} */
};

var campaigns = {
	//rtUrl: window.location.protocol+'//'+window.location.hostname,
	ajaxOpt: {
		//mkt: "1000",//useless: it's already printed in page as fiat_marketcode
		lang: "5"//italian
	},
	wrapper: null,
	select: null,
	selectLi: null,
	resetBtn: null,
	cars: null,
	c_results: null,
	resultList: null,
	splittedRel: [],
	splittedIndex: 0,
	init: function(){
		campaigns.wrapper = $("div.campaigns");
		campaigns.select = campaigns.wrapper.find("div.select");
		campaigns.selectLi = campaigns.select.find("li");
		campaigns.resetBtn = campaigns.select.find("a.close_select");
		campaigns.cars = campaigns.wrapper.find("div.carousel").find("li");
		campaigns.c_results = $("div.campaigns_results");
		campaigns.resultList = campaigns.c_results.find("ol.results_list");
		campaigns.resultWrap = campaigns.c_results.find("div.results_wrapper");
		
		campaigns.modelFiltering();
		campaigns.hideSelect();
		campaigns.resetAll();
		campaigns.doCarousel();
		campaigns.handleResults();
		campaigns.doAccordion();
	},
	modelFiltering: function(){
		campaigns.select.find("ul.filters").delegate("a", "click", function(){
			var $this = $(this),
				thisParent = $this.parent("li"),
				adjacents = thisParent.siblings("li"),
				liHeight = campaigns.selectLi.parent("ul").height(),
				ulHeight = campaigns.selectLi.height(),
				modelName = $this.text(),
				rel = $this.attr("rel");
			//if the select is closed, open it up
			if (ulHeight === liHeight) {
				campaigns.selectLi.show();
			} else {
				
				thisParent.addClass("on").show();
				adjacents.removeClass("on").hide();
				
				campaigns.cars.removeClass("on");
				campaigns.cars.find("a").filter("[rel=" + rel + "]").closest("li").addClass("on");
				
				campaigns.c_results.find("div.heading").hide();//hiding the CTA
				campaigns.resultWrap.show().find("h4").text(modelName);//writing model name
				
				campaigns.splittedRel = [];//reset
				campaigns.splittedIndex = 0;//reset
				
				campaigns.splittedRel = rel.split('_');
				switch (campaigns.splittedRel.length) {
					case 0:
						//$.log('0');
						return false;
					break;
					case 1:
						fiatCom.multiple = false;
						//$.log('1');
						//campaigns.c_results.find("h5").remove();//empty the DOM
						//campaigns.c_results.find("ol.results_list").remove();//empty the DOM
						campaigns.resultList.empty();
						campaigns.resultWrap.append(fiatCom.loading);
						var data = "MODEL="+rel+"|ALLYEARS=Y";
						campaigns.ajaxCall(data, campaigns.printYears);
						
					break;
					default:
						fiatCom.multiple = true;
						//$.log('+1');
						//campaigns.c_results.find("h5").remove();//empty the DOM
						//campaigns.c_results.find("ol.results_list").remove();//empty the DOM
						campaigns.resultList.empty();
						campaigns.resultWrap.append(fiatCom.loading);
						//for (var i=0,l=splittedRel.length; i<l; i++) {
							//var data = "MODEL="+splittedRel[i]+"|ALLYEARS=Y";
							//campaigns.ajaxCall(data, campaigns.printYears);
							var data = "MODEL="+campaigns.splittedRel[campaigns.splittedIndex]+"|ALLYEARS=Y";
							campaigns.ajaxCall(data, campaigns.printYears);
						//}
				}
				
				
				//campaigns.resultList.attr('rel',rel).html(fiatCom.loading);
				
				
				
			}
			return false;
		});
	},
	hideSelect: function(){
		fiatCom.body.click(function(){
			campaigns.selectLi.hide();
			
			//if exists a LI with class on, show it, else show the first one
			(campaigns.selectLi.hasClass("on")) ? campaigns.select.find("li.on").show() : campaigns.selectLi.eq(0).show();
		});
	},
	resetAll: function(){
		campaigns.resetBtn.click(function(e){
			campaigns.selectLi.removeClass("on").hide();
			campaigns.selectLi.eq(0).show();
			campaigns.cars.removeClass("on");
			campaigns.resultList.html("");//empty the DOM
			//campaigns.c_results.find("h5").remove();//empty the DOM
			//campaigns.c_results.find("ol.results_list").remove();//empty the DOM
			campaigns.c_results.find("div.heading").show();//showing the CTA
			campaigns.resultWrap.hide();
			
			e.preventDefault();
		});
	},
	doCarousel: function(){
		if( campaigns.cars.length > 5 ){
			campaigns.wrapper.find("a.btn_prev").addClass("disabled");
			campaigns.wrapper.find("div.carousel").jCarouselLite({
				btnNext: "a.btn_next",
				btnPrev: "a.btn_prev",
				visible: 5,
				circular: false,
				speed: 300
			});
		}else{
			campaigns.wrapper.find("a.btn_prev, a.btn_next").addClass("disabled");
		}
	},
	doAccordion: function(){
		//campaigns.c_results.delegate("li.c_number", "click", function(){
		campaigns.resultList.delegate("li.c_number", "click", function(){
			var $this = $(this);
			var year = $this.attr("id").split('_')[1];
			var id = $this.attr("id").split('_')[2];
			var rel = $this.closest('ol.results_list').attr('rel');
			var data = "YEAR="+year+"|MODEL="+rel+"|ID="+id;
			
			if( $this.hasClass("open") ){return}
			campaigns.resultList.find("li.c_number.open").removeClass("open").children('ul.results_content').slideUp();
			//campaigns.c_results.find("ol.results_list").find("li.c_number.open").removeClass("open").children('ul.results_content').slideUp();
			//$this.toggleClass('open').children('ul.results_content').slideToggle();
			//campaigns.ajaxCall( "ID = " + id, campaigns.printDetails);
			
			//$.log('esistenza dettagli: '+ $this.find("ul.results_content").length );
			if( $this.find("ul.results_content").length>0 ){
				$this.addClass('open').children('ul.results_content').slideDown()
			} else {
				$this.append(fiatCom.loading);
				campaigns.ajaxCall(data, campaigns.printDetails);
			}
			
			
		});
	},
	handleResults: function(){
		campaigns.cars.parent("ul").delegate("a", "click", function(e){
			var $this = $(this);
			if ($this.hasClass('btn')){
				var modelName = $this.prev('a').text();
			} else {
				var modelName = $this.text();
			}
			var rel = $this.attr("rel");
			var data = "MODEL="+rel+"|ALLYEARS=Y";
			
			campaigns.cars.removeClass("on");
			campaigns.cars.find("a").filter("[rel=" + rel + "]").closest("li").addClass("on");
			campaigns.selectLi.removeClass("on");
			campaigns.selectLi.find("a").filter("[rel=" + rel + "]").closest("li").addClass("on");
			
			campaigns.c_results.find("div.heading").hide();//hiding the CTA
			campaigns.resultWrap.show().find("h4").text(modelName);//writing model name
			
			//campaigns.resultList.attr('rel',rel).html(fiatCom.loading);
			
			campaigns.splittedRel = [];//reset
			campaigns.splittedIndex = 0;//reset
			
			campaigns.splittedRel = rel.split('_');
				
				switch (campaigns.splittedRel.length) {
					case 0:
						//$.log('0');
						return false;
					break;
					case 1:
						fiatCom.multiple = false;
						//$.log('1');
						//campaigns.c_results.find("h5").remove();//empty the DOM
						//campaigns.c_results.find("ol.results_list").remove();//empty the DOM
						campaigns.resultList.empty();
						campaigns.resultWrap.append(fiatCom.loading);
						var data = "MODEL="+rel+"|ALLYEARS=Y";
						campaigns.ajaxCall(data, campaigns.printYears);
						
					break;
					default:
						fiatCom.multiple = true;
						//$.log('+1');
						//campaigns.c_results.find("h5").remove();//empty the DOM
						//campaigns.c_results.find("ol.results_list").remove();//empty the DOM
						campaigns.resultList.empty();
						campaigns.resultWrap.append(fiatCom.loading);
						//for (var i=0,l=splittedRel.length; i<l; i++) {
							//var data = "MODEL="+splittedRel[i]+"|ALLYEARS=Y";
							var data = "MODEL="+campaigns.splittedRel[campaigns.splittedIndex]+"|ALLYEARS=Y";
							campaigns.ajaxCall(data, campaigns.printYears);
						//}
				}
			
			//campaigns.ajaxCall(data, campaigns.printYears);
			
			e.preventDefault();
		});
	},
	ajaxCall: function(data, callback){
		$.ajax({
			type: "POST",
			//url: "http://auth.carconfigurator.fiat.com/ProductCatalog.asmx?op=getCallBackCampaigns?market="+mkt+"&brand=00&codLanguage="+lang+"&filters=",
			//url: campaigns.rtUrl+'/transport.php?action=http://auth.carconfigurator.fiat.com/ProductCatalog.asmx/getCallBackCampaigns',
			//url: '/webservices/carconf/ProductCatalog.asmx?op=getCallBackCampaigns',
			url: '/webservices/carconf/ProductCatalog.asmx/getCallBackCampaigns',//panacea
			//contentType: "application/x-www-form-urlencoded",
			dataType: 'xml',
			//data: "market=" + fiat_marketcode + "&brand="+ fiat_brandcode +"&codLanguage=" + campaigns.ajaxOpt.lang + "&filters=" + encodeURIComponent(data) + "",//get
			data: {market:fiat_marketcode, brand:fiat_brandcode, codLanguage:campaigns.ajaxOpt.lang, filters:data},
			cache: true,
			complete: function(){
				campaigns.resultWrap.find('div.loading').remove();
			},
			success: function(data){
				var response = data;
				callback(response);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				var sStatus = XMLHttpRequest.status;
				var sResponse = XMLHttpRequest.responseText;
				var sXml = XMLHttpRequest.responseXml;
				alert('http status: '+sStatus+', text response entity body: '+sResponse+', document response entity body: '+sXml+', type of error: '+textStatus);
			}
			/* error: function(){
				layerError = new Layer();//create a new layer for the error message
				layerError.init();
				layerError.loaderWrapper.addClass("error_status");//setting class for style
				layerError.writeLayer();
			} */
		});
	},
	printYears: function(response){
		var currentModel = $(response).find("CAMPAIGNS").children("LIST").children("CALLBACK");
		var modelId = currentModel.attr('model');
		var modelName = currentModel.text().split('-')[0];//weak solution...
		//var code = '<h5 id="model_'+modelId+'">'+modelName+'</h5>';
		//var code = '<ol class="results_list" rel="'+modelId+'">';
		var list = $(response).find("CAMPAIGNS").find("LIST");
		var code = '';
		
		if ( fiatCom.multiple ) {
			list.each(function(index){
				if (index == list.length-1) {//avoid last iteration: it seems redundant
					return false;
				}
				code = '';
				var $this = $(this);
				var year =  $this.attr("year");
				//$.log('year----'+year+'-----');
				if ( campaigns.resultList.find('li.year_'+year).length==0 ) {
					//$.log('0');
					code += '<li class="year year_'+year+'">' + year;
					//$.log(code);
					
				}
				code += 	"<ul>";
				
				$this.find("CALLBACK").each(function(){
					var $this = $(this);
					var id = $this.attr("id");
					var txt = $this.text();
					
					code +=	'<li class="c_number" id="c_'+ year +'_'+ id +'">'+ txt +' - '+ printMsg('campaigns', 'campaign') +' '+ id + '</li>';
				});
				
				code += 	"</ul>";
				if ( campaigns.resultList.find('li.year_'+year).length==0 ) {
					code += "</li>";
					//$.log('00-'+code);
					campaigns.resultList.append(code);
				} else {
					//$.log('01-'+code);
					campaigns.resultList.find('li.year_'+year).append(code);
				}
			});
			//$.log('indice '+campaigns.splittedIndex);
			//$.log('totale '+campaigns.splittedRel.length);
			campaigns.splittedIndex++;
			if ( campaigns.splittedIndex<campaigns.splittedRel.length ) {
				var data = "MODEL="+campaigns.splittedRel[campaigns.splittedIndex]+"|ALLYEARS=Y";
				campaigns.ajaxCall(data, campaigns.printYears);
			} else {
				//campaigns.resultList.find('li.year').tsort('',{order:'desc'});
				//$.log('finito');
				
				//var list = $()document.getElementById('mylist');
				var items = campaigns.resultList.children('li.year');
				items.sort(function(a, b) {
					return a.innerHTML == b.innerHTML
									? 0
									: (a.innerHTML < b.innerHTML ? 1 : -1);
				});
				for (i = 0; i < items.length; ++i) {
					campaigns.resultList.append(items[i]);
				}
				
				
				
			}
		} else {
			list.each(function(index){
				if (index == list.length-1) {//avoid last iteration: it seems redundant
					return false;
				}
				var $this = $(this);
				var year =  $this.attr("year");
				
				code += "<li class='year'>" + year;
				code += 	"<ul>";
				
				$this.find("CALLBACK").each(function(){
					var $this = $(this);
					var id = $this.attr("id");
					var txt = $this.text();
					
					code +=	'<li class="c_number" id="c_'+ year +'_'+ id +'">'+ txt +' - '+ printMsg('campaigns', 'campaign') +' '+ id + '</li>';
				});
				
				code += 	"</ul>";
				
				code += "</li>";
			});
			campaigns.resultList.append(code);
		}
		
		//code += "</ol>";
		//campaigns.resultList.html(code);
		//var h5 = campaigns.resultWrap.find('h5');
		//if ( fiatCom.multiple ) {
			//modelName = modelName.replace(' ','');//trim blank spaces
			//var anchor = '<a href="#model_'+modelId+'">'+modelName+'</a>';
			//campaigns.resultWrap.find('h4').append(anchor);
			//h5.show();
		//} else {
			//h5.hide();
		//}
	},
	printDetails: function(response){
		var detail = $(response).find("DETAILS");
		var year = detail.attr("year");
		var id = detail.attr("id");
		var code = "";
		
		code +=	"<ul class='results_content'>";
		
		detail.find("DETAIL").each(function(){
			var $this = $(this);
			var name = $this.attr("name");
			var txt = $this.text();
				
			code +=	"<li>";
			code +=		"<span>"+name+"</span>";
			code +=		"<span class='c_code'>"+txt+"</span>";
			code +=	"</li>";
		});
		
		code +=	"</ul>";
		
		//var li = campaigns.resultList.find("li.c_number").filter("[id=" + id + "]");
		var li = campaigns.c_results.find("li.c_number").filter('[id="c_' +year+ '_' +id+ '"]');
		
		//if( li.find("ul.results_content").length ){return}//stop appending if there's already an UL
		li.append(code);
		
		
		li.addClass('open').children('ul.results_content').slideDown();
		
	}
};

////////////////////////////////////////////////////
 // AIR TECH - start
////////////////////////////////////////////////////

function RenderLayout(){
	this.pageWrapper =  $("div.page_wrapper");
	this.container = this.pageWrapper.find("div.container");
	this.select = this.pageWrapper.find("div.select");
	this.cars_filters = this.pageWrapper.find("ul.cars a");
	fiatCom.element = this.pageWrapper.find("div.element");
};

RenderLayout.prototype = {
	init: function(trigger){
		
		//setting isotope's options
		var opt = {
			masonry: {
				rowHeight: 140,
				columnWidth: 5
			},
			getSortData : {
				green : function( $elem ) {
					return parseInt( $elem.find('span.green').text(), 10 );
				},
				simple : function( $elem ) {
					return parseInt( $elem.find('span.simple').text(), 10 );
				},
				fun : function( $elem ) {
					return parseInt( $elem.find('span.fun').text(), 10 );
				},
				save : function( $elem ) {
					return parseInt( $elem.find('span.save').text(), 10 );
				},
				power : function( $elem ) {
					return parseInt( $elem.find('span.power').text(), 10 );
				},
				engines : function( $elem ) {
					return parseInt( $elem.find('span.engines').text(), 10 );
				},
				fuels : function( $elem ) {
					return parseInt( $elem.find('span.fuels').text(), 10 );
				},
				efficient : function( $elem ) {
					return parseInt( $elem.find('span.efficient').text(), 10 );
				},
				heritage : function( $elem ) {
					return parseInt( $elem.find('span.heritage').text(), 10 );
				},
				qubo : function( $elem ) {
					return parseInt( $elem.find('span.qubo').text(), 10 );
				},
				punto : function( $elem ) {
					return parseInt( $elem.find('span.punto').text(), 10 );
				},
				bravo : function( $elem ) {
					return parseInt( $elem.find('span.bravo').text(), 10 );
				},
				f500 : function( $elem ) {
					return parseInt( $elem.find('span.f500').text(), 10 );
				},
				doblo : function( $elem ) {
					return parseInt( $elem.find('span.doblo').text(), 10 );
				},
				panda : function( $elem ) {
					return parseInt( $elem.find('span.panda').text(), 10 );
				}
			},
			sortAscending : false,
			animationEngine : 'best-available',
			animationOptions: {
				duration: 450,
				easing: 'linear',
				queue: false
			}
		};
		
		this.closeSelect(trigger, this.select);
		this.expandSelect(this.container, fiatCom.element, trigger, this.select, opt);
		this.reArrangeSelect(this.container, fiatCom.element, trigger, this.select, opt);
		this.resetPage(trigger, this.select, this.container, opt);
		this.loadContent(this.container, fiatCom.element, this.cars_filters, this.select, opt);
		this.setFilters(fiatCom.element, trigger);
		this.startIsotope(this.container, opt);
		layerAirTech.init();
        combo.init();
	},
	setFilters: function(el, trigger){
		var filters = [];
		
		trigger.each(function(){
			var _this = $(this),
				filterName = _this.attr('href').split('=')[1];
			
			if(jQuery.inArray(filterName,filters) == -1){
				filters.push(filterName);
			}
		});

		el.each(function(){
			var _this = $(this),
				code = '';
			
			for(var i=0, len=filters.length; i<len; i++){
				code += '<span class="'+filters[i]+'">';
				
				(_this.hasClass(filters[i])) ? code += '1' : code += '0';
				
				code += '</span>';
			}

			_this.prepend(code);
		});
	},
	startIsotope: function(obj, opt){
		obj.isotope(opt);
	},
	triggerFiltering: function(obj, el, _this, trigger, opt){
		var $this = _this,
			$optionSet = $('ul.filters');
		
		if($this.hasClass('selected')){return false;}

		$optionSet.find('.selected').removeClass('selected');
		$this.addClass('selected');
		
		// make option object dynamically, i.e. { filter: '.my-filter-class' }
		var options = {},
			value = $this.attr('href').split('=')[1];

		options[ 'sortBy' ] = value;
		
		//which select I clicked
		if(_this.parents().hasClass("cars")){
			var classSorting = _this.attr("href").split("=")[1],
				img_src = _this.find("img").attr("src").split(".")[0],
				path = 'img',
				ext = '.png',
				img_bg_src = img_src+"_big"+ext,
				$newItems = $('<div class="box4 element added '+classSorting+'"><div class="img_wrapper"><img src="'+img_bg_src+'" alt="" width="460" height="300"/></div></div>');
			
			//reset isotope options
			obj.isotope( 'destroy' );
			
			//insert spans for sorting
			RenderLayout.prototype.setFilters($newItems, trigger);
			
			//prepending new elements and init isotope 
			obj.prepend($newItems)
				.isotope(opt)
				.isotope( 'reloadItems' )
				.isotope( 'updateSortData', $newItems )
				.isotope({sortBy: value });
		}else{
			obj.isotope( options);
		}
		
		//to keep the opacity to 0.2 if I click again and again on the same voice of the menu
		if($this.parent("li").hasClass("on")){
			el.css('opacity','1');
			el.not('.'+value).css('opacity','0.2');
		}else{
			el.not('.'+value).animate({'opacity':'0.2'},800);
		}		 	
	},
	expandSelect: function(obj, el, trigger, select, opt){
		var firstTrigger = trigger.eq(0);
		
		firstTrigger.click(function(){
			
			var _this = $(this),
				parent = _this.closest("li"),
				adjacents = parent.siblings();//,
				//liH = parent.height();
			
			parent.hide();
			adjacents.show();
			adjacents.eq(5).addClass("on");
		
			var selectH = select.height();
			
			select.addClass('opened').css({
				//height: selectH,
				top:-(selectH/2)+"px"
			});
			
			return false;
		});
	},
	reArrangeSelect: function(obj, el, trigger, select, opt){
		var li = $("ul.filters > li"),
			selectHorigin = (li.height() * li.length),
			cars = $("ul.cars"),
			liCars = cars.find("a"),
			firstTrigger = trigger.eq(0),
			liWord = trigger.not(firstTrigger).not(liCars);
		
		liCars.click(function(){
			var _this = $(this),
				parent = _this.parents(".cars").parent(),
				adjacents = parent.siblings(),
				carName = _this.find("img").attr("alt").split(" ")[1];
			
			select.removeClass('opened');
			adjacents.removeClass("on").hide();
			parent.addClass("on").show();
			cars.hide();
			
			combo.setDriving(carName);
			
			// setting select position
			var toTop = combo.driving.position().top;	
			select.css({
				top:-(toTop/2)+"px"
			});
			
			// removing added items if any
			var added = $("div.added");
			if( added.length != 0 ){ obj.isotope(opt).isotope( 'remove', added ).isotope('reLayout') };

			//do the filtering
			RenderLayout.prototype.triggerFiltering(obj, el, _this, trigger, opt);
			return false;
		});	
		
		liWord.click(function(){
			
			var _this = $(this),
				parent = _this.parent("li"),
				adjacents = parent.siblings();
				
			if ( _this.hasClass("driving") && select.hasClass("opened") ) {return false};
			
            layerAirTech.closeLayer();
			trigger.eq(0).parent("li").hide();
			adjacents.removeClass("on").hide();
			parent.addClass("on").show();
      
            cars.show();
			
			//Open or close select
			//If the select is closed, open it up
			if( !select.hasClass("opened") ){
				select.addClass('opened').css({
					top: -(selectHorigin/2)+"px"
				});
				adjacents.not(adjacents.eq(0)).show();
			}else{
				select.removeClass('opened').css({
					top: 0
				});
				// removing added items if any
				var added = $("div.added");
				if( added.length !=0 ){ obj.isotope(opt).isotope( 'remove', added ).isotope('reLayout'); }
				//do the filtering only when re-opening the select
				RenderLayout.prototype.triggerFiltering(obj, el, _this, trigger, opt);
			}
			
			return false;
		});	
	},
	closeSelect: function(trigger, select){
		this.pageWrapper.click(function(){
			RenderLayout.prototype.hideSelect(trigger,select);
		});
	},
    hideSelect: function(trigger, select){
		var liOn = trigger.parent("li.on");
			
		if (liOn.length==0)	return false;
		if(select.height() < $("ul.filters > li:first").height()){return false;}
		
		trigger.parents("ul.filters").children("li").hide();
		liOn.show();	
		liOn.find("ul.cars").hide();

		select.removeClass("opened").css({
			top:0
		});
    },
	resetPage: function(trigger, select, obj, opt){
			var firstLi = trigger.eq(0).parent("li"),
				otherLi = firstLi.siblings("li"),
				filters =  $("ul.filters");
				
		$("div.close_select a").click(function(e){
			layerAirTech.closeLayer(true);
            $(".added").hide().remove();
			firstLi.show();
			otherLi.hide();
			select.css({
				top: 0
			});
			//layerAirTech.closeLayer();

            filters.children("li").hide();
            filters.find("li").removeClass("on");
            $("ul.filters li:first").show();

            combo.setDriving("");
            var ulCars = filters.find("ul.cars");
            if (ulCars.is(":hidden")) ulCars.show();
			
			obj.find(".isotope-item").css({opacity: 1});//re-setting full opacity when re-setting the page
			obj.isotope('destroy').isotope(opt);
           
			e.preventDefault();
			//return false;
		});
	},
	loadContent: function(obj, el, trigger,select, opt){
		var box = $("div.container > .element > div:first-child"),
			boxParent = $("div.container > .element");
	
		
		box.click(function(e){
			var _this = $(this),
				thisParent = _this.parent(),
				name = thisParent.attr('class').split(' ')[0];
			
			e.stopPropagation();
			RenderLayout.prototype.hideSelect(trigger,select);
			
			//now open a new one			
			//closing the other layer before opening a new one
			if(layerAirTech.loader.is(":visible")){
				layerAirTech.closeLayer(true);
			} 
			
			thisParent.append(layerAirTech.loader);
			
			layerAirTech.loader.closest(boxParent).css({
				zIndex: 100,
				opacity: 1
			});
			
			layerAirTech.obj = obj;				
			
            layerAirTech.reArrangeLayout(name, thisParent, trigger, opt);            
		});
	}
};

var combo = {
    driving: null,
    span: null,
    cars: null,
    init: function(){
        combo.driving=$("div.page_wrapper a.driving");
        combo.span=combo.driving.find("span");
        combo.cars=combo.driving.siblings("ul.cars");
    },
    setDriving: function(value){
        combo.span.html(value);
    }
};

var layerAirTech = {
	loader: null,
	loaded_content: null,
	close: null,
	obj: null,//initialized in RenderLayout.prototype.loadContent()
	init: function(){
		layerAirTech.loader = $("div.loader");
		layerAirTech.loaded_content = layerAirTech.loader.find("div.loaded_content");
		layerAirTech.close = layerAirTech.loader.find("a.close");
		layerAirTech.callbacks();
	},
	reArrangeLayout: function(content, thisParent, trigger, opt){
		//console.log("reArrangeLayout");
		thisParent.addClass('auto');
		thisParent.find("div:first").addClass("large");
		layerAirTech.populateContent(content, trigger, opt)	
	},
	populateContent: function(content, trigger, opt){
		//$(".element").removeClass("pad");
		layerAirTech.loader.stop().fadeIn(function(){            
            layerAirTech.loaded_content.html($(".preload").find("."+content+"_html").clone());
            layerAirTech.loader.parent().height(layerAirTech.loader.outerHeight(true));
                
			//layerAirTech.obj.isotope('reLayout');
			setTimeout("layerAirTech.obj.isotope('reLayout')",600);

			//layerAirTech.obj.isotope('reLayout');

			layerAirTech.loaded_content.find("ul.cars a").click(function(){
				var _this = $(this),
					ulFilters=$("ul.filters > li"),
					carName = _this.find("img").attr("alt").split(" ")[1];
			  
				$(".added").remove();
				combo.setDriving(carName);
				ulFilters.removeClass("on").hide();
				ulFilters.last().addClass("on").show();
				
				combo.cars.hide();
				combo.driving.show();
			   
				RenderLayout.prototype.triggerFiltering(layerAirTech.obj, fiatCom.element, _this, trigger, opt);
				layerAirTech.closeLayer();

				return false;
			});
		});
	},
	closeLayer: function(stopIsotope){
        if (layerAirTech.obj!=null&&layerAirTech.loader.is(":visible")){
			var h = layerAirTech.loader.parent(fiatCom.element).hasClass("box1") || layerAirTech.loader.parent(fiatCom.element).hasClass("box2") ? 140 : 300;
		    layerAirTech.loader.parent(".auto").removeClass("auto");
		    layerAirTech.loader.siblings(".large").removeClass('large');
		    layerAirTech.loader.hide().find(layerAirTech.loaded_content).html('');
			layerAirTech.loader.parent(fiatCom.element).css('height', h);
		
		    if (!stopIsotope) setTimeout("layerAirTech.obj.isotope('reLayout')",600);//layerAirTech.obj.isotope('reLayout');
        }
	},
	callbacks: function(){
		layerAirTech.close.click(function(){
			layerAirTech.closeLayer();
			return false;
		});
	}
};


////////////////////////////////////////////////////
 // AIR TECH - end
////////////////////////////////////////////////////

/************ UGO *********/
function startPage() {
	/* if($(".special").length){pageSpecial()};
	if($("div.gucci:not(.isotope-item)").length){pageSpecialGucci()};// :not is necessary to avoid adding the bg in Fiatpedia */
	handleSpecialEditions();

  if($('.accordion').length){jQuery('.accordion').accordion();}
  if($('.autoheight').length){autoheight()};
  if($('.img_external').length){verticalCenterImg()};
  if($('.tables-drag').length){tables.init($('.tables-drag'))};
  if($('.lights').length){lights.init();};
  if($('.haccordion').length){haccordion()};
  if($('.game_imgslide.two').length){
	//imgslide.init();
	var opt = {
			step: 2,
			stepTime: 500,
			sliderStep: 100
		};
	var imgSlide = new ImgSlide( opt );
	imgSlide.start();
  };
  if($('.game_imgslide.three').length){
	//imgslide.init();
	var opt = {
			step: 3,
			stepTime: 500,
			sliderStep: 50,
			startPos: 0
		};
	var imgSlide = new ImgSlide( opt );
		$('.game_imgslide').find('span.start').click(function(){
		imgSlide.start();
		//imgSlide.automate();
	});
	
	
	//imgSlide.start();
  };
  if($('.game_imgslide.five').length){
	//imgslide.init();
	var opt = {
			step: 5,
			stepTime: 500,
			sliderStep: 25
		};
	var imgSlide = new ImgSlide( opt );
	
	$('.game_imgslide').find('span.start').click(function(){
		imgSlide.start();
		imgSlide.automate();
	});
  };
  if($(".stickmenu").length){stickMenu()};
  if($(".center_x").length){centerX()};
  if($(".media_video").length){mediavideo()};
  if($(".slideshow").length){slideSwitch.init()};
  if($(".gallery_item").length){gallery.init()};
  if($("div.five_sec_wrapper").length){ var rolling = new Rolling(); }
  removeEmpty();//removes empty <p>
  trigBuild();
  openObj( $("#below a.tdrive") );
  if($("div.compare_selector").length){tableCompareEngines.init();}
	if( !($.browser.msie && $.browser.version < 9) ){
		//alert('non ie');
		if( $("div.ytplayer").length ){initYT();}
	} //else {
		//console.log('ciriciao');
	//}
}
function haccordion(){
  $('.haccordion').each(function(){
    var $this = $(this),
		wrapper_w = $this.width(),
        header_w = $this.find('.header').width(),
        header_n = $this.find('.header').length -1,
		my_width = wrapper_w - header_w * header_n;
		
    $this.haccordion({'contentwidth': my_width});
    $('.header',this).eq(0).click();
  });
}
function autoheight(){
	var maxH = 0;
	$('.autoheight').each(function(){
		var el;
		$(this).children('div').each(function(){
			$(this).children('.box').is('div') ? $el = $(this).children('.box') : $el = $(this);
			var myH = $el.innerHeight();
			myH > maxH ? maxH = myH : maxH;
		});
		$(this).children('div').each(function(){
			$(this).children('.box').is('div') ? $el = $(this).children('.box') : $el = $(this);
			var padT = $el.css('paddingTop').replace("px", ""),
			padB = $el.css('paddingBottom').replace("px", "");
			$el.height(maxH - padT - padB);
		});
	maxH = 0;
	});
}

function verticalCenterImg(){
	$('.img_external').each(function(){
		var myH = $(this).find('img').height(),
			innerH = $(this).find('.inner').innerHeight();
		$(this).height(myH);
		$(this).find('.inner').css('margin-top', '-' + parseInt(innerH + (myH-innerH)/2, 10) + 'px');
	});
}
function centerX(){
  $('.center_x').each(function(){
    var myW = $(this).innerWidth(),
        contentW = $(this).parent().width();
    $(this).css('margin-left',  Math.floor((contentW - myW)/2) + 'px');
  });
}
/* function pageSpecial(){
	$('#layout').addClass('special');
	//$('.nav_top_second ul').css('margin-left', (960-$('.nav_top_second li').length * $('.nav_top_second li').width())/2);
}
function pageSpecialGucci(){
	$('#layout').addClass('special gucci');
	//$('.nav_top_second ul').css('margin-left', (960-$('.nav_top_second li').length * $('.nav_top_second li').width())/2);
} */

function handleSpecialEditions(){
	if($(".special").length){
		$('#layout').addClass('special');
	}
	if($("div.gucci:not(.isotope-item)").length){// :not is necessary to avoid adding the bg in Fiatpedia
		$('#layout').addClass('special gucci');
	}
	
	if($('div.below_content div.special').length<=0 && $('div.below_content div.special.gucci').length<=0){
		$("#layout").removeClass('special').removeClass('gucci');
	}
	if($('div.below_content div.special').length>0 && $('div.below_content div.special.gucci').length<=0){
		$("#layout").removeClass('gucci');
	}
}

////////////////////////////////////////////////////
 // LOAD PAGE
////////////////////////////////////////////////////
var origContent = "";
var loadPage = {
	firstNav: '.nav-top',
	secondNav: '.nav_top_second',
	container : 'div.below_content',
	belowInner: 'div.below_inner',
	start: true,
	lastTab: '', // per attivare sempre il load
	init: function(){
		loadPage.trigCarouselFlag();
		loadPage.trigViewAll(); 
		loadPage.trigInnerLink(); 
		loadPage.handleLanding();
		
		if ( !$.support.pjax ) {//ie
			loadPage.action();//toppa
			if(document.location.href.indexOf('#') != -1){
				myurl = document.location.href.split('#')[1];
				var $myA = $(loadPage.firstNav).find("a[href='" + myurl + "']");
				loadPage.checkNav($myA);
			}
		} else {
			loadPage.pjaxAction();
		}

    /*
	  loadPage.action();
    if(document.location.href.indexOf('#') != -1){
      myurl = document.location.href.split('#')[1];
      var $myA = $(loadPage.firstNav).find("a[href='" + myurl + "']");
      loadPage.checkNav($myA);
    }
    */

	},
	pjaxAction : function(){
		$(loadPage.firstNav + ' a').pjax(loadPage.container, {fragment: loadPage.container, timeout: 5000});
		$(loadPage.container)
		.bind('pjax:start', function(event) {
			$(loadPage.belowInner).height( $(loadPage.belowInner).height() );//setting the height to prevent page resizing when emptying the DOM
			$(loadPage.container).html(fiatCom.loading);
		})
		.bind('pjax:end', function(event, response) {
			var myurl = window.location.href;
    
			var startUrl = "";
			if(myurl.indexOf('http') != -1){
			  startUrl = myurl.split('/')[2];
			} else {
			  startUrl = myurl.split('/')[0];
			}
			myurl = myurl.split(startUrl)[1];	
	
			var $myA = $(loadPage.firstNav).find("a[href='" + myurl + "']");
			loadPage.initPage($myA);
			loadPage.makeActive($myA);
			
/* 			if($('div.below_content div.special').length<=0 && $('div.below_content div.special.gucci').length<=0){
				$("#layout").removeClass('special').removeClass('gucci');
			}
			if($('div.below_content div.special').length>0 && $('div.below_content div.special.gucci').length<=0){
				$("#layout").removeClass('gucci');
			} */
			
			if( $myA.parent(".active").find("div.nav_top_second").length == 0 ){//removing margin-bottom necessary only if there's a second nav menu
				$myA.parent(".active").css("margin-bottom", "0");
			}
		});
	},
	action: function(){
		$(loadPage.firstNav + ' a').click(function(e){
			var $this = $(this);
			$('iframe').remove();
			$('div.ytplayer').remove();
			
			loadPage.makeActive($this);
			
			/* console.log('special: '+$('div.below_content div.special').length);
			console.log('special gucci: '+$('div.below_content div.special.gucci').length);
			
			if($('div.below_content div.special').length<=0 && $('div.below_content div.special.gucci').length<=0){
				$("#layout").removeClass('special').removeClass('gucci');
			}
			if($('div.below_content div.special').length>0 && $('div.below_content div.special.gucci').length<=0){
				$("#layout").removeClass('gucci');
			} */
			
			if( $this.parent(".active").find("div.nav_top_second").length == 0 ){//removing margin-bottom necessary only if there's a second nav menu
				$this.parent(".active").css("margin-bottom", "0");
			}
			loadPage.checkNav($this);
			loadPage.position($this);
			e.preventDefault();
			e.stopPropagation();
		});
	},
	hashTolink : function(hash){
		hash = hash.replace('#', '');
		link = hash;
		$myA = $('.nav-top a[href="' + link + '"]');
		link += ' div.below_content';
		loadPage.makeActive($myA);
		loadPage.makeTab(link);
		loadPage.position($myA);
	},  
	makeActive : function(el){
		$(loadPage.firstNav + " li").removeClass("active");
		el.parent().addClass("active");
		var $closest = el.closest('div');
		if($closest.attr('class') != "nav-top"){
			$closest.parent().addClass("active");
		}
	},
	position : function(myA){
		var pos = ( myA.parents("div.nav_top_second").hasClass("nav_top_second") ) ?  myA.parents("div.nav-top").offset().top : myA.offset().top,
			el = ( $.browser.webkit ) ? fiatCom.body : $("html");
		if( $(window).scrollTop() != pos  ){//using the if to avoid continuous call if the user is already at the menu
			el.animate({scrollTop: pos}, 500);//scroll the page to the menu
		}
	},
	checkNav: function(el_link){
		if(el_link){
			var myurl = el_link.attr('href');
		}

		document.location.hash = myurl;
	},
	checkNum: function(num){
		if(num === -1){num=0};
		num < 10 ? num = '0' + num : num;
		return num;
	},
	makeTab: function(link){
		$(loadPage.belowInner).height( $(loadPage.belowInner).height() );//setting the height to prevent page resizing when emptying the DOM
		$(loadPage.container).html(fiatCom.loading);
		$(loadPage.container).load(link, function(){
			startPage();
			$(loadPage.belowInner).css("height", "auto");//resetting the height to default
			$("div.content").height( $("div.content").find("img").height() );//forzare altezza contenuto accordion
			dragtable.start = false;
			dragtable.init();
		});
	},
	initPage: function(el){
		startPage();
		loadPage.position(el);
		$(loadPage.belowInner).css("height", "auto");//resetting the height to default
		$("div.content").height( $("div.content").find("img").height() );//forzare altezza contenuto accordion
		dragtable.start = false;
		dragtable.init();
	},
	trigCarouselFlag: function(){
		$("ul.flags.mp").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			var url = $(this).attr("href");
			var link = $(loadPage.secondNav).find("a[href='"+url+"']");
			if( link.length ){
				link.trigger("click").parent().parents("li").addClass("active");
			}
			e.preventDefault();
		});
	},
	trigViewAll: function(){//view all others trims
		$("div.model_panel div.view_all").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			//var url = $(this).attr("href");
			$(handleTab.secondNav).find("li").eq(0).children('a').trigger("click").parent().parents("li").addClass("active");
			e.preventDefault();
		});
	},
	trigInnerLink: function(){
		$("#below .below_content").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			var url = $(this).attr("href");
			var link = $(loadPage.secondNav).find("a[href='"+url+"']");
			if( link.length ){
				link.trigger("click").parent().parents("li").addClass("active");
				e.preventDefault();
			}
		});
	},
	handleLanding: function(){
		var myurl = window.location.href;
		var startUrl = "";
		if(myurl.indexOf('http') != -1){
		  startUrl = myurl.split('/')[2];
		} else {
		  startUrl = myurl.split('/')[0];
		}
		myurl = myurl.split(startUrl)[1];
		if ( myurl.indexOf('?')!=-1 ) {//cleaning up all parameters to permit perfect match
			myurl = myurl.substring(0, myurl.indexOf('?'));
		}
		if ( myurl.indexOf('#')!=-1 ) {//cleaning up anchor to permit perfect match
			myurl = myurl.substring(0, myurl.indexOf('#'));
		}
		
		//$.log('myurl: '+myurl);
		//$.log('startUrl: '+startUrl);
		//var count = myurl.match(/\//g);//regex: looking for / occurrences
		//$.log(count.length);
		//if ( count.length >= 3 ) {//more than 2 '/' means a subpage, so scroll down to below
		var status = GetUrlParam('status');
		//$.log( typeof(status) );
		if ( status === "" ) {
			var $myA = $(".nav-top").find("a[href='" + myurl + "']");
			//$.log($myA);
			loadPage.makeActive($myA);//make active the right menu tab
			loadPage.position($myA);//scroll to right section
			if( $myA.parent(".active").find("div.nav_top_second").length == 0 ){//removing margin-bottom necessary only if there's a second nav menu
				$myA.parent(".active").css("margin-bottom", "0");
			}
		}
	}
};
////////////////////////////////////////////////////
 // HANDLE TAB
////////////////////////////////////////////////////
/* var handleTab = {
	firstNav: '.nav-top',
	secondNav: '.nav_top_second',
	start: true,
	lastTab: '', // per attivare sempre il load
	init: function(){
		$('.below_content').wrap('<div class="handle_tab"/>');
		handleTab.action();
		handleTab.checkNav();
		handleTab.trigCarouselFlag();
		handleTab.trigViewAll();
		handleTab.trigViewAll();
	},
	checkNav: function(el_link){
		var activeFirst = handleTab.checkNum($(handleTab.firstNav + ' .active').eq(0).index()),
			activeSecond = handleTab.checkNum($(handleTab.secondNav + ' .active').index());
		//if(el_link && el_link.parent().parent().parent().attr('class') == handleTab.firstNav.replace('.','')) {activeSecond = '00'}
		if(el_link && el_link.closest('div').attr('class') == handleTab.firstNav.replace('.','')) {activeSecond = '00'}
		var myTab = activeFirst + activeSecond;
		if(el_link){var link = el_link.attr('href') + ' div.below_content';}
		//$('.' + myTab).length ? handleTab.activeTab(myTab) : handleTab.makeTab(myTab, link);
		//$.log(myTab+'|'+link);
		handleTab.makeTab(myTab, link); // per attivare sempre il load
	},
	checkNum: function(num){
		num < 10 ? num = '0' + num : num;
		return num;
	},
	makeTab: function(tab, link){
		var belowInner = $("div.below_inner");
		if (handleTab.start) {
			$('.below_content').wrap('<div class="tab ' + tab + '"/>');
			handleTab.lastTab = $('.' + tab); // per attivare sempre il load
			handleTab.start = false;
		} else {
			//$('.handle_tab').append('<div class="tab ' + tab + '"></div>');//old version without loading gif
			belowInner.height( belowInner.height() );//setting the height to prevent page resizing when emptying the DOM
			$('.handle_tab').html(fiatCom.loading).append('<div class="tab ' + tab + '"></div>');
			

			$('.' + tab).load(link, function(){
				$('.handle_tab').find("div.loading").remove();
				$('.tab').hide();
				$(this).show();
				if(handleTab.lastTab){handleTab.lastTab.remove()};// per attivare sempre il load
				handleTab.lastTab = $(this);// per attivare sempre il load
				startPage();
				belowInner.css("height", "auto");//resetting the height to default
				$("div.content").height( $("div.content").find("img").height() );//forzare altezza contenuto accordion
				dragtable.start = false;
				dragtable.init();
			});
		};
		document.location.hash = tab;
	},
	action: function(){
		$(handleTab.firstNav + ' a, ' + handleTab.secondNav + ' a').click(function(e){
			var $this = $(this);
			$this.parent().siblings().removeClass('active');
			$this.parent().addClass('active');
			if( $("#layout.special").hasClass("special") ){
				$("#layout.special").removeClass("special");
			}
			if( $("#layout.gucci").hasClass("gucci") ){
				$("#layout.gucci").removeClass("gucci").removeClass("special");
			}
			
			if( $this.parent(".active").find("div.nav_top_second").length == 0 ){//removing margin-bottom necessary only if there's a second nav menu
				$this.parent(".active").css("margin-bottom", "0");
			}
			
			handleTab.checkNav($this);
			
			var pos = ( $this.parents("div.nav_top_second").hasClass("nav_top_second") ) ?  $this.parents("div.nav-top").offset().top : $this.offset().top;			
			var el = ( $.browser.webkit ) ? fiatCom.body : $("html");
			
			if( $(window).scrollTop() != pos  ){//using the if to avoid continuous call if the user is already at the menu
				el.animate({//scroll the page to the menu
					scrollTop: pos
				}, 500);				
			}		
			
			
			e.preventDefault();
			e.stopPropagation();
			//return false;
		});
	},
	trigCarouselFlag: function(){
		$("ul.flags.mp").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			var url = $(this).attr("href");
			
			if( $(handleTab.secondNav).find("a[href=' "+url+" ']").length ){
				$(handleTab.secondNav).find("a[href=' "+url+" ']").trigger("click").parent().parents("li").addClass("active");
			}
			e.preventDefault();
		});
	},
	trigViewAll: function(){//view all others trims
		$("div.model_panel div.view_all").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			//var url = $(this).attr("href");
			$(handleTab.secondNav).find("li").eq(0).children('a').trigger("click").parent().parents("li").addClass("active");
			e.preventDefault();
		});
	},
	trigInnerLink: function(){
		$("#below .below_content").delegate("a", "click", function(e){//open the tab relative to the flag clicked and activate the menu
			var url = $(this).attr("href");
			
			if( $(handleTab.secondNav).find("a[href=' "+url+" ']").length ){
				$(handleTab.secondNav).find("a[href=' "+url+" ']").trigger("click").parent().parents("li").addClass("active");
			}
			
			e.preventDefault();
		});
	}
}; */
////////////////////////////////////////////////////
 // SLIDE SHOW
////////////////////////////////////////////////////
var slideSwitch = {
	switchSpeed : 400,
	intervalSpeed: 4000,
	interval : '',
	pause : false,
	click : false,
	maxWidth : 900,
	init : function(){
		var newHtml = '<ul class="slideshow_list">',
			section = [],
			sectionTitle = [],
			i = 0;
		$('.slideshow h2').each(function(){
			var value = $(this).html(),
				title = 'section_' + i;
			section.push(value);
			sectionTitle.push(title);
			$(this).next('ul').find('li').each(function(){
				var src = $(this).find('input').attr('value'),
					myclass = $(this).attr('class');
				newHtml += '<li class="' + myclass + '" title="' + title  + '"><input type="hidden" value="' + src + '"/></li>';
			});
			i++;
		});
		newHtml += '</ul><div class="slideshow_loading"><img src="'+fiat_respath+'img/ajax.gif"/></div>';
		$('.slideshow').html(newHtml);
		slideSwitch.menu(section,sectionTitle);
		slideSwitch.interval = setInterval( "slideSwitch.slide()", slideSwitch.intervalSpeed );
	},
	menu : function(section,sectionTitle) {
		var newhtml = '<div class="slideshow_controls"><div id="slideshow_pause">&nbsp;</div><div class="slideshow_timeline">&nbsp;</div>',
			buttonW = Math.floor((900/section.length)-40);
			newhtml += '<ul class="slideshow_button">';
			i = 0;
		for (i=0; i<section.length;i++){
			newhtml += '<li style="width:' + buttonW + 'px" title="' + sectionTitle[i] + '">' + section[i] + '</li>';
		}
		newhtml += '</ul>';
		newhtml += '</div>';
		$('.slideshow').append(newhtml);
		slideSwitch.menuAction();
		slideSwitch.timeline();
	},
	menuAction : function(){
		var $pause = $('#slideshow_pause');
		$pause.click(function(){
			if(slideSwitch.pause === false) {
				clearInterval(slideSwitch.interval);
				//$('.slideshow_timeline').stop();
			} else {
				//slideSwitch.interval = setInterval( "slideSwitch.slide()", slideSwitch.intervalSpeed );
				slideSwitch.slide();
			}
			$pause.toggleClass('on');
			slideSwitch.pause = ! slideSwitch.pause;
		});
		$('.slideshow_button li').click(function(){
			slideSwitch.changeSection($(this));
			clearInterval(slideSwitch.interval);
			slideSwitch.pause = true;
			var section = $(this).attr('title');
			var $active = $('.slideshow .item.active'),
				$next = $('.slideshow_list li[title="'+section+'"]').eq(0);
			$active.addClass('last-active');
			slideSwitch.click = true;
			slideSwitch.changeImg($active, $next);
		});
	},
	slide : function(){
		var $active = $('.slideshow .item.active'),
			$loading = $('.slideshow_loading');
		if ( $active.length === 0 ) {$active = $('.slideshow .item:last');}
		var $next =  $active.next('.item').length ? $active.next('.item') : $('.slideshow .item:first');
		$active.addClass('last-active');
		var img = new Image();
		src = $next.find('input').attr('value');
		if ($next.find('input').length === 1){
			$loading.show();
			$(img).load(function () {
				clearInterval(slideSwitch.interval);
				$next.html('').append(img);
				slideSwitch.changeImg($active, $next);
				$loading.hide();
				if (slideSwitch.pause === false){slideSwitch.interval = setInterval( "slideSwitch.slide()", slideSwitch.intervalSpeed );}
			}).attr('src', src);
		} else {
			slideSwitch.changeImg($active, $next);
			if (slideSwitch.pause === true){slideSwitch.interval = setInterval( "slideSwitch.slide()", slideSwitch.intervalSpeed );}
		}
	},
	changeImg : function($active, $next){
		$next.css({opacity: 0.0}).addClass('active').stop().animate({opacity: 1.0}, slideSwitch.switchSpeed, function() {
			var startTimeline = $active.index() + 1,
				endTimeline = $next.index() + 1;
			$('.slideshow .item').removeClass('active last-active');
			$next.addClass('active');
			slideSwitch.changeSection($next);
			slideSwitch.timeline(startTimeline,endTimeline);
			if( slideSwitch.click){
				slideSwitch.click = false;
				slideSwitch.pause = false;
				slideSwitch.interval = setInterval("slideSwitch.slide()", slideSwitch.intervalSpeed );
			};
		});
	},
	timeline : function(start, end){
		var $timeline = $('.slideshow_timeline'),
			end = Math.floor(end * slideSwitch.maxWidth / $('.slideshow .item').length),
			start = end - Math.floor(slideSwitch.maxWidth / $('.slideshow .item').length);
		if(isNaN(end)){end=0};
		if(isNaN(start)){start=0};
		$timeline.stop().width(start).animate({width: end}, slideSwitch.intervalSpeed, function(){
			if ($timeline.width() === 900 ){ $timeline.width(0)};
		});
	},
	changeSection : function(el){
		var mysection = el.attr('title');
		$('.slideshow_button li').removeClass('on');
		$('.slideshow_button li[title=' + mysection + ']').addClass('on');
	}
};
////////////////////////////////////////////////////
 // GALLERY
////////////////////////////////////////////////////
var gallery = {
	startScroll : 0,
	init : function(){
		var newHtml = '<div class="gallery_dinamic">',
			galleryList = '<div class="gallery_comand"><div class="gallery_list"><h2></h2><ul>',
			i = 0;
		newHtml += '<div id="gallery" class="content"><div id="controls" class="controls"></div><div class="slideshow-container"><div id="loading" class="loader"></div><div id="mygallery" class="slideshow"></div></div><div id="caption" class="caption-container"></div></div>';
		$('.gallery_item').each(function(){
			var title   = ($(this).find("h2").length) ? $('h2',this).html() : "",
				mygallery = 'gallery_' + i;
			$('a',this).addClass(mygallery);
			newHtml     += '<div class="gallery_dinamic_item" id="' + mygallery + '">';
			newHtml     += gallery.convertInput($(this), title);
			newHtml     += '</div>';
			galleryList += '<li class="' + mygallery + '">' + title + '</li>';
			i++;
		});
		newHtml += '</div>';
		galleryList += '</ul></div><div class="gallery_download"><p>Download</p></div><div class="gallery_share"></div><div class="gallery_open_thumbs"><span class="tooltip">'+printMsg('gallery', 'tooltipThumb')+'</span></div><div class="gallery_exit"><span class="tooltip">'+printMsg('gallery', 'tooltipClose')+'</span></div></div>';
		$('.below').append(newHtml);
		$('#gallery').append(galleryList);
		if($('.gallery_item').length == 1 & ($('.gallery_item h2').html() == "" || $('.gallery_item h2').length == 0)){
			$('.gallery_list').hide();
			$('.gallery_comand').css('width', '160px');
		}    
		gallery.action();
	},
	convertInput : function(el, title){
		imgs = '<ul class="thumbs noscript">';
		$('input', el).each(function(){
			var val   = $(this).attr('value');
			thumb = val.split(',')[0],
			img   = val.split(',')[1];
			imgs += '<li><a class="thumb" alt="'+title+'" href="' + img + '"><img src="' + thumb + '" alt="'+title+'"/></a><div class="caption"><div class="download"></div><div class="image-title"></div><div class="image-desc"></div></div></li>'
		});
		imgs += '</ul>';
		return imgs;
	},  
	action: function(){
		$('.gallery_item a').click(function(e){
			gallery.startScroll = $(window).scrollTop();
			if($('.blockUI').length){
				var myGallery = $(this).attr('class');
				$('html').css({'height': $(window).height(), 'width' : '100%', 'overflow' : 'hidden'});
				gallery.activateGallery(myGallery);
				//var myT = $(window).scrollTop();
				var myT = 0;
				$('.blockPage').css('top',myT);
				$('.blockUI').show();
			} else {
				gallery.block();
				var myGallery = $(this).attr('class'),
					activeGallery = $('#' + myGallery);
				activeGallery.addClass('on done');
				$('.gallery_list .' + myGallery).addClass('on');
				$('.gallery_list h2').html($('.gallery_list .' + myGallery).html());
				gallery.makeGallery(activeGallery);
				$('.gallery_dinamic_item').css('display','none');
				$('.image-wrapper img').live('mouseover', function(){
					$(this).draggable({ containment: "html", scroll: false });
					$('.image-wrapper img').css('display', 'none');
					$('.image-wrapper img.ui-draggable').css('display', 'block');
				});
			}
			$(window).scrollTop(0);
			e.preventDefault();
		});
		$('.gallery_list li').live('click',function(){
			var myGallery = $(this).attr('class');
			gallery.activateGallery(myGallery);
		});
		$('.gallery_exit').live('click', function(){
		$('html').css({'height': 'auto', 'width' : 'auto', 'overflow' : 'auto'});
		$('.blockUI').hide();
			$(window).scrollTop(gallery.startScroll);
		});
		$('.gallery_open_thumbs').live('click', function(){
			$('.gallery_dinamic_item.on').toggle();
			$(this).toggleClass('on');
		});
		$('.gallery_download').live('click', function(){$(this).toggleClass('on')});
	},
	activateGallery : function(myGallery){
		var activeGallery = $('#' + myGallery);
		$('.gallery_list li').removeClass('on');
		$('.gallery_list .' + myGallery).addClass('on');
		$('.gallery_list h2').html($('.gallery_list .' + myGallery).html());
		if (activeGallery.attr('class').indexOf('done') == -1){
			gallery.makeGallery(activeGallery);
			$('.gallery_dinamic_item').css('display','none');
		};
		$('.gallery_dinamic_item').removeClass('on').css('display','none');
		activeGallery.addClass('on done');
		activeGallery.find('li').eq(0).find('a').click();
	},
	block : function(){
		//var myT = $(window).scrollTop();
		var myT = 0;
		$.blockUI({
			message: $('.gallery_dinamic').html(),
			overlayCSS:  { backgroundColor: '#000', opacity: 1 },
			css: { top: myT, left: '0px', cursor: 'default', border: 'none', background: 'none', position: 'absolute', width: '100%', 'text-align': 'left'}
		});
		$('html').css({'height': $(window).height(), 'width' : '100%', 'overflow' : 'hidden'});
		$('.below .gallery_dinamic').remove();
	},
	makeGallery : function(activeGallery){
		var gallery = activeGallery.galleriffic({
			delay:                     2500,
			numThumbs:                 4,
			preloadAhead:              10,
			enableTopPager:            true,
			enableBottomPager:         true,
			maxPagesToShow:            5,
			imageContainerSel:         '#mygallery',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true,
			renderNavControls:         true,
			playLinkText:              'Play Slideshow',
			pauseLinkText:             'Pause Slideshow',
			prevLinkText:              '&lsaquo; Previous Photo',
			nextLinkText:              'Next Photo &rsaquo;',
			nextPageLinkText:          'next',
			prevPageLinkText:          'prev',
			enableHistory:             false,
			autoStart:                 false,
			syncTransitions:           true,
			defaultTransitionDuration: 900
		});
	}
};
////////////////////////////////////////////////////
 // TABLES
////////////////////////////////////////////////////
var tables = {
  headings: {
    generic_rows: null,
    inner_rows: null,
    inner_cols: null,
    inner_table: null,
    inner_th: null
  },
  features: {
    generic_rows: null,
    inner_rows: null,
    inner_cols: null,
    inner_table: null,
    inner_th: null
  },
  init: function(container){
    //initialize properties
    tables.headings = container.find(".headings");
    tables.headings.generic_rows = tables.headings.find("tr");
    tables.headings.inner_rows = tables.headings.find("tbody").children("tr");
    tables.headings.inner_cols = tables.headings.inner_rows.children("td");
    tables.headings.inner_table =  tables.headings;
    tables.headings.inner_th = tables.headings.find("tbody").find("th");
    
    tables.features = container.find(".features");
    tables.features.generic_rows = tables.features.find("tr");
    tables.features.inner_rows = tables.features.find("tbody").children("tr");
    tables.features.inner_cols = tables.features.inner_rows.children("td");
    tables.features.inner_table =  tables.features;
    tables.features.inner_th = tables.features.find("tbody").find("th");
    
    
    // calling methods
    tables.equalizeHeight();
    tables.accordion();
    if ($('.table-compare').length){tables.compare(tables.headings.inner_rows, tables.features.inner_rows)};
    tables.findEqual();
    
    
    tables.slide = new Carousel_Slide(
      tables.features.inner_table, // obj
      container.find("button"), // btns
      {  //options
        step: parseInt(tables.features.inner_cols.outerWidth()),//calculate columns' width
        visible: 4,
        lft: 0,
        total: tables.features.find('thead').find('th').length,
        btn_next: container.find(".next"),
        btn_prev: container.find(".prev")
      }
    );
  },
  slide: null,
  equalizeHeight: function(){
    tables.headings.generic_rows.each(function(index){
      var $this = $(this);
      $this.children().eq(0).wrapInner('<div/>');
      var left_H = $this.height(),
          right_H = tables.features.generic_rows.eq(index).height(),
          h = Math.max(left_H,right_H);
      $this.height(h);
      tables.features.generic_rows.eq(index).height(h);
    });
    //tables.features.height( tables.headings.height() );
  },
  accordion: function(){
    tables.headings.inner_cols.parent().addClass('tr_close');
    tables.features.inner_cols.parent().addClass('tr_close');
    tables.headings.inner_th.parent().addClass('fine');
    tables.features.inner_th.parent().addClass('fine');

    tables.headings.inner_th.click(function(){
      var $this = $(this),
          par = $this.parent(),
          clicked = par.index();
      par.nextUntil('tr.fine').toggleClass('tr_close');
      $this.toggleClass('on');
      tables.features.inner_rows.eq(clicked).nextUntil('tr.fine').toggleClass('tr_close');
      tables.changeTop();
      //tables.features.height( tables.headings.height());
    });
    tables.headings.inner_th.eq(0).trigger('click');
  },
  changeTop : function(){
    tables.headings.inner_table.find('tr.fine').each(function(){
      var $this = $(this),
          myTop = $this.position().top,
          myRel = $this.attr('rel');
      $('.tr_equal[rel=' + myRel + ']').css('top', myTop);
    });
  },
  compare : function(headingsgRow, featuresRow){
    $('input[name="compare"]').click(function(){
      var action = $(this).attr('value');
      headingsgRow.removeClass('tr_hide');
      featuresRow.removeClass('tr_hide');
      if (action == "different" || action == "equal"){
        featuresRow.each(function(){
          var equal = true,
              myIndex = $(this).index();
          var val = $(this).find('td').eq(0).text();
          $(this).find('td').each(function(){
            var myval = $(this).text();
            if (!(myval == val)){equal = false};
          });
          if (action == 'equal' & equal == false & featuresRow.eq(myIndex).find('th').length == 0) {
            headingsgRow.eq(myIndex).addClass('tr_hide');
            featuresRow.eq(myIndex).addClass('tr_hide');
          }
          if (action == 'different' & equal == true & featuresRow.eq(myIndex).find('th').length == 0) {
            headingsgRow.eq(myIndex).addClass('tr_hide');
            featuresRow.eq(myIndex).addClass('tr_hide');
          }
        });
      }
    });
  },
  findEqual : function(){
    var myIndex = 0;
    $('.table_wrap tr.fine').each(function(){
      var myT =  $(this).position().top,
          equal = true;
          val = $(this).find('th').eq(0).text();
      $(this).find('th').each(function(){
        var myval = $(this).text();
        if (!(myval == val)){equal = false};
      });
      if (equal === true) {
        $('.table_wrap').append('<div class="tr_equal" rel="' + myIndex + '" style="top:' +myT+ 'px;">' +val+ '</div>');
        tables.headings.inner_table.find('.fine').eq(myIndex).attr('rel', myIndex);
      }
      myIndex ++;
    });
  }
};

var Carousel_Slide = function(obj, btns, opt){
  var defaults = {
    step: 0,
    visible: 1,
    lft: 150,
    total: 0,
    btn_next: null,
    btn_prev: null
  };
  var opt = $.extend(defaults, opt);
  defaults.btn_prev.hide();
  btns.click(function(){
    ($(this).hasClass('next')) ? defaults.lft -= defaults.step : defaults.lft += defaults.step;
    obj.stop().animate(
      {
        'margin-left': defaults.lft
      },
      {
        step: function(){//triggered at every step of animation
          var myLeft = Math.floor(obj.css("margin-left").replace("px", ""));
          myLeft > -(defaults.step)+1 ? defaults.btn_prev.hide() : defaults.btn_prev.show();
          myLeft <= -(defaults.step*(defaults.total-defaults.visible-1)+1) ? defaults.btn_next.hide() : defaults.btn_next.show();
        }
      }
    );
    return false;
  });
};
////////////////////////////////////////////////////
 // LIGHTS
////////////////////////////////////////////////////
var lights = {
  init: function(){
    lights.actions();
  },
  actions : function(){
    var step = 380,
        el = $('.lights img');
    $('.lights_btn').click(function(){
      el.css('margin-top',  -(($(this).index() - 1) * step) + 'px');
      if ( !($('.blockUI').is('div')) ) {lights.overlay();}
      if ($(this).index() == 1) {setTimeout($.unblockUI, 200)}
    });
  },
  overlay : function(){
    var myT = $('.lights').offset().top,
        myL = $('.lights').offset().left;
    $.blockUI({
        message: '<div class="container_12 lights"><div class="grid_9">' + $('.lights').html() + '</div></div>',
        overlayCSS:  { backgroundColor: '#000', opacity: 0.9 },
        css: { top: myT+'px', left: myL+'px', cursor: 'default', border: 'none', background: 'none', position: 'absolute' }
    });
    lights.actions();
  }
};
////////////////////////////////////////////////////
 // GAME IMGSLIDE
////////////////////////////////////////////////////
/* var imgslide = {//originale ugo
  step : 5,
  marginT : 0,
  stepTime : 200,
  moveImg: '',
  init : function(){
    $('.game_imgslide span.start').click(function(){imgslide.start()});
  },
  start : function(){
    $('.game_imgslide').height($('.game_imgslide img').height());
    var maxStep = $('.game_imgslide').height() * imgslide.step,
        imgH = $('.game_imgslide').height(),
        newHtml = '<div id="game_imgslide_slide">&nbsp;</div>';
    newHtml += '<div class="timeline">&nbsp;</div>';
    newHtml += '<div id="slider">&nbsp;</div>';
    $('.game_imgslide').html(newHtml);
    
    $('#game_imgslide_slide').html('<div class="loading"><img src="img/ajax.gif"/></div>');
    var img = new Image();
    $(img).load(function () {
      $('#game_imgslide_slide').html('').append(img);
    }).attr('src', 'img/game-imgslide-slide.jpg');
    
    imgslide.moveImg = setInterval(function(){imgslide.move(maxStep,imgH)}, imgslide.stepTime);
    imgslide.action(imgH);
  },
  move : function(maxStep, imgH){
    imgslide.marginT += imgH;
    imgslide.marginT >= maxStep ? imgslide.marginT = 0 : imgslide.marginT;
    $('.game_imgslide img').css('margin-top', -(Math.floor(imgslide.marginT)) +"px");
  },
  action : function(imgH){
    var slider = $("#slider" ).slider({
      min: 0, 
      step: 25,
      slide: function( event, ui ) {
        clearInterval(imgslide.moveImg);
        imgslide.marginT = ui.value / 25 * imgH;
        $('.game_imgslide img').css('margin-top', -(Math.floor(imgslide.marginT)) +"px");
      }
    });
  }
}; */

/* var ImgSlide = function(opt){//modifica paolo
	var defaults = {
		step: 1,
		stepTime: 100,
		sliderStep: 100,
		startPos: 0
	};
	var opt = $.extend(defaults, opt);
	var _self = this;
	var obj = $('div.game_imgslide');
	var imgSrc = obj.find("input[type=hidden]").val();
	var maxStep = obj.height() * defaults.step;
	var imgH = obj.find("img").height();
	var label = obj.find("div.lbl");
	
	this.marginT = 0;
	this.moveImg = "";
	
	this.start = function(){
		//obj.height( obj.find("img").height() );
		obj.height( imgH );
		
		var newHtml = '<div id="game_imgslide_slide">&nbsp;</div>';
			newHtml += '<div class="timeline">&nbsp;</div>';
			newHtml += '<div id="slider">&nbsp;</div>';
		
		
		obj.html(newHtml);
		
		$('#game_imgslide_slide').html(fiatCom.loading);
		
		var img = new Image();
		
		$(img).load(function(){
			$('#game_imgslide_slide').html(img);
		}).attr('src', imgSrc);
		
		label.find("div.lbl_content").eq(0).addClass("on");//switching on the first label
		label.prependTo(obj);//re-inserting the label in the DOM
		
		//_self.moveImg = setInterval(function(){ _self.move(_self.maxStep, _self.imgH) }, defaults.stepTime);
		_self.action(imgH);
	};
	this.move = function( maxStep, imgH ){
		_self.marginT += imgH;
		( _self.marginT >= maxStep ) ? _self.marginT = 0 : _self.marginT;
		
		obj.find("img").css('margin-top', -( parseInt(_self.marginT, 10) ) +"px");//usare margin-bottom se lo start e a destra?
	};
	this.action = function(imgH){
		var slider = $("#slider").slider({
			step: defaults.sliderStep,
			value: defaults.startPos,
			slide: function( event, ui ) {
				clearInterval( _self.moveImg );
				_self.marginT = parseInt( ui.value / defaults.sliderStep * imgH, 10 );
				obj.find("img").css('margin-top', -( parseInt(_self.marginT, 10) ) +"px");
				label.find("div.on").removeClass("on").siblings().addClass("on");//switching on/off the label
			}
		});
	};
	this.automate = function(){
		_self.moveImg = setInterval(function(){ _self.move( maxStep, imgH) }, defaults.stepTime);
	};
}; */

var ImgSlide = function(opt){//variabili con this
	var defaults = {
		step: 1,
		stepTime: 100,
		sliderStep: 100,
		startPos: 0
	};
	var opt = $.extend(defaults, opt);
	var _self = this;
	this.obj = $('div.game_imgslide');
	this.imgSrc = this.obj.find("input[type=hidden]").val();
	this.maxStep = this.obj.height() * defaults.step;
	this.imgH = this.obj.find("img").height();
	this.label = this.obj.find("div.lbl");	
	this.marginT = 0;
	this.moveImg = "";
	
	this.start = function(){
		_self.obj.height( _self.imgH );
		
		var newHtml = '<div id="game_imgslide_slide">&nbsp;</div>';
			newHtml += '<div class="timeline">&nbsp;</div>';
			newHtml += '<div id="slider">&nbsp;</div>';
		
		
		_self.obj.html(newHtml);
		
		$('#game_imgslide_slide').html(fiatCom.loading);
		
		var img = new Image();
		
		$(img).load(function(){
			$('#game_imgslide_slide').html(img);
		}).attr('src', _self.imgSrc);
		
		_self.label.find("div.lbl_content").eq(0).addClass("on");//switching on the first label
		_self.label.prependTo(_self.obj);//re-inserting the label in the DOM
		
		_self.action(_self.imgH);
	};
	this.move = function( maxStep, imgH ){
		_self.marginT += imgH;
		( _self.marginT >= maxStep ) ? _self.marginT = 0 : _self.marginT;
		
		_self.obj.find("img").css('margin-top', -( parseInt(_self.marginT, 10) ) +"px");//usare margin-bottom se lo start e a destra?
	};
	this.action = function( imgH ){
		var slider = $("#slider").slider({
			step: defaults.sliderStep,
			value: defaults.startPos,
			slide: function( event, ui ) {
				clearInterval( _self.moveImg );
				_self.marginT = parseInt( ui.value / defaults.sliderStep * imgH, 10 );
				_self.obj.find("img").css('margin-top', -( parseInt(_self.marginT, 10) ) +"px");
				_self.label.find("div.on").removeClass("on").siblings().addClass("on");//switching on/off the label
			}
		});
	};
	this.automate = function(){
		var fn = function(){ _self.move( _self.maxStep, _self.imgH ) };
		_self.moveImg = setInterval( fn, defaults.stepTime);
	};
};

ImgSlide.prototype = {

};

////////////////////////////////////////////////////
 // STICK MENU
////////////////////////////////////////////////////
function stickMenu(){
	var $wrapper = $('.stickmenu'),
		$win = $(window),
		menuHtml = '<ul>';
		numLi = 0;

	$('.titles h2').each(function(){
		var ancor = 'title_' + numLi;
		$(this).parent().attr('id', ancor);
		menuHtml += '<li><a rel="' + ancor + '">' + $(this).attr('title') + '</a></li>';
		numLi ++;
	});  
	menuHtml += '</ul>';
	$wrapper.html(menuHtml);
	$('.stickmenu a').width(Math.floor(940/numLi) - 25 + 'px');
	$('.stickmenu a').click(function(){
	$('.stickmenu a').removeClass('on');
		$(this).addClass('on');
	});
	// posizione del menu
	var menu = $('.stickmenu ul'),
		menuPos = menu.offset().top,//posizione verticale del menu (rispetto al document)
		scrollbarPosStart = $win.scrollTop();//posizione verticale della scrollbar prima dello scroll

	$win.scroll(function(){
		var scrollbarPosEnd = $win.scrollTop();//posizione verticale della scrollbar dopo lo scroll
		if(scrollbarPosStart < scrollbarPosEnd && scrollbarPosEnd > menuPos){//vado giu: quando lo scroll arriva al menu, ancoro il menu a top pagina
			if(!($('.faker').length)) {
				$wrapper.append('<div class="faker" />');
				$('.faker').height($wrapper.height());
			}      
			menu.addClass("fix");
		}else if(scrollbarPosStart > scrollbarPosEnd && scrollbarPosEnd < menuPos){//vado su: quando lo scroll arriva al menu, rilascio il menu
			$('.faker').remove();
			menu.removeClass("fix");
		}
		scrollbarPosStart = scrollbarPosEnd;
		var activeTitle = '';
		$('.titles h2').each(function(){
			scrollbarPosStart += 30;//fake value to add class ON to the stickmenu
			var myScroll = $(this).parent("div.box").offset().top - $(this).parent("div.box").outerHeight();
			myScroll < scrollbarPosStart ? activeTitle = $(this).parent().attr('id') : activeTitle;
			$('.stickmenu a').removeClass('on');
			$('.stickmenu a[rel=' + activeTitle + ']').addClass('on');
		});
		scrollbarPosStart = scrollbarPosEnd;//re-setting the value
	});
	$wrapper.find('a').click(function(){
		var link = $(this).attr('rel');
		var div = $('#'+link);
		var myPos = (Math.floor(div.offset().top) - div.outerHeight());
		$(window).scrollTo(myPos, 500);
	});
} 


////////////////////////////////////////////////////
 // MEDIA VIDEO
////////////////////////////////////////////////////
function mediavideo(){
  $('.media_video img').click(function(){
    var video = $(this).parent().find('input').attr('value'),
        myW   = 620,
        myH   = 350,
        myT   = ($(window).height() - myH) / 2 + $(window).scrollTop(),
        myL   = ($(window).width() - myW) / 2;
    $.blockUI({
        message:      '<div id="media_player">&nbsp;</div>',
        overlayCSS:   { backgroundColor: '#000', opacity: 0.5 },
        css:          {top: myT+'px', left: myL+'px', cursor: 'default', border: 'none', background: 'none', position: 'absolute' }
    });
    jwplayer("media_player").setup({
      flashplayer: "video/player.swf",
      height: myH,
      width: myW,
      levels: [ 
        { file: "video/" + video + ".mp4" }, // H.264 version
        { file: "video/" + video + ".webm" }, // WebM version 
        { file: "video/" + video + ".ogv" }	// Ogg Theroa version
      ],
      events: { 
        onReady: function() { this.play(); }
      }
    });
    $('.blockOverlay').click(function(){setTimeout($.unblockUI, 500)});
  });
}

(function($){
  function loadContent(hash) {
    //alert(hash);
		if(hash != "") {
			//if ( hash.indexOf('model_') == -1 ) {//obsolete; to prevent IE errors in callback campaign page (who has internal anchor links)
				loadPage.hashTolink(hash);
			//}
		}
  }
  $(document).ready(function() {
    if ( !$.support.pjax ) {$.history.init(loadContent);}
  });
})(jQuery);

/**youtube**/
var num = 0;
var player;
function initYT(){
	var tag = document.createElement('script');
	tag.type = "text/javascript";
	tag.src = "http://www.youtube.com/player_api";
	var firstScriptTag = document.getElementsByTagName('script')[0];
	firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function onYouTubePlayerAPIReady(){
	$("div.ytplayer").each(function(){
		$(this).children("iframe").attr({
			"id": "player_"+num+"",
			"allowfullscreen": false
		});
		
		//player = new YT.Player('player_1', {
		player = new YT.Player('player_'+num, {
			playerVars : {
				autohide : 1,
				showinfo : 0,
				autoplay : 0,
				fs: 0,
				wmode : 'opaque'
			},
			events: {
				'onStateChange': onPlayerStateChange
			}
		});
		num++;
	});
}

function onPlayerStateChange(event) {
	for(var i = 0; i < num; i++){
		if (event.data === -1) {
			document.getElementById('player_'+i).parentNode.parentNode.parentNode.setAttribute("class", "lbl");
		} else {
			document.getElementById('player_'+i).parentNode.parentNode.parentNode.setAttribute("class", "lbl playing");
		}
	}
}
