// global vars
isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
var frmActive = false;
var pageloaded = false;
var loadMethods = [];

function $get(objid) {
	return document.getElementById(objid);
}
function comAddEventListener(el, event, func) {
	if (el == document && event == 'ready') hs.push(hs.onReady, func);
	try {
		el.addEventListener(event, func, false);
	} catch (e) {
		try {
			el.detachEvent('on'+ event, func);
			el.attachEvent('on'+ event, func);
		} catch (e) {
			el['on'+ event] = func;
		}
	} 
}
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function comRemoveEventListener(el, event, func) {
	try {
		el.removeEventListener(event, func, false);
	} catch (e) {
		try {
			el.detachEvent('on'+ event, func);
		} catch (e) {
			el['on'+ event] = null;
		}
	}
}

//ensure highslide adds it's container to the form element
hs.onActivate = function() {
	var theForm = document.forms[0];
	if (theForm) theForm.appendChild(hs.container);
}
//turn off credits (we have a paid version)
hs.showCredits = false;

function pageLoaded() {
    var txtSearch = $get("txtSearch");
    if (txtSearch != null) {
    	if (!txtSearch.hasFocus) {
    		txtSearch.value = txtSearch.defaultValue;
    	}
    }

    pageloaded = true;
    if (IsArray(loadMethods) && loadMethods.length > 0) {
    	for (x = 0; x < loadMethods.length; x++) {
    		CallMethod(loadMethods[x], x);
    	}
    }
    if (typeof hs != "undefined") {
    	if (hs.expandCursor) {
    		var sel = '.highslide img',
			dec = 'cursor: url(' + hs.graphicsDir + hs.expandCursor + '), pointer !important;';

    		var style = hs.createElement('style', { type: 'text/css' }, null,
			document.getElementsByTagName('HEAD')[0]);

    		if (!hs.ie) {
    			style.appendChild(document.createTextNode(sel + " {" + dec + "}"));
    		} else {
    			var last = document.styleSheets[document.styleSheets.length - 1];
    			if (typeof (last.addRule) == "object") last.addRule(sel, dec);
    		}
    	}
    	hs.registerOverlay({
    		html: '<div class="closebutton" onclick="return hs.close(this)" title="Close"></div>',
    		position: 'top right'
    	});
    	hs.Expander.prototype.onAfterExpand = function() {
    		if (this.a.id == 'loginAnchor') {
    			var ctl = getLoginEmailControl();
    			if (ctl.value.length == 0) {
    				ctl.value = getValue('loginEmail');
    			}
    			if (ctl.value.length > 0) {
    				ctl = getLoginPswdControl();
    			}
    			ctl.blur();
    			ctl.focus();
    		}
    	}
    	hs.outlineType = 'rounded-white';
    }
}

function CallMethod(val, idx)
{
	eval(val+'()');
}

function AddValue(arry, val) {
	if (arry == null || !IsArray(arry))
	{
		arry = [];
	}
	arry.push(val);
}

