function populateFields(chkThis, frmThis, arFieldsFrom, arFieldsTo) {
	var i, j;
	var fefrom;
	var feto;
	var fetorep;

	if (chkThis.checked) {
		for (i = 0; i < arFieldsFrom.length; i++) {
			if (frmThis[arFieldsTo[i]]) {
				fefrom = frmThis[arFieldsFrom[i]];
				feto = frmThis[arFieldsTo[i]];
				if (fefrom.tagName.toLowerCase() == "select" && feto.tagName.toLowerCase() == "select") {
					feto.options.length = 1;

					for (j = 1; j < fefrom.options.length; j++) {
						fetorep = feto.options.add ? feto.options : feto;
						fetorep.add(document.createElement("option"));
						feto.options[feto.options.length - 1].value = fefrom.options[j].value;
						feto.options[feto.options.length - 1].text = fefrom.options[j].text;
					}
					feto.selectedIndex = fefrom.selectedIndex;
				} else {
					frmThis[arFieldsTo[i]].value = frmThis[arFieldsFrom[i]].value;
				}
			}
		}
	} else {
		for (i = 0; i < arFieldsFrom.length; i++) {
			if (frmThis[arFieldsTo[i]])
				frmThis[arFieldsTo[i]].value = '';
		}
	}
}
//place holders to be used to store and get locale text assets
function AddTextAsset(key, value) {
	if (!window.acuTextAssets)
		window.acuTextAssets = {};
	window.acuTextAssets[key] = value;
}
function GetTextAsset(id) {
	if (window.acuTextAssets)
		return window.acuTextAssets[id];
}

/*JONK's getAcuElementById------
// some browser sniffing:*/
document.version = parseFloat(navigator.appVersion);
document.hostApplication = navigator.appName.substring(0, 3);
document.browserClass = parseInt(document.version);

if (document.browserClass >= 4) {
	if (document.browserClass == 4) { /* might need to check NN5 browsers as well*/
		if (document.hostApplication == "Net") {/* got netscape?*/
			/* need to "fake" the style attribute
			// so we add a little misdirection
			// by creating an object that will
			// intercept the property setting.
			// we make NN think it's setting properties 
			// in A style object, when it is actually
			// redirected to set the property to the actual layer
			// and you might have thought it couldn't be done...*/
			function _style() {
				this.layerRef = null;    /* this will be set when <B style="COLOR: black; BACKGROUND-COLOR: #ffff66">getElementByID</B> is called

			we don't actually need these -- it's just pseudocode
			this.visibility = "";
			this.top = 0;
			this.left = 0;

			// very cool method in NN (only) -- 
			// since these aren't "real" object properties
			// it's more like a watchdog
			// for more info -- check Netscape's docs */
				this.watch("visibility", function(id, old, nval) {  /* set the "real" property of the layer here*/
					eval("this.layerRef." + id + " = '" + nval + "'");
					return nval;
				});
				/* you must return either old or nval*/
				this.watch("top", function(id, old, nval) {
					eval("this.layerRef." + id + " = '" + nval + "'");
					return nval;
				});
				this.watch("left", function(id, old, nval) {
					eval("this.layerRef." + id + " = '" + nval + "'");
					return nval;
				});

				/* note: all the inline functions are exactly the same
				//  you can cut'n'paste for each property you need to watch!*/
			}

			/* here we set up the "appearance" of a style property*/

			Layer.prototype.style = new _style();
			/* each time a new layer is created, a new _style() object
			// is attached to it*/

		} /* end if NN*/

		/* here, getElementById is getting declared by BOTH IE4 and NN4 browsers*/
		document.getAcuElementById = function(name) {
			if (document.hostApplication == "Net") /*netscape 4*/
			{
				if (document.browserClass == 4) {
					var lyr = eval("document." + name);

					/* only need to do this once, but
					// what the hey...*/
					if (lyr.style != null) lyr.style.layerRef = lyr;

					return lyr;
				} else {
					return document.layers('" + name + "');
				}
			}
			else /* IE*/
			{
				return eval("document.all." + name);
			}
		}
	} else {/* end browserClass == 4*/
		if (document.hostApplication == "Net") {
			document.getAcuElementById = function(name) {
				if (!eval("document." + name)) {
					return document.getElementById(name);
				} else {
					return eval("document." + name);
				}
			}
		} else {
			document.getAcuElementById = function(name) {
				return document.getElementById(name);
			}
		}
	}
}
/*END JONK's getAcuElementById---------*/

