var _deptBox;
var _classBox;
var _subclassBox;
var _brandBox;
var _sizeBox;
var _subsizeBox;
var _searchForm;

var _formWorking = false;
var _isIE = false;

function setupForm() {
	if(window.ActiveXObject) {
		_isIE = true;
	}

	_searchForm = document.getElementById("advSearchForm");

	if(!validateObject(_searchForm, 'No user selectable search form')) { return; }

	/* populate and validate global variables */
	/* these are all required */
	_deptBox = _searchForm.dept;
	if(!validateObject(_deptBox, "no department select box")) { return; }

	_classBox = _searchForm.elements.namedItem('class');
	if(!validateObject(_classBox, "no class select box")) { return; }
	
	_subclassBox = _searchForm.subclass;
	if(!validateObject(_subclassBox, "no subclass select box")) { return; }

	/* optional */
	_brandBox = _searchForm.manufacturer;
	_sizeBox = _searchForm.size;
	_subsizeBox = _searchForm.subsize;

	resetToAllDepartments();

	_formWorking = true;
}

function resetToAllDepartments() {
	_deptBox.selectedIndex = 0;

	setDisabledSelectOption(_classBox, '-- Select A Department --', '');
	setDisabledSelectOption(_subclassBox, '-- Select A Department --', '');

	if(_sizeBox) {
		setDisabledSelectOption(_sizeBox, '-- Select A Department --', '');
	}

	if(_subsizeBox) {
		setDisabledSelectOption(_subsizeBox, '-- Select A Department --', '');
	}
}

function submitAdvSearch() {
	if(!_formWorking) {
		alert('An error has previously occurred and we are unable to run your search.')
		return false;
	}
	
	var sizeSelection = '';
	var subsizeSelection = '';

	if(_sizeBox) {
		sizeSelection = getMultiselectValue(_sizeBox);
	}

	if(_subsizeBox) {
		subsizeSelection = getMultiselectValue(_subsizeBox);
	}

	if( (isAllOrNoneOption(sizeSelection) || sizeSelection == '') && 
		(isAllOrNoneOption(subsizeSelection) || subsizeSelection == '') ) {

		/* no size search */
		_searchForm.a.value = "29";
	} else {
		/* size search */
		_searchForm.a.value = "69";
	}
	
	_searchForm.action = "istar.asp"
	_searchForm.action = "istar.asp"
	return true;
}

function getMultiselectValue(box) {
	if(box.selectedIndex == -1) {
		return "";
	} else {
		return box.options[box.selectedIndex].value;
	}
} 

function isAllOrNoneOption(data) {
	if(data == "ALL" || data == "NONE") {
		return true;
	} else {
		return false;
	}
}

function isAllOption(data) {
	if(data == "ALL") {
		return true;
	} else {
		return false;
	}
}

function removeEmptyOptionFromSelect(box) {
	if( box.options[0].value.length == 0 ) {
		box.remove(0);
	}
}

function repopulateAllManufacturers() {
	if(!_brandBox) 
		return;
	
	setDisabledSelectOption(_brandBox, '-- Updating --');
	sendAjaxRequest('istar.asp?a=68', gotAllManufacturers, 'deptOutput=0&mfgOutput=1' );
}

function gotAllManufacturers(httpRequest) {
	if(httpRequest.readyState != 4) {
		return;
	}
	
	if(!validateHttpRequest(httpRequest))
		return;


	var xmlDoc = httpRequest.responseXML;
	validateObject('No XML document available. (all brands)');

	var xmlManufacturers = xmlDoc.getElementsByTagName("manufacturers");
	if( !validateTagExists(xmlManufacturers, 'No XML manufacturers container') ) 
		return;

	xmlManufacturers = xmlManufacturers[0].getElementsByTagName("manufacturer");

	updateSelectFromXML(_brandBox, xmlManufacturers, 'all manufacturers');

	_brandBox.disabled = false;
}

