var IDZero = "00000000000000000000000000000000";

var _DEFAULT_POLL_TIMEOUT_ = 200; // milliseconds

// handler parameters
var DEFAULT_HANDLER_EXTENSION = ".clw";
var DEFAULT_HANDLER_EXTENSION_LENGTH = DEFAULT_HANDLER_EXTENSION.length;
var DEFAULT_FRONT_END_HANDLER_NAME = "user" + DEFAULT_HANDLER_EXTENSION;

// function to compare object by name attribute
function _CompareNameAttributeValues(aFirst, aSecond)
{
	return (aFirst.name < aSecond.name) ? -1 : ((aFirst.name == aSecond.name) ? 0 : 1);
}

function _Compare_N_AttributeValue(aFirst, aSecond)
{
	return (aFirst.n < aSecond.n) ? -1 : ((aFirst.n == aSecond.n) ? 0 : 1);
}

function StringStringPair(aText, aValue)
{
	this.n = aText;
	this.v = aValue;
	StringStringPair.Sort=_Sort;
	function _Sort(aFirst, aSecond)
	{
		return (aFirst.n < aSecond.n) ? -1 : ((aFirst.n == aSecond.n) ? 0 : 1);
	}
}

// same as StringStringPair but other member names and constructor
function IdentifiedName(aText, aValue)
{
	this.id = "";
	this.name = "";
	
	if (1 == arguments.length)
	{
		var a = arguments[0].split('|');
		if (a.length >= 2)
		{
			this.name = unescape(a[0]);
			this.id = a[1];
		}
	}
	else if (2 == arguments.length)
	{
			this.name = aText;
			this.id = aValue;
	}
	IdentifiedName.Sort=_Sort;
	
	function _Sort(aFirst, aSecond)
	{
		return _CompareNameAttributeValues(aFirst, aSecond);
	}
}

// standard price object
function price(aVal)
{
	this.IsTBD = true;
	this.val = 0;
	this.toString = _toString;
	this.PackToString = _toString;
	this.Set = _Set;
	this.Get = _Get;
	this.Multiply = _Multiply;
	this.CopyValue = _CopyValue;
	
	this.Set(aVal);
	
	function _toString()
	{
		if (this.IsTBD) return "TBD";
		else return formatCurrency(this.val);
	}

	function _Set(aVal)
	{
	    if(!aVal && isNaN(aVal))
	    {
			return false;
		}
		this.IsTBD = true;
		this.val = 0;
		if ("TBD" != (new String(aVal)).toUpperCase())
		{
			var v = parseFloat(aVal);
			if (!isNaN(v))
			{
				this.val = v;
				this.IsTBD = false;
			}
		}
		return true;
	}
	
	function _Get()
	{
		return (this.IsTBD) ? 0 : this.val;
	}
	
	function _Multiply(qty)
	{
		return (this.IsTBD) ? (new price()) : (new price(this.val * qty));
	}
	
	function _CopyValue(aPriceToCopyTo)
	{
		aPriceToCopyTo.IsTBD = this.IsTBD;
		aPriceToCopyTo.val = this.val;
	}
}

unit_price.prototype=new price();
unit_price.prototype.constructor=unit_price;
unit_price.superclass=price.prototype;

// price with 4 decimals.
function unit_price(aVal)
{
	this.Set(aVal);

	this.toString = _xtoString;
	function _xtoString()
	{
		if (this.IsTBD) return "TBD";
		else return formatCurrency4(this.val);
	}
}

function PadLeft(aStrToExtend, aLength, aCharToUse)
{
	if (aStrToExtend.length >= aLength) return aStrToExtend;
	else
	{
		var r = "";
		var a = aCharToUse.substr(0, 1);
		for(var i = aLength - aStrToExtend.length; i > 0; i--) r += a;
		return r + aStrToExtend;
	}
}
function PadLeftZero(aStrToExtend, aLength)
{
	return PadLeft(aStrToExtend, aLength, "0");
}

