var bVisible = false;
var bProcessingMessageVisible = false;
var iProcessingDots = 3;
var bAddListToCart = false;
var bMiniCartBubble = true;
var ProcessingMessageReturned = false;
var ProcessingMessageHTML = "";
var ProcessingMessagePlain = false;
var iProcessingDotCount = 0;
var oProcessingDots;
var oBody;
var eBodyCartBox;

function getElementById(id) {
  if (document.getElementById) {

    if (document.getElementById(id))
      return document.getElementById(id);
    else
      return document.getElementsByName(id)[0];
  }

  if (document.all)
    return document.all[id];
}


function getPageCoords(elementId) {
     var coords = {xRelative: 0, yRelative: 0, xActual: 0, yActual: 0, containerWidth: 0, containerHeight: 0} 
     var element; 

     element = getElementById(elementId);
     origElement = element;

     while (element) {

       if ((origElement != element) && ((element.tagName == "DIV") || (element.tagName == "SPAN"))) {
         coords.xActual += element.offsetLeft; 
         coords.yActual += element.offsetTop; 
         coords.containerWidth = element.offsetWidth;
         coords.containerHeight = element.offsetHeight;
       }

       else {
         coords.xActual += element.offsetLeft; 
         coords.yActual += element.offsetTop; 

         if (!coords.containerWidth) {
           coords.xRelative += element.offsetLeft; 
           coords.yRelative += element.offsetTop;
         }

       }

       element = element.offsetParent; 
       origElement = null;
     } 

     return coords;
}


function displayMiniCart(url) {

  if (url.charAt(0) == "/")
    url = url.substr(1);

  if (url.charAt(url.length - 1) != "?")
    url += "?";

  url = url.replace("//customer", "/customer");


  if (bVisible)
    return;

  txtMiniCart = "MiniCart";
  eMiniCart = getElementById(txtMiniCart);
  if (!eMiniCart)
    eMiniCart = addMiniCartDiv(txtMiniCart, url);
  
  if (!eMiniCart)
    return;

  postMiniCartHTML(url);
}


function addListToCart(FormName, url, sProcessingURL) {
  url += "&ButtonAddListToCart.x=1";
  addItemsToCart(FormName, url, sProcessingURL);
}


