// Alon wrote this hack to allow multiple functions to run in window.onload
window.onloadFunctions = new Array();
window.clearOnloadFunctions = function()
{
  window.onloadFunctions = new Array();
}
window.addOnload = function(onloadFunction) {
  window.onloadFunctions[window.onloadFunctions.length] = onloadFunction;
}
window.onload = function() {
  for (var i = 0; i < onloadFunctions.length; i++) {
//    alert('about to time ' + onloadFunctions[i]);
//    var initTimeStart = new Date();
    onloadFunctions[i]();
//    var initTimeEnd = new Date();
//    var initTime = initTimeEnd - initTimeStart;
//    window.status = "it took : " + initTime;
  }
  if(window.myOnload !== undefined && myOnload)
  {
    myOnload();
  }
//  alert('done');
}


// this function will patch a click method onto anchor elements for Mozilla. Due apparently to confusion in the early DOM spec, (they honestly forgot to specify that anchors had a click method) anchor elements in mozilla are missing click methods. This will attach a click method to HTMLElement so that all elements, being descendants of this object will inherit it if they dont have one of their own.
if (!document.all) {
  try {
    //  i think you need this to force the prototype to get created if maybe the page has no anchors.
		document.createElement('a');
		HTMLElement.prototype.click = function () {
			if (typeof this.onclick == 'function') {
				if (this.onclick({type: 'click'}) && this.href)
					window.open(this.href, this.target ? this.target : '_self');
			}
			else if (this.href)
				window.open(this.href, this.target ? this.target : '_self');
		}
	}
	catch (e) {
		window.status='Warning: your browser is unable to attach click methods to all elements.';
	}
}


// general purpose Browser detection object.
function Browser(){
  this.ua = navigator.userAgent.toLowerCase();
  this.dom = document.getElementById?1:0;
  this.ie4 = (document.all && !this.dom)?1:0;
  this.ns4 = (document.layers && !this.dom)?1:0;
  this.ns6 = (this.dom && !document.all)?1:0;
  this.ie5 = (this.dom && document.all)?1:0;
  this.ie50 = (navigator.appVersion.indexOf("MSIE 5.0")!=-1);
  this.ie55 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1);
  this.mac = (navigator.appVersion.indexOf('Mac') == -1)?0:1;
  this.platform = navigator.platform;
  this.safari = (this.ua.indexOf("safari") != -1)?1:0;
  this.opera  = (this.ua.indexOf("opera") != -1)?1:0;
  if (this.unSupported()) {
    var unsupportedPopup = window.open('/jsp/user/unsupported-browser.jsp', 'unsupported','width=500,height=400');
  }
}
Browser.prototype.unSupported = function() {
  if (
      ((this.safari) && (parseFloat(navigator.appVersion)<5)) ||
      (this.ie5 && this.mac) ||
      (this.opera) ||
      (!this.dom) ||
      (this.ie50) ||
      (this.ie55)
    )
  return true;
  else return false;
}
var browser = new Browser();

function init() {

  if (typeof(ContextMenuManager)!="undefined") cmm = new ContextMenuManager();
	if (typeof(CheckboxManager)!="undefined") cbm = new CheckboxManager();
	if (typeof(VisibilityManager)!="undefined") visibilityManager = new VisibilityManager();
	if (typeof(GraphicalCheckboxManager)!="undefined") graphicalCheckboxManager = new GraphicalCheckboxManager();
}

var cmm;
var cbm;
var visibilityManager;
var graphicalCheckboxManager;


function traverseDOM(node) {
  var nodesToTraverse = ["TBODY","TH","LI"];

  for (var i=0; i<nodesToTraverse.length; i++) {
    var workerCollection = node.getElementsByTagName(nodesToTraverse[i]);
    for (var j=0; j<workerCollection.length; j++) {
      if (workerCollection[j].className && workerCollection[j].className.indexOf("mouse-sensitive") != -1) {
        initMouseSensitivity(workerCollection[j]);
      }
      if (workerCollection[j].className && workerCollection[j].className.indexOf("truncate") != -1) {
        truncateText(workerCollection[j]);
      }
    }
  }

/*
  var children = node.childNodes;
  for (var i = 0; i < children.length; i++) {
    if (children[i].className && children[i].className.indexOf("mouse-sensitive") != -1) {
      initMouseSensitivity(children[i]);
    }
    if (children[i].className && children[i].className.indexOf("truncate") != -1) {
      truncateText(children[i]);
    }
    traverseDOM(children[i]);
  }
  */
}