function IsArray(testObject) {
	return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function is_default(txtBox) {
	if (txtBox.value == txtBox.defaultValue)
		return true;
	return false;
}
function search_Blur(txtBox)
{
	txtBox.hasFocus = false;
	if(txtBox.value=='') txtBox.value=txtBox.defaultValue;
}
function search_Focus(txtBox)
{
	txtBox.hasFocus = true;
	if(is_default(txtBox)) txtBox.value='';
}
function search_KeyPress(e, txtBox)
{
	var key;
	if (window.event)	// test for Netscape
		key = window.event.keyCode;
	else if (e)			// test for IE
		key = e.which;
	else				// all other browsers
		return true;

	var keyChar = String.fromCharCode(key);
	var validChar = true;

	if (key == 13)		// test for Enter key
	{
		if (txtBox.value.length > 0) {
			validChar = false;
			doSearch();
		}
	}

	return validChar;
}

function doSearch()
{
	var txtSearch = $get("txtSearch");
	var val = txtSearch.value;
	var is_itm_num = false;
	if (val == txtSearch.defaultValue || val.length == 0) {
		alert('No search value entered.');
	}
	else {
		val = val.toLowerCase().replace('#',' ').replace(':',' ').trim();
		//check for item specific search
		if (val.substring(0, 4) == 'item') {
			val = val.replace('item','').replace(' ', '').trim();
		}
		if (val.indexOf(' ') == -1 && val.indexOf('-') > 0) {
			var parts = val.split('-');
			if (parts.length == 2 && IsInteger(parts[0]) && IsInteger(parts[1])) {
				is_itm_num = true;
			}
		}
		if (is_itm_num) {
			top.location.href = 'Product.aspx?itm=' + escape(val);
		}
		else {
			top.location.href = SearchURL + 'w=' + escape(val);
		}
	}
}

function IsInteger(val) {
	if (val == null || val.toString().length == 0) {
		return false;
	}
	if (isNaN(val)) {
		return false;
	}
	if (parseInt(val).toString() == val && parseInt(val) > 0) {
		return true;
	}
	return false;
}

function mailingList(page, ctl) {
	if (!is_default($get(ctl))) {
		top.location.href = page + $get(ctl).value;
	}
	else {
		alert('Please enter your e-mail address first.');
	}
}

// common forms processing function
function FormRefresh() {
	__doPostBack('', '');
	//document.forms[0].submit();
}
function FormSubmit(act, elementname, elementvalue)
{
	if (!frmActive)
	{
		frmActive = true;
		$get("act").value = act;
		if (elementname != "")
		{
			$get(elementname).value = elementvalue;
		}
		FormRefresh();
	}
}
function FormSubmitValidate(question,act,elementname,elementvalue)
{
	if ( (confirm(question) ? "yes":"no") == "yes")
	{
		FormSubmit(act,elementname,elementvalue);
	}
}
function fnValidateFieldNumeric(objField) {
	// Convert empty fields to zero, and remove leading zeroes, converting field value to an integer number:
	if (objField.value == "") objField.value = 0;
	objField.value = Number(objField.value);
}
function fnSelectAll(objField)
{
	// Select all text upon arriving in a field.  IE5 does this automatically, IE4 doesn't.
	objField.select();
}
//Auto tab feature for phone # split into 3 fields (requires the calling page to implement getControl function)
function phone(e, curobj, nextctrl, len) {
	var nextobj = getControl(nextctrl);

	//ignore keys which are not numeric
	if (e.keyCode < 48 || e.keyCode > 57) {
		return true;
	}

	if (curobj != null && nextobj != null) {
		if (curobj.value.length == len) {
			nextobj.focus();
		}
	}

	return true;
}
function fnValidateKey(e,tp,prc)
{
	// Test for valid characters based on the type (tp) of character being expected.
	// 'e' = passed event object;
	// 'tp' = type of character to mask;
	// 'prc' = process Enter and if so form element to set focus to
	//		* if prc = 0 enter will not be handled special
	var key;
	if (window.event)	// test for Netscape
	   key = window.event.keyCode;
	else if (e)			// test for IE
	   key = e.which;
	else				// all other browsers
	   return true;
	
	var keyChar = String.fromCharCode(key);
	var validChar = true;
	if (key == 13)		// test for Enter key
	{
		if (prc.length > 0) {
			validChar = false;
			$get(prc).focus();
			return false;
		}
	}
	else if ( key < 32 )
	{
		//allow all extended keypresses through
		return true;
	}
	else
	{
		switch (tp)
		{
			case "#":	// numeric only
				// Use regular expression test, "/^\d/", to see if it's a digit.
				if (!(/^\d/.test(keyChar))) { validChar = false; }
				break;
			case "$":	// dollar amount
				if (!(/^[0-9\.]/.test(keyChar))) { validChar = false; }
				break;
			case "A":	// alpha only with space, underscore, & period
				// Use regular expression test, "/^[a-zA-Z\x20]/", to see if it's a word character.
				// Allows letters (upper & lowercase), spaces, periods, and the underscore character.
				if (!(/^[a-zA-Z\x20\.]$/.test(keyChar))) { validChar = false; }
				break;
			case "A!":	// alpha only with space
				// Use regular expression test, "/^[a-zA-Z\x20]/", to see if it's a word character.
				// Allows letters (upper & lowercase) and spaces.
				if (!(/^[a-zA-Z\x20]$/.test(keyChar))) { validChar = false; }
				break;
			case "A#":	// alpha-numeric with space, underscore, & period
				// Use regular expression test, "/^[\w\x20]/", to see if it's a word character or digit.
				// Allows letters (upper & lowercase), spaces, periods, and the underscore character.
				if (!(/^[\w\x20\.]$/.test(keyChar))) { validChar = false; }
				break;
			case "A#~":	// alpha-numeric with underscore & period
				// Use regular expression test, "/^[\w]/", to see if it's a word character or digit.
				// Allows letters (upper & lowercase), periods, and the underscore character.
				if (!(/^[\w\.]$/.test(keyChar))) { validChar = false; }
				break;
			case "A#!":	// alpha-numeric only
				// Use regular expression test, "/^[a-zA-Z0-9]/", to see if it's a word character or digit.
				// Allows letters (upper & lowercase) and numbers only.
				if (!(/^[a-zA-Z0-9]/.test(keyChar))) { validChar = false; }
				break;
			case "email":	// alpha-numeric with underscore, period, "-", "@"
				// Use regular expression test, "/^[\w]/", to see if it's a word character or digit.
				// Allows letters (upper & lowercase), periods, and the underscore character.
				if (!(/^[\w\.\-\@]$/.test(keyChar))) { validChar = false; }
				break;
			case "phone":	// phone number; numeric only + "-" + "." + "," + space
				// Use regular expression test, "/^\d/", to see if it's a digit.
				if (!(/^[0-9\-\.\x20\,]/.test(keyChar))) { validChar = false; }
				break;
			case "pswd":	// alpha-numeric with select symbols (no spaces)
				// Use regular expression test, "/^[\w]/", to see if it's a word character or digit.
				// Allows letters (upper & lowercase), and symbols: ! @ # $ % ^ * _ - = + .
				if (!(/^[\w\.\-\@\!\#\$\%\^\*\+\=]$/.test(keyChar))) { validChar = false; }
				break;
		}
	}
	// If it's not a valid character, throw away the keypress:
	if ( !validChar && keyChar >= ' ' && keyChar <= '~' ) {
		e.cancelBubble = true;
		e.returnValue = false;
		return false;
	}
	return true;
}
// Limit size of input into a textarea field
function txtLimit(objFld, cntFld, limit)
{
	if (objFld.value.length > limit)	// truncate anything past limit
		objFld.value = objFld.value.substring(0, limit);
	else 	// let user know how many characters are left if there is such a field
		if (cntFld != null)
			cntFld.value = limit - objFld.value.length;
}

// common popup window management
function help(page)
{
	window.open(page,'help','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=500,height=400,top=1,left=1');
}
function openpic(itm_id)
{
	var msgWindow
	msgWindow = window.open('./showpic.asp?tp=full&item='+itm_id,'thi_pic','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=600,height=400,top=1,left=1');
	msgWindow.focus()
}
function openlink(page)
{
	window.open(page,'tlink','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=500,height=400,top=1,left=1');
}
function printOrder() {
	window.open(receiptURL, 'receipt', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=800,height=600,top=1,left=1');
}

// common mouseover buttons
function turnon(name)
{
	$get(name).src = eval(name + "On.src");
}
function turnoff(name)
{
	$get(name).src = eval(name + "Off.src");
}

function on(name)
{
	if (pageloaded) turnon(name);
}
function off(name)
{
	if (pageloaded) turnoff(name);
}

// Misc functions
function printpage(psFrame)
{
	top.frames[psFrame].focus();
	top.frames[psFrame].print();
	self.focus();
}
function reloadTop(page)
{
	if (document.images)
		top.location.replace(page);
	else
		top.location.href = page;
}
function logout() {
	SetCookie("mem_loginEmail", "");
	SetCookie("mem_md5_loginPswd", "");
}
//get URL parameter
function gup(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}

var dev = true;  //change me to true to skip adding the javascript error trapping routine (helps when using IE/VS to debug js)
if (!dev) {
	window.onerror = function(msg, url, line) {
		alert('******* an error has occurred ********'
        + '\n\n------------------------------------------------------'
        + '\nError details'
        + '\nText:' + msg + '\nurl:' + url + '\nline:' + line);
	}
}

comAddEventListener(window, 'load', pageLoaded);