function addItemsToCart(FormName, url, sProcessingURL) {
  var i, sItemCode, eAddToCart, elem2, elemList;
  var aItemCodes = new Array();
  var aItemQuantities = new Array();
  var aItemPrices = new Array();
  var aUOM = new Array();
  var aHTMLFormRowNumber = new Array();
  var sHTMLFormRow;
  var sMiniCartDisplay;

  ProcessingMessageReturned = false;
  oCartBox = getElementById("CartBox");

  if (oCartBox)
    sMiniCartDisplay = oCartBox.getAttribute("MiniCartDisplay");

  if (sMiniCartDisplay != "TRUE")
    bMiniCartBubble = false;

  // Custom by Ply.  New loading message approach for Quick Order Pages
  if(FormName.indexOf("Quick_Order_Content") > -1 || FormName.indexOf("My_Account_Shopping_List_Detail_Content") > -1 || FormName.indexOf("frmItemSearchResults") > -1) {
    fsh.showLoadingMessage();
  } else {
    scroll(0,0);
    displayProcessingMessage(sProcessingURL);
  }
  oForm = document.forms[FormName];

  if ((FormName == "frmItemSearchResults") || (FormName == "frmPastPurchaseList") || (FormName == "frmPastPurchaseDetail") || (FormName == "frmMyAccountResultArea") || (FormName == "frmGoTogethers") || (FormName == "frmSubstitutes")) {
    if (FormName == "frmPastPurchaseDetail")
      iItemsToSearch = 1;
    else
      iItemsToSearch = getElementById("txtISRLines").value;

    for (i = 0; i <= (iItemsToSearch - 1); i++) {
      if (oForm.elements["txtQuantity" + i] && trimAll(oForm.elements["txtQuantity" + i].value) != '') {
        aItemCodes.push(oForm.elements["txtItemID" + i].value);
        aItemQuantities.push(oForm.elements["txtQuantity" + i].value);
        if (oForm.elements["selUOM" + i] && trimAll(oForm.elements["selUOM" + i].value) != '')
          aUOM.push(oForm.elements["selUOM" + i].value);
	oForm.elements["txtQuantity" + i].value = '';
      }
    }
  }

  else if (FormName == "frmMyAccountResultAreaOQD")  {
    iItemsToSearch = getElementById("txtISRLines").value;

    for (i = 0; i <= (iItemsToSearch - 1); i++) {
      if (oForm.elements["AJAXtxtQuantity" + i] && trimAll(oForm.elements["AJAXtxtQuantity" + i].value) != '') {
        aItemCodes.push(oForm.elements["AJAXtxtItemID" + i].value);
        aItemQuantities.push(oForm.elements["AJAXtxtQuantity" + i].value);
	aItemPrices.push(oForm.elements["txtUnitPrice" + i].value);
        if (oForm.elements["selUOM" + i] && trimAll(oForm.elements["selUOM" + i].value) != '')
          aUOM.push(oForm.elements["selUOM" + i].value);
	oForm.elements["AJAXtxtQuantity" + i].value = '';
      }
    }
  }

  else if (FormName == "Item_Detail_Content") {
    if (oForm.elements["txtQuantity0"] && trimAll(oForm.elements["txtQuantity0"].value) != '') {
      aItemCodes.push(oForm.elements["ItemCode"].value);
      aItemQuantities.push(oForm.elements["txtQuantity0"].value);
      oForm.elements["txtQuantity0"].value = '';
    }
  }

  else if (FormName.indexOf("Quick_Order_Content") > -1) {
    iItemsToSearch = getElementById("txtQOPLines").value;

    for (i = 0; i <= (iItemsToSearch - 1); i++) {
      if (oForm.elements["txtQuantity" + i] && trimAll(oForm.elements["txtQuantity" + i].value) != '') {
        aItemCodes.push(oForm.elements["txtItemID" + i].value);
        aItemQuantities.push(oForm.elements["txtQuantity" + i].value);
	oForm.elements["txtItemID" + i].value = '';
	oForm.elements["txtQuantity" + i].value = '';
      }
    }
  }

  else if (url.indexOf("ButtonAddListToCart") > -1) {
    var sATCUID = "";
    lid = getElementById("lid").value;

    /* Grab HTMLFormRowNumber */
    oAllElements = document.getElementsByTagName("*");
    if (oAllElements == null)
      oAllElements = document.all;

    for (j = 0; j <= oAllElements.length - 1; j++) {
      oElem = oAllElements[j];

      sElementName = oElem.getAttribute("name");
      sElementValue = oElem.getAttribute("value");

      if (sElementName && sElementValue) {
        if (sElementName.indexOf("HTMLFormRowNumber") > -1) {
          aHTMLFormRowNumber.push("&" + sElementName + "=" + sElementValue);

          oElem2 = getElementById("txtShoppingListQuantity" + sElementValue);
          if (oElem2)
            aItemQuantities.push("&" + oElem2.name + "=" + oElem2.value);

          oElem2 = getElementById("selUOM" + sElementValue);
          if (oElem2)
            aUOM.push("&" + oElem2.name + "=" + oElem2.value);
        }
      }
    }

  }

  else if (FormName.indexOf("My_Account_Shopping_List_Detail_Content") > -1) {
    var sATCUID = "";
    lid = getElementById("lid").value;

    /* Find checked items */
    oATCUID = document.getElementsByName("atcuid");

    for (i = 0; i <= oATCUID.length - 1; i++) {
      if (oATCUID[i].checked) {
	oATCUID[i].checked = false;
        sATCUID += oATCUID[i].value + ",";

        /* Grab HTMLFormRowNumber */
        oAllElements = document.getElementsByTagName("*");
        if (oAllElements == null)
          oAllElements = document.all;

        for (j = 0; j <= oAllElements.length - 1; j++) {
          oElem = oAllElements[j];

          sElementName = oElem.getAttribute("name");
          sElementValue = oElem.getAttribute("value");

          if (sElementName && sElementValue) {
            if ((sElementName.indexOf("HTMLFormRowNumber") > -1) && (sElementValue == oATCUID[i].value)) {
	      aHTMLFormRowNumber.push("&" + sElementName + "=" + sElementValue);
            }
          }
        }

        oElem = getElementById("txtShoppingListQuantity" + oATCUID[i].value);
        if (oElem)
          aItemQuantities.push("&" + oElem.name + "=" + oElem.value);

        oElem = getElementById("selUOM" + oATCUID[i].value);
        if (oElem)
          aUOM.push("&" + oElem.name + "=" + oElem.value);
      }
    }

    if ((sATCUID) && (sATCUID.length > 0) && (sATCUID.charAt(sATCUID.length - 1) == ","))
      sATCUID = sATCUID.substring(0, sATCUID.length - 1);
  }

  txtMiniCart = "MiniCart";
  eMiniCart = getElementById(txtMiniCart);
  if (!eMiniCart)
    eMiniCart = addMiniCartDiv(txtMiniCart, url);
  
  if (!eMiniCart)
    return;

  if (FormName.indexOf("My_Account_Shopping_List_Detail_Content") > -1)
    postMiniCartHTMLFromShoppingList(url, "addItemsToCartFromShoppingList", lid, sATCUID, aHTMLFormRowNumber, aItemQuantities, aUOM);
  else
    postMiniCartHTML(url, "addItemsToCart", aItemCodes, aItemQuantities, aUOM, aItemPrices);

}


