var isIE = (navigator.appVersion.indexOf("MSIE") != -1);

var breadcrumbMake = null;
var breadcrumbModel = null;
var breadcrumbProduct = null;

function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function loadVehicleSelection(make, model, year, product) {
	if (make && model && year) {
		loadMakeModelYear(make, model, year, product);
	} else {
		loadMakes();
	}
}

function loadMakeModelYear(smake, smodel, syear, sproduct) {

	//console.log('loadMakeModelYear()');

	var make = document.getElementById('jumpalt').make;
	var model = document.getElementById('jumpalt').model;			
	var year = document.getElementById('jumpalt').year;
	var product = document.getElementById('jumpalt').product;
	
	make.options.length = 0;
	model.options.length = 0;
	year.options.length = 0;
	
	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: smake, model: smodel, year: syear},
		onSuccess: function(transport){
		
			//console.log('success...');
		
			var results = eval('(' + transport.responseText + ')');

			//console.log('hit1');

			// Populate makes
			//document.getElementById('makeSelection').style.display = '';

			//console.log('hit2');

			make.disabled = false;
			make.options[0] = new Option('> Select Make <', '');
			make.selectedIndex=0;

			//console.log('hit3');

			var makes = results.makes;
			
			//console.log('hit4');
			//console.log(makes);
			
			var h=1;
			for (var i=0; i<makes.length; i++) {
				//console.log('Make: ' + makes[i]);
				make.options[h++] = new Option(makes[i], makes[i]);
				if (makes[i] == smake) {
					make.selectedIndex = h-1;
				}
			}

			// Populate makes

			document.getElementById('modelSelection').style.display = '';
			
			model.disabled = false;
			model.options[0] = new Option('> Select Model <', '');
			model.selectedIndex=0;
			
			var models = results.models;

			var h=1;
			for (var i=0; i<models.length; i++) {
				model.options[h++] = new Option(models[i], models[i]);
				if (models[i] == smodel) {
					model.selectedIndex = h-1;
				}
			}
			
			// Populate Years

			document.getElementById('yearSelection').style.display = '';

			year.disabled = false;
			year.options[0] = new Option('> Select Year <', '');
			year.selectedIndex=0;
			
			var years = results.years;

			var h=1;
			for (var i=0; i<years.length; i++) {
				year.options[h++] = new Option(years[i], years[i]);
				if (years[i] == syear) {
					year.selectedIndex = h-1;
				}
			}
			
			// Display product selection
			document.getElementById('productSelection').style.display = '';

			if (sproduct && sproduct != '') {
				for (var i=0; i<product.options.length; i++) {
					if (product.options[i].value == sproduct) {
						product.selectedIndex = i;
						break;
					}
				}
			}

		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});
}

function gotoProductSection() {
	var product = getCookie('product');
	if (product && product != '') {
		location.href+="#" + product;
	}
}

function loadMakes(){

	var make = document.getElementById('jumpalt').make;
	if (make.options.length < 2) {
		new Ajax.Request('/vehicleSelector/vehicles.php',
		{
			method:'get',
			onSuccess: function(transport){
				var makes = eval('(' + transport.responseText + ')');
				
				makes = makes.makes;
				
				var h=1;
				for (var i=0; i<makes.length; i++) {
					make.options[h++] = new Option(makes[i], makes[i]);
				}
			},
			onFailure: function(){
				alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
			}
		});
	}
}

function loadModels(){

	var make = document.getElementById('jumpalt').make;
	var model = document.getElementById('jumpalt').model;
	var year = document.getElementById('jumpalt').year;
	
	if (make.value == '') {
		model.disabled=true;
		model.options.length=0;
		model.options[0] = new Option('> Select Model <', '');
		model.selectedIndex=0;
		return false;
	}
	
	model.options.length = 0;
	model.options[0] = new Option('Loading...', '');

	year.disabled=true;
	year.options.length=0;
	year.options[0] = new Option('> Select Year <', '');
	year.selectedIndex=0;
	
	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: make.value},
		onSuccess: function(transport){
			var models = eval('(' + transport.responseText + ')');
			models = models.models;

			document.getElementById('modelSelection').style.display = '';
			
			model.disabled = false;
			model.options[0] = new Option('> Select Model <', '');
			model.selectedIndex=0;

			var h=1;
			for (var i=0; i<models.length; i++) {
				model.options[h++] = new Option(models[i], models[i]);
			}
		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});
}

