﻿var ROOT_URL = "/mmfr/";
var makes, models;


$().ready(function() {
	if (!makes) return;
	
	if (document.location.href.indexOf("/vconfig") > 0 || document.location.href.indexOf("/mm") < 0) {
		ROOT_URL = "/vconfig/";
	} else {
		var matches = document.location.href.match(/\/mm\w{2}\//i);
		if (matches && matches.length > 0) {
			ROOT_URL = matches[0];
		}
	}
	
	var inputSelector = '#search input[type=text]';
	var submitSelector = '#search input[type=submit]';
	var inputMakeSelector = '#search input[id="make"]';
	var inputModelSelector = '#search input[id="model"]';
	var textChangeTimeout;
	
	$('#search div.fields img').mousedown(function(event) {
		event.preventDefault();
		var inputID = $(this).attr('id');
		inputID = inputID.replace("Arrow", "");
		getInput(inputID).attr("value", "");
		getInput(inputID).trigger("focus");
	});
	
	$(inputSelector).map(function(index, obj) {
		if (!$(obj).data('prompt')) {
			$(obj).data('prompt', $(obj).attr("title"));
		}
	});	

	$(inputSelector).focus(function(event) {
		//event.preventDefault();
		clearTimeout(textChangeTimeout);
		
		//$('#search #' + $(this).attr('id') + 'Arrow').hide();
		
		var defValue = $(event.target).data('prompt');

		if ($(event.target).attr("value") == defValue) {
			$(event.target).attr("value", "");
		} else {
			//$(event.target).select();
		}	
		$(event.target).removeAttr("class");		
		
				
		if ($(event.target).attr("value").length == 0) {
			$(event.target).data('autocompleter').activateNow();
		}
	});	
	
	/*
	$(inputSelector).keyup(function(event) {
		var value = getInputValue($(event.target).attr("id"));
		if (value.length == 0) {
			clearTimeout(textChangeTimeout);
			textChangeTimeout = setTimeout("findMakeModel()", 100);
		}
	});*/
	
	$(inputSelector).bind("textchange", function(event) {
		if ($(this).attr("id") == "make") {
			$(inputModelSelector).attr("value", "");
			$(inputModelSelector).trigger("blur");
		}
		
		clearTimeout(textChangeTimeout);		
	});
	
	$(inputSelector).blur(function(event) {	
		clearTimeout(textChangeTimeout);
		textChangeTimeout = setTimeout("findMakeModel()", 1000);
		
		var value = getInputValue($(event.target).attr("id"));		
		
		if (value.length == 0) {
			clearInput($(this).attr("id"));
		} else {
			$(event.target).removeAttr("class");						
		}
	});
	
	$(inputSelector).attr('autocomplete', 'off');	
	
	$(inputMakeSelector).autocomplete(
		{
			data: makes.split(","), delay: 10,  minChars: 0, sortResults: false,
			onItemSelect: function(value, data) {
				clearInput("model");
				findMakeModel(true);
			}
		}
	);
	
	$(inputModelSelector).autocomplete(
		{
			data: models.split(","), delay: 10,  minChars: 0,
			onItemSelect: function(value, data) {
				findMakeModel();
			}
		}
	);
		
	$(submitSelector).click(function(event) {
		event.preventDefault();
		
		var categoryRegex = /(.*)\/(?:Promo|Stock|VN|All)(.*)/i;
		
		var action = $('form#main').attr('action');
		action = action.replace(".aspx", "");
		action = action.replace(categoryRegex, "$1");
		var make = encodeURIAdvanced(getInputValue("make"));
		var model = encodeURIAdvanced(getInputValue("model"));
		document.location.href = buildURL(action, getVehicleType(), make, (make == "" && model.length > 0) ? "?model=" + model : model);
	});

	
	$('div.makes a[href*="/catalog/"]').click(function(event) {
		event.preventDefault();
		
		if ($(this).data("disabled")) return;
		
		var make = $(this).text();		
		document.location.href = buildURL(ROOT_URL, "catalog", getVehicleType(), make);
	});
	
	
	//  INIT
	findMakeModel(false, false, getVehicleType(), "", "");
});


function buildURL() {
	var url = "";
	for (var i = 0; i < arguments.length; i++) {
		var s = arguments[i];
		if (url.length > 0 && url.charAt(url.length - 1) != "/" && s.charAt(0) != "/") url += "/";
		url += s;
	}
	if (url.indexOf("vconfig") > 0) {
		if (url.charAt(url.length - 1) == "/") {
			url = url.substring(0, url.length - 1);
		}
		url = url.replace("/?", "?");
		url = url.replace("?", ".aspx?");
		
		if (url.indexOf(".aspx") < 0) url += ".aspx";
	}
	return url;
}


function getVehicleType() {
	return "All";
}


function getVehicleTypeLabel(type) {
	if (lang && lang["au total"]) return " " + lang["au total"];
	return " au total";
}


function getInput(inputID) {
	var input = $('#search input[id="' + inputID + '"]');
	return input;
}

function clearInput(inputID) {
	var input = $('#search input[id="' + inputID + '"]');
	var defValue = input.data('prompt');
	input.attr("value", defValue);
	input.attr("class", "label");	
	$('#search #' + inputID + 'Arrow').show();
}

function getInputValue(inputID) {
	var input = $('#search input[id="' + inputID + '"]');
	var value = input.attr("value");
	if (value == input.data("prompt")) value = "";
	return value;
}

function resetAutocompleterData(inputID, newData) {
	if (inputID == "make") return;

	var acm = getInput(inputID).data('autocompleter');
	var opt = acm.options;
	opt.data = newData;
	
	if (acm.dom.$results.is(":visible")) {
		acm.finish();
		acm.activateNow();
	}
}


var cacheMap = {};


function findMakeModel(moveFocus, silent, vehicleType, make, model) {
	vehicleType = vehicleType || getVehicleType();
	make = encodeURIAdvanced(make || getInputValue("make"));
	model = encodeURIAdvanced(model || getInputValue("model"));
	
	var url = buildURL(ROOT_URL, "/vehicleCount?" + "make=" + make + "&model=" + model);
	
	
	if (cacheMap[url]) {		
		$('#search div.searchResult').html(cacheMap[url].count);	
		resetAutocompleterData("model", cacheMap[url].models);
		resetAutocompleterData("make", cacheMap[url].makes);
		
		if (moveFocus) setTimeout(function() {getInput("model").focus();}, 10);
		return;
	}

	
	if (!silent) {
		if (model == "") {
			getInput("model").attr('disabled', 'disabled');
		}
		if (make == "") {
			getInput("make").attr('disabled', 'disabled');
		}
		$('#search div.searchResult').html("...");
	}
	
	$.ajax({
		url: url,
		type: "GET",
		success: function(data) {			
			if (data == null) data = {};
			if (!data.hasOwnProperty("total")) data.total = 0;
			if (!data.hasOwnProperty("makeList")) data.makeList = [];
			if (!data.hasOwnProperty("modelList")) data.modelList = [];
			
			if (data.total == undefined || isNaN(data.total) || data.total < 0) return;
			
			cacheMap[url] = {};			
			var voitures = (lang && lang["voitures"]) ? lang["voitures"] : "voitures";
			cacheMap[url].count = data.total + " " + voitures + " " + getVehicleTypeLabel(vehicleType);
			cacheMap[url].makes = data.makeList;
			cacheMap[url].models = data.modelList;
			
			// fill makes			
			if (make == "" && model == "") {				
				if (!silent) resetAutocompleterData("make", cacheMap[url].makes);
			}
			
			// fill models			
			if (model == "") {
				if (!silent) resetAutocompleterData("model", cacheMap[url].models);				
			}
			if (!silent && moveFocus) {
				setTimeout(function() {getInput("model").focus();}, 10);
			}
			
			// render
			if (!silent)  {
				$('#search div.searchResult').html(cacheMap[url].count);
				getInput("model").removeAttr('disabled');
				getInput("make").removeAttr('disabled');
			}
		},
		error: function(data) {
			if (!silent) {
				$('#search div.searchResult').html("0");
				getInput("model").removeAttr('disabled');
				getInput("make").removeAttr('disabled');
			}
		}
	});
}