function displayProcessingMessage(sProcessingURL)
{
  if (bProcessingMessageVisible)
    return;

  iProcessingDots = 0;

  eCartBox = getElementById("CartBox");

  if ((eCartBox && bMiniCartBubble) || (!sProcessingURL)) {
    ProcessingMessagePlain = true;
    ProcessingMessageReturned = true;
    ProcessingMessageHTML = "<HTML><BODY><TABLE ID='MiniShoppingCartView_MainTable' WIDTH='150'><TR ID='MiniShoppingCartView_HeaderRow'><TD><TABLE WIDTH='100%'><TR><TD ALIGN='center'>Processing<DIV ID=ProcessingMessageDots>.</DIV></TD></TR></TABLE></TD></TR></TABLE></BODY></HTML>";
  }

  if (!ProcessingMessageReturned) {
    getProcessingMessageHTML(sProcessingURL);
    return;
  }


  divProcessingMessage = document.createElement("div");
  divProcessingMessage.id = 'DivProcessingMessage';
  divProcessingMessage.name = 'DivProcessingMessage';
  divProcessingMessage.style.visibility = 'hidden';
  divProcessingMessage.className = "MiniCart";
  divProcessingMessage.style.position = "absolute";
  divProcessingMessage.style.zIndex = "110";

  if (ProcessingMessagePlain) {
    divProcessingMessage.style.width = "150";
    divProcessingMessage.style.height = "50";
  }

  divProcessingMessage.innerHTML = ProcessingMessageHTML;


  windowWidth = document.body.clientWidth;
  windowHeight = document.body.clientHeight;

  eCartBox = getElementById("CartBox");

  if (eCartBox && bMiniCartBubble) {
    coordsCartBox = getPageCoords(eCartBox.id);

    if ((parseInt(windowWidth) / 2) < (coordsCartBox.xActual + (parseInt(eCartBox.offsetWidth)/2))) {
      if (coordsCartBox.containerWidth)
        divProcessingMessage.style.right = coordsCartBox.containerWidth - (coordsCartBox.xRelative + parseInt(eCartBox.offsetWidth))
      else
        divProcessingMessage.style.right =  parseInt(windowWidth) - (coordsCartBox.xActual + parseInt(eCartBox.offsetWidth));
    }

    divProcessingMessage.style.top = coordsCartBox.yRelative + (eCartBox.offsetHeight + 1);
  }

  else {
    eCartBox = getElementById("CartBox2");
    bMiniCartBubble = false;
    divProcessingMessage.className = "ProcessingMessage";

    eCartBox.id = "CartBox2";
    eCartBox.name = "CartBox2";
    eCartBox.className = "MiniCart";
    eCartBox.style.overflow = "auto";
    eCartBox.style.position = "absolute";
    eCartBox.style.zIndex = "110";
    eCartBox.style.visibility = "visible";
    var sWidth = 0;

    if (divProcessingMessage.innerHTML.indexOf("MiniShoppingCartView_MainTable") > -1) {
      sContent = divProcessingMessage.innerHTML.split("MiniShoppingCartView_MainTable")[1];
      if (sContent.indexOf("width=") > -1)
        sWidth = sContent.substring((sContent.indexOf("width=") + 6), sContent.indexOf(">")).split(" ")[0];
    }

    eCartBox.style.top = f_scrollTop() + (windowHeight / 3);
    eCartBox.style.left = (windowWidth / 2) - 75;

    eCartBox.style.width = "0";
    eCartBox.style.height = "0";

    divProcessingMessage.style.top = eCartBox.style.top;
    divProcessingMessage.style.left = eCartBox.style.left;
  }

  eCartBox.parentNode.appendChild(divProcessingMessage);
  viewProcessingMessage();
}


