﻿/*
 *****************************
 *	CONSTANTS
 *****************************
 */

var PANEL_STATE_COOKIE_NAME = 'FiatPanelStates';
var PANEL_STATE_COOKIE_EXPIRY = 10;
var SELECTED_MODELS_DEFAULT_IMAGE_NAME = 'no-image';

/*
 *****************************
 *	UTILITIES
 *****************************
 */
 
//returns the QS from a complete URL
function getQueryString(url)
{ 
	var args = new Object(); 
	var query = url.substring(url.indexOf("?") + 1);
	var pairs = query.split("&"); 
	for(var i = 0; i < pairs.length; i++)
	{ 
		var pos = pairs[i].indexOf("="); 
		if (pos == -1) continue; 
		var argname = pairs[i].substring(0,pos); 
		var value = pairs[i].substring(pos+1); 
		args[argname] = unescape(value); 
	} 
	return args; 
}

//function used to trim any leading whitespace
function trimString(val) {
	while(val[0] == ' ') {
		val = val.substr(1);
	}
	return val;
}

//formats the postcode to add in a space if the user hasn't entered one
function formatPostcode(postcode) {
	if(postcode[0].value != "")
	{
		postcode.val(postcode.val().replace(/ /g,''));
		if(postcode.val().indexOf(' ') == -1) {
			newPostcode = postcode.val().substr(0,postcode.val().length-3) + ' ' + postcode.val().substr(postcode.val().length-3,3);
			postcode.val(newPostcode);
		}
	}
	else
	{
		postcode.val(postcode.val());
	}
}

//function used to check if the user has entered a valid UK postal code
function isValidPostcode(val) {
	var regex = '^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$';
	return val.match(regex);
}

//returns all of the data after a certain character
function stringAfterLast(data, character)
{
	return (data.lastIndexOf(character) > 0) ? data.substring(data.lastIndexOf(character) + 1, data.length) : data;
}

//function used to store a cookie on the users machine
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+1);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
} 

//function used to retrieve a cookie
function getCookie(c_name) {
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
}

//function used to build a complez
function getPanelStateArray() {
	//get the open or closed state of each of the panels
	var modelState = $('li.selected-models').hasClass('selected');
	var fineTuneState = $('li.fine-tune').hasClass('selected');
	var mustHaveState = $('li.must-haves').hasClass('selected');
	//var vehicleEnquiryState = $('li.vehicle-enquiry').hasClass('selected');
	//var sendFriendState = $('li.send-to-friend').hasClass('selected');
	var newSearchBasicState = $('li.new-search-basic').hasClass('selected');
	var newSearchAdvancedState = $('li.new-search-advanced').hasClass('selected');
	var favouritesState = $('div.panel-favourites').hasClass('panel-open');
	var compareState = $('div.panel-compare').hasClass('panel-open');
	
	//build the string to be returned
	var panelStateString = '';
	panelStateString += 'li.selected-models;selected;' + modelState + ',';
	panelStateString += 'li.fine-tune;selected;' + fineTuneState + ',';
	panelStateString += 'li.must-haves;selected;' + mustHaveState + ',';
	//panelStateString += 'li.vehicle-enquiry;selected;' + vehicleEnquiryState + ',';
	//panelStateString += 'li.send-to-friend;selected;' + sendFriendState + ',';
	panelStateString += 'li.new-search-basic;selected;' + newSearchBasicState + ',';
	panelStateString += 'li.new-search-advanced;selected;' + newSearchAdvancedState + ',';
	panelStateString += 'div.panel-favourites;panel-open;' + favouritesState + ',';
	panelStateString += 'div.panel-compare;panel-open;' + compareState;
	return panelStateString;
}

