// Functions to refresh the header + simple AJAX library

// Make a request to the web server, works with multiple threads, but don't try too many at once.
// req = an old HTTP Request to reuse, or null to make a new one with NewXHR.
// url_str = the URL to load
// func = the callback function, which is called with every status change
// param = an additional parameter that can be passed to func
// Returns req or the newly created HTTP Request
//
// Usage:
// var global_request = null;  // We only want to use one request at a time in this example.
// function Something_Status_Change(request, param) {  // This is the callback function
// 	if (request.readyState != 4) return 1;  // Only care if we finished the request
//    if (request.status != 200) {
//       alert('We did not get a successful return code from the request.  Handle appropriately.');
//       return 1;
//    }
//    alert('We have finished.  The data returned by the request is ...')
//    alert(request.responseText);
//    alert('Also, we have the parameter passed with the MakeRequest() function, 1234 == ' + param);
//    return 0;  // Signal that we do not want further calls to this callback for this request
// }
// function Something_On_Update() {
//   global_request = MakeRequest(global_request, 'http://site/ajax.php', Something_Status_Change, '1234');
// }

var prices = Array();
var makes = Array();
var models = Array();
var networks = Array();
var colours = Array();

function MakeRequest(req, url_str, func, param) {
	function BindCallback() {
		if (func_ts) {
			if (! func_ts(req_ts, param_ts)) {
				func_ts = null;
			}
		}
	}

	var req_ts = req;
	var func_ts = func;
	var param_ts = param;

	if (req_ts && req_ts != null) {
		req_ts.abort();
	} else {
		req_ts = NewXHR();
	}

	req_ts.onreadystatechange = BindCallback;
	req_ts.open("GET", url_str, true);
	req_ts.send(null);

	return req_ts;
}


// Create a new HTTP Request for various different types of browsers
// Probably should not be called directly by any external programs
function NewXHR() {
	var obj = false;

	if (! obj && typeof(XMLHttpRequest) != 'undefined') {
		try {
			obj = new XMLHttpRequest();
		} catch (e) {
			obj = false;
		}
	}
	if (! obj && window.createRequest) {
		try {
			obj = window.createRequest();
		} catch (e) {
			obj = false;
		}
	}
	if (! obj && window.ActiveXObject) {
		try {
			obj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			obj = false;
		}
	}
	if (! obj && window.ActiveXObject) {
		try {
			obj = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			obj = false;
		}
	}

	return obj;
}


var selectsRequest = null;


function enableSelects(isEnabled) {
	var costElem = document.getElementById('price');
	var makeElem = document.getElementById('makeID');
	var modelElem = document.getElementById('productVariantID');
	var networkElem = document.getElementById('networkID');
	var giftElem = document.getElementById('gift');
	var indicatorElem = document.getElementById('indicator');
	
	var disabledValue = ! isEnabled;
	
	if (! costElem || ! makeElem || ! modelElem || ! networkElem) {
		return;
	}
	
	costElem.disabled = disabledValue;
	makeElem.disabled = disabledValue;
	modelElem.disabled = disabledValue;
	networkElem.disabled = disabledValue;
	giftElem.disabled=disabledValue;
	if (disabledValue) {
		indicatorElem.style.display = 'inline';
	} else {
		indicatorElem.style.display = 'none';
	}
}


function requerySelects(selectObj) {
	var costElem = document.getElementById('price');
	var makeElem = document.getElementById('makeID');
	var modelElem = document.getElementById('productVariantID');
	var networkElem = document.getElementById('networkID');
	
	if (! costElem || ! makeElem || ! modelElem || ! networkElem) {
		return;
	}
	
	enableSelects(0);
	
	var query = '/ajax/home/QuickSearch';
	var data = new Object();
	if (costElem.value != "") {
		data.price = escape(costElem.value);
	}
	if (makeElem.value != "") {
		data.makeID = escape(makeElem.value);
	}
	if (modelElem.value != "") {
		data.productVariantID = escape(modelElem.value);
	}
	if (networkElem.value != "") {
		data.network = escape(networkElem.value);
	}
	if (modelElem.value != "") {
		data.productVariantID =escape(modelElem.value);
	}
	$.get('/ajax/home/QuickSearch', data, requeryCallback);
}

function requeryDealCreator() {
	//var costElem = document.getElementById('dealcreator_price');
	var makeElem = document.getElementById('dealcreator_makeID');
	var modelElem = document.getElementById('dealcreator_productVariantID');
	
	var colourElem = document.getElementById('dealcreator_colourID');
	
	if (! makeElem || ! modelElem) {
		return;
	}
	
	//enableSelects(0);
	
	var query = '/ajax/home/QuickSearch';
	var data = new Object();
	if (makeElem.value != "") {
		data.makeID = escape(makeElem.value);		
	}
	if (modelElem.value != "") {
		data.productVariantID = escape(modelElem.value);		
	}
	if( colourElem.value!=""){
		data.colour = escape(colourElem.value);
	}
	
	$.get('/ajax/home/QuickSearch', data, requeryDCCallback);

}

