var xmlHttp = null;
var appBase = null;
var currentType = null;
var currentPage = null;
var units = 'english';
var oHeight = 1680;
var is_ie6 = navigator.userAgent.match("MSIE 6");

function getXmlHttpObject() {
	try {
		// Firefox, Opera 8.0+, Safari
   		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function showLoading() {
	Element.hide('get_started_heading');
	Element.hide('results');
	Element.hide('search_heading');
	Element.hide('conversion');
	Element.show('loading');
}

function loadApp(base) {
	appBase = base;
	document.getElementById('search').style.display = 'block';
	resetFields();
}

function hideResults() {
	Effect.Fade('search_heading');
	Effect.Fade('results');
	Effect.Fade('conversion');
}

function loadResults(results) {
	document.getElementById('results').innerHTML = results;
}

function showResults() {
	currentPage = 1;
	setTimeout("Effect.Fade('loading')", 800);
	setTimeout("Effect.Appear('search_heading')", 2200);
	setTimeout("Effect.Appear('results')", 2200);
	setTimeout("Effect.Appear('conversion')", 3000);
	oHeight = 1680;
	document.getElementById('search').style.height='' + oHeight + 'px';
	resizeColumns();
}

function loadOptions(dropdown, options) {
	dropdown.options.length = 0;
	
	dropdown.options[0] = new Option("", "");
	if(options.length > 0) {
		for(x=0; x < options.length; x++) {
			dropdown.options[x + 1] = new Option(options[x]["value"], options[x]["id"]);
		}
	} else {
		dropdown.options[1] = new Option("None Available", "");
	}
}

function manufactGrab() {
	Element.hide('get_started_heading');
	showLoading();
	var man = document.manufact.manufact_drop.selectedIndex;
	var manValue = document.manufact.manufact_drop.options[man].value;
	var url = appBase + "/products/search_query";
	var units = 'english';
	if (document.conversion.conversion_drop.options[1].selected == true) {
		units = 'metric';
	}
	
	// Determine the product line
	var productLine = null;
	if (currentType == 'container') {
		productLine = 'container';
	} else {
		productLine = 'pallet';
	}
	
	var params = "type=manufacturer&query=" + manValue + '&units=' + units + "&line=" + productLine;
	
	loadOptions(document.model.model_drop, models[manValue]);
	
	xmlHttp = getXmlHttpObject();
	xmlHttp.open("POST", url, true);

	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");		
	xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			hideResults();	
			setTimeout("loadResults(xmlHttp.responseText)", 1000);
			setTimeout("showResults()", 1000);
		}
	}
	xmlHttp.send(params);	
	
	Effect.Appear('model');
}

function modelGrab() {
	var mod = document.model.model_drop.selectedIndex;
	var modValue = document.model.model_drop.options[mod].value;
	var url = appBase + "/products/search_query";
	var units = 'english';
	if (document.conversion.conversion_drop.options[1].selected == true) {
		units = 'metric';
	}	
	
	// Determine the product line
	var productLine = null;
	if (currentType == 'container') {
		productLine = 'container';
	} else {
		productLine = 'pallet';
	}	
	
	var params = "type=model&query=" + modValue + "&units=" + units + "&line=" + productLine;
	
	if(modValue.length > 0) {
		showLoading();	
		xmlHttp = getXmlHttpObject();
		xmlHttp.open("POST", url, true);
	
		//Send the proper header information along with the request
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");		
		xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
				hideResults();	
				setTimeout("loadResults(xmlHttp.responseText)", 1000);
				setTimeout("showResults()", 1000);
			}
		}
		xmlHttp.send(params);		
	}
}