//function used to set the states of the panels from the string stored in the cookies
function setPanelStates() {
	//ok we need to split up the string and extract the values used to open and close the correct panels
	var val = getCookie(PANEL_STATE_COOKIE_NAME);
	var panels = val.split(',');
	for(var i=0;i<panels.length;i++) {
		var panel = panels[i];
		var parts = panel.split(';');
		
		if(parts[2] == 'true') {
			$(parts[0]).addClass(parts[1]);
			
			//if this is the fine-t
			if(parts[0] == 'li.fine-tune') {
				RenderSliders();
			}
		}
		else {
			$(parts[0]).removeClass(parts[1]);
		}
	}
}

/*
 *****************************
 *	PAGE INIT
 *****************************
 */

$(document).ready(
	function() {
		setPanelStates();
		var container = $("div.container-model-items.mp-list-control");
		
		//ok now finally we need to decide on whether we want to show or hide the instructions
//		if(container.find('div.item-model').length > 1)
//			$('div.accordion-content div.instructions').hide();
//		else
//			$('div.accordion-content div.instructions').show();	
	}
);


/*
 *****************************
 *	OPEN LINK IN NEW BROWSER WINDOW
 *****************************
 */
	$(document).ready(function() {
		$("a[@rel = 'external']").click(
			function () {
				var link = $(this);
				var qs = getQueryString(link.attr("href"));
				if (!qs.w) qs.w = 800;
				if (!qs.h) qs.h = 600;
				window.open(link.attr("href"), link.attr("id"), "width=" + qs.w + ",height=" + qs.h + ",menubar=yes,location=yes,resizable=yes,status=yes,toolbar=yes,scrollbars=yes");
				return false;
			}
		);
	}); 

/*
 *****************************
 *	VALIDATION POPUP
 *****************************
 */
 
 function hideValidation() {
	$('div.overlay-alert').hide();
	$('div.alerts-container').hide();
 }
 
 function showValidation(showModel,showPostcode) {
	var overlay = $('div.overlay-alert');
	var message = $('div.alerts-container');
	var modelMessage = message.find('p.model-select');
	var postcodeMessge = message.find('p.postcode');
	overlay.show();
	message.show();
	
	if(showModel)
		modelMessage.show();
	else
		modelMessage.hide();
		
	if(showPostcode)
		postcodeMessge.show();
	else
		postcodeMessge.hide();
	
	//wireup the close event
	message.find('a.search').click(
		function(event) {
			event.preventDefault();
			
			hideValidation();	
		}
	);
 }

//function used to return the number of models selected
function getSelectedModelCount() {
	var select = $('select.select.range');
	var options = select.find('option');
	var selectedModelCount = 0;
	for(var i=0;i<options.length;i++) {
		if(options[i].selected && options[i].value != 'null') {
			selectedModelCount++
		}
	}
	
	//alert($('div.container-model-items div.item-model png mp-list-control-item').length);
	
	return selectedModelCount;
}

/*
 *****************************
 *	COLLAPSABLE SIDE PANEL HEADER INTERACTION - [ FAVOURITES // COMPARE ]
 *****************************
 */
	$(document).ready(function() 
	{ 
		$("div.column2 > div.panel.style2 > div.header").hover(
			function () {
				$(this).addClass("header-over");
			}, 
			function () {
				$(this).removeClass("header-over");
			}
		);
		
		$("div.column2 > div.panel.style2 > div.header").click(
			function () {
				togglePanelState($(this).parent("div.panel"));
			}
		);
		
	});
	
	
	/**
	 *	COLUMN 2 :: PANEL STYLE 2 :: OPEN / CLOSE TOGGLE
	 */
		function togglePanelState (targetJQueryObjectRef)
		{
			var _this = targetJQueryObjectRef;
			
			if (_this.hasClass("panel-open"))
			{
				_this.removeClass("panel-open");
			}
			else
			{
				_this.addClass("panel-open");
			}		
			
			setCookie(PANEL_STATE_COOKIE_NAME,getPanelStateArray(),PANEL_STATE_COOKIE_EXPIRY);
		}
	
	