function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}


function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function addMiniCartDiv(txtMiniCart, url)
{
  var divMiniCart, eCartBox, windowWidth;
  var bMouseOut = false;

  eCartBox = getElementById("CartBox");
 
  if (!eCartBox) {
    eCartBox = getElementById("CartBox2");
    if (!eCartBox) {
      return null;
    }
  }

  if (eCartBox.onmouseout)
    bMouseOut = true;


  divMiniCart = document.createElement("div");
  divMiniCart.id = txtMiniCart;
  divMiniCart.name = txtMiniCart;
  divMiniCart.className = txtMiniCart;

  if (bMiniCartBubble)
    divMiniCart.style.overflow = "auto"; 

  divMiniCart.style.position = "absolute";
  divMiniCart.style.zIndex = "110";
  divMiniCart.style.visibility = "hidden";

  if (bMouseOut)
    divMiniCart.onmouseout = hideMiniCart;

  divMiniCart.onblur = hideMiniCart;
  divMiniCart.onclick = processOnClick;

  coordsCartBox = getPageCoords(eCartBox.id);

  windowWidth = document.body.clientWidth;

  if ((parseInt(windowWidth) / 2) < coordsCartBox.xActual + (parseInt(eCartBox.offsetWidth)/2)) {
    if (coordsCartBox.containerWidth)
      divMiniCart.style.right = coordsCartBox.containerWidth - (coordsCartBox.xRelative + parseInt(eCartBox.offsetWidth))
    else
      divMiniCart.style.right =  parseInt(windowWidth) - (coordsCartBox.xActual + parseInt(eCartBox.offsetWidth));
  }

  divMiniCart.style.top = coordsCartBox.yRelative + (eCartBox.offsetHeight + 1);

  eCartBox.parentNode.appendChild(divMiniCart);

  return divMiniCart;
}


function getMiniCartHTML(url) {
  url += "&random=" + Math.random();

  if(window.XMLHttpRequest) {
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = processReqChange;
    xmlHttpRequest.open('GET', url, true);
    xmlHttpRequest.send(null);
  }

  else if(window.ActiveXObject) {
    xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
    if(xmlHttpRequest) {
      xmlHttpRequest.onreadystatechange = processReqChange;
      xmlHttpRequest.open('GET', url, true);
      xmlHttpRequest.send();
    }
  }
}


function getProcessingMessageHTML(sProcessingMessageURL) {
  if(window.XMLHttpRequest) {
    xmlHttpRequest2 = new XMLHttpRequest();
    xmlHttpRequest2.onreadystatechange = DisplayProcessingMessage;
    xmlHttpRequest2.open('GET', sProcessingMessageURL, true);
    xmlHttpRequest2.send(null);
  }

  else if(window.ActiveXObject) {
    xmlHttpRequest2 = new ActiveXObject('Microsoft.XMLHTTP');
    if(xmlHttpRequest) {
      xmlHttpRequest2.onreadystatechange = DisplayProcessingMessage;
      xmlHttpRequest2.open('GET', sProcessingMessageURL, true);
      xmlHttpRequest2.send();
    }
  }
}