function YMD(anYOrPackedString, aM, aD)
{
	if (0 == arguments.length)
	{
		this.Y = this.M = this.D = 0;
	}
	else if (1 == arguments.length)
	{
		var hexp = "0x";
		this.Y = parseInt(hexp + anYOrPackedString.substr(0, 3));
		if (isNaN(this.Y)) this.Y = this.M = this.D = 0;
		else
		{
			this.M = parseInt(hexp + anYOrPackedString.substr(3, 1));
			if (isNaN(this.M)) this.Y = this.M = this.D = 0;
			else
			{
				this.D = parseInt(hexp + anYOrPackedString.substr(4));
				if (isNaN(this.D)) this.Y = this.M = this.D = 0;
			}
		}
	}
	else
	{
		this.Y = anYOrPackedString;
		this.M = aM;
		this.D = aD;
	}
	this.PackToString = _PackToString;
	this.FillSelectElements=_FillSelectElements;
	this.GetFromSelectElements = _GetFromSelectElements;
	this.IsValid = function() {return (0 != this.D && 0 != this.M && 0 != this.Y);}
	this.toDate = function() { return (this.IsValid()) ? new Date(this.Y, this.M-1, this.D) : null; }
	function _PackToString()
	{
		return PadLeftZero(this.Y.toString(16), 3) + this.M.toString(16) + PadLeftZero(this.D.toString(16), 2)
	}
	function _FillSelectElements(aForm, aYearSelect, aMonthSelect, aDaySelect)
	{
		setSelectedByValue(aForm.elements[aYearSelect], this.Y.toString());
		setSelectedByValue(aForm.elements[aMonthSelect], this.M.toString());
		if (aForm.elements[aDaySelect].options[1].value)
		{
			setSelectedByValue(aForm.elements[aDaySelect], this.D.toString());
		}
		else
		{
			setSelectedByText(aForm.elements[aDaySelect], this.D.toString());
		}
	}
	function _GetFromSelectElements(aForm, aYearSelect, aMonthSelect, aDaySelect, bVerify)
	{
		this.Y = this.M = this.D = 0;
		var els = aForm.elements;
		var el = els[aYearSelect];
		var idx = el.selectedIndex;
		if (idx < 0) return el;
		var v = parseInt(el.options[idx].value);
		if (isNaN(v)) return el;
		this.Y = v;
		el = els[aMonthSelect];
		idx = el.selectedIndex;
		if (idx < 0) return el;
		var v = parseInt(el.options[idx].value);
		if (isNaN(v)) return el;
		this.M = v;
		el = els[aDaySelect];
		idx = el.selectedIndex;
		if (idx < 0) return el;
		var v = parseInt(el.options[idx].value);
		if (isNaN(v))
		{
			v = parseInt(el.options[idx].text);
			if (isNaN(v)) return el;
		}
		this.D = v;
		if (bVerify)
		{
			var d = new Date(this.Y, this.M - 1, this.D);
			if (isNaN(d)) return els[aMonthSelect];
			if (d.getFullYear() != this.Y) return els[aYearSelect];
			if (d.getMonth() + 1 != this.M) return els[aMonthSelect];
			if (d.getDate() != this.D) return els[aDaySelect];
		}
		return null;
	}
	function _IsValid()
	{
		return (0 != this.D && 0 != this.M && 0 != this.Y);
	}
}

var _MainSiteID_ = "00000000000000000000000000000000";

var g_spaces = " \t\r\n";

function trimAll(x) {
	var e = x.length;
	if (0 == e) return x;
	
	for (b = 0; b < e; b++) {
		if (g_spaces.indexOf(x.substr(b, 1)) == -1) break;
	}
	if (b == e) return "";
	for (--e; e > b; e--) {
		if (g_spaces.indexOf(x.substr(e, 1)) == -1) break;
	}
	return x.substr(b, e - b + 1);
}

function trimZero(str)
{
	var x = "" + str;
	var g_zero="0";
	var e = x.length - 1;
	if (0 <= e) return x;
	var b;
	for (b = 0; b < e; b++)
	{
		if (g_zero.indexOf(x.substr(b, 1)) == -1) break;
	}
	if (b == e) return "";
	return x.substr(b, e - b + 1);
}

// null if empty
function NullIfEmpty(aStr)
{
	return (aStr) ? aStr : null;
}