function DoAjaxRequest(params, callback, url, m) {
	new Ajax.Request(url, {
		method: m,
		parameters: params,
		onSuccess: function(transport) {
			if (callback)
				callback(transport);
		}
	});
}

function showHideDisplay(obj) {
	if (typeof (obj) == "string") obj = $(obj);
	if (obj) {
		if (getStyleByObj(obj, "display") == "none") {
			obj.style.display = "block";
		} else if (getStyleByObj(obj, "display") == "block") {
			obj.style.display = "none";
		}

	}
}

/*get the value of a parameters from the query string*/
function getQueryParam(name) {
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var tmpURL = window.location.href;
	var results = regex.exec(tmpURL);
	if (results == null)
		return "";
	else
		return results[1];
}

/*
replaceQueryParam finds and replaces a query string parameter in a url
*/
function replaceQueryParam(url, param, value) {
	var delim = '&'; if (url.indexOf('?') == -1) delim = '?';
	var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");

	if (url.match(re))
		return url.replace(re, '$1' + param + "=" + value + '$2');
	else
		return url + delim + param + "=" + value;
}

/*get the value of a cookie by name*/
function getCookieValue(name) {
	var nameEQ = name.toLowerCase() + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length).toLowerCase();
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

/*
get the value of a cookie by 
name - cookie name
value - value to set
expire days - number of days after which this should expire
*/
function setCookieValue(name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + '; path=/');
}

/*
check to see if the client supports cookes
returns true/false
*/
function cookiesSupported() {
	setCookieValue('test', '0', 1);
	var cookieEnabled = (document.cookie && document.cookie != '') ? true : false;
	if (cookieEnabled) setCookieValue('test', '', -1);
	return cookieEnabled;
}

