/******************************************************************************
Central location for managing all javascript bound search controls and ui interaction.	
*******************************************************************************/
$(document).ready(function()
{
	//Global script to hide any non js required controls.
	$(".mp-script-disabled").hide();
	
	//Hide our control list data sources, and multi select enable.
	var peListControl = $("div.mp-list-control");
	peListControl.each(function(iPeControlList)
	{
		var peListControlInstance =  $(this);
		var peControlData = peListControlInstance.children("select");
		//peControlData.hide();
		if(peControlData[0]) peControlData[0].multiple = true;
		//Hide any list control template fragments.
		peListControlInstance.children("div.mp-list-control-template").hide();
	});
	
	//Bind up any search submit buttons.
	$("form.mp-search-form").find("a.mp-search-submit.validate").click(
		function (event) {
			event.preventDefault();
			
			var showModelError = false;
			var showPostcodeError = false;
			var selectedModeCount = getSelectedModelCount();
			var postcode = $('input.text.postcode');
						
			//format the postcode then validate it
			if(postcode.length > 0) {
				formatPostcode(postcode);
				if(!isValidPostcode(postcode.val())) {
					showPostcodeError = true;
				}
			
				//only allow the form submit when the user has selected a model
				if(selectedModeCount == 0) {
					showModelError = true;
				}
			}
			
			if(selectedModeCount == 0) {
					showModelError = true;
				}
			
			//check if we need to show the validation popup or if we wanna run the search
			if(showModelError || showPostcodeError) {
				showValidation(showModelError,showPostcodeError);
			}
			else {
				$(this).parents("form.mp-search-form.").submit();
				return false;	
			}
		}
	);
	
	//bind up the click event for the basic search that only validates the postcode
	$("form.mp-search-form").find("a.mp-search-submit.validate-postcode").click(
		function(event) {
			event.preventDefault();
			
			var showModelError = false;
			var showPostcodeError = false;
			var postcode = $('input.text.postcode.mp-control-data');
			
			if(postcode.length > 0)
			{
			//format the postcode then validate it
			formatPostcode(postcode);
			if(!isValidPostcode(postcode.val())) {
				showPostcodeError = true;
			}
			}		
			//check if we need to show the validation popup or if we wanna run the search
			if(showPostcodeError) {
				showValidation(showModelError,showPostcodeError);
			}
			else {
				$(this).parents("form.mp-search-form.").submit();
				return false;	
			}

		}
	);
	
	//Bind up any search submit buttons.
	$("form.mp-search-form").find("a.mp-search-submit.non-validate").click(
		function () {
			$(this).parents("form.mp-search-form").submit();
			return false;	
		}
	);
	
	//Bind any select post back controls.
	$("form.mp-search-form").find("select.mp-control-postback").change(
		function () {
			$(this).parents("form.mp-search-form").submit();
			return false;
		}
	);
		
	//Bind mp-list-control-item-remove options via the UI.
	$("form.mp-search-form").find("a.mp-list-control-item-remove").click(
		function () {
			var peRemoveButton = $(this);
			var peListControl = peRemoveButton.parents("div.mp-list-control");
			var peControlData = peListControl.children("select")[0];

			//Loop through each of our options and set the state of our checked/unchecked element.
			for(var _i=0; _i < peControlData.options.length;_i++) 
			{
				if(peControlData.options[_i].value = peRemoveButton.parent("div.mp-list-control-item").attr("title"))
				{
					peControlData.options[_i].selected = 0;
				}
			}
						
			//Now post back our changes.
			peListControl.parents("form.mp-search-form").submit();
		}
	);
	
	//Bind our image based select control selection make this a pe selector eventually.
	$("form.mp-search-form").find("div.imagelist fieldset img").click(
		function () {
			var container = $(this).parent("fieldset.imagegroup");
			var image = $(this);
			var colour = stringAfterLast(image.attr("id"), "_");
			if($(this).hasClass("selected"))
			{
				//if this is ie6 then the image url will have been hidden by the png fix and we'll have to
				//rebuild this
				if($.browser.msie && $.browser.version < 7 ) {
					image.attr("src", '/assets/images/colourSelector/icn_' + colour + '_up.png');
					fix_PNG(image[0]);
				}
				else {
					//De-Select the clicked item.
					image.attr("src", image.attr("src").replace("down","up"));
				}
				image.removeClass("selected");
			}
			else
			{
				//if this is ie6 then the image url will have been hidden by the png fix and we'll have to
				//rebuild this
				if($.browser.msie && $.browser.version < 7 ) {
					image.attr("src", '/assets/images/colourSelector/icn_' + colour + '_down.png');
					fix_PNG(image[0]);
				}
				else {
					//Set the clicked item to selected.
					image.attr("src", image.attr("src").replace("up","down"));
				}
				image.addClass("selected");
			}
			setImageGroupValue(container, colour);
			
			//Now our hidden field has been set set-up our ajax request.
			var ctrl = container.children("input:hidden");
			var ctrlName = stringAfterLast(ctrl.attr("id"), "_");
			var ctrlValue = ctrl.val();
		}
	);
	
	configureMustHaveResetButton($('div.must-have-controls'));
	configureAdvancedSearchButton($('div.fine-tune-controls'));
});
/******************************************************************************/



