var hashStart = '#/';
var c1, c2, c3, newHash, currentHash, hashParts;

$(document).ready(function(){
	$("select.compare").change(function() { updateLocation(); getCompareData(); }); // add onChange functionality
	$("a.copyLink").click(function() { $("input#linkCopyField").val(document.location); $("input#linkCopyField").show(); return false; });
	$("input#linkCopyField").focus(function() { this.select(); });
	c1 = document.getElementById('compareOne');
	c2 = document.getElementById('compareTwo');
	c3 = document.getElementById('compareThree');
	fetchHashParts();
	doUpdate();
	supportBackButton();
});

function updateLocation() {
	// build URL
	newHash = '#/' + c1.value + ',' + c2.value + ',' + c3.value;
	document.location = newHash; 
	$("input#linkCopyField").val(document.location);
}

function fetchHashParts() {
	currentHash = document.location.hash;
	// must start with #/ -- check
	if ((currentHash.length > 2) && (currentHash.substr(0,2) == hashStart)) {
		// trim off starting junk
		currentHash = currentHash.substring(2,currentHash.length);
		hashParts = currentHash.split(','); // split into three
	} else {
		hashParts = false;
	}
}

function getCompareData() {
	// make ajax call to get new data
	$.ajax({
		type: "GET",
		url: "/content/bikes/bikeComparisonTable.php",
		data: "lang=" + language_id + "&country=" + country_id + "&c1=" + c1.value + "&c2=" + c2.value + "&c3=" + c3.value,
		success: function(msg){ $("table#compareData").html(msg); }
	});
	doTracking();
}
		
function updateSelect(e,value) {
	var x;
	for(x=0; x<e.options.length; x++) {
		if(e.options[x].value == value) {
			e.selectedIndex = x;
		}
	}
}

function doUpdate() {
	// do an update if we can
	// make sure that we have 3 parts -- if we don't, fudge it
	if (hashParts.length < 3) {
		if (!hashParts[0]) { hashParts[0] = 'empty'; }
		if (!hashParts[1]) { hashParts[1] = 'empty'; }
		if (!hashParts[2]) { hashParts[2] = 'empty'; }
	}
	if (hashParts.length == 3) {
		updateSelect(c1, hashParts[0]);
		updateSelect(c2, hashParts[1]);
		updateSelect(c3, hashParts[2]);
		getCompareData();
	}
}

function supportBackButton() {
	// update choices if the back button was pressed, or the location.hash was otherwise changed
	setInterval("if (newHash && (document.location.hash != newHash)) { newHash = document.location.hash; fetchHashParts(); doUpdate(); }", 2500);
}

function doTracking() {
	// do Analytics tracking -- track each individual bike compared
	trackingBase = "/" + country_id + "/" + language_id + "/bikes/compare/";
	if (c1.value.length && (c1.value != "empty")) {
		analytics(trackingBase + c1.value);
	}
	if (c2.value.length && (c2.value != "empty")) {
		analytics(trackingBase + c2.value);
	}
	if (c3.value.length && (c3.value != "empty")) {
		analytics(trackingBase + c3.value);
	}
}

function analytics(string) {
	pageTracker._trackPageview(string);	
}