function loadYears(){

	var make = document.getElementById('jumpalt').make;

	if (make.value == '') {
		alert('Please choose a make first');
		return false;
	}
	
	var model = document.getElementById('jumpalt').model;

	if (model.value == '') {
		var year = document.getElementById('jumpalt').year;
		year.disabled = true;
		year.selectedIndex = 0;
		return false;
	}
	
	var year = document.getElementById('jumpalt').year;
	
	year.options.length = 0;
	year.options[0] = new Option('Loading...', '');
	
	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: make.value, model: model.value},
		onSuccess: function(transport){
			var years = eval('(' + transport.responseText + ')');
			years = years.years;

			document.getElementById('yearSelection').style.display = '';

			year.disabled = false;
			year.options[0] = new Option('> Select Year <', '');
			year.selectedIndex=0;

			var h=1;
			for (var i=0; i<years.length; i++) {
				year.options[h++] = new Option(years[i], years[i]);
			}
		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});
}

function loadProducts() {
	document.getElementById('productSelection').style.display = '';
}

function showProducts(make, model, year, product) {

	//alert('MMY: ' + make + ':' + model + ':' + year);

	if (make == undefined || make == '') {
		alert('Please choose a make first');
		return false;
	}

	if (model == undefined || model == '') {
		alert('Please choose a model');
		return false;
	}

	if (year == undefined || year == '') {
		alert('Please choose a year');
		return false;
	}
	
	// Save selections
	setCookie('make', make, 30);
	setCookie('model', model, 30);
	setCookie('year', year, 30);
	setCookie('product', product, 30);
	
	var url = 'http://www.customautoaccessories.com/vehicleProducts.php?';
	url += 'make=' + escape(make);
	url += '&model=' + escape(model);
	url += '&year=' + escape(year);
	if (product && product != '') {
		url += '&product=' + escape(product);
	}
	
	window.location.href=url;
}

function findPosition(oElement) {
	if( typeof( oElement.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;
		}
		return [ posX, posY ];
	} else {
		return [ oElement.x, oElement.y ];
	}
}

function toggleDropdown(id) {
	var listContainer = document.getElementById(id + 'ListContainer');
	if (listContainer.style.display != 'block') {
		// display
		var dropdown = document.getElementById(id);
		var xy = findPosition(dropdown);
		listContainer.style.left = (xy[0]) + 'px';
		listContainer.style.top = (xy[1] + dropdown.offsetHeight) + 'px';
		listContainer.style.display = 'block';
	} else {
		// hide
		listContainer.style.display = 'none';
	}
	shim(listContainer);
}

function showDropdown(id) {
	var listContainer = document.getElementById(id + 'ListContainer');
	if (listContainer.style.display != 'block') {
		var dropdown = document.getElementById(id);
		var xy = findPosition(dropdown);
		listContainer.style.left = (xy[0]) + 'px';
		listContainer.style.top = (xy[1] + dropdown.offsetHeight) + 'px';
		listContainer.style.display = 'block';
		shim(listContainer);
	}
}

function hideDropdown(id) {
	var listContainer = document.getElementById(id + 'ListContainer');
	if (listContainer.style.display != 'none') {
		listContainer.style.display = 'none';
		shim(listContainer);
	}
}

function shim(obj) {
	if (!isIE) return;
	var shim = document.getElementById('shim');
	if (shim) {
		if (obj.style.display == 'none') {
			shim.style.display='none';
		} else {
			shim.style.width=obj.offsetWidth+'px';
			shim.style.height=obj.offsetHeight+'px';
			shim.style.left=obj.offsetLeft+'px';
			shim.style.top=obj.offsetTop+'px';
			shim.style.display='block';
		}
	}
}