// AJAX timer for preventing request floods on javascript events such as onkeyup
var timer = 0;
var running = false;
var ajaxDelay = 1000; // in milliseconds
function ajaxTimer(action, bypass, event) {
	if (!bypass) {
		if (event != undefined && !isAcceptedChar(event)) {
			return;
		}	
		
		if (!running) {
			//console.log("Starting AJAX timer");
			timer = ajaxDelay;
			running = true;
			setTimeout("ajaxTimer('" + action + "', true)", 500);
		} else {
			//console.log("New keystroke, resetting AJAX timer");		
			timer = ajaxDelay;
		}
		return;
	} else {
		if (timer <= 0) {
			//Reset Timer Data
			timer = 0;
			running = false;
					
			if (isSearchBlank()) {
				console.log('blank search!');
				return;
			}
			showLoading();
			
			//Grab appropriate data for AJAX call
			postVars = new Array();
			tmpVars = new Array();
			
			type = null;
			if (isSet(document.general.product_number)) {
				postVars[0] = new Array();
				if (document.general.product_number.value.length > 0) {
					postVars[0][0] = document.general.product_number.value;						
				}
			}
			type = 'number';
			if(isSet(document.general.side1) || isSet(document.general.side2) || isSet(document.general.height)) {
				postVars[1] = new Array();
				if (document.general.side1.value.length > 0 && document.general.side2.value.length > 0) { 
					postVars[1][0] = document.general.side1.value;
					postVars[1][1] = document.general.side2.value;
					postVars[1][2] = document.general.height.value;	
				} else if (document.general.side1.value.length > 0) {
					postVars[1][0] = document.general.side1.value; 					
				} else if (document.general.side2.value.length > 0) {
					postVars[1][1] = document.general.side2.value; 					
				}
				
				if (document.general.height.value.length > 0) {
					postVars[1][2] = document.general.height.value;
				}
				
				for(x = 0; x < document.general.units_length.length; x++) {
					if (document.general.units_length[x].checked) {
						postVars[1][3] = document.general.units_length[x].value;
					}
				}

				type = 'dimensions';		
			} 
			if (isSet(document.general.top)) {
				postVars[2] = new Array();
				var num = 0;
				for(x = 0; x < document.general.top.length; x++) {
					if (document.general.top[x].checked) {
						postVars[2][num] = document.general.top[x].value;
						num++;
					}
				}
				type = 'top';
			}
			if (isSet(document.general.access_forklift)) {
				postVars[3] = new Array();
				var num = 0;
				for(x = 0; x < document.general.access_forklift.length; x++) {
					if (document.general.access_forklift[x].checked) {
						postVars[3][num] = document.general.access_forklift[x].value;
						num++;
					}
				}
				type = 'access_forklift';
			}
			if (isSet(document.general.access_pallet_jack)) {
				postVars[4] = new Array();
				var num = 0;
				for(x = 0; x < document.general.access_pallet_jack.length; x++) {
					if (document.general.access_pallet_jack[x].checked) {
						postVars[4][num] = document.general.access_pallet_jack[x].value;
						num++;
					}
				}
				type = 'access_pallet_jack';
			}
			if (isSet(document.general.attribs)) {
				postVars[5] = new Array();
				var num = 0;
				for(x = 0; x < document.general.attribs.length; x++) {
					if (document.general.attribs[x].checked) {
						postVars[5][num] = document.general.attribs[x].value;
						num++;
					}
				}
				type = 'attribs';
			}			
			
			// Determine the product line
			var productLine = null;
			if (currentType == 'container') {
				productLine = 'container';
			} else {
				productLine = 'pallet';
			}
			
			// Do the AJAX call
			var url = appBase + "/products/search_query";
			var params = "type=" + type + "&line=" + productLine;
			for(x=0; x < postVars.length; x++) {
				if (postVars[x] != undefined) {
					params = params + "&" + x + "=" + postVars[x];
				}
			}
			var xmlParams = params;
			//console.log(params);
			
			//console.log("Initializing AJAX Call...");
			//console.log(params);
				
			xmlHttp = getXmlHttpObject();
			xmlHttp.open("POST", url, true);
		
			//Send the proper header information along with the request
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", params.length);
			//xmlHttp.setRequestHeader("Connection", "close");		
			xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
				//console.log("State changed to: " + xmlHttp.readyState);
				if(xmlHttp.readyState == 4) {
					if (xmlHttp.status == 200) {
						hideResults();	
						setTimeout("loadResults(xmlHttp.responseText)", 800);
						setTimeout("showResults()", 1200);
					} else {
						//console.log("Error... status: " + xmlHttp.status);
						hideResults();
                                                setTimeout("loadResults('Error contacting database! Please try again later...')", 800);
                                                setTimeout("showResults()", 1200);
					}
				}
			}
			xmlHttp.send(xmlParams);
			//setTimeout("xmlHttp.abort()", 15000);
			
		} else {
			//console.log("Decrement...");
			timer-=500;
			setTimeout("ajaxTimer('" + action + "', true)", 500);
		}
	}
}