function DisplayProcessingMessage() {
  if (xmlHttpRequest2 != null) {
    if(xmlHttpRequest2.readyState == 4) {
        ProcessingMessageReturned = true;
        ProcessingMessageHTML = xmlHttpRequest2.responseText;
        displayProcessingMessage("Success");
    }
  }

}


function postMiniCartHTML(url, action, aItemCodes, aItemQuantities, aUOM, aItemPrices) {
  var i, params, sQuoteNumberOQD;

  url += "&random=" + Math.random()

  if (action)  
    url += "&action=" + action;

  if (bMiniCartBubble)
    url += "&UsingMiniCartBubble=True";
  else
    url += "&UsingMiniCartBubble=False";

  sQuoteNumberOQD = getElementById("QuoteNumberOQD");
  if (sQuoteNumberOQD)
    url += "&AJAXQuoteNumberOQD=" + sQuoteNumberOQD.value;

  if (aItemCodes) {
    params = "AJAXTotalItemsToAdd=" + aItemCodes.length;

    for (i = 0; i < aItemCodes.length; i++) {
      params += "&AJAXItemCode" + i + "=" + aItemCodes[i];
    }

    for (i = 0; i < aItemQuantities.length; i++) {
      params += "&AJAXItemQuantity" + i + "=" + aItemQuantities[i];
    }

    for (i = 0; i < aUOM.length; i++) {
      params += "&selUOM" + i + "=" + aUOM[i];
    }

    for (i = 0; i < aItemPrices.length; i++) {
      params += "&AJAXUnitPrice" + i + "=" + aItemPrices[i];
    }
  }
  
  // Ply Expansion
  // Detect which section we're on
  var cartFunction  =   (($('#ButtonQOPAddToCart').length > 0) || ($('.ItemSearchResults_AddButtonsCell').length > 0))  ? fsh.processQuickOrderSubmission : processReqChange;

  if(window.XMLHttpRequest) {
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open('POST', url, true);
    xmlHttpRequest.onreadystatechange = (cartFunction);
    xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpRequest.send(params);
  }

  else if(window.ActiveXObject) {
    xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
    if(xmlHttpRequest) {
      xmlHttpRequest.open('POST', url, true);
      xmlHttpRequest.onreadystatechange = (cartFunction);
      xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttpRequest.send(params);
    }
  }

}


function postMiniCartHTMLFromShoppingList(url, action, lid, sATCUID, aHTMLFormRowNumber, aItemQuantities, aUOM) {
  var i, params = "";

  if (url.indexOf("ButtonAddListToCart") == -1)
    url += "&ButtonAddCheckedToCart.x=1";
    
  url += "&random=" + Math.random() + "&MiniCart=True";

  if (action)  
    url += "&action=" + action;

  if (lid)  
    url += "&lid=" + lid;

  if (sATCUID)
    url += "&atcuid=" + sATCUID;

  if (bMiniCartBubble)
    url += "&UsingMiniCartBubble=True";
  else
    url += "&UsingMiniCartBubble=False";

  if (aHTMLFormRowNumber) {

    for (i = 0; i < aHTMLFormRowNumber.length; i++) {
      params += aHTMLFormRowNumber[i];
    }

    for (i = 0; i < aItemQuantities.length; i++) {
      params += aItemQuantities[i];
    }

    for (i = 0; i < aUOM.length; i++) {
      params += aUOM[i];
    }
  }

  // Ply Expansion
  // Detect which section we're on

  var cartFunction = ($('.ShoppingList_AddListToCartButton').length > 0) ? fsh.processAddWorksheetToCart : processReqChange;

  if(window.XMLHttpRequest) {
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.open('POST', url, true);
    xmlHttpRequest.onreadystatechange = cartFunction;
    xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpRequest.send(params);
  }

  else if(window.ActiveXObject) {
    xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
    if(xmlHttpRequest) {
      xmlHttpRequest.open('POST', url, true);
      xmlHttpRequest.onreadystatechange = cartFunction;
      xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttpRequest.send(params);
    }
  }
}