/*
 *****************************
 *	COLLAPSABLE SIDE ACCORDION HEADER INTERACTION
 *****************************
 */	
	$(document).ready(function() 
	{ 
		$("div.column2 div.panel ul.accordion h3.accordion-header").click(
			function () {
				var li = $(this).parent("li");
				toggleAccordionState(li);
				
				if(li.hasClass('fine-tune')) {
					if(li.hasClass("selected")) {
						RenderSliders();
					}
					else {
						DestroySliders();
					}
				}
			}
		);
		
		
		$("div.column2 div.panel ul.accordion h3.accordion-header a").hover(
			function () {
				$(this).addClass("accordion-header-over");
			}, 
			function () {
				$(this).removeClass("accordion-header-over");
			}
		);
		/*
		 * SETUP AND STYLE PANEL HEADERS (see SIFR/sifr-config.js);
		 */
	});
		
		function toggleAccordionState (targetJQueryObjectRef)
		{
			var _this = targetJQueryObjectRef;
			
			if (_this.hasClass("selected"))
			{
				_this.removeClass("selected");
			}
			else
			{
				_this.addClass("selected");
			}	
			
			setCookie(PANEL_STATE_COOKIE_NAME,getPanelStateArray(),PANEL_STATE_COOKIE_EXPIRY);
		}
	
	
	

/*
 *****************************
 *	MODEL SELECTION ITEMS
 *****************************
 */
$(document).ready(function() 
{ 
	$("div.column1 > div.panel-model-selection > div.content > div.item").hover(
		function () {
			$(this).addClass("item-over");
		}, 
		function () {
			$(this).removeClass("item-over");
			
		}
	);
	
	$("div.column1 > div.panel-model-selection > div.content > div.item").click(
		function () 
		{			
			toggleSelectedModelState($(this));
		}
	);
	
	//wire up the model removal actions
	//$('div.column2 > form.mp-search-form > fieldset > div.panel-search-settings-basic > div.body > div.content > ul.accordion > li.selected-models > div.accordion-content > div.container-model-items > div.item-model > a.remove').click(
	$("div.column2").find("a.mp-list-control-item-remove").click(
		function(event) {
			event.preventDefault();

			
			//ok get the title from the item being clicked
			var title = $(this).prev().prev().html();
			var titleId = title.replace(/ /g,'');
			
			//ok we have the title id so we need to search the select list and remove it,
			//then force the displayed models to refresh
			var container = $('div.container-model-items.mp-list-control');
			var dataContainer = container.find('select');
			if(container.find('div.item-'+titleId)[0]) {
				var modelToRemove = container.find('div.item-'+titleId);
				modelToRemove.remove();
			}
			
			//ok now we need to update the select list
			dataContainer.find('option').each(
				function() {
					if($(this).text().replace(/ /g,'') == titleId) {
						$(this)[0].selected = false;
					}					
				}
			);
			
			//we need to detect if we are in the model selection page and if so then update
			//the main panel aswell, otherwise they will get out of synch
			titleId = titleId.toLowerCase();
			var panel = $('div.uvl-container div.panel div.content div.item-' + titleId);
			if(panel[0]) {
				toggleSelectedModelState(panel);
			}
			
			var selectedModelCount = getSelectedModelCount();
			
			//update the selected models count
			$('li.selected-models h3 a span').html('(' + selectedModelCount + ')');
			
			//now we need to show the update search button
			$('li.selected-models div.accordion-content div.divider').show();
			$('li.selected-models div.accordion-content div.links').show();
			
			//if the selected model count it 0 then we need to remove the validation from the search button as it will
			//now send the user straight back to the model selection page
			if(selectedModelCount == 0) {
				var button = $("form.mp-search-form").find("a.mp-search-submit.validate");
				button.removeClass('validate').addClass('non-validate');
				button.unbind('click');
				button.click(
					function(event) {
						event.preventDefault();
						$(this).parents("form.mp-search-form.").submit();
						return false;	
					}
				);
			}	

		}
	);		
});
	