function loadBreadcrumbs(smake, smodel, syear) {

	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: smake, model: smodel, year: syear},
		onSuccess: function(transport){
		
			var results = eval('(' + transport.responseText + ')');
			
			// Make
			
			var makeDropdownSelector = document.getElementById('makeBreadcrumb');
			var makeDropdownList = document.getElementById('makeBreadcrumbList');

			var h=1;
			for (var i=0; i<results.makes.length; i++) {

				var a = document.createElement('a');
				a.href = 'javascript:breadcrumbSelectMake(\'' + results.makes[i] + '\');';
				a.appendChild(document.createTextNode(results.makes[i]));
				
				var li = document.createElement('li');
				li.appendChild(a);
			
				makeDropdownList.appendChild(li);
				
				if (results.makes[i] == smake) {
					makeDropdownSelector.getElementsByTagName('a').item(0).firstChild.nodeValue = results.makes[i];
				}
			}
			
			// Model

			var modelDropdownSelector = document.getElementById('modelBreadcrumb');
			var modelDropdownList = document.getElementById('modelBreadcrumbList');
			
			var h=1;
			for (var i=0; i<results.models.length; i++) {
			
				var a = document.createElement('a');
				a.href = 'javascript:breadcrumbSelectModel(\'' + results.models[i] + '\')';
				a.appendChild(document.createTextNode(results.models[i]));
				
				var li = document.createElement('li');
				li.appendChild(a);
			
				modelDropdownList.appendChild(li);
				
				if (results.models[i] == smodel) {
					modelDropdownSelector.getElementsByTagName('a').item(0).firstChild.nodeValue = results.models[i];
				}
			}

			// Year

			var yearDropdownSelector = document.getElementById('yearBreadcrumb');
			var yearDropdownList = document.getElementById('yearBreadcrumbList');
			
			var h=1;
			for (var i=0; i<results.years.length; i++) {
			
				var a = document.createElement('a');
				a.href = 'javascript:breadcrumbSelectYear(\'' + results.years[i] + '\')';
				a.appendChild(document.createTextNode(results.years[i]));
				
				var li = document.createElement('li');
				li.appendChild(a);
			
				yearDropdownList.appendChild(li);
				
				if (results.years[i] == syear) {
					yearDropdownSelector.getElementsByTagName('a').item(0).firstChild.nodeValue = results.years[i];
				}
			}

		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});

}

