var s = '';

function onCategoryKeyPress(e) {
	var code;

	if (!e) {
		var e = window.event;
	}

	if (e.keyCode) {
		code = e.keyCode;
	} else if (e.which) {
		code = e.which;
	}

	processCategoryKeyCode(code);
}

function processCategoryKeyCode(code) {
	if (code == 13) {
		submitForm('advanced_search');
	}
}

function onManufacturerKeyPress(e) {
	var code;

	if (!e) {
		var e = window.event;
	}

	if (e.keyCode) {
		code = e.keyCode;
	} else if (e.which) {
		code = e.which;
	}

	processManufacturerKeyCode(code);

	return false;
}

function processManufacturerKeyCode(code) {
	if (code == 13) {
		submitForm('advanced_search');
	} else {
		s += String.fromCharCode(code);
		selectElement('as_manufacturers_id');
	}
}

function onTopManufacturerKeyPress(e) {
	var code;

	if (!e) {
		var e = window.event;
	}

	if (e.keyCode) {
		code = e.keyCode;
	} else if (e.which) {
		code = e.which;
	}

	processTopManufacturerKeyCode(code);

	return false;
}

function processTopManufacturerKeyCode(code) {
	if (code == 13) {
		submitForm('advanced_search');
	} else {
		s += String.fromCharCode(code);
		selectElement('as_manufacturers_id');
	}
}

function selectElement(elementId) {
	selectOptions = document.getElementById(elementId).options;

	var isFound = false;
	if ((s.toUpperCase().indexOf('HP') == 0) && (!isFound)) {
		hpIndex = getOptionIndex(selectOptions, 'Hewlett');
		if (hpIndex >= 0) {
			selectOptions[hpIndex].selected = true;
			isFound = true;
		}
	}

	for (var i = 0; i < selectOptions.length; i++) {
		if ((selectOptions[i].text.toUpperCase().indexOf(s.toUpperCase()) == 0) && (!isFound)) {
			selectOptions[i].selected = true;
			isFound = true;
		} else {
			selectOptions[i].selected = false;
		}
	}
}

function getOptionIndex(selectOptions, optionText) {
	for (var i = 0; i < selectOptions.length; i++) {
		if (selectOptions[i].text.toUpperCase().indexOf(optionText.toUpperCase()) == 0) {
			return i;
		}
	}

	return -1;
}

function submitForm(formId) {
	document.getElementById(formId).submit();
}

function clearSearchString() {
	s = '';
}

function submitSelect(select){
    if (select.value != -1) {
      select.form.submit();
    }
}
/*
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}
onkeyup="limitTextArea(this,350,0);" onkeydown="limitTextArea(this,350,0);" onblur="limitTextArea(this,350,0);" onfocus="limitTextArea(this,350,0);"
*/
function limitTextArea(what,limitNum,counter) {

	if (what.value.length > limitNum) {
		what.value=what.value.substring(0,limitNum);
	}
	if (counter == '' || counter == 0) {
	   counter = what.name + '_cnt';
	}
	var c = document.getElementById(counter);
	c.innerHTML = limitNum - what.value.length;
}