function EmptyStringIfNull(anObj)
{
	return (null == anObj) ? "" : anObj;
}

var gForm;

function getForm()
{
	if (!gForm)
	{
		gForm = self.document.forms['adminForm'];
	}
	return gForm;
}

function _GlobalGetPage(aPage, anAnchor)
{
	if (!notifyLeavingPage(aPage, anAnchor)) return;
	getForm().elements["TargetPage"].value = aPage;
	if (arguments.length > 1)
	{
		var t = getForm().action;
		if (!t) t = self.location.toString();
		if (t.lastIndexOf("#") >= 0) t = t.substr(0, t.lastIndexOf("#"));
		getForm().action = t + "#" + anAnchor;
	}
		getForm().submit();
}

function CallGetPage(anArgs)
{
	var i = anArgs.length;
	if (0 == i) 
		_GlobalGetPage();
	else if(1 == i)
		_GlobalGetPage(anArgs[0]);
	else if(2 == i)
		_GlobalGetPage(anArgs[0], anArgs[1]);
}

function getPage(aPage, anAnchor)
{
	EnsureURL();
	CallGetPage(arguments);
}

function EnsureURL()
{
	var pn = self.location.pathname;
	if (pn.length < DEFAULT_HANDLER_EXTENSION_LENGTH
		|| DEFAULT_HANDLER_EXTENSION != pn.substr(pn.length - DEFAULT_HANDLER_EXTENSION_LENGTH, DEFAULT_HANDLER_EXTENSION_LENGTH).toLowerCase())
	{
		var frs = document.forms;
		for(var i = frs.length - 1; i >= 0; --i)
		{
			frs[i].action = DEFAULT_FRONT_END_HANDLER_NAME;
		}
	}
}

function getBusiness()
{
	getPage('catalog_business');
}

function notifyLeavingPage(aPage, anAnchor)
{
	return true;
}

function formatDecimal(aValue, aDigits)
{
	var v = parseFloat(aValue);
	var digits = parseInt(aDigits);
	if (isNaN(digits)) digits = 0;
	if (isNaN(v)) return aValue;

	var dec = Math.pow(10, digits);

	var vtest = v * dec;
	var resup = Math.ceil(vtest);
	var resdown = Math.floor(vtest);

	var deltaup = resup - vtest;
	var deltadown = vtest - resdown;

	var res = (deltaup > deltadown) ? resdown : (deltaup < deltadown) ? resup : (resup & 1) ? resdown : resup;

	var sres = (res / dec).toString();
	if (digits > 0)
	{
		var ntoadd = digits;
		var pointidx = sres.indexOf('.');
		if (pointidx < 0)
		{
			sres += '.';
		}
		else
		{
			ntoadd -= sres.length - pointidx - 1;
		}
		for(;ntoadd > 0; ntoadd--)
		{
			sres += '0';
		}
	}
	return sres;
}

// format number with up to 4 non-zero but not less then 2 decimal places
function formatCurrency4(aValue)
{
	var t = formatDecimal(aValue, 4);
	var n = t.length;
	if ('0' == t.charAt(n-1))
	{
		if ('0' == t.charAt(n-2))
		{
			n -= 2;
		}
		else
		{
			--n;
		}
		t = t.substr(0, n);
	}
	return t;
}

function formatCurrency(aValue)
{
  return formatDecimal(aValue, 2);
}

function formatValueWithCommas(aValue)
{
   var svalue = aValue.toString();
   var s="";
   var t="";
   var pointidx = svalue.indexOf('.');
      if (pointidx < 0)   //int
      {
         ivalue= svalue;
       }else{
         ivalue= svalue.substr(0,pointidx);
         t= svalue.substr(pointidx,svalue.length-1);
       }
   do
   {
      
      if (ivalue.length >3) 
      {
         s = (s=="")? ivalue.substr(ivalue.length-3, ivalue.length-1):(ivalue.substr(ivalue.length-3, ivalue.length-1) +","+s);
         ivalue = ivalue.substr(0, ivalue.length-3);
      } else 
      {
          s = (s=="")? ivalue.substr(0, ivalue.length):(ivalue.substr(0, ivalue.length) +","+s);
          ivalue="";
      }
    } while (ivalue.length > 0);
   return s+t;
}