//function used to upate the select list used to store which models are currently selected		
function updateModelSelect(value) {	
	var peCheckBoxArray = $("div.mp-search-form").find("input.mp-list-control-checkbox");
	var peListControl = $("div.mp-list-control");
	var peControlData = peListControl.children("select")[0];
	var selectedModelsCount = 0;

	//Loop through each of our options and set the state of our checked/unchecked element.
	for(var i=1; i < peControlData.options.length;i++) 
	{
		peControlData.options[i].selected = peCheckBoxArray[i-1].checked;
		var title = $(peCheckBoxArray[i-1]).parent().parent().find('a').html();
		var quantity = $(peCheckBoxArray[i-1]).parent().parent().find('p.availability strong').html();
		if(peCheckBoxArray[i-1].checked && (peCheckBoxArray[i-1].value = value)) {
			createSelectedModel(title,quantity,true);	
			selectedModelsCount++;
		}
		else if(!peCheckBoxArray[i-1].checked && (peCheckBoxArray[i-1].value = value)) {
			createSelectedModel(title,quantity,false);	
		}
	}
	
	//update the selected models count
	$('li.selected-models h3 a span').html('(' + selectedModelsCount + ')');
}


//function used to create a selected model in the criteria panel
function createSelectedModel(title,quantity,show) {
	var container = $("div.container-model-items.mp-list-control");
	//alert(title);
	var titlePlaceholder = "TITLE";
	var titleId =  title.replace(/ /g,'');
	
	//if we're adding this model and it doesn't exist in the selected models then add it
	if(!(container.find("div.item-" + titleId)[0]) && show) {
		//create the cloned template for the drop
		var drop = container.find("div.item-model.mp-list-control-template").clone();
		
		//populate the drop with the selected models items
		drop.attr("class",drop.attr("class").replace(titlePlaceholder,titleId)).removeClass("mp-list-control-template").addClass("mp-list-control-item");
		var h4 = drop.find("h4");
		
		h4.html(title); //+ ' (' + quantity + ')'
		h4.attr("title",h4.attr("title").replace(titlePlaceholder,title));
		var img = drop.find("img");
		var mainImg = document.getElementById("img-"+title);
		var mainImgSrc = mainImg.src;
		if (mainImgSrc.indexOf("no-image")<0)
		    img.attr("src",img.attr("src").replace(titlePlaceholder,titleId));
		else
		    img.attr("src",img.attr("src").replace(titlePlaceholder,"no-image"));
		img.attr("alt",img.attr("alt").replace(titlePlaceholder,title));
		img.attr("title",img.attr("title").replace(titlePlaceholder,title));
				
		
		//wire up the remove button
		drop.find('a.remove').click(
			function() {
				//alert( 'createSelectedModel(title,quantity,show) drop wire up the remove button');				
				removeSelectedModel(titleId);
			}
		);
			
		container.append(drop);
		
		//
		// Run PNG fix on all relevent elements within the new model as png fixes removed from template to avoid clone problems
		//	
		// -- ONLY EVER DO THIS IF IE.6
		//
		if($.browser.msie && $.browser.version < 7 ) 
		{
			fix_PNG(drop[0]);
			fix_PNG(drop.find('a')[0]);	
			fix_PNG(drop.find('img')[0]);	
		}
	}
	
	//if we're removing this model and it does exist in the selected models then remove it
	if(container.find('div.item-'+title.replace(/ /g,''))[0] && !show) {
		var modelToRemove = container.find('div.item-'+title.replace(/ /g,''));
		modelToRemove.remove();
	}
	
	//ok now finally we need to decide on whether we want to show or hide the instructions
	if(container.find('div.item-model').length > 1)
		$('div.accordion-content div.instructions').hide();
	else
		$('div.accordion-content div.instructions').show();	
}