/*
check to see if we need to redirect to the choose country page
*/
function tlfCountryCheck(changecountry, id) {
	if (cookiesSupported()) {
		var countryID = getCookieValue('countryid');
		if (countryID != id) countryID == null;
		//if country id null, or change in country id and country id is valid int
		if ((countryID != id || countryID == null) && parseInt(id) > 0) {
			setCookieValue('countryid', id, 365);
		}
		//show choose country window if called for
		if (changecountry) {
			showProtoWindow("choosecountry", "/choosecountry/choosecountry.aspx");
		}
	}
}
function CountryLookup(s, dc) {
	//only perform if cookies are supported;
	if (cookiesSupported()) {
		//check for countryid already set, if set, do nothing;
		var countryID = getCookieValue('countryid');
		var qs = document.location.search.toQueryParams();
		//if countryid cookie not set / null, then do ip look up;
		//allow for override, force IP lookup, ip=true
		if ((countryID == null) || (typeof qs.ip != 'undefined')) {
			//set default country cookie in case lookup fails
			tlfCountryCheck(false, dc);
			//set up handler url
			var url = document.location.protocol + '//' + document.location.hostname + '/handlers/country-lookup-1.0.aspx';
			var params = { "siteid": s };
			//set up callback function to evaluate response;
			var callback = function(t) {
				//get json response;
				var json = t.responseText.evalJSON();
				//make sure we have an iplookup obj;
				if (json.iplookup) {
					//check for redirect
					if (json.iplookup.redirect) {
						var redirect = json.iplookup.url + location.pathname;
						if (document.location.search != '') redirect += document.location.search + '&';
						else redirect += '?';
						redirect += 'countryid=' + json.iplookup.regionid;
						var cid = getCookieValue('cid');
						if (cid != null)
							redirect += '&cid=' + cid;
						//call AbandonCart and perform redirect
						AbandonCart(redirect);
					} else if (parseInt(json.iplookup.regionid) > 0)
						tlfCountryCheck(false, json.iplookup.regionid); //if regionid = 0 means none found, do nothing
				}
			};
			//do ajax post
			DoAjaxRequest(params, callback, url, 'POST');
		}
	}
}
function showProtoWindow(id, a_href) {
	var name = id + 'Proto';
	var win = new Window(name, {
		className: "dialog",
		width: 860,
		height: 458,
		draggable: false,
		minimizable: false,
		maximizable: false,
		resizable: true,
		url: a_href,
		destroyOnClose: true,
		zIndex: 3000
	});
	win.showCenter(true, 60);
}
function SetCurrency(sid, lid, cid, type) {
	var url = document.location.protocol + '//' + document.location.hostname + '/handlers/customer-info-1.0.aspx';
	var params = {
		"action": 'set_currency',
		"siteid": sid,
		"lcid": lid,
		"cur": cid
	};
	if (type == 2) setCookieValue('acu-lcid', lid, 1);
	var callback = function(t) {
		var json = t.responseText.evalJSON();
		if (json.cid == cid) {
			var locale = json.prefix + '-' + json.code;
			window.location.replace(document.location.protocol + '//' + document.location.hostname + '/' + locale + CleanLocalePath());
		} else if (json.error) {
			alert(json.error);
		}
	};
	DoAjaxRequest(params, callback, url, 'GET');
}
function GoToSite(base, rid, cid) {
	var redirect = document.location.protocol + '//' + base;
	if (/^\/.*\.aspx$/.test(document.location.pathname))
		redirect += document.location.pathname;
	else
		redirect += '/home/home.aspx';
	redirect += '/?countryid=' + rid;
	if (cid != '') redirect += '&cid=' + cid;
	AbandonCart(redirect);
}
function AbandonCart(redirect) {
	var callback = function(t) {
		window.location = redirect;
	};
	var url = document.location.protocol + '//' + document.location.hostname + '/default.asp?processor=asp&asp_processor=store&action=abandoncart';
	var params = { "rngn": 'xml' };
	DoAjaxRequest(params, callback, url, 'GET');
}
function CleanLocalePath() {
	var regex = /^(\/[a-z]{2}\-[a-z]{3})/i;
	if (regex.match(document.location.pathname))
		return document.location.pathname.replace(regex, '');
	else
		return document.location.pathname;
}
function ToggleULMenu(anchor) {
	var ul = $(anchor).next('ul', 0);
	$('locale-menu').select('a.on', 'li.on').each(function(item) {
		item.removeClassName('on');
	});

	//toggle current UL menu
	if (ul && !ul.visible())
		ul.show();
	else if (ul)
		ul.hide();

	//set parent visibility and 'on' class	
	var parent = $(anchor).up(0);
	while (parent != null && parent.nodeName.toUpperCase() != 'DIV') {
		if (parent.nodeName.toUpperCase() == "LI") {
			parent.down(0).addClassName('on');
		} else if (parent.nodeName.toUpperCase() == "UL") {
			parent.show();
		}
		parent = parent.up(0);
	}
}
function SetCurrentLI(pagename) {
	var li = $('li-' + pagename);
	if (li) ToggleULMenu(li.down(0));
}
function MiniCartInit() {
	jQuery('#checkoutaddtocart').removeAttr('disabled');
	if ($('recommendations') && $('mini-cart-rec-products')) {
		var items = $('recommendations').select('div.departmentitem');
		var l = (items.length > 4 ? 4 : items.length);
		for (var i = 0; i < l; i++) {
			$('mini-cart-rec-products').insert(Element.clone(items[i], true));
		}
		$('mini-cart-rec-products').insert('<div style="clear:both;"></div>');
	}
	jQuery(document).click(function(event) {
		var target = jQuery(event.target);
		var id = target.attr('id');
		if (jQuery('#mini-cart').is(':visible') && target.parents('#mini-cart').length == 0) {
			if ((id && !id.match(/^mini\-cart/) && !id.match(/^checkoutaddtocart/)) || (typeof id == 'undefined')) {
				jQuery('#mini-cart').hide();
			}
		}
	});
}
var _miniCartInProc = false;
function CartAdd() {
	var cartForm = jQuery('#prodform');
	if (!_miniCartInProc && cartForm.length > 0) {
		_miniCartInProc = true;
		jQuery('#h_processor').val('cart');
		jQuery('#h_action').val('addtocart');
		var url = window.location.protocol + '//' + window.location.host + '/application.aspx'; //cartForm.attr('action');
		jQuery.ajax({
			'url': url,
			'type': 'post',
			'dataType': 'xml',
			'data': cartForm.serialize() + '&rngn=xml',
			'success': function(xml) { CartUpdateUI(xml); _miniCartInProc = false; },
			'error': function() { HandleAlertMessage('Failed to add item the cart, please refresh the page and try again.', 'user-message', 'alert'); _miniCartInProc = false; }
		});
	}
}
function CartUpdate() {
	var cartForm = jQuery('#cart-update');
	if (!_miniCartInProc && cartForm.length > 0) {
		_miniCartInProc = true;
		var url = window.location.protocol + '//' + window.location.host + '/application.aspx'; //cartForm.attr('action');
		jQuery.ajax({
			'url': url,
			'type': 'post',
			'dataType': 'xml',
			'data': cartForm.serialize(),
			'success': function(xml) { CartUpdateUI(xml); _miniCartInProc = false; },
			'error': function() { HandleAlertMessage('Failed to update the cart, please refresh the page and try again.', 'user-message', 'alert'); _miniCartInProc = false; }
		});
	}
}
function CartRemove(id) {
	var cartForm = jQuery('#cart-delete');
	if (!_miniCartInProc && cartForm.length > 0) {
		_miniCartInProc = true;
		var url = window.location.protocol + '//' + window.location.host + '/application.aspx'; //cartForm.attr('action');
		jQuery.ajax({
			'url': url,
			'type': 'post',
			'dataType': 'xml',
			'data': cartForm.serialize() + '&cartitemid=' + id,
			'success': function(xml) { CartUpdateUI(xml); _miniCartInProc = false; },
			'error': function() { HandleAlertMessage('Failed to update the cart, please refresh the page and try again.', 'user-message', 'alert'); _miniCartInProc = false; }
		});
	}
}
function CartUpdateUI(xml) {
	var errorArray = [];
	jQuery(xml).find('user_errors error').each(function(idx) {
		errorArray[errorArray.length] = jQuery(this).text();
	});
	if (errorArray.length > 0) {
		var errorHtml = '';
		for (var i = 0; i < errorArray.length; i++)
			errorHtml += errorArray[i] + '<br/>';
		HandleAlertMessage(errorHtml, 'user-message', 'alert');
	} else {
		var fields = jQuery(xml).find('field');
		var json = {};
		if (fields.length > 0) {
			var l = fields.length;
			for (var i = 0; i < l; i++) {
				if (jQuery(fields[i]).attr('id') == 'cartsummary') {
					json = jQuery.parseJSON(jQuery(fields[i]).find('value').text());
					break;
				}
			}
			if (json.cart) {
				jQuery('#header-cart-count').text('(' + json.cart.item_count + ') ');
				jQuery('#header-cart-total').text(' ' + window.currencySymbol + FormatNumber(json.cart.order_subtotal));
				jQuery('#cart-total').text(window.currencySymbol + FormatNumber(json.cart.order_subtotal));
				var headerRow = jQuery('#cart-items').find('tr.header');
				if (json.cartitems && json.cartitems.length > 0) {
					var count = json.cartitems.length;
					var carttable = jQuery('#cart-items');
					carttable.html(headerRow);
					for (var i = 0; i < count; i++) {
						carttable.append(RenderCartRow(json, i));
						RenderQtyInput(json.cartitems[i]);
					}
					BindQtyInputs();
				} else {
					jQuery('#cart-items').html(headerRow);
					jQuery('#cart-items').append('<tr><td colspan="5" align="center"><h3>There are currently no items in your shopping cart.</h3></td></tr>');
					if (jQuery('#applyoffercode').length == 1) {
						jQuery('.cart-offer-code').remove();
						jQuery('#cart-buttons').remove();
						jQuery('#checkoutupdatecart').remove();
					}
				}
			}
		}
		jQuery('#mini-cart').show();
	}
}
function BindQtyInputs() {
	jQuery('#cart-items input[name^="quantity_"]').keydown(function(event) {
		if (event.keyCode == 13) {
			event.preventDefault();
			CartUpdate();
		}
	});
}
function RenderCartRow(json, idx) {
	var cartitem = json.cartitems[idx];
	var cls = ((idx % 2) == 0) ? 'even' : 'odd';
	if (json.cartitems.length == (idx + 1)) cls += ' last';
	var html = '<tr class="' + cls + '"><td class="item-desc"><div>' + cartitem.alu + ' - <a href="/store/' + cartitem.alu + '.aspx">' + cartitem.name + '</a><br/>';
	if (jQuery('#applyoffercode').length != 0) {
		html += '<span class="carterror">';
		//add additional ph message
		if (cartitem.additional_ph > 0) html += ' ' + window.currencySymbol + cartitem.additional_ph + '.';
		//add cart item note
		if (cartitem.additional_ph_note != '') html += ' ' + cartitem.additional_ph_note;
		//add cart item errors
		if (json.carterrors) html += GetCartErrors(json.carterrors, cartitem.cartitemid);
		html += '</span>';
	}
	html += '</div><input type="hidden" value="' + cartitem.cartitemid + '" name="cartitemid_' + cartitem.cartitemid + '"/></td>';
	html += '<td class="price">' + window.currencySymbol + FormatNumber(cartitem.price) + '</td><td class="qty"></td>';
	html += '<td class="line-total">' + window.currencySymbol + FormatNumber(cartitem.ext_price) + '</td>';
	if (jQuery('#applyoffercode').length != 0) {
		html += '<td class="remove"><a onclick="if (confirm(\'' + window.removeFromCartMsg + '\')) CartRemove(\'' + cartitem.cartitemid + '\'); return false;" href="#">[ X ]</a></td>';
	}
	html += '</tr>';
	return html;
}
function RenderQtyInput(cartitem) {
	var html = '';
	var aveQty = parseInt(cartitem.average_quantity);
	if (isNaN(aveQty) || aveQty == 0) aveQty = 1;
	if (aveQty == 1)
		html += '<input type="text" value="' + cartitem.quantity + '" name="quantity_' + cartitem.cartitemid + '"/>';
	else {
		var cartitemQty = parseInt(cartitem.quantity);
		html += '<select name="quantity_' + cartitem.cartitemid + '">';
		//var maxitems = (cartitemQty > (12 * aveQty)) ? (cartitemQty / aveQty) : 12;
		var maxitems = 12;
		for (var i = 1; i <= maxitems; i++) {
			var increment = i * aveQty;
			html += '<option value="' + increment + '"';
			if (cartitemQty == increment)
				html += ' selected="selected"';
			html += '>' + increment + '</option>';
		}
		html += '</select>';
	}
	jQuery('#cart-items td.qty').last().html(html);
}
function GetCartErrors(carterrors, cartitemid) {
	var count = carterrors.length;
	var ret = '';
	for (var i = 0; i < count; i++) {
		if (carterrors[i].cartitemid == cartitemid) {
			if (ret == '') ret += '<br/>';
			ret += carterrors[i].error_msg;
		}
	}
	return ret;
}
function FormatNumber(number) {
	var fNumber = parseFloat(number);
	if (isNaN(fNumber)) return '0.00';
	var n1 = fNumber.toFixed(2).toString().split('.');
	var n2 = n1[0].split('');
	var ret = '';
	var m = 3;
	var l = n2.length - 1;
	for (var i = l; i >= 0; i--) {
		ret = n2[i] + ret;
		if (i != 0 && ret.length % m == 0) {
			ret = ',' + ret;
			m = m + 4;
		}
	}
	ret += '.' + n1[1];
	return ret;
}
function BindAjaxAC(input, url, div, span) {
	new Ajax.Autocompleter(input, div, url, {
		paramName: "value",
		minChars: 2,
		indicator: span
	});
}