function formatValueWithoutCommas(aValue)
{
   var svalue = aValue.toString();
   var s = "";
   var a = svalue.split(',');
   for(var i = 0; i < a.length; i++)
   {
     s +=a[i];
   } 	
   return s;
}

function formatPrice(aValue, aRounding)
{
	return formatCurrency(RoundPrice(aValue, aRounding));
}

function RoundPrice(aValue, aRoundingIncrement)
{
	return (aRoundingIncrement < 0.000001) ? aValue : Math.round(aValue/aRoundingIncrement) * aRoundingIncrement;
}

function isValidEMail(aString)
{
	var x = trimAll("" + aString);
	if (x)
	{
		if (x.indexOf(' ') > 0) return false;
		var i = x.indexOf("@");
		if (i > 0)
		{
			if (x.substr(i + 1).indexOf(".") > 0) return true;
		}
	}
	return false;
}


function FormatTaxRate(aCaller)
{
	var val = parseFloat(aCaller.value);
	if (!isNaN(val) || val < 0)
	{
		var tstr = val.toString();
		var vstr = tstr.split('.');
		aCaller.value = (2 == vstr.length && "" == trimAll(vstr[1])) ? vstr[0] : tstr;
	}
	else aCaller.value = "";
}

function CheckIfValidURL(aValue)
{
	if (!aValue) return false;
	var AllowedChars="-_";
	for(var i = 0; i < aValue.length; i++)
	{
		var a = aValue.charAt(i);
		if (!((a >= "A" && a <= "Z") || (a >= "a" && a <= "z") ||(a >= "0" && a <= "9") || AllowedChars.indexOf(a) >= 0))
			return false;
	}
	return true;
}

function confirmCancelRegistration()
{
	if (getForm().elements["NewUser"] && "Y" == getForm().elements["NewUser"].value)
		return confirm("Your registration is not yet complete. Are you sure you want to abandon it?");
	else 
		return confirm("Your updates have not yet been saved. Are you sure you want to abandon them?");
}

function doLogin()
{
	var frm = self.document.forms["loginForm"];
	var frme = frm.elements;
	el = frme["uid"];
	var v = trimAll(el.value);
	el.value = v;
	if (!v)
	{
		alert("Please enter your Login ID.");
		el.focus();
		return;
	}	
	el = frme["pwd"];
	if (!el.value)
	{
		alert("Please enter your password.");
		el.focus();
		return;
	}
    
    frme["CurrentPage"].value = getForm().elements["CurrentPage"].value;
    frme["TargetPage"].value = getForm().elements["TargetPage"].value;
    
	frme["Command"].value = "login";
	frm.submit();
}

function doLogout()
{
	var frm = self.document.forms["loginForm"];
	var frme = frm.elements;
	frme["CurrentPage"].value = getForm().elements["CurrentPage"].value;
	frme["TargetPage"].value = getForm().elements["TargetPage"].value;
	frme["Command"].value = "logout";
	frm.submit();
}

function getPrimaryCategoryCatalog(aBusinessID)
{
	getForm().elements["Command"].value = "getPrimaryCategoryCatalog," + aBusinessID;
	return getPage("catalog_business");
}

function getSecondaryCategoryCatalog(aProductCategoryID)
{
	getForm().elements["Command"].value = "getSecondaryCategoryCatalog," + aProductCategoryID;
	return getPage("catalog_product");
}

function getCategories(aKeyWord)
{
	getForm().elements["Command"].value = "getCategories," + aKeyWord;
	return getPage("catalog_business");
}

function getProduct(aProductID)
{
   	if (!aProductID) return;
	getForm().elements["Command"].value = "getProduct," + aProductID;
	return getPage("catalog_details");
}

function setSelectedByValue(aSelect, aValue)
{
    if(aSelect && aSelect.options)
    {
		for (var i = 0; i < aSelect.options.length; i++)
		{
			if (aValue == aSelect.options[i].value)
			{
				aSelect.options[i].selected = true;
				break;
			}
		}
	}
}