function processReqChange() {
  var iAJAXId, oddResults, oFirst, tmpDD, oInputBox;

  if (xmlHttpRequest != null) {
    if(xmlHttpRequest.readyState == 4) {
      if(xmlHttpRequest.status == 200) {
        eMiniCart = getElementById("MiniCart");

        if (!eMiniCart)
          return;

        eMiniCart.innerHTML = xmlHttpRequest.responseText;

        eItemCount = getElementById("ItemCount");

        if (eItemCount) {
          sCountType = eItemCount.getAttribute("CountType");

          if (sCountType == "item")
            sInnerText = eMiniCart.innerHTML.substring((eMiniCart.innerHTML.indexOf("CartItemCount") + 20), (eMiniCart.innerHTML.indexOf("NameCartItemCount") - 18));
          else if (sCountType == "line")
            sInnerText = eMiniCart.innerHTML.substring((eMiniCart.innerHTML.indexOf("CartLineCount") + 20), (eMiniCart.innerHTML.indexOf("NameCartLineCount") - 18));
          
          if ((sInnerText.length > 0) && (IsNumeric(sInnerText)))
            eItemCount.innerText = sInnerText;	
        }

	windowWidth = document.body.clientWidth;
	windowHeight = document.body.clientHeight;

        if (bMiniCartBubble) {
          coordsMiniCart = getPageCoords(eMiniCart.id);

          AvailableHeight = windowHeight - coordsMiniCart.yActual;
        
          if (AvailableHeight < parseInt(eMiniCart.offsetHeight))
            eMiniCart.style.height = (AvailableHeight - 50) + "px";
        }

        else {
          var sWidth = 0;

          if (eMiniCart.innerHTML.indexOf("MiniShoppingCartView_MainTable") > -1) {
            sContent = eMiniCart.innerHTML.split("MiniShoppingCartView_MainTable")[1];
            if (sContent.indexOf("width=") > -1)
              sWidth = sContent.substring((sContent.indexOf("width=") + 6), sContent.indexOf(">")).split(" ")[0];
          }

          eMiniCart.style.top = f_scrollTop() + (windowHeight / 3);
          eMiniCart.style.left = (windowWidth / 2) - 75;
        }

        if (bProcessingMessageVisible)
          hideProcessingMessage();

        if (!bVisible)
          viewMiniCart();
      
      }
    }
  }
}


function hideProcessingMessage() {
  if (!bProcessingMessageVisible)
    return;

  eProcessingMessage = getElementById("DivProcessingMessage");
  if (!eProcessingMessage)
    return;
  
  eProcessingMessage.style.visibility = 'hidden';
  bProcessingMessageVisible = false;
}


function processOnClick(e) {

  var eMiniCart, eCartBox, oEvent, iClientX, iClientY, coords;

  if (!bVisible)
    return;

  eMiniCartClose = getElementById("MiniShoppingCartView_close");

  if (eMiniCartClose) {
    oEvent = window.event ? window.event : e;

    if (document.documentElement && document.documentElement.scrollTop)
      root = document.documentElement;
    else if (document.body)
      root = document.body;

    iClientX = oEvent.clientX + root.scrollLeft;
    iClientY = oEvent.clientY + root.scrollTop;

    coordsMiniCartClose = getPageCoords(eMiniCartClose.id);

    if ((iClientX >= coordsMiniCartClose.xActual) && (iClientX <= (coordsMiniCartClose.xActual + parseInt(eMiniCartClose.offsetWidth)))) {
      if ((iClientY >= coordsMiniCartClose.yActual) && (iClientY <= (coordsMiniCartClose.yActual + parseInt(eMiniCartClose.offsetHeight)))) {
        bVisible = false;
        fadeOutMiniCart("MiniCart");
        return;
      } 
    }
  }
}