//function used to allow the user to click any of the model hover and update the search criteria
function toggleSelectedModelState (targetJQueryObjectRef)
{
	var _this = targetJQueryObjectRef;
		
	var _cb = _this.find("input");
	
	if (_this.hasClass("item-selected"))
	{
		_this.removeClass("item-selected");
		
		if (_cb.attr("checked"))
		{
			_cb.removeAttr("checked");
		}
	}
	
	else
	{
		_this.addClass("item-selected");
		
		if (!_cb.attr("checked"))
		{
			_cb.attr("checked", "true");
		}
	}
	
	//now update the select
	updateModelSelect($(_cb).val());	
}

//function used to handle the user selecting to remove a model
function removeSelectedModel(titleId) {
	//now we need to update up the selected models display in the main panel	
	titleId = titleId.toLowerCase();
	var item = $('div.uvl-container div.panel div.content div.item-' + titleId);
	toggleSelectedModelState(item);
	updateSelectedModelCount();
}

//function used to update the selected model count shown to the user
function updateSelectedModelCount() {
	var peListControl = $("div.mp-list-control");
	var peControlData = peListControl.children("select")[0];
	var selectedModelsCount = 0;

	//Loop through each of our options and set the state of our checked/unchecked element.
	for(var i=1; i < peControlData.options.length;i++) 
	{
		if(peControlData.options[i].selected) {
			selectedModelsCount++;
		}
	}
	
	//update the selected models count
	$('li.selected-models h3 a span').html('(' + selectedModelsCount + ')');
}

/*
 *****************************
 *	VEHICLE DETAILS ITEMS
 *****************************
 */
	/*
	 *	VEHICLE IMAGE BUTTONS
	 */
		$(document).ready(function() 
		{ 
			$("div.column1 div.panel-vehicle-view div.content div.vehicle-image-button").hover(
				function () {
					$(this).addClass("button-over");
				}, 
				function () {
					$(this).removeClass("button-over");
				}
			);
			
			$("div.column1 div.panel-vehicle-view div.content div.vehicle-image-button").click(
				function () 
				{
					var _this = $(this);
					var mainImage = _this.siblings("img.vehicle-image-main");
					var mainImageWidth = mainImage.width();
					var mainImageHeight = mainImage.height();
					
					if(_this.find('img.vehicle-image-main').attr('alt').indexOf("NO IMAGE") < 0)
					{
						
					
						//RESET :: REMOVE THE SELECTED BUTTON
						_this.siblings("div.vehicle-image-button.button-selected").removeClass("button-selected");
						
						//SET :: MAKE THIS BUTTON SELECTED
						_this.addClass("button-selected");
						
						//SET :: OUR MAIN IMAGE SOURCE TO EQUAL THAT OF THE SELECTED IMAGE
						var imageUrl = _this.children("img.vehicle-image-main").attr("src");
						imageUrl = imageUrl.replace(/width=111/i,"width=" + mainImageWidth);
						imageUrl = imageUrl.replace(/height=74/i,"height=" + mainImageHeight);
						mainImage.attr("src",imageUrl);
					}
					
					/*
					//REMOVE :: IF CLAUSE AND 1ST STATEMENT -- LEAVE ONLY 'ELSE' ACTIONS
					if (_this.hasClass("button-selected"))
					{
						_this.removeClass("button-selected");
						
						//SET :: OUR MAIN IMAGE SOURCE TO EQUAL THAT OF THE SELECTED IMAGE
						var imageUrl = _this.attr("src");
						imageUrl.replace(/width=111/,"width=" + mainImageWidth);
						imageUrl.replace(/height=74/,"height=" + mainImageHeight);
						mainImage.attr("src",imageUrl);
						alert(imageUrl);
					}
					else
					{
						_this.addClass("button-selected");
						//RESET ALL OTHER BUTTONS
					}
					*/
				}
			);
		});

		
		$(document).ready(function() 
		{ 
			$("div.column1 div.panel-vehicle-view div.content ul.vehicle-full-details li div.accordion-header").hover(
				function () 
				{					
					var isSelected = $(this).parent().hasClass('selected');
					
					if (!isSelected)
					{
						$(this).addClass("accordion-header-over");
					}
				}, 
				function () 
				{
					if (!$(this).hasClass("selected"))
					{
						$(this).removeClass("accordion-header-over");
					}
					
				}
			);
			
			
			$("div.column1 div.panel-vehicle-view div.content ul.vehicle-full-details li div.accordion-header").click(
				function () {					
					openAccordionPanel($(this).parent("li"));
				}
			);	
			
			
		});
	
			/**
			 *	COLUMN 2 :: PANEL STYLE 2 :: OPEN / CLOSE TOGGLE
			 */
				function openAccordionPanel (targetJQueryObjectRef)
				{
					var _this		= targetJQueryObjectRef;
					var _siblings	= _this.parent("ul").children("li");
					
					if (!_this.hasClass("selected"))
					{
						
						/* CLOSE ALL OPEN */
						for (var i = 0; i < _siblings.length; i++)
						{
							var tgt = $(_siblings[i]);
							if (tgt.hasClass("selected"))
							{
								tgt.removeClass("selected");
							}
						}
						
						/* OPEN CLICKED */
						_this.addClass("selected");	
					}		
				}
	
	//
	
	
	
	
	
	