function deptChange() {
	if(isAllOption(getValueFromSelectBox(_deptBox))) {
		/* they selected "all" */
		resetToAllDepartments();
		repopulateAllManufacturers();
	} else {
		/* they selected a real department */
		
		setDisabledSelectOption(_classBox, '-- Updating --');

		if(_brandBox) {
			setDisabledSelectOption(_brandBox, '-- Updating --');
		}

		if(_sizeBox) {
			setDisabledSelectOption(_sizeBox, '-- Updating --');
		}

		if(_subsizeBox) {
			setDisabledSelectOption(_subsizeBox, '-- Updating --');
		}

		sendAjaxRequest('istar.asp?a=68', gotClasses, 'deptSizesOutput=1&deptSubsizesOutput=1&deptMfgOutput=1&dept=' + escape(getValueFromSelectBox(_deptBox)) );
	}
}

function classChange() {
	if( getValueFromSelectBox(_classBox) == 'ALL' ) {
		setDisabledSelectOption(_subclassBox, '-- Select A Class --');
		return;
	}

	setDisabledSelectOption(_subclassBox, '-- Updating --');

	sendAjaxRequest('istar.asp?a=68', gotSubclasses, 'dept=' + escape(getValueFromSelectBox(_deptBox)) + '&class=' + escape(getValueFromSelectBox(_classBox)));
}

function gotSubclasses(httpRequest) {
	if(httpRequest.readyState != 4) {
		return;
	}
	
	if(!validateHttpRequest(httpRequest))
		return;

	var xmlDoc = httpRequest.responseXML;
	validateObject('No XML document available. (subclasses)');

	var xmlSubclasses = xmlDoc.getElementsByTagName("subclasses");
	if( !validateTagExists(xmlSubclasses, 'No XML subclasses container') ) 
		return;

	xmlSubclasses = xmlSubclasses[0].getElementsByTagName("subclass");

	updateSelectFromXML(_subclassBox, xmlSubclasses, 'subclass');

	_subclassBox.disabled = false;
}

function gotClasses(httpRequest) {
	if(httpRequest.readyState != 4) {
		return;
	}
	
	if(!validateHttpRequest(httpRequest))
		return;

	var xmlDoc = httpRequest.responseXML;
	validateObject(xmlDoc, 'No XML document available. (classes)');

	var xmlClasses = xmlDoc.getElementsByTagName("classes");
	if( !validateTagExists(xmlClasses, 'No XML classes container') ) 
		return;

	xmlClasses = xmlClasses[0].getElementsByTagName("class");

	updateSelectFromXML(_classBox, xmlClasses, 'class');

	if(xmlClasses.length == 0) {
		/* no classes available, so no subclasses either */
		setSelectNoneAvailable(_subclassBox);
	} else {
		setDisabledSelectOption(_subclassBox, '-- Select A Class --', '');
	}

	/* handle brands, they come with classes */
	var xmlManufacturers = xmlDoc.getElementsByTagName("deptManufacturers");
	if(!validateTagExists(xmlManufacturers, 'No XML department brands container.'))
		return;

	xmlManufacturers = xmlManufacturers[0];
	
	gotManufacturers(xmlManufacturers);

	/* handle sizes, they come with classes */
	var xmlSizes = xmlDoc.getElementsByTagName("deptSizes");
	if(!validateTagExists(xmlSizes, 'No XML department sizes container.'))
		return;

	xmlSizes = xmlSizes[0];
	
	gotSizes(xmlSizes);

	/* handle subsizes, they come with sizes */
	var xmlSubsizes = xmlDoc.getElementsByTagName("deptSubsizes");
	if(!validateTagExists(xmlSizes, 'No XML department subsizes container.'))
		return;

	xmlSubsizes = xmlSubsizes[0];
	
	gotSubsizes(xmlSubsizes);

	_classBox.disabled = false;
}