function reset() {
	Element.hide('search_heading');
	Element.hide('results');
	Element.hide('gen_search');
	Element.hide('get_started_heading');

	if (currentType == 'industry') {
		// Sheet-Fed boxes
		Element.hide('conversion');
		Element.hide('model');
		Element.hide('manufacturer');
	} else if (currentType == 'container') {
		Element.hide('conversion');
		Element.hide('gen_search');
		Element.hide('dimensions');
		Element.hide('product_num');
	} else {
		// General Search boxes
		Element.hide('conversion');
		Element.hide('gen_search');
		Element.hide('pallet_jack_access');
		Element.hide('forklift_access');
		document.getElementById('search').style.height='800px';
		Element.hide('top');
		Element.hide('attributes');
		Element.hide('dimensions');
		Element.hide('product_num');
		resizeColumns();
	}
	Effect.Appear('industry');
	Effect.Appear('get_started_heading');
	
	currentType = null;
	
	window.scroll(0,0);
	resetFields();
}

function industry() {
	currentType = 'industry';
	
	Element.hide('industry');
	Effect.Appear('manufacturer');
	Effect.Appear('gen_search');
}

function generalSearch() {
	// Reset search criteria from session (if any)
	/*var url = appBase + "/products/search_reset";

	xmlHttp = getXmlHttpObject();
	xmlHttp.open("GET", url, true);

	xmlHttp.onreadystatechange = function() {//Call a function when the state changes.
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		
		}
	}
	xmlHttp.send(null);*/
	document.getElementById('search').style.height='' + oHeight + 'px';	
	Element.hide('search_heading');
	Element.hide('get_started_heading');
	Element.hide('results');
	Element.hide('gen_search');
	Element.hide('industry');
	resizeColumns();
	
	/*var offset = 0;
	if (currentType == 'industry') {
		// Sheet-Fed boxes
		Effect.Fade('model');
		setTimeout("Effect.Fade('manufacturer')", 500);
		setTimeout("Effect.Fade('industry')", 1000);
		offset = 1000;
	} else {
		Effect.Fade('industry');
	}*/
	
	// General Search boxes
	Effect.Appear('product_num');
	Effect.Appear('get_started_heading');
	setTimeout("Effect.Appear('dimensions')", 500);
	setTimeout("Effect.Appear('attributes')", 1000);
	setTimeout("Effect.Appear('top')", 1500);
	setTimeout("Effect.Appear('forklift_access')", 2000);
	setTimeout("Effect.Appear('pallet_jack_access')", 2500);;
	setTimeout("Effect.Appear('gen_search')", 3000);
	
	currentType = 'general';
}

function containers() {		
	Element.hide('industry');

	Effect.Appear('product_num');
	Effect.Appear('get_started_heading');
	setTimeout("Effect.Appear('dimensions')", 500);
	setTimeout("Effect.Appear('gen_search')", 1000);
	
	currentType = 'container';
}

function detailView(id) {
	document.getElementById('product-' + id).style.height='200px';
	document.getElementById('pallet-' + id).style.display='none';
	document.getElementById('description_preview-' + id).style.display='none';
	document.getElementById('more_details-' + id).style.display='none';
	Effect.Appear('product_number-' + id);
	Effect.Appear('pallet_big-' + id);
	if(currentType !== 'container') {
		Effect.Appear('load_bearing-' + id);
	}
	Effect.Appear('top_type-' + id);
	Effect.Appear('fl_access-' + id);
	Effect.Appear('desc_content-' + id);
	Effect.Appear('less_details-' + id);
	Effect.Appear('contact-' + id);
	oHeight += 140;
	document.getElementById('search').style.height='' + oHeight + 'px';
	resizeColumns();
}