function setSelectedByText(aSelect, aText)
{
    if(aSelect && aSelect.options)
    {
		for (var i = 0; i < aSelect.options.length; i++)
		{
			if (aText == aSelect.options[i].text)
			{
				aSelect.options[i].selected = true;
				break;
			}
		}
	}
}

function SetSelectedOptions(aSelect, aValuesArray)
{
	var l = aSelect.options;
	for (var k = 0; k < aValuesArray.length; k++)
	{
		var v = aValuesArray[k];
		for (var i = 0; i < l.length; i++)
		{
			if (v == l[i].value) l[i].selected = true;
		}
	}
}

function CheckBoxByValue(aBoxArray, aValue)
{
	for (var i = 0; i < aBoxArray.length; i++)
	{
		if (aValue == aBoxArray[i].value)
		{
			aBoxArray[i].checked = true;
			return;
		}
	}
}

function GetCheckedValue(aBoxArray)
{
	for (var i = 0; i < aBoxArray.length; i++)
		if (aBoxArray[i].checked) return aBoxArray[i].value
	return null;
}

function checkSearchData()
{
	if (!trimAll(self.document.forms["searchForm"].elements["search"].value)) return false;
	var frme = self.document.forms["searchForm"].elements;
	frme["CurrentPage"].value = getForm().elements["CurrentPage"].value;
	frme["TargetPage"].value = getForm().elements["CurrentPage"].value;
	frme["Command"].value = "search";
	return true;
}

function clearForm(aForm)  
{
	var f = aForm;
	if (f) f = f.elements;
	for(var i= 0; i < f.length; i++)
	{
		var item = f[i];
		if (item.options) clearElement(item);
		else
		{
			if (item.length)
			{
				for (var j= 0; j < item.length; j++) clearElement(item[j]);
			}
			else clearElement(item);
		}	
	}
}

function clearElement(e)
{
	switch(e.type)
	{
		
		case "text":
		case "textarea":
//		case "hidden":
		case "password":
			e.value = "";
			break;
		case "checkbox":
		case "radio":
			e.checked = false;
			break;
		case "select-one":
		case "select-multiple":
			for(var i=0; i < e.options.length; i++) e.options[i].selected = false;
			if (e.options.length) e.options[0].selected = true;
	}
}

function ChangeAllItemsSelectionState(aSelectObject, bSelected)
{
	var opt = aSelectObject.options;
	for (var i = 0; i < opt.length; i++) opt[i].selected = bSelected;
}

function UnselectAllItems(aSelectObject)
{
	if (aSelectObject.type == "select-one") {aSelectObject.value = ""; return;}
	ChangeAllItemsSelectionState(aSelectObject, false);
}

function SelectAllItems(aSelectObject)
{
	ChangeAllItemsSelectionState(aSelectObject, true);
}

function alertNoRights()
{
  alert("You are not authorized to access this link.");
}

function showImagePopup(aCommand)
{
  var imageWindowName = "image";
  var w = window.open("", imageWindowName,'scrollbars=yes,resizable=yes,width=620,height=400');
  var f = GetPopupForm();
  var els = f.elements;
  els["TargetPage"].value = "image_popup";
  var ts = f.target;
  var t_cmd = els["Command"].value;
  els["Command"].value = aCommand;
  f.target = imageWindowName;
  f.submit();
  f.target = ts;
  els["Command"].value = t_cmd;
  els["TargetPage"].value = els["CurrentPage"].value;
}

function showImageEnlarged(aCommand)
{
  var imageWindowName = "image";
  var w = window.open("", imageWindowName,'scrollbars=yes,resizable=yes,width=520,height=520');
  var f = GetPopupForm();
  var els = f.elements;
  els["TargetPage"].value = "image_enlarged";
  els["Command"].value = aCommand;
  var ts = f.target;
  f.target = imageWindowName;
  f.submit();
  f.target = ts;
  els["TargetPage"].value = els["CurrentPage"].value;
}

// may be replaced by the specializations.
function GetPopupForm()
{
	return getForm();
}