var evenColor = AColor.hex2AColor("#EEF3E6");
var oddColor = AColor.hex2AColor("#FFFFFF");
var overMask = new AColor(1,1,0,.2);
var selectedMask = new AColor(1,1,0,.3);


function initMouseSensitivity(node) {
  if (node.className.indexOf('selectable') != -1) {
    if     (node.className.indexOf("even") != -1) node.style.backgroundColor = evenColor.toHex();
    else if (node.className.indexOf("odd") != -1) node.style.backgroundColor = oddColor.toHex();
  }

  node.onmouseover = function() {
    if (this.className.indexOf('selectable') != -1) {
      var background = AColor.parse(this.style.backgroundColor);
      this.style.backgroundColor = background.merge(overMask).toHex();
    }
    else if (this.className.indexOf(' over') == -1) {
      this.className += " over";
    }
  }
  node.onmouseout = function() {
    if (this.className.indexOf('selectable') != -1) {
      var background = AColor.parse(this.style.backgroundColor);
      this.style.backgroundColor = background.remove(overMask).toHex();
    }
    else if (this.className.indexOf(' over') != -1) {
      this.className = this.className.replace(" over","");
    }
  }
  node.onmousedown = function()
  {
    if (this.className.indexOf(' down') == -1) {
      this.className += " down";
    }
    if (this.className.indexOf('selectable') != -1) {
      if (this.className.indexOf(' selected') == -1) {
        this.className += " selected";
        var background = AColor.parse(this.style.backgroundColor);
        this.style.backgroundColor = background.merge(selectedMask).toHex();
        new FormWrapper(this).checkall(true);
      }
      else {
        this.className = this.className.replace(" selected","");
        var background = AColor.parse(this.style.backgroundColor);
        this.style.backgroundColor = background.remove(selectedMask).toHex();
        new FormWrapper(this).checkall(false);
      }
    }
  }
  node.onmouseup = function() {
    this.className = this.className.replace(" down","");
  }
}

var magicIsAlreadyClicked = 0;
function clickOnce(url)
{
  if (magicIsAlreadyClicked == 0)
  {
    window.location=url;
  }
  magicIsAlreadyClicked += 1;

  if (magicIsAlreadyClicked > 1 )
  {
    var idx = url.indexOf("unverifiedLots");
    if (idx != -1)
    {
      window.location='http://www.talking-bear.com/pages/Prim%20and%20proper%20ladies.htm';
    }
  }
}

var truncateCache = new Array(); // a hashmap to speed up the truncate function

function truncateText(node) { // shortens a string inside an anchor, span or p until it fits inside a div
  var truncatee = node.getElementsByTagName("a")[0]; // get the text to truncate
  if (truncatee == null) truncatee = node.getElementsByTagName("span")[0];
  if (truncatee == null) truncatee = node.getElementsByTagName("p")[0];
  if (truncatee == null)
  {
    alert("No value to truncate in " + node);
    return;
  }

  var truncateWidth = node.offsetWidth; // get the width of the containing div
  var truncateeWidth = truncatee.offsetWidth; // get the width of the truncatee

  if (truncateeWidth < truncateWidth) { // if it's short enough already, exit
    return;
  }

  var ellipsis = "..."; // what to add to the end on strings that are too long
  var originalText = truncatee.firstChild.nodeValue; // store the original text for the title tag

  if (truncateCache[originalText] != null) { // if it's in the cache, pull it out and exit
    truncatee.firstChild.nodeValue = truncateCache[originalText];
    return;
  }

  truncatee.firstChild.nodeValue += ellipsis;

  if (truncatee.offsetWidth == truncateeWidth) { // if the browser can't correctly measure modified elements,
    truncatee.title = originalText; // first set the title tag
    return; // then exit
  }

  while (truncatee.offsetWidth >= truncateWidth) { // keep removing the 4th last character until it's short enough
    truncatee.firstChild.nodeValue = truncatee.firstChild.nodeValue.slice(0, -4) + ellipsis;
  }

  if (truncatee.firstChild.nodeValue.slice(-4, -3) == " ") { // remove a possible trailing space
    truncatee.firstChild.nodeValue = truncatee.firstChild.nodeValue.slice(0, -4) + ellipsis;
  }

  truncateCache[originalText] = truncatee.firstChild.nodeValue; // put the shortened text in the cache

  truncatee.title = originalText; // set the title tag to the original text
}