function breadcrumbSelectMake(smake) {

	// Update dropdown headings
	document.getElementById('makeBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = smake;
	document.getElementById('modelBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = 'Select Model';
	document.getElementById('yearBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = 'Select Year';
	
	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: smake},
		onSuccess: function(transport){
		
			var results = eval('(' + transport.responseText + ')');
			
			// Model

			var modelDropdownSelector = document.getElementById('modelBreadcrumb');
			var modelDropdownList = document.getElementById('modelBreadcrumbList');

			// First clear the list
			while (modelDropdownList.childNodes.length >= 1) {
				modelDropdownList.removeChild(modelDropdownList.firstChild);
			}
			
			var h=1;
			for (var i=0; i<results.models.length; i++) {
			
				var a = document.createElement('a');
				a.href = 'javascript:breadcrumbSelectModel(\'' + results.models[i] + '\');';
				a.appendChild(document.createTextNode(results.models[i]));
				
				var li = document.createElement('li');
				li.appendChild(a);
			
				modelDropdownList.appendChild(li);
			}

			// Year

			var yearDropdownSelector = document.getElementById('yearBreadcrumb');
			var yearDropdownList = document.getElementById('yearBreadcrumbList');
			
			//yearDropdownList.childNodes.length = 0;
			/*
			for (var i=0; i < yearDropdownList.childNodes.length; i++) {
				yearDropdownList.removeChild(yearDropdownList.childNodes.items(i));
			}
			*/

			/*
			while (cells[i].childNodes[0]) {
				cells[i].removeChild(cells[i].childNodes[0]);
			}
			*/

			while (yearDropdownList.childNodes.length >= 1) {
				yearDropdownList.removeChild(yearDropdownList.firstChild);
			}
			
			// Hide the menu
			hideDropdown('makeBreadcrumb');

		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});

}

function breadcrumbSelectModel(smodel) {

	var smake = document.getElementById('makeBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue;

	// Update dropdown headings
	document.getElementById('makeBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = smake;
	document.getElementById('modelBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = smodel;
	document.getElementById('yearBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = 'Select Year';
	
	new Ajax.Request('/vehicleSelector/vehicles.php',
	{
		method:'get',
		parameters:{make: smake, model: smodel},
		onSuccess: function(transport){
		
			var results = eval('(' + transport.responseText + ')');
			
			// Year

			var yearDropdownList = document.getElementById('yearBreadcrumbList');

			// First clear the list
			while (yearDropdownList.childNodes.length >= 1) {
				yearDropdownList.removeChild(yearDropdownList.firstChild);
			}
			
			var h=1;
			for (var i=0; i<results.years.length; i++) {
			
				var a = document.createElement('a');
				a.href = 'javascript:breadcrumbSelectYear(\'' + results.years[i] + '\');';
				a.appendChild(document.createTextNode(results.years[i]));
				
				var li = document.createElement('li');
				li.appendChild(a);
			
				yearDropdownList.appendChild(li);
			}
			
			// Hide the menu
			hideDropdown('modelBreadcrumb');

		},
		onFailure: function(){
			alert('Sorry, the vehicle selection tool isn\'t available right now... Check back in a minute or two.')
		}
	});

}

function breadcrumbSelectYear(syear) {

	document.getElementById('yearBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue = syear;

	// Hide the menu
	hideDropdown('yearBreadcrumb');
	
	var smake = document.getElementById('makeBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue;
	var smodel = document.getElementById('modelBreadcrumb').getElementsByTagName('a').item(0).firstChild.nodeValue;
	
	var sproduct = '';
	
	if (breadcrumbProduct) {
		sproduct = breadcrumbProduct;
	}

	setCookie('make', smake, 30);
	setCookie('model', smodel, 30);
	setCookie('year', syear, 30);
	setCookie('product', sproduct, 30);

	var url = 'http://www.customautoaccessories.com/vehicleProducts.php?';
	url += 'make=' + escape(smake);
	url += '&model=' + escape(smodel);
	url += '&year=' + escape(syear);
	if (sproduct != '') {
		url += '&product=' + escape(sproduct);
	}

	window.location.href=url;
}

function continueShopping() {
	var make = getCookie('make');
	var model = getCookie('model');
	var year = getCookie('year');
	
	var url = 'http://www.customautoaccessories.com/';
	
	if (make && model && year) {
		url = 'http://www.customautoaccessories.com/vehicleProducts.php?';
		url += 'make=' + escape(make);
		url += '&model=' + escape(model);
		url += '&year=' + escape(year);
	}
	
	window.location.href = url;
}

/**
 * Parse query string
 */

function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(this.q && this.q.length > 0) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}

	this.getLength = function() { return this.keyValuePairs.length; } 
}

function queryString(key){
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}

function initVehicleSelectors() {

	var make = queryString('make');
	var model = queryString('model');
	var year = queryString('year');
	var product = queryString('product');
	
	if (make == 'false' || model == 'false' && year == 'false') {
		// Incomplete vehicle in URL, try from cookies
		make = getCookie('make');
		model = getCookie('model');
		year = getCookie('year');
		product = getCookie('product');
	}
	
	if (product == 'false') {
		product = '';
	}

	if (document.getElementById('jumpalt')) {
		loadVehicleSelection(make, model, year, product);
	}

	if (document.getElementById('makeBreadcrumb')) {
		if (breadcrumbMake) {
			loadBreadcrumbs(breadcrumbMake, breadcrumbModel); // Load the specific make and model
		} else if (breadcrumbProduct) {
			loadBreadcrumbs(); // Load breadcrumbs without any default selection
		} else {
			loadBreadcrumbs(make, model, year); // Load breadcrumbs with MMY from query string or cookie
		}
	}
}