function textElementChanged(anElement)
{
}

function MakeOptions(aSelectElement, aNameValuePairsArray, aSelectedValue, DoNotResetList)
{
	var l = aSelectElement.options;
	if (!DoNotResetList) l.length = 0;
	
	for (var i = 0; i < aNameValuePairsArray.length; i++)
	{
		l[l.length] = new Option(aNameValuePairsArray[i].name, aNameValuePairsArray[i].value)
		if (aSelectedValue == aNameValuePairsArray[i].value) l[l.length-1].selected = true;
	}
}

function IsValidNumber(aValue, aLowerLimit, anUpperLimit)
{
	var v = parseFloat(aValue);
	if (isNaN(v)) return false;
	if (arguments.length > 1 && v < aLowerLimit) return false;
	if (arguments.length > 2 && v > anUpperLimit) return false;
	return true;
}

function IsValidInteger(aValue, aLowerLimit, anUpperLimit)
{
	var v = parseInt(aValue);
	if (isNaN(v)) return false;
	if (arguments.length > 1 && v < aLowerLimit) return false;
	if (arguments.length > 2 && v > anUpperLimit) return false;
	return true;
}

function ActivateContext()
{
	var el = getForm().elements["Command"];
	if (el)
	{
		el.value = "TransitionInContext";
	}
}

function getIndexOfValue(aSelect, aValue)
{
	var opt = aSelect.options;
	if (!opt) return -1;
	for (var i = 0; i < opt.length; i++) if (aValue == opt[i].value) return i;
	return -1;
}

function PackOptions(aSelectElement)
{
	var r = "";
	var opt = aSelectElement.options;
	for (var i = 0; i < opt.length; i++)
	{
		if (i > 0) r += ",";
		r += opt[i].value;
	}
	return r;
}

function PackSelectedOptions(aSelectElement)
{
	var r = "";
	var opt = aSelectElement.options;
	for (var i = 0; i < opt.length; i++)
	{
		if (!opt[i].selected) continue; 
		if (r.length > 0) r += ",";
		r += opt[i].value;
	}
	return r;
}


function SubmitForSequence(aForm, aPage)
{
	if (checkFormData())
	{
		aForm.elements["TargetPage"].value = aPage;
		aForm.submit();
	}
}
function AddToList(ListName, newText, newVal)
{
    var DestList = getForm().elements[ListName].options;
	for(var i = 0; i < DestList.length; i++) {
	if ((DestList[i].text == newText) || (newText=="")) return false;
	if  ((DestList[i].value == newVal)&&(newVal!="")) return false;
    }
	var l = DestList.length;
	var i = 0;
	
	while(i < l && newText > DestList[i].text) i++;
	for (var j = l; j > i; j--)
	DestList[j] = new Option(DestList[j-1].text, DestList[j-1].value);
	DestList[i] = new Option(newText, newVal);
}

function ClearSelectedIndex(ListName)
{
  var List=getForm().elements[ListName].options;
  List.selectedIndex = -1;
}

function ListSelectionChanged(ListName, InputField, idx, InputField2) 
{
	var els = getForm().elements;
	var sList = els[ListName];
	var e = els[InputField]; 
	if (sList.selectedIndex < 0 || sList.options.length == 0) return -1;
	if (idx==sList.selectedIndex)
	{
	   sList.selectedIndex = -1;
	   if (e.type == "text" || e.type == "textarea") e.value = "";
       if (e.type == "select-one" || e.type == "select-multiple") ClearSelectedIndex(InputField);
	   if(InputField2) els[InputField2].value="";
	   
	}else
	{ 
	   if (e.type == "text" || e.type == "textarea") e.value = sList.options[sList.selectedIndex].text;;
       if (e.type == "select-one" || e.type == "select-multiple") 
       { 
         for(var j = 0; j < e.length; j++)
            if (e.options[j].value == sList.options[sList.selectedIndex].value)  e.options[j].selected=true;
             else  e.options[j].selected=false;
        }
	   if(InputField2) els[InputField2].value = sList.options[sList.selectedIndex].value.split("|")[1];
	}
	return sList.selectedIndex;
}