function goWine(wineID, year) {
  document.location="/do/cellar/vintage?pageName=overview&vintage.wine.id=" + wineID + "&vintage.year=" + year;
}

function getWindowHeight() {
  if (self.innerHeight) {
    return self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientWidth)
	{
		return document.documentElement.clientHeight;
	}
  else if (document.body) {
   return document.body.clientHeight;
  }
}

function setTopMargin(elt, newTopMargin) {
  if (document.all) {
    elt.style.marginTop =  newTopMargin;
  }
  else {
    elt.style.cssText = "margin-top:"+ newTopMargin +"px;";
  }
}

function setLeftMargin(elt, newRightMargin) {
  if (document.all) {
    elt.style.marginLeft =  newRightMargin;
  }
  else {
    elt.style.cssText = "margin-left:"+ newRightMargin +"px;";
  }
}

function getInlinePosition(elt) {
  var workerBee = elt;
  var inlinePosition = new Array();
  inlinePosition[0] = inlinePosition[1] = 0;
  while (workerBee.offsetParent) {
    inlinePosition[0] += workerBee.offsetLeft;
    inlinePosition[1] += workerBee.offsetTop;
    workerBee = workerBee.offsetParent;
  }
  return inlinePosition;
}

function stripClassName (elt, classNameToRemove) {

  var oldClassName = elt.className;
  var newClassName = elt.className.replace(" "+classNameToRemove +" ","");
  newClassName = elt.className.replace(" "+classNameToRemove,"");
  newClassName = elt.className.replace(classNameToRemove,"");
  elt.className = newClassName

}

var sortLabel = "";
function setSortLabel(label)
{
  sortLabel = label;
}
function getSortLabel()
{
  return sortLabel;
}

function replaceHTMLCharacters(value)
{
  var amp = "&amp;";
  value = xreplace(value, amp, " ");

  var apos = "&#39;";
  value = xreplace(value, apos, " ");
  return value
}

function xreplace(checkMe,toberep,repwith)
{
  var temp = checkMe;

  var i = temp.indexOf(toberep);
  while(i > -1)
  {
    temp = temp.replace(toberep, repwith);
    i = temp.indexOf(toberep, i + repwith.length + 1);
  }
  return temp;
}



function printCustomerCase(caseName)
{
  document.printBarcodeApplet.printCustomerCases(printableCases[caseName]);
}

function printWarehouseCase(caseName)
{
  document.printBarcodeApplet.printWarehouseCases(printableCases[caseName]);
}

function viewCart()
{
  window.location="/do/store/cart";
}

function customerService()
{
  window.location="/customerService-overview.jsp";
}

function goToAccount ()
{
  window.location="/do/winestore/myAccount";
}

function isNotBlank(value)
{
  return !isBlank(value)
}

function isBlank(value)
{
  if (value == null) return true;
  if (value == "") return true;
  if (value == "null") return true;
  if (value == "undefined") return true;
  return false;
}

function isBlankOrNull(text)
{
  if (text != null && text != "")
  {
    return isWhitespace(text);
  }
  return  true;
}

function isWhitespace(text)
{
  // Search through text's characters one by one
  // until we find a non-whitespace character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < text.length; i++)
  {
    // Check that current character isn't whitespace.
    var character = text.charAt(i);

    if (character != " ") return false;
  }

  // All characters are whitespace.
  return true;
}

function isNumber(checkStr)
{
  if (isBlankOrNull(checkStr)) return false;

  var checkOK = "0123456789";
  var allValid = true;
  var allNum = "";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j)) break;
      if (j == checkOK.length)
      {
        allValid = false;
        break;
      }
      if (ch != ",") allNum += ch;
  }
  if (!allValid) return false;
  return true;
}

function vfAsyncRequest(method, uri, callback)
{
  uri = appendRandomNumber(uri);
  return YAHOO.util.Connect.asyncRequest(method, uri, callback);
}