function hideMiniCart(e) {
  var eMiniCart, eCartBox, oEvent, iClientX, iClientY, coords;

  if (!bVisible)
    return;

  eMiniCart = getElementById("MiniCart");
  if (!eMiniCart)
    return;

  eCartBox = getElementById("CartBox");
  if (!eCartBox)
    return null;

  oEvent = window.event ? window.event : e;

  if (document.documentElement && document.documentElement.scrollTop)
    root = document.documentElement;
  else if (document.body)
    root = document.body;

  iClientX = oEvent.clientX + root.scrollLeft;
  iClientY = oEvent.clientY + root.scrollTop;

  coordsCartBox = getPageCoords(eCartBox.id);
  coordsMiniCart = getPageCoords(eMiniCart.id);

  CartBoxHeight = coordsMiniCart.yActual - coordsCartBox.yActual;

  if ((iClientX < coordsCartBox.xActual) && (iClientY < coordsMiniCart.yActual)) {
    bVisible = false;
    fadeOutMiniCart("MiniCart");
    return;
  }

  if ((iClientX >= coordsMiniCart.xActual) && (iClientX <= (coordsMiniCart.xActual + parseInt(eMiniCart.offsetWidth)))) {
    if ((iClientY >= (coordsCartBox.yActual)) && (iClientY <= (coordsCartBox.yActual + CartBoxHeight + parseInt(eMiniCart.offsetHeight))))
      return;	
  }

  bVisible = false;
  fadeOutMiniCart("MiniCart");
}

function setOpacity(elemName, value) {
 getElementById(elemName).style.opacity = value / 10;
 getElementById(elemName).style.filter = 'alpha(opacity=' + value * 10 + ')';
}

function fadeInMiniCart(elemName) {
 for( var i = 0 ; i <= 100 ; i++ )
   setTimeout( 'setOpacity("' + elemName + '",' + (i / 10) + ')' , 3 * i );
}

function fadeOutMiniCart(elemName) {
 for( var i = 0 ; i <= 100 ; i++ ) {
   setTimeout( 'setOpacity("' + elemName + '",' + (10 - i / 10) + ')' , 3 * i );
 }

 setTimeout('closeElem("' + elemName + '")', 300 );
}

function closeElem(elemName) {
 getElementById(elemName).style.visibility = 'hidden';
}

function viewMiniCart() {
 bVisible = true;
 setOpacity("MiniCart", 0);
 getElementById("MiniCart").style.visibility = 'visible';
 getElementById("MiniCart").focus();
 fadeInMiniCart("MiniCart");
}

function viewProcessingMessage() {
 bProcessingMessageVisible = true;
 setOpacity("DivProcessingMessage", 0);
 getElementById("DivProcessingMessage").style.visibility = 'visible';
 fadeInMiniCart("DivProcessingMessage");
 displayProcessingDots();
}


function tkanimate1() {
  var i;
  var dots;
  dots = ".";

  for (i = 0; i < iProcessingDotCount; i++) {
    if (iProcessingDotCount >= 10) {
      dots = ".";
      iProcessingDotCount = 0;
    }
    else {
      dots += ".";
    }
  }

  oProcessingDots.firstChild.nodeValue = dots;
  iProcessingDotCount++;
  setTimeout("tkanimate1()",500);
}


function displayProcessingDots() {
  oProcessingDots = getElementById("ProcessingMessageDots");
  iProcessingDotCount = 0;
  if (oProcessingDots)
    tkanimate1();
}

/* Enhancements by Ply */