function SpellImprintingType(anAbbr)
{
	if ("i" == anAbbr)
		return "imprinting";
	else if ("e" == anAbbr)
		return "embroidery";
	else if ("s" == anAbbr)
		return "silk-screening";
	else
		return "";
}


function DeSelectOption(ListName, idx, PreIdx, ClearFieldNames)
{
    if (idx == PreIdx)
	{
       ClearSelectedIndex(ListName); 
      if(ClearFieldNames)
       for (var i= 0; i < ClearFieldNames.length; i++)
       {
         var s=ClearFieldNames[i];
         var e = getForm().elements[s]; 
         if (e.type == "text" || e.type == "textarea") e.value = "";
         if (e.type == "select-one" || e.type == "select-multiple") ClearSelectedIndex(s);
   	   }
   	 return true;
   	}else return false;
}

function CenterLayerInWindow(aLayerObj)
{
	aLayerObj.style.left = document.body.scrollLeft + (document.body.clientWidth-aLayerObj.offsetWidth)/2;
	aLayerObj.style.top = document.body.scrollTop + (document.body.clientHeight-aLayerObj.offsetHeight)/2;
}

function gotoHandler(aCommand)  //There are a few pages use this function, it is moved from admin_index to utilities.js
{
  getForm().elements["Command"].value = aCommand;
  getForm().submit();
}

function InitializeWebService(aServiceElementName)
{
	var CLWServiceName = "CLWService.asmx?WSDL";
	ServiceElement.useService(CLWServiceName, (aServiceElementName) ? aServiceElementName : "ServiceEntry");
}

function CheckNotLoggedInException(aMessage)
{
	return (aMessage.toString()).indexOf("__Not_Logged_In__") >= 0;
}

function ProcessNotLoggedInException(aMessage)
{
	if (CheckNotLoggedInException(aMessage))
	{
		getPage('admin_logout');
		return false;
	}
	return true;
}

function NormalizeInputQuantity(anObj, bDontCheckValuePositive)
{
	var v = trimAll(anObj.value);
	if ("" != v)
	{
		v = parseInt(v);
		if (!isNaN(v) && (bDontCheckValuePositive || v > 0))
		{
			anObj.value = v.toString();
		}
		else
		{
			anObj.value = "";
		}
	}
	else
	{
		anObj.value = "";
	}
	return v;
}

function NormalizeInputPrice(anObj, bExtendedPrecision, bEnsurePositive, bNoTBD)
{
	var v = trimAll(anObj.value);
	if ("" != v)
	{
		v = (bExtendedPrecision) ? new unit_price(v) : new price(v);
		if ( (bNoTBD && v.IsTBD) || (bEnsurePositive && (v.Get() < 0)) )
			v = (bExtendedPrecision) ? new unit_price(0) : new price(0);
		anObj.value = v.toString();
	}
	else
	{
		anObj.value = "";
		v = new price();
	}
	return v;
}

function getNextRecord()
{
  navigationPageSubmit("nextrecord");
}

function getPreviousRecord()
{
  navigationPageSubmit("previousrecord");
}

function goBackToList()
{
   navigationPageSubmit("backtolist");
}

function navigationPageSubmit(anCommand)
{
   var els = getForm().elements;  
   els["Command"].value = anCommand;
   els["TargetPage"].value = els["CurrentPage"].value;
   getForm().submit();
}

// web service call data
var _SRV_CallInProgress = false;
var _SRV_CallID = 0;
var _SRV_HandlingParameters = null;

function InitServiceCallData()
{
	_SRV_CallInProgress = false;
	_SRV_CallID = 0;
	_SRV_HandlingParameters = null;
}

// IFrameMask operations
/*
 * The following block of functions and constants is used to control
 * implementation of the "shield" that should prevent user from interacting 
 * with UI and (optionally) show "Please wait..." blurb.
 *
 * Required: "shield_and_wait_layer.lbi" DreamWeaver library file
 *
 * Synopsis:
 *	DisableUI([show_Please_Wait_Blurb])
 *	EnableUI()
 *	ShieldPersist() - service function called asynchronously to ensure the frame is always on top of the client window
 *	_Center_Layer(aLayerObj) - place a layer object in the center of the client area. 
 *	StartWait() - safely call DisableUI(true)
 *	FinishWait() - hide "Please wait..." blurb.
 *
 */