function listView(id) {
	document.getElementById('product-' + id).style.height='100px';
	document.getElementById('pallet_big-' + id).style.display='none';
	document.getElementById('desc_content-' + id).style.display='none';
	document.getElementById('less_details-' + id).style.display='none';
	document.getElementById('load_bearing-' + id).style.display='none';
	document.getElementById('top_type-' + id).style.display='none';
	document.getElementById('fl_access-' + id).style.display='none';
	document.getElementById('contact-' + id).style.display='none';
	Effect.Appear('description_preview-' + id);
	Effect.Appear('more_details-' + id);
	Effect.Appear('product_number-' + id);
	Effect.Appear('pallet-' + id);
	oHeight -= 140;
	document.getElementById('search').style.height='' + oHeight + 'px';
	resizeColumns();
}


function loadPage(direction, max, similarPage) {
	var newPage = 0;
	if (direction == 'next') {
		newPage = currentPage + 1;
	} else {
		newPage = currentPage - 1;
	}
	document.getElementById('page_number').innerHTML = newPage;
	
	if (newPage > 1) {
		Effect.Appear("pagination_prev");
	}
	
	if (newPage == 1) {
		Effect.Fade("pagination_prev");
	}
	
	if (newPage == (max - 1)) {
		Effect.Fade("pagination_next");
	} else {
		Effect.Appear("pagination_next");
	}	
	
	if (newPage == (similarPage + 1) && direction == 'next') {
		Element.hide("search_heading");
		Effect.Appear("similar_match_heading");
	} else if (newPage == similarPage && direction == 'prev') {
		Element.hide("similar_match_heading");
		Effect.Appear("search_heading");
	}
	
	Effect.Fade('page_' + currentPage);
	setTimeout("Effect.Appear('page_" + newPage + "')", 1000);
	currentPage = newPage;
	
	window.scroll(0,0);
}

function changeDimensionsUnits(value) {
	if (document.getElementById('page_1') != undefined) {
		convertUnits(value);
	} else {
	    convertUnits(value);
		ajaxTimer('dimensions');
	}
}

function convertUnits(value) {

	if (units == value) {
		// No need to convert
		return;
	}
	
	var spans = document.getElementsByTagName('span');

	for(x = 0; x < spans.length; x++) {
		//console.log(spans[x].getAttribute('class'));
		if (spans[x].className == 'dimensions_' + units) {
			//console.log(spans[x]);
			Element.hide(spans[x]);
		}
	}
	
	//Effect.Fade('dimensions_' + units);
	
	if (value == 'metric') {
		document.conversion.conversion_drop.options[1].selected = true;
		document.general.units_length[1].checked = true;
	} else {
		document.conversion.conversion_drop.options[0].selected = true;
		document.general.units_length[0].checked = true;
	}
	
	for(x = 0; x < spans.length; x++) {
		if (spans[x].className == 'dimensions_' + value) {
			Effect.Appear(spans[x]);
		}
	}
	units = value;
}

function resetFields() {
	document.general.reset();
	document.manufact.reset();
	document.model.reset();
	
	if (currentType == 'industry') {
		Element.hide('model');
	}
}

function isSearchBlank() {
	var isBlank = true;
	
	if (isSet(document.general.product_number) ||
	(isSet(document.general.side1) || isSet(document.general.side2) || isSet(document.general.height)) ||
	isSet(document.general.top) ||
	isSet(document.general.access_forklift) ||
	isSet(document.general.access_pallet_jack) ||
	isSet(document.general.attribs)) {
		isBlank = false;
	}
	
	return isBlank;
}

function isSet(field) {
	var set = false;

	if (field.type == 'text' || field.type == 'hidden') {
		if (field.value.length > 0) {
			set = true;
		}
	} else if (field.type == 'radio' || field.type == 'checkbox') {
		for(x = 0; x < field.length; x++) {
			if (field[x].checked) {
				set = true;
			}
		}	
	} else if (field.type == undefined && field.length > 0) {
		for(x = 0; x < field.length; x++) {
			if (field[x].checked) {
				set = true;
			}
		}	
	}

	return set;
}

function isAcceptedChar(event) {
	var keyNum = null;
	var isAccepted = false;
	
	if (window.event) {
		keyNum = event.keyCode;
	} else if (event != undefined && event.which) {
		keyNum = event.which;
	}
	
	if (keyNum != null && keyNum != undefined) {
		isAccepted = true;
	}
	
	return isAccepted;
}