function requeryDCCallback(request) {
	var searchData = eval('(' + request + ')');

	//var costElem = document.getElementById('price');
	var makeElem = document.getElementById('dealcreator_makeID');
	var modelElem = document.getElementById('dealcreator_productVariantID');
	var colorElem = document.getElementById('dealcreator_colourID');

	
	if (makeElem && modelElem && searchData.makes.length && searchData.models.length) {
		updateSelects(makeElem, makes, searchData.makes);
		updateSelects(modelElem, models, searchData.models);
		//updateSelects(networkElem, networks, searchData.networks);

	//var networkElem = document.getElementById('dealcreator_networkID');

		//updatePriceRanges(costElem, searchData.prices);
		//alert(searchData);
	}
	if(searchData.colours.length){
		//alert(searchData.colours + " "+colours[3].value);
		updateSelects(colorElem,colours,searchData.colours);
		
	}
	
	//enableSelects(1);
	
	return 0;  // Signal that we do not want further calls to this callback for this request
}


function requeryCallback(data) {
	var searchData = eval('(' + data + ')');
	var costElem = document.getElementById('price');
	var makeElem = document.getElementById('makeID');
	var modelElem = document.getElementById('productVariantID');
	var networkElem = document.getElementById('networkID');
	if (makeElem && modelElem && networkElem) {		
		updateSelects(makeElem, makes, searchData.makes);
		updateSelects(modelElem, models, searchData.models);
		updateSelects(networkElem, networks, searchData.networks);
		updatePriceRanges(costElem, searchData.prices);
	}

	enableSelects(1);
	
	return 0;  // Signal that we do not want further calls to this callback for this request
}

function updateSelects(selectObj, optionsObj, filteredList) {
	var selectedValue = selectObj.options[selectObj.selectedIndex].value;
	//alert(selectObj.options.length);
	var selectedIndex = 0;
	var str="";
	var opt=0;
	if(optionsObj.length==0)return;
	$(selectObj).removeOption(/./);
	
	//for (var opt in optionsObj) {
	while(opt<optionsObj.length){
			//str+=opt+":";
			var found = 0;
			for (var hit in filteredList) {
			//alert(filteredList[hit]);
				if (filteredList[hit] == optionsObj[opt].value) {
					found = 1;
					filteredList[hit] = null;
				}
			}
			if (found) {
				$(selectObj).addOption(optionsObj[opt].value, optionsObj[opt].text);
				if (selectedValue == optionsObj[opt].value)	{
					selectedIndex = selectObj.options.length - 1;
				}
			} 
			opt++;
			//str+=found+"\n";
			selectObj.selectedIndex = selectedIndex;
	}
	//alert(str);
}

function updatePriceRanges(costElem, prices) {
	var previousSelectionIndex = costElem.selectedIndex;
	var previousSelection = costElem.options[costElem.selectedIndex].value;
	while (costElem.options.length > 2) {
		costElem.remove(2);
	}
	for (var price in prices) {
		var opt = document.createElement('option');
		opt.value = prices[price][0];
		opt.text = prices[price][1];
		try {
			costElem.add(opt, null);  // Standards, but not IE
		} catch (e) {
			costElem.add(opt);  // IE
		}
	}
	if (previousSelectionIndex < 2) {
		costElem.selectedIndex = previousSelectionIndex;
	} else {
		for (opt in costElem.options) {
			if (costElem.options[opt] && costElem.options[opt].value == previousSelection) {
				costElem.selectedIndex = opt;
			}
		}
	}
}

function submitFind(formName){
	var costElem = document.getElementById('price');
	var makeElem = document.getElementById('makeID');
	var modelElem = document.getElementById('productVariantID');
	var networkElem = document.getElementById('networkID');
	document.getElementById('pageNum').value = '0';

	if ( costElem.selectedIndex > 1 ) {
		document.getElementById('sortBy').value = 'orderByEffectivePrice';
	}

	if (costElem.disabled==1 || makeElem.disabled==1  || modelElem.disabled==1 || networkElem.disabled==1) {
	return false;
	}
	else{
	document[formName].submit();
	return true;
	}
}

function saveQuickSearchData()	{
	//in iframe sites these things wont exist/.. 
	if(document.getElementById("price")==null)return;

	var costElem = document.getElementById('price');
	var makeElem = document.getElementById('makeID');
	var modelElem = document.getElementById('productVariantID');
	var networkElem = document.getElementById('networkID');
	
	if(document.getElementById("dealcreator_colourID")){
		var coloursElem = document.getElementById("dealcreator_colourID");
		
		for (var i = 0; i < coloursElem.options.length; i++)	{
			colours.push(coloursElem.options[i]);
		}
	}
	//alert(colours);
	for (var i = 0; i < costElem.options.length; i++)	{
		prices.push(costElem.options[i]);
	}
	for (var i = 0; i < makeElem.options.length; i++)	{
		makes.push(makeElem.options[i]);
	}
	for (var i = 0; i < modelElem.options.length; i++)	{
		models.push(modelElem.options[i]);
	}
	for (var i = 0; i < networkElem.options.length; i++)	{
		networks.push(networkElem.options[i]);
	}
}