var _ShieldFrameName = "IFrameMask";
var _PleaseWaitLayerName = "PleaseWaitLayer";
var _ShieldFrameZIndex = 250;

function EnableUI()
{
	var fo_style = self.document.getElementById(_ShieldFrameName).style;
	_ShieldFrameZIndex = fo_style.zIndex;
	if (null != fo_style._ShieldTimeout) window.clearTimeout(fo_style._ShieldTimeout);
	if (fo_style.vx_waitlayer && "y" == fo_style.vx_waitlayer)
	{
		self.document.getElementById(_PleaseWaitLayerName).style.display = "none";
	}
	fo_style.zIndex = -1;
}

function DisableUI(aShowWaitLayer)
{
	var st_obj = self.document.getElementById(_ShieldFrameName).style;
	st_obj.zIndex = _ShieldFrameZIndex;
	if (aShowWaitLayer)
	{
		var wl = self.document.getElementById(_PleaseWaitLayerName);
		if (wl)
		{
			wl.style.display = "block";
			st_obj.vx_waitlayer="y";
		}
		else
		{
			st_obj.vx_waitlayer="n";
		}
	}
	else
	{
		st_obj.vx_waitlayer="n";
	}
	ShieldPersist();
	st_obj = null;
}

function ShieldPersist()
{
	// position the shield frame exactly on top of the client area.
	var st_obj = document.getElementById(_ShieldFrameName).style;
	if (null != st_obj._ShieldTimeout) window.clearTimeout(st_obj._ShieldTimeout);
	
	var main_body = document.body;
	
	var pX = parseInt(main_body.clientTop) + parseInt(main_body.scrollTop);
	var pY = parseInt(main_body.clientLeft) + parseInt(main_body.scrollLeft);
	
	var cH = parseInt(main_body.clientHeight);
	var cW = parseInt(main_body.clientWidth);
	
	var ReCenterRequired = false;
	
	if (pX != parseInt(st_obj.top) || pY != parseInt(st_obj.left))
	{
		st_obj.top = pX;
		st_obj.left = pY;
		ReCenterRequired = true;
	}
	
	if (cW != parseInt(st_obj.width) || cH != parseInt(st_obj.height))
	{
		st_obj.width = cW;
		st_obj.height = cH;
		ReCenterRequired = true;
	}
	
	if (ReCenterRequired && st_obj.vx_waitlayer && "y" == st_obj.vx_waitlayer)
	{
		_Center_Layer(self.document.getElementById(_PleaseWaitLayerName));
	}
	
	st_obj._ShieldTimeout = window.setTimeout("ShieldPersist()", _DEFAULT_POLL_TIMEOUT_);
	st_obj = null;
	main_body = null;
}

function _Center_Layer(anObj)
{
	var anObj_st = anObj.style;
	
	var d_b = document.body;
	
	var pX = Math.floor(d_b.scrollLeft + (d_b.clientWidth-anObj.offsetWidth)/2);
	var pY = Math.floor(d_b.scrollTop + (d_b.clientHeight-anObj.offsetHeight)/2);
	
	if (pX != parseInt(anObj_st.left))
	{
		anObj_st.left = pX;
	}
	if (pY != parseInt(anObj_st.top))
	{
		anObj_st.top = pY;
	}
	anObj_st = null;
	d_b = null;
}

function StartWait()
{
	var obj = document.getElementById(_ShieldFrameName);
	if (null != obj) DisableUI(true);
	else document.body.style.cursor="wait";
	obj = null;
}

function FinishWait()
{
	var obj = document.getElementById(_ShieldFrameName);
	if (null != obj) EnableUI();
	else document.body.style.cursor="auto";
}

// this function should be overrided on the pages operating under the order lock active
// to prevent order unlocking upon the "unload" event.
function IndicateOrderSubmitted()
{
}

function CLWServiceAvailable()
{
	_CLW_Service_Initialized = true;
}