/*
 *****************************
 *	SET-UP collapsable panel headers (set links for ie && SIFR styling) 
 *****************************
 */

	$(document).ready(function() 
	{
		setup_panel_headers();
		
		if ($.browser.msie && (Number($.browser.version) < 7))
		{
			configure_alert_overlay();
		}
	});
	
	function configure_alert_overlay ()
	{
		var container = $("div.mainContainer");
		var target = $("div.overlay-alert");
		
		var w = container.width();
		var h = container.height();
		
		var temp = $(document);
		
		//alert("Overlay dimensions :: w = " + w + " // height = " + h);
		
		target.css("width", w);
		target.css("height", h);
	}
	
	function position_alert_loading ()
	{
		var scroll_y	= $(document).scrollTop();
		var offset_y	= $("div.mainContainer").position().top; //This is the height of the header ie.the offset of the mainContainer 
		
		var container	= $("div.mainContainer");
		var container_w = $("div.mainContainer").width();
		
		var target		= $("div.mainContainer > div.alerts-container > div.panel-loading");
		var target_h	= target.height();
		var target_w	= target.width();
		
		var win_h		= pageHeight();
		
		var _x			= (container_w - target_w) / 2;
		var _y;
		
		if (scroll_y <= offset_y)
		{
			var _offset = offset_y - scroll_y;
			_y			= ((win_h - _offset) / 2) - (target_h / 2);
		}
		else
		{
			var _offset_body	= scroll_y - offset_y;
			_y					= ((win_h - target_h) / 2) + _offset_body;
		}
		
		target.css("position", "absolute");
		target.css("top", _y);
		target.css("left", _x);
	}
	
	
	function pageWidth() {
		return window.innerWidth != null? window.innerWidth: document.documentElement.clientWidth != null? document.documentElement.clientWidth:null;
	}
	
	function pageHeight() {
		return window.innerHeight != null? window.innerHeight: document.documentElement.clientHeight != null? document.documentElement.clientHeight:null;
	}
	

/*
 *****************************
 *	SIFR text within div link
 *****************************
 */
	/*
	$(document).ready(function() 
	{ 
		$("div#testLinkContainer").hover(
			function () {
				//alert("OVER");
				$(this).addClass("over");
			}, 
			function () {
				//alert("OUT");
				$(this).removeClass("over");
				
			}
		); 
		
	});
	*/
	
	
//store the state of the panels
$(document).ready(
	function(event) {
		setCookie(PANEL_STATE_COOKIE_NAME,getPanelStateArray(),PANEL_STATE_COOKIE_EXPIRY);	
	}
);