// Init FSH global object.  Future javascript should utilize / expand upon
// this as to help avoid global scope pollution.
var fsh = fsh || {};
// All additional script is contained within an anonymous function (closure -- again
// to reduce global scope pollution.
(function($) {
    
    var countItemsInCart = 0;
        
    $(document).ready(function() {
        // Insert appropriate messaging
        $('#ButtonQOPAddToCart').after($('<div id="msgLoading" class="iconMessage">Saving to cart</div>'))
                                .after($('<div id="msgError" class="iconMessage msgError">An error occured. Please verify the part number, quanity and try again.</div>'))        
                                .after($('<div id="msgSuccess" class="iconMessage msgSuccess">Items added to cart. <a href="/default.aspx?page=Shopping%20Cart">View Cart</a></div>'));        

        $('.ShoppingList_AddListToListButton').after($('<img src="customer/fisuco/images/spacer.gif" width="100%" height="25"/>'))
                                .after($('<div id="msgLoading" class="iconMessage">Saving to cart</div>'))
                                .after($('<div id="msgError" class="iconMessage msgError">An error occured. Please verify the items and try again.</div>'))        
                                .after($('<div id="msgSuccess" class="iconMessage msgSuccess">Items added to cart. <a href="/default.aspx?page=Shopping%20Cart">View Cart</a></div>'))
                                .after($('<img src="customer/fisuco/images/spacer.gif" width="100%" height="25"/>'));        

        $('input[name=ButtonResultsAddToCart]').after($('<img src="customer/fisuco/images/spacer.gif" width="100%" height="25"/>'))
                                .after($('<div id="msgLoading" class="iconMessage">Saving to cart</div>'))
                                .after($('<div id="msgError" class="iconMessage msgError">An error occured. Please verify the items and try again.</div>'))        
                                .after($('<div id="msgSuccess" class="iconMessage msgSuccess">Items added to cart. <a href="/default.aspx?page=Shopping%20Cart">View Cart</a></div>'))
                                .after($('<img src="customer/fisuco/images/spacer.gif" width="100%" height="25"/>'));   

        // Grab the current cart-count
        if($('#cart-count').length > 0) {
            countItemsInCart += parseInt($('#cart-count').text(), 10);
        }
        
        // Inline fix for MSIE < 8 browsers.
        // @todo: Refactor this approach to use an external stylesheet loaded only for IE < 8
        if($.browser.msie == true && parseInt($.browser.version, 10) < 8) {
            $('.iconMessage').css(
                {
                    'margin-left'   :   (parseInt($.browser.version, 10) < 7 ? '-85px' : '-105px')
                }
            );

            $('.ShoppingList_AddButtonsCell .iconMessage').css(
                {
                    'margin-left'   :   (parseInt($.browser.version, 10) < 7 ? '-330px' : '-330px')
                }
            );
        }
        
        // Hide any existing success/error messages when a MiniCart button is clicked.
        $('#ButtonQOPAddToCart').bind('click', function() {
            $('#msgSuccess, #msgError').css('visibility', 'hidden');
        });

        $('.ShoppingList_AddListToCartButton').bind('click', function() {
            $('#msgSuccess, #msgError').css('visibility', 'hidden');
        });

        $('.ShoppingList_AddCheckedToCartButton').bind('click', function() {
            $('#msgSuccess, #msgError').css('visibility', 'hidden');
        });
        
        $('input[name=ButtonResultsAddToCart]').bind('click', function() {
            $('#msgSuccess, #msgError').css('visibility', 'hidden');
        });
        
    });
    
    /**
     * Displays the loading message.
     **/
    fsh.showLoadingMessage = function() {
        $('#msgLoading').css('visibility', 'visible');
    }
    
    /**
     * Handles a completed Quick Order Page Async Request.
     **/
    fsh.processQuickOrderSubmission = function() {
        if(xmlHttpRequest != null && xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            var $response =  $('<div />').append(xmlHttpRequest.responseText);
            // We test for success by parsing out the updated item count from the 
            // response text (which is a big chunk of HTML).
            $('#msgLoading').css('visibility', 'hidden');
            if($response.find('input#CartItemCount').length > 0 && parseInt($response.find('input#CartItemCount').val(), 10) > countItemsInCart) {               
                $('#msgSuccess').css('visibility', 'visible');
                countItemsInCart = parseInt($response.find('input#CartItemCount').val(), 10);
                $('#cart-count').text(countItemsInCart + ' Items'); 
            } else {
                $('#msgError').css('visibility', 'visible');
            }
        }
    }
    /**
     * Handles a completed Worksheet Page Async Request.
     **/
    fsh.processAddWorksheetToCart = function() {
        if(xmlHttpRequest != null && xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            var $response =  $('<div />').append(xmlHttpRequest.responseText);
            // We test for success by parsing out the updated item count from the 
            // response text (which is a big chunk of HTML).
            $('#msgLoading').css('visibility', 'hidden');
            if($response.find('input#CartItemCount').length > 0 && parseInt($response.find('input#CartItemCount').val(), 10) > countItemsInCart) {               
                $('#msgSuccess').css('visibility', 'visible');
                countItemsInCart = parseInt($response.find('input#CartItemCount').val(), 10);
                $('#cart-count').text(countItemsInCart + ' Items'); 
            } else {
                $('#msgError').css('visibility', 'visible');
            }
        }
    }
})(jQuery);