function updateSelectFromXML(box, xmlArray, dataType) {
	/* dataType is just a string that is used in errors thrown from here */
	
	emptySelect(box);

	if(xmlArray.length == 0) {
		setSelectNoneAvailable(box);
	} else {
		addOptionToSelect(box, 'All', 'ALL', null);

		for(var i=0; i < xmlArray.length; i++) {
			var dataName = xmlArray[i].getElementsByTagName("name");
			if( !validateTagExists(dataName, 'No XML ' + dataType + ' name element') )
				return;

			dataName = dataName[0];

			if( !validateObject(dataName.firstChild, 'No XML ' + dataType + ' name text element') )
				return;

			var dataCode = xmlArray[i].getElementsByTagName("code");
			if( !validateTagExists(dataCode, 'No XML ' + dataType + ' code element') )
				return;

			dataCode = dataCode[0];

			if( !validateObject(dataCode.firstChild, 'No XML ' + dataType + ' code text element') )
				return;

			addOptionToSelect(box, dataName.firstChild.nodeValue, dataCode.firstChild.nodeValue, null);
		}
	}
}

function gotManufacturers(xmlDoc) {
	if(!_brandBox) {
		return;
	}

	var xmlManufacturers = xmlDoc.getElementsByTagName("manufacturer");

	updateSelectFromXML(_brandBox, xmlManufacturers, 'department brand');

	_brandBox.disabled = false;
}

function gotSizes(xmlDoc) {
	if(!_sizeBox) {
		return;
	}

	var xmlSizes = xmlDoc.getElementsByTagName("sizeGroup");

	updateSelectFromXML(_sizeBox, xmlSizes, 'department size');

	_sizeBox.disabled = false;
}

function gotSubsizes(xmlDoc) {
	if(!_subsizeBox) {
		return;
	}

	var xmlSubsizes = xmlDoc.getElementsByTagName("subsizeGroup");

	updateSelectFromXML(_subsizeBox, xmlSubsizes, 'department subsize');

	_subsizeBox.disabled = false;
}

function setSelectNoneAvailable(box) {
	emptySelect(box);
	addOptionToSelect(box, 'None Available', 'NONE', null);
	box.disabled = false;
}

function validateTagExists(o, errorText) {
	if(!validateObject(o, errorText)) {
		return false;
	}
	
	if(o.length == 0) {
		ajaxError(errorText);
		return false;
	}

	return true;
}

function validateObject(o, errorText) {
	if(!o) {
		ajaxError(errorText);
		return false;
	}

	return true;
}

function setDisabledSelectOption(box, name, value) {
	/* this empties the box as well */

	box.disabled = false;

	emptySelect(box);
 	addOptionToSelect(box, name, value, null);

	box.disabled = true;
}

function addOptionToSelect(box, name, value, afterOption) {
	var option = document.createElement('OPTION');
	option.text = name;
	option.value = value;
	
	if(afterOption == null) {
		if(_isIE) {
			box.add(option);
		} else {
			box.add(option, null);
		}
	} else {
		if(_isIE) {
			box.add(option, afterOption.index);
		} else {
			box.add(option, afterOption);
		}
	}	

	return option;
}

function emptySelect(box) {
	while(box.length) {
		box.remove(0);
	}
}

function sendAjaxRequest(url, callback, parameters) {
	var httpRequest;

	if(window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
	} else {
		httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}

	httpRequest.onreadystatechange = function() { callback(httpRequest); }
	httpRequest.open('POST', url, true);
	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	httpRequest.send(parameters);
}

function getValueFromSelectBox(box) {
	if(box.selectedIndex == -1) {
		return "";
	} else {
		return box.options[box.selectedIndex].value;
	}
}

function isGood(o) {
	if(o) {
		alert("object is good");
	} else {
		alert("object is bad");
	}
}

function ajaxError(errorText) {
	alert('Error: ' + errorText);
	_formWorking = false;
}

function validateHttpRequest(httpRequest) {
	if(httpRequest.status != 200) {
		ajaxError('Invalid HTTP response status (' + httpRequest.status + ')');
		return false;
	}

	return true;
}