/******************************************************************************/
function setImageGroupValue(container, toggleValue)
{
	//get our hidden field that stores the data.
	var hiddenField = container.children("input:hidden");
	//Get what format the hidden field data needs to be stored as.
	var valueFormat = stringAfterLast(container.attr("class"), " ");
	
	switch(valueFormat)
	{
		case "sum" :
			//Convert our value to an integer.
			toggleValue = parseInt(toggleValue);
			//If our value is undefined then set it to a string value.
			if(!hiddenField.attr("value"))
			{
				hiddenField.attr("value", toggleValue);
			}
			else
			{
				//Check if the bit has already been set and add or remove it accordingly.
				if((parseInt(hiddenField.attr("value")) & toggleValue) == toggleValue)
				{
					hiddenField.attr("value", parseInt(hiddenField.attr("value")) - toggleValue);
				}
				else
				{
					hiddenField.attr("value", parseInt(hiddenField.attr("value")) + toggleValue);
				}
			}
			//If we have no selected items clear the value as 0 is the equivelent of none selected.
			if(hiddenField.attr("value") == "0") hiddenField.attr("value", "");
			break;
			
		default :
			if(!hiddenField.attr("value"))
			{
				hiddenField.attr("value", toggleValue);
			}
			else
			{
				var valueArray = hiddenField.attr("value").split(",");
				
				if(jQuery.inArray(toggleValue, valueArray) > -1)
				{
					valueArray.splice(jQuery.inArray(toggleValue, valueArray),1);
					hiddenField.attr("value", valueArray.join(","));
				}
				else
				{
					valueArray.push(toggleValue)
					hiddenField.attr("value", valueArray.join(","));
				}
			}
			break;
	}	
}
/******************************************************************************/


/******************************************************************************
RESET BUTTONS FOR ADV SEARCH AND MUST HAVES
*******************************************************************************/
function configureMustHaveResetButton(container) { 
	container.find('a.reset').click(
		function(event) {
			//stop the normal click through
			event.preventDefault();
			
			//uncheck all of the musthaves
			container.find('input').each(
				function() {
					$(this)[0].checked = false;
				}
			);
		}
	);
}

function configureAdvancedSearchButton(container) {
	container.find('a.reset').click(
		function(event) {
			//stop the default click through from happeneing
			event.preventDefault();
			
			//transmission
			var transmission = container.find('select.select.transmission');
			transmission.find('option').each(
				function() {
					if($(this).html().indexOf('Any') > -1) {
						$(this)[0].selected = true;
					}
				}
			);
			
			//fuel type
			var fuelType = container.find('div.fueltype');
			fuelType.find('input').each(
				function() {
					if($(this).val() == 'null') {
						$(this)[0].checked = true;
					}
				}
			);
			
			//exterior colours
			var colours = container.find('div.colour.imagelist');
			colours.find('img').each(
				function() {
					var image = $(this);
					if(image.hasClass("selected")) {
						setImageGroupValue($(this).parent("fieldset.imagegroup"), stringAfterLast(image.attr("id"), "_"));
						image.removeClass("selected");
						image.attr("src", image.attr("src").replace("down","up"));
					}
				}
			);
			
			//distance
			var distance = container.find('div.distance');
			ResetSlider(distance);
			
			//mileage
			var mileage = container.find('div.odometerto');
			ResetSlider(mileage);
			
			//Age
			var age = container.find('div.ageto');
			ResetSlider(age);
			
			//Price
			var price = container.find('div.pricerange');
			ResetSlider(price);
		}
	);
}