function appendRandomNumber(uri)
{
  var number = Math.floor(Math.random() * 10000);
  if (uri.indexOf("?") > 0)
  {
    uri += "&random=" + number;
  }
  else
  {
    uri += "?random=" + number;
  }
  return uri;
}

function getElementsByClassName(oElm, strTagName, strClassName){
  var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/-/g, "\-");
  var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
  var oElement;
  for(var i=0; i<arrElements.length; i++){
    oElement = arrElements[i];
    if(oRegExp.test(oElement.className)){
      arrReturnElements.push(oElement);
    }
  }
  return (arrReturnElements)
}

EwsConsoleLoaders = function ()
{
  var customerID;
};

EwsConsoleLoaders.prototype =
{
	init: function(id)
	{
    this.customerId = id;
    this.getValuation(this);
  },

  getValuation: function( evt )
  {
    var url = "/do/admin/ewsConsole?doAction=asyncGetValuation&customer.id=" + this.customerId;

    var getValuationCallback = {success:this.handleGetValuationSuccess,failure:this.handleAsyncFailure};
    var getValuationRequest = vfAsyncRequest("POST", url, getValuationCallback);
  },

  handleGetValuationSuccess: function(response)
  {
    var jsonObject = getJsonObject(response);
    valueSpan = document.getElementById('collectionValueSpan');
    valueSpan.innerHTML = "$" + addCommas(jsonObject.totalRetailEnhancedValue.toFixed(2));
    return false;
  },

  handleAsyncFailure: function()
  {
    alert("There was a problem loading the valuation.");
  }
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

//exampleIntlShipRates is placed here in order to be accessible from different sources, including some in marcomm area, and some under WEB-INF/jsp
var exampleIntlShipRates = '<center><table border="0">'
+ ' <tr><th colspan="4" align="center"><strong>International Shipping Rate Example (as of 08/18/08)</strong></th></tr> '
+ ' <tr><th colspan="4">&nbsp;</th></tr> '
+ ' <tr><th colspan="4" align="center"><em>Estimated air freight cost per case</em></th></tr> '
+ ' <tr><th align="left">Quantity Shipped</th><th align="center">Japan</th><th align="center">Hong Kong</th></tr> '
+ ' <tr><td align="left">1 case</td><td align="right">$107.55</td><td align="right">$153</td></tr> '
+ ' <tr><td align="left">5 cases</td><td align="right">$107.55</td><td align="right">$87</td></tr> '
+ ' <tr><td align="left">10 cases</td><td align="right">$107.76</td><td align="right">$66.51</td></tr> '
+ ' <tr><th colspan="4">&nbsp;</th></tr> '
+ ' <tr><th colspan="4" align="center"><em>Estimated duties and taxes</em></th></tr> '
+ ' <tr><th align="left">Quantity Shipped</th><th align="center">Japan</th><th align="center">Hong Kong</th></tr> '
+ ' <tr><td align="left">Invoice value of case</td><td align="right">$1,200.00</td><td align="right">$1,200.00</td></tr> '
+ ' <tr><td align="left">Est. duty/tax per case</td><td align="right">$88.34</td><td align="right">$0</td></tr> '
+ ' <tr><td align="left">% of case invoice value</td><td align="right">7.4%</td><td align="right">0%</td></tr> '
+ ' <tr><th colspan="4">&nbsp;</th></tr> '
+ ' <tr><th colspan="4" align="center"><em>Estimated total shipping/duty/tax cost per case</em></th></tr> '
+ ' <tr><th align="left">Quantity Shipped</th><th align="center">Japan</th><th align="center">Hong Kong</th></tr> '
+ ' <tr><td align="left">1 case</td><td align="right">$195.89</td><td align="right">$153</td></tr> '
+ ' <tr><td align="left">5 cases</td><td align="right">$195.89</td><td align="right">$87</td></tr> '
+ ' <tr><td align="left">10 cases</td><td align="right">$196.10</td><td align="right">$66.51</td></tr> '
+ ' <table></center> ';



function Home_onload()
{
	interfaceObj = new YAHOO.widget.HomeInterface();
	interfaceObj.initNavigator();
}

function CustW_onload()
{
	interfaceObj = new YAHOO.widget.ACustWInterface();
	interfaceObj.initNavigator();
}

