// customLib.js
//
// Custom JS library
//

var selectedShipRate = '';
var locPage = '';
var inPopup = false;
var personalType;

try {
  var qs = new Querystring();  
  locPage = qs.get('page','');
}
catch (e) { locPage = ''; }

//URL Functions
var eLinkUrl = {

    // public method for url encoding
    encode : function (val) {
        if ( val==null || val+''=='undefined' || (val+'' == '') )
          return '';
        else
          return escape(this._utf8_encode(val));
    },

    // public method for url decoding
    decode : function (val) {
        return this._utf8_decode(unescape(val));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (val) {
        var strVal = String(val).replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < strVal.length; n++) {

            var c = strVal.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function doLogin(strFunction){

  var strResponse = '';
  var strTemp = '';
  var strUser = document.getElementById('txtUserName').value;
  var strPassword = document.getElementById('txtPassword').value;
  var argCount = doLogin.arguments.length;
  var newPage = true;
  var curPage = qs.get('page','');

  if (curPage.toLowerCase()=="checkout" && (strUser == '' || strPassword == '') ) {
    strUser = document.getElementById('txtCheckoutUserName').value;
    strPassword = document.getElementById('txtCheckoutPassword').value;
  }

  if ( !IsBlank(strUser) && !IsBlank(strPassword) )
  {
    document.body.style.cursor="wait";
    if (strFunction!='loginLink') {
      var showTimer = setTimeout("showPopWin('','<DIV id=\"modalContent\" style=\"margin-top:25px;\"><TABLE align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"200px\"><TR><TD id=\"loadingMsg\"align=\"center\"><span style=\"font-size:10pt;font-weight:bold;\">Retrieving Login Information.<br>Please Wait...</span></TD></TR></TABLE></DIV>',325,100,refreshCurrentPage);", 100);
      var hideTimer = setTimeout("hidePopWin(true);", 500);
    }
    
    /* Grey out the form here */
    if (browserVersion == 1) {
      window.onkeypress = stopEntry;
      window.onclick = stopEntry;
    }

    blnDisabled = true;
    //loc=loc.replace('http:','https:');
    //if (browserVersion==1)
    //  strResponse = xmlHTTPCall(loc+'Includes/ajaxFunctions.aspx?type=login&user=' + strUser + '&pwd=' + strPassword, false,false,false);
    //else
    strResponse = xmlHTTPCall('../Includes/ajaxFunctions.aspx?type=login&user=' + strUser + '&pwd=' + strPassword, false,false,false);
    document.body.style.cursor="default";

    var aryResponse = strResponse.split('|');
    try {
      if ( aryResponse[0] == 'true' ) {
        if ( aryResponse.length > 1 && Trim(aryResponse[1].toLowerCase()) == 'admin' ) {    
          location.replace('../CustomerScripts/page.aspx?page=admin');
        }
        else {
          try {
            if (document.getElementById('loginTable')!=null)
              document.getElementById('loginTable').style.display='none';
          }
          catch (e) { }
          
          try {
            if (strFunction=='loginLink') {
            
              try {
                parent.window.hs.close('loginLink');
              }
              catch (e) {
                hs.close('loginLink');
              }
              newPage = false;
            }
            else {
              document.getElementById('loginBox').style.display = 'none';
              if (document.getElementById('loginError') != null) {
                document.getElementById('loginError').innerHTML = '';
                document.getElementById('loginError').style.display = 'none';
                if (document.getElementById('loginErrorText') != null) {
                  document.getElementById('loginErrorText').style.display = 'none'; 
                }
              }
            }
          }
          catch (e) { }

          if ( strFunction == 'checkout' || curPage.toString().toLowerCase()=='checkout'){
            document.getElementById('billingFirstName').value = aryResponse[2];
            document.getElementById('billingInitial').value = aryResponse[3];
            document.getElementById('billingLastName').value = aryResponse[4];
            document.getElementById('billingAddress1').value = aryResponse[5];
            document.getElementById('billingAddress2').value = aryResponse[6];
            document.getElementById('billingCity').value = aryResponse[7];

            SetSelectValue('cboBillingState',aryResponse[8]);

            document.getElementById('billingZip').value = aryResponse[9];
            document.getElementById('billingPhone').value = aryResponse[10];
            document.getElementById('billingEmail').value = aryResponse[11];
            document.getElementById('loginAnchor').innerHTML = '<span id="myAccountAnchor"><a href="../CustomerScripts/page.aspx?page=myaccount&pagetype=1" id="memberLink" alt="" title="" >My Account</a><span> | </span><a href="../CustomerScripts/page.aspx?page=logout" id="logoutlink" alt="" title="" >Logout</a></span>';
            blnDisabled = false;
            //window.location.reload();
            try {
              nextCheckoutPage(0,2);
            }
            catch (e) { }
            return false;
          }
          else if ( strFunction == 'custom' ) {
            blnDisabled = false;
            if ( argCount > 1 )
              window.location.replace(doLogin.arguments[1].toString());
            else
              window.location.reload();
            return false;
          }
          else if (strFunction == 'loginLink') {
            //Reset Account Info

            try {            
              customerNumber = aryResponse[12];
              customer = aryResponse[13];
              userLevel = parseInt(aryResponse[14]);

              taxableSale = parseInt(aryResponse[15]);
              applyShipping = parseInt(aryResponse[16]);

              allowPO = parseInt(aryResponse[17]);
              allowOrder = parseInt(aryResponse[18]);
              allowAR = parseInt(aryResponse[19]);
              orderLimit = parseFloat(aryResponse[20]);
              cart = parseInt(aryResponse[21]);
              cartItems = parseInt(aryResponse[22]);
              cartTotal = formatDollar(aryResponse[23]);

              try {
                document.getElementById('cartQty').innerHTML = cartItems;
              }
              catch (e) { }
              
              try {
                document.getElementById('cartSubTotal').innerHTML = formatDollar(cartTotal,true);
              }
              catch (e) { }
              
              document.getElementById('topLinkAnchor').innerHTML = '<li><span id="myAccountAnchor"><a href="javascript:void(0);" id="memberLink" onclick="displayInline(\'myaccount\');" alt="" title="" >My Account</a></span></li><li><span style=""color:#ffffff;""> | </span></li><li><span><a href="../CustomerScripts/page.aspx?page=logout" id="logoutlink" alt="" title="" >Logout</a></span></li>'; //<li><span style=""color:#ffffff;""> | </span></li>
              
              try {
                if ( curPage.toString().toLowerCase()=='checkout'){
                  document.getElementById('billingFirstName').value = aryResponse[2];
                  document.getElementById('billingInitial').value = aryResponse[3];
                  document.getElementById('billingLastName').value = aryResponse[4];
                  document.getElementById('billingAddress1').value = aryResponse[5];
                  document.getElementById('billingAddress2').value = aryResponse[6];
                  document.getElementById('billingCity').value = aryResponse[7];

                  SetSelectValue('cboBillingState',aryResponse[8]);

                  document.getElementById('billingZip').value = aryResponse[9];
                  document.getElementById('billingPhone').value = aryResponse[10];
                  document.getElementById('billingEmail').value = aryResponse[11];
                  //blnDisabled = false;
                  //window.location.reload();
                  try {
                    nextCheckoutPage(0,2);
                  }
                  catch (e) { }
                  return false;
                }
              }
              catch (e) { }
            }
            catch (e) { 
              //alert(e.message);
            }
          }
          else {
            document.body.style.cursor='default';
            blnDisabled = false;
            if (document.URL.toString().toLowerCase().indexOf('login')!=-1)
              window.location.replace('../CustomerScripts/page.aspx?type=defaultbrowse');
            else
              window.location.reload();
            return false;
          }
        }
      }
      else {
        try {
          if (document.getElementById('loginError') != null) {
            if ( aryResponse[1]+'' == 'undefined' || aryResponse[1] == '' || aryResponse[1] == null ) {
              document.getElementById('loginErrorText').innerHTML = 'Unable to Login. Please try again.';
            }
            else {
              document.getElementById('loginErrorText').innerHTML = 'Invalid Login'; //aryResponse[1];
            }
            clearTimeout(hideTimer);
            document.getElementById('loginErrorText').style.display = '';
            document.getElementById('loginError').style.display = '';
          }
        }
        catch (e) { 
          document.body.style.cursor='default';
          blnDisabled = false;
        }
      }
    }
    catch (e) { 
      //TODO
    }

    if (browserVersion == 1) {
      window.onkeypress = null;
      window.onclick = null;
    }

  }
  
  document.body.style.cursor='default';
  blnDisabled = false;
  //if (gPopupIsShown)
  //  setTimeout("hidePopWin(true);",150);

  return false;
}

function displayInline(stype) {
   
    var iwidth=535;
    var iheight=310;
    var strOpts = '';
    var currentTime = new Date();

    hs.dimmingOpacity = 0.25;
    hs.onDimmerClick = function() {
      return false;
    };
    
    if (displayInline.arguments.length > 1 )
      strOpts = displayInline.arguments[1];

    strOpts += '&currenttime=' + currentTime.getTime();

    hs.Expander.prototype.onAfterClose = function() {
       this.onDimmerClick = null;
    };

    switch (stype.toLowerCase()) {
      
      case 'register':
          iwidth=700;
          iheight=395;
          //if (is_fx)
          //  iwidth=625;
                
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: '../CustomerScripts/page.aspx?page=register&currenttime=' + currentTime.getTime(), preserveContent: false, headingText: 'Create Account' } );    
        break;
      case 'myaccount':
          if (domainName.toLowerCase() == 'retailer.elegantbaby.com') {
            siteNavigate('https://retailer.elegantbaby.com/customerscripts/page.aspx?page=myaccount','',1,0);
          }
          else {
          iwidth=680;
          iheight=525;
          if (is_fx)
            iwidth=695;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: 700, objectHeight: 525, src: '../CustomerScripts/page.aspx?page=accountinfo&currenttime=' + currentTime.getTime(), preserveContent: false, headingText: 'My Account' } );      
          }
        break;
      case 'ordersearch':
          iwidth=680;
          iheight=525;
          if (is_fx)
            iwidth=695;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: 700, objectHeight: 525, src: '../CustomerScripts/page.aspx?page=orderSearch' + strOpts, preserveContent: false, headingText: 'Order Lookup' } );      
        break;
      case 'passwordreminder':
          iwidth=320;
          iheight=260;
          if (is_fx) {
            iwidth=330;
          }                
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: '../CustomerScripts/page.aspx?page=passwordreminder&currenttime=' + currentTime.getTime(), preserveContent: false, headingText: 'Password Reminder' } );    
        break;
      case 'displayorder':
          iwidth=700;
          iheight=575;
          if (is_fx) {
            iwidth=710;
          }
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: strOpts, preserveContent: false, headingText: '' } );    
        break;
      case 'wishlistadd':
          iwidth=245;
          iheight=120;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, contentId: 'addWishList', preserveContent: false, headingText: '' } );
        break;
      case 'addtocart':
          iwidth=225;
          iheight=110;
          hs.htmlExpand(document.getElementById('pageLink1'), { width: iwidth, height:iheight, contentId: 'addCartItem', preserveContent: false, headingText: '' } );
        break;
      case 'locatorwindow':
          iwidth=300;
          iheight=175;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, contentId: 'locatorWindow', preserveContent: false, headingText: '' } );
        break;
      case 'makepayment':
          iwidth=725;
          iheight=425;
          if (is_ie7) {
            iwidth=725;
            iheight=475;          
          }
          hs.htmlExpand(document.getElementById('pageLink1'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: strOpts, preserveContent: false, headingText: 'Make \'On Account\' Payment' } );    
        break;
      case 'itemdetail':
          iwidth=750;
          iheight=500;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: strOpts, preserveContent: false, headingText: 'Item Detail' } );      
      case 'giftwrap':
          iwidth=400;
          iheight=150;
          hs.htmlExpand(document.getElementById('pageLink'), { width: iwidth, height:iheight, objectType: 'iframe', objectWidth: iwidth, objectHeight: iheight, src: strOpts, preserveContent: false, headingText: 'Gift Wrap Message' } );      
    }

}

function displayInlineCart() {

  try {
    
    var loc = document.URL.toString().toLowerCase();
    if ((cartItems != 0 || inPopup==true) && loc.indexOf('checkout') == -1) { 
      hs.htmlExpand(document.getElementById('cartLink'), { width: 725, objectType: 'iframe', objectWidth: 725, objectHeight: 280, src: '../CustomerScripts/page.aspx?page=cartReview', preserveContent: false, headingText: 'Cart Review' } );
    }
    else
      return false;
  }
  catch (e) { 
    return false; 
  }
  return false;
}

function addToCart(strItem, price, intQty) {

  var updateCartTotals = true;
  var argCount = addToCart.arguments.length;
  var strReturn = '';
  var uom = '';
  var options = '';
  var strPostVal = '';
  var updatePersonal = true;
  
  if (allowOrder==0) {
    showPopWin('','<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Ordering functions for this login have been disabled.<br>Please see your administrator.</span></TD></TR></TABLE></DIV>',250,125,null);
    return false;
  }
    
  if ( argCount > 4 )
    updatePersonal = false;
  else if (argCount == 4)
    uom = addToCart.arguments[3];

  try { 
    if ( !IsBlank(strItem) && !IsBlank(intQty) && allowOrders == 1 ) {

      // See if we can get the uom from the selected size
      try {
        if (uom+''=='' || uom=='undefined') {
          var test = GetSelectValue('sizes'+strItem);
          if (test!=null)
            uom=test;
        }
      }
      catch (e) { 
        uom='';
      }

      /* hack so the UOM can retain multiple spaces */
      uom=uom.replace('<pre>','');
      uom=uom.replace('</pre>','');
      
      // Personalization options
      try {

        if (document.getElementById('personalize-tab') && strItem != 'giftwrap') {
        
          var style = GetRadioValue(document.forms['personal-radio-form'].elements['personal']);
          var color = GetSelectValue("color-select");
          var font = GetRadioValue(document.forms['personal-monogram-form'].elements['monogram']);
          var text = '';
          var birthday = document.getElementById('txtBirthDay').value;
          var birthdayFormat = GetRadioValue(document.forms['personal-embroidery-form'].elements['birthday']);
          
          switch (font) {
            case "1":
              font = "fishtail";
              break;
            case "2":
            case "8":
              font = "brush script";
              break;
            case "3":
              font = "boomerang";
              break;
            case "4":
            case "7":
              font = "block";
              break;
            case "5":
              font = "amazone";
              break;
            case "6":
              font = "curlz";
              break;
          
          }

          switch (style.toLowerCase()) {
            case "initials":
                text = document.getElementById('txtFirstInitial').value + document.getElementById('txtMiddleInitial').value + document.getElementById('txtLastInitial').value;
                text = text.toUpperCase();
              break;
              
            case "monogram":
                text = document.getElementById('txtFirstInitialM').value + document.getElementById('txtLastInitialM').value + document.getElementById('txtMiddleInitialM').value;
                text = text.toUpperCase();
              break;

            case "name":
                text =  document.getElementById('txtName').value;
              break;              
            
          }
          
          switch (birthdayFormat) {
            case "0":
              birthdayFormat = "Short Date";
              break;
            case "1":
              birthdayFormat = "Long Date";
              break;
            case "2":
              birthdayFormat = "Euro Date";
              break;
            default:
              birthdayFormat="";
              break;
          }
          
          if (text != '') {
            options = '&dn=detailnotes&notes='+style+'|'+color+'|'+font+'|'+text+'|'+birthday+'|'+birthdayFormat;
            price = parseFloat(stripCharsInBag(document.getElementById('itemPrice').innerHTML,'$, ')) + 8;
          }
          
          if ((style=="" || (color=="" && personalType!="3")|| font=="" || text == "") && updatePersonal) {
            alert("Please add Personalization Style, Color, Font Type and\r\nPersonalization Text before adding to the cart.");
            return false;
          }
        
        }        
      }
      catch (e){ }
      
      if (!updatePersonal)
        options = '&dn=detailnotes&notes=';

      strPostVal = '../Includes/ajaxFunctions.aspx?type=addtocart&item=' + strItem + '&prc=' + price + '&qty=' + intQty + '&uom=' + uom + options;
      strResponse = xmlHTTPCall(strPostVal, false, false, false);
      var aryResponse = strResponse.split('|',20);

      if ( aryResponse[0] == 'true' ) {
        strReturn = aryResponse[1] + '|' + aryResponse[2];
        if (inPopup==true) {
          try{
            parent.window.document.getElementById('cartQty').innerHTML = aryResponse[1];
          }
          catch (e) { }
          try {
            parent.window.document.getElementById('cartSubTotal').innerHTML = formatDollar(aryResponse[2],true);
            cartItems = parseInt(aryResponse[1]);
          }
          catch (e) { }

          try {
            if ( updateCartTotals == true )
              parent.window.document.getElementById('viewCartDiv').style.display = '';
            }
          catch (e) { }
        }
        else {
          try{
          document.getElementById('cartQty').innerHTML = aryResponse[1];
          }
          catch (e) { }
          document.getElementById('cartSubTotal').innerHTML = formatDollar(aryResponse[2],true);
          cartItems = parseInt(aryResponse[1]);              

          try {
            if ( updateCartTotals == true )
              document.getElementById('viewCartDiv').style.display = '';
            }
          catch (e) { }
        }
      }
      else {

        if (aryResponse[1] == 'overlimit') {
          showPopWin('','<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Adding this item would put you over your Order Limit.</span></TD></TR></TABLE></DIV>',250,100,null);    
        }

      }

      //document.body.style.cursor='default';
      blnDisabled = false;

    }
  }
  catch (e) { }
  
  if ( parseInt(intQty) > 0) {
    switch (locPage.toLowerCase()) {
      case "itemdetail":
      case "defaultbrowse":
      case "browse":
        if (inPopup==false)
          displayInline('addtocart');
        else {
          parent.window.hs.close();
          parent.window.displayInlineCart();

        }
        break;
    }
  }
  
  return strResponse;
  
}

function doOrderSearch() {

  try {
    var order = document.getElementById('txtSearchNumber').value;
    var user = document.getElementById('txtSearchEmail').value;
    var strOpts = '';
    
    if (order+''=='' || user+''=='') {
      showPopWin('', 'Order Number and Email Address as required..', 250, 110, null);
      return false;
    }

    strOpts = '&o=' + order;
    strOpts += '&u=' + Url.encode(user);
    
    var loc = document.URL.toString().toLowerCase();
    loc = loc.substring(0,loc.indexOf('customerscripts'));
    strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=ordertest' + strOpts, false,false,false);
    var aryResponse = strResponse.split('|',20);

    if ( aryResponse[0] == 'true' ) {
      hs.close('orderLookup');
      setTimeout("displayInline('ordersearch','" + strOpts + "')",250);
    }
    else {
      showPopWin('', 'Unable to find Order Information.', 250, 110, null);
    }
  }
  catch (e) { }
  
}

function forgotPassword() {

  try {

    try {
      parent.window.hs.close('loginLink');
    }
    catch (e) {
      try {
        hs.close('loginLink');
      }
      catch (e) { }
    }
    
    displayInline('passwordreminder');
      
  }
  catch (e) {
    //No Errors
  }

}

function resendPassword(email) {

  try {

    //closeHS();

    var loc = document.URL.toString().toLowerCase();
    loc = loc.substring(0,loc.indexOf('customerscripts'));
    strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=PasswordReminder&user='+email, false,false,false);

    var aryResponse = strResponse.split('|',20);
    //resetPopWin(250,110);

    if ( aryResponse[0] == 'true' ) {
      showPopWin('', '<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Your new password has been sent.<br>Please check your email.</span></TD></TR></TABLE></DIV>', 250, 110, closeHS);
    }
    else {
      showPopWin('', '<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Email address is not on file.</span></TD></TR></TABLE></DIV>', 250, 110, closeHS);
    }

  }
  catch (e) {
    // No Errors
  }

}

function processShipReturn(strResponse, blnCheckout){

  var strTemp = '';
  var dblShipping = 0;
  var lngWeight  = 0;
  var strCompany = '';
  var dblRate = 0;

  try {
    if ( !blnCheckout )
      var aryResponse = strResponse.split('|',20);
    else
      var aryResponse = new Array(10);

    if ( aryResponse[0] == 'true' || ( blnCheckout == 1 && !IsBlank(strResponse)) ) {

      if ( blnCheckout != 1) {
        updateShipping(aryResponse[1]);
      }
      else {

        if (browserVersion == 1 ){
          //aryResponse = strResponse.split('|',20);
          var xmlDoc = new Sarissa.getDomDocument();
          xmlDoc.async = false;
          xmlDoc.onreadystatechange=IExmlVerify;
          xmlDoc.loadXML(strResponse);
          var root = xmlDoc.documentElement;
        }
        else{
          var oDomDoc = strResponse;
          var root = oDomDoc.getElementsByTagName('Rates').item(0);
        }     
        // Build the HTML for Shipping Tables

        var rateCnt = 0;
        var companyCnt = 0;
        var strChecked = '';

        for (var d = 0; d < 20; d++){
            options[d] = new Array(40);
        }

        for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
          var node = root.childNodes.item(iNode);
          if (node.childNodes.length > 0) {
            strCompany = node.getAttribute("ID");
            company[companyCnt] = strCompany;
            rateCnt = 0;
            for (var i = 0; i < node.childNodes.length; i++) {
              var sibl = node.childNodes.item(i);
              var len = parseInt(sibl.childNodes.length / 2);
              for (x = 0; x < sibl.childNodes.length; x++) {
                var sibl2 = sibl.childNodes.item(x);
                var sibl3;
                if (sibl2.childNodes.length > 0) {
                  sibl3 = sibl2.childNodes.item(0);
                  options[companyCnt][rateCnt] = sibl3.data;
                  rateCnt++;
                }
              }
            }

            if ( strCompany != '' )
              companyCnt++;
          }
        }


        //always gets one too many in the loop?????       
        //companyCnt = companyCnt - 1;
        if ( companyCnt != 0){

          // First build the Shippers Table
          var s='<table class="visible" border="0" cellpadding="0" cellspacing="0" width="97%">';
          s+='<tr>';

          for (var i = 0; i < companyCnt; i++) {
            if (i == 0){
              strChecked='checked';
            }
            else{
              strChecked = '';
            }
            s+='<td class="reviewFont"><input id="company' + i + '" name="shipper" onclick="buildRates(this.value);" value="' + i + '" type="radio" class="checkoutRadio" ' + strChecked + '><span id="shipper' + i + '">' + company[i] + '</span></td>';
            s+='</tr>';
          }

          s+='<tr class="reviewFont">';
          s+='<td class="reviewFont">&nbsp;</td>';
          s+='</tr>';
          s+='<tr class="reviewFont">';
          s+='<td class="reviewFont">&nbsp;* Available Shippers</td>';
          s+='</tr>';
          s+='</table>';

          if (document.getElementById('shippers') ) {
            document.getElementById('shippers').innerHTML = s;
          }

          s = null;
          // First build the Shippers Table


          var t = buildRates(0);
          nextCheckoutPage(0,4);

        }

      }
    }
    else {

        // Displaying shipping error msg

    }

    if (browserVersion == 1) {
      window.onkeypress = null;
      window.onclick = null;
    }

  }
  catch (e) {
    //TODO
  }
  
  document.body.style.cursor='default';
  blnDisabled = false;


  return true;
}

function buildRates(intCompany, objID){

  var strChecked = '';
  var intMod = 0;
  var lowest = 0;
  var lowCheck = 999999999;
  var test;

  try {
    intCompany = stripCharsNotInBag(Trim(intCompany),'0123456789.');
    intCompany = intCompany * 1; // Back to a number
    setShippingMessages(company[intCompany]);
    var s = '<table bgcolor="#FFFFFF" class="visible" border="0" cellpadding="0" cellspacing="0" width="100%">';
    s+='<tr>';

    for (var z = 0; z < 10; z++) {


      if (z == 0){
        strChecked = ''; //'checked';
      }
      else{
        strChecked = '';
      }

      intMod = z % 2;
      if ( options[intCompany][z]+'' != '' && options[intCompany][z]+'' != 'undefined'  && options[intCompany][z] != null ){
        if (intMod != 0){
          s+='<td id="rateAmttd' + z + '" class="priceBold" align="right"><span id="rateAmt' + z + '" style="margin:0 5px; 0 20px">' + formatDollar(stripCharsNotInBag(Trim(options[intCompany][z]),'0123456789.'),true) + '</span></td>';
          s+='</tr>';
          s+='<tr>';

          test = stripCharsNotInBag(options[intCompany][z],'0123456789.');
          test = test * 1; // Convert to a number
          if (test < lowCheck ){
            lowCheck = test;
            lowest = z - 1;
          }
        }
        else{
          s+='<td class="reviewFont"><input id="rate' + z + '" name="rate" onclick="var amt=document.getElementById(\'rateAmt' + (z + 1) + '\').innerHTML;updateShipping(amt);" style="border: 0pt none ;" ' + strChecked + ' type="radio" class="checkoutRadio" value="' + changeCase(options[intCompany][z]) + '">' + changeCase(options[intCompany][z]) + '</td>';
        }
      }
    }

    s+='<tr class="reviewFont">';
    s+='<td class="reviewFont">&nbsp;</td>';
    s+='</tr>';
    s+='<tr class="reviewFont">';
    s+='<td class="reviewFont">&nbsp;* Available Rates</td>';
    s+='</tr>';
    s+='</table>';

    document.getElementById('shipRates').innerHTML = s;
    document.getElementById('rate'+lowest).checked = true;

    updateShipping(lowCheck); 
    
  }
  catch (e) {
    //TODO
  }
  
  return true;

}

function updateShipping(dblVar){

  var dblTotal = 0;
  var dblHandling = 0;
  var dblTax = 0;
  var dblTemp = 0;
  var dblShipping = 0;
  var review = 0;

  try {
  
    try {
      if (document.getElementById('co-shipping-method-form')) {
        var rateLength = document.frmShipping.rate.length;
        for (var i=0;i<rateLength;i++) {
          if (document.frmShipping.rate[i].checked)
            selectedShipRate = document.frmShipping.rate[i].value;
        }
      }      
    }
    catch (e) { }
    

    dblTotal = stripCharsNotInBag(document.getElementById('orderSubTotal').innerHTML,'0123456789.');
    dblHandling = stripCharsNotInBag(document.getElementById('cartHandling').innerHTML,'0123456789.');
    dblTax = stripCharsNotInBag(document.getElementById('cartTax').innerHTML,'0123456789.');

    dblTotal = dblTotal * 1; // Convert to a number
    dblHandling = dblHandling * 1;
    dblTax = dblTax * 1;

    dblTemp = stripCharsNotInBag(Trim(dblVar),'0123456789.');
    dblShipping = dblTemp * 1; // Convert back to a number

    dblTotal = dblTotal + dblShipping + dblHandling + dblTax;

    document.getElementById('cartShipping').innerHTML = formatDollar(dblShipping,true);
    document.getElementById('cartShippingHandling').innerHTML = formatDollar(dblShipping+dblHandling,true);
    document.getElementById('cartTotal').innerHTML = formatDollar(dblTotal,true);

  }
  catch (e) {
    //TODO
  }
  
}

function doUpdateAccount(comp,cust) {

  var strOpts = '';
  var strLocal = '';
  var newsLetter = '0'
    
  try {

    strOpts = strOpts + '&co=' + comp;
    strOpts = strOpts + '&cm=' + cust;
    strOpts = strOpts + '&u=' + document.getElementById('txtUserLogin').value;
    strOpts = strOpts + '&op=' + document.getElementById('txtOldPassword').value;
    strOpts = strOpts + '&p=' + document.getElementById('txtNewPassword').value;
    strOpts = strOpts + '&fn=' + document.getElementById('txtBillingNameFirst').value;
    strOpts = strOpts + '&mn=' + document.getElementById('txtBillingNameMI').value;
    strOpts = strOpts + '&ln=' + document.getElementById('txtBillingNameLast').value;
    strOpts = strOpts + '&gn=' + GetSelectValue(document.getElementById('cboBillingNameGen'));
    strOpts = strOpts + '&a1=' + document.getElementById('txtShipToAddr1').value;
    strOpts = strOpts + '&a2=' + document.getElementById('txtShipToAddr2').value;
    strOpts = strOpts + '&c=' + document.getElementById('txtShipToCity').value;
    strOpts = strOpts + '&s=' + GetSelectValue(document.getElementById('cboShipToState'));
    strOpts = strOpts + '&z=' + document.getElementById('txtShipToZip').value;
    strOpts = strOpts + '&e=' + document.getElementById('txtShipToEMail').value;
    strOpts = strOpts + '&pn=' + document.getElementById('txtShipToPhone').value;
    strOpts = strOpts + '&ep=' + document.getElementById('txtEncryptedPassword').value;
    if (doUpdateAccount.arguments.length > 2)
      strOpts = strOpts + '&usertype=' + doUpdateAccount.arguments[2];
    else
      strOpts = strOpts + '&usertype=0';

    try {
    if (document.getElementById('chkNewsLetter').checked)
      newsLetter = '1';
    }
    catch (e) { }
    strOpts = strOpts + '&nl='+newsLetter;

    document.body.style.cursor='wait';

    blnDisabled = true;
    var loc = document.URL.toString().toLowerCase();
    loc = loc.substring(0,loc.indexOf('customerscripts'));
    strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=updateProfile' + strOpts, false,false,false);

    var aryResponse = strResponse.split('|',20);

    if ( aryResponse[0] == 'true' ) {
      if ( doUpdateAccount.arguments.length >= 3 )  {
        if (doUpdateAccount.arguments.length > 3) {
          if (doUpdateAccount.arguments[3] == 'checkout') {
            try {
              parent.window.document.getElementById('txtUserName').value = document.getElementById('txtUserLogin').value;
              parent.window.document.getElementById('txtPassword').value = document.getElementById('txtNewPassword').value;
              parent.window.hs.close();
            }
            catch (e) {
              try {
                hs.close();
              }
              catch (e) { }
            }
            parent.window.setTimeout("doLogin('checkout')",300);
            return false;
          }          
        }
        else
          showPopWin('', aryResponse[1], 250, 110, redirectHome);
      }
      else
        showPopWin('', aryResponse[1], 250, 110, null);
    }
    else {
      showPopWin('', 'Unable to update Profile Information.', 250, 110, null);
    }

  }
  catch (e) {
    //Abort Update
    blnDisabled = false;
    document.body.style.cursor='default';
  }
  finally {
  
    blnDisabled = false;
    document.body.style.cursor='default';
  }
  
}

function addToWish(strItem, qty) {

  var strReturn = '';
  var uom = '';
  
  if (addToWish.arguments.length>2)
    uom = addToWish.arguments[2];
  
  try { 
    if ( !IsBlank(strItem) ) {

      // See if we can get the uom from the selected size
      try {
        if (uom+''=='' || uom=='undefined') {
          var test = GetSelectValue('sizes'+strItem);
          if (test!=null)
            uom=test;
        }
      }
      catch (e) { 
        uom='';
      }

      /* hack so the UOM can retain multiple spaces */
      uom=uom.replace('<pre>','');
      uom=uom.replace('</pre>','');
      
      strResponse = xmlHTTPCall('../Includes/ajaxFunctions.aspx?type=addtowishlist&item=' + strItem + '&uom=' + uom, false, false, false);

      var aryResponse = strResponse.split('|',20);

      if ( aryResponse[0] == 'true' ) {
        if (qty>0)
          displayInline('wishlistadd');
      }
      else {

        showPopWin('','<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Unable to update your wish list.</span></TD></TR></TABLE></DIV>',250,100,null);    

      }

      //document.body.style.cursor='default';
      blnDisabled = false;

    }
  }
  catch (e) {

  }
  
  return strReturn;
  
}

function storeLocatorSearch() {

  searchLocations();
  
/*
  try {

    var addr = document.getElementById('txtAddress').value;  
    var city = document.getElementById('txtCity').value;
    var state = GetSelectValue(document.getElementById('cboState'));
    var zip = document.getElementById('txtZipCode').value;
    var distance = document.getElementById('txtRadius').value;
  
    if (zip != '') {
      strResponse = xmlHTTPCall('../Includes/ajaxFunctions.aspx?type=storelocatorsearch&addr=&city=&state=&zip=' + zip + '&distance=' + distance, false, false, false);
      var aryResponse = strResponse.split('|',20);

      if ( aryResponse[0] == 'true' ) {
        document.getElementById('totalStores').innerHTML = aryResponse[1].toString();
        document.getElementById('divResults').innerHTML = aryResponse[2].toString();
        document.getElementById('searchResults').style.display ='';
      }
      else {

        showPopWin('','<DIV id="modalContent" style="margin-top:25px;"><TABLE align="center" border="0" cellpadding="0" cellspacing="0" width="200px"><TR><TD id="loadingMsg"align="center"><span style="font-size:10pt;font-weight:bold;">Unable to find Zip Code.</span></TD></TR></TABLE></DIV>',250,100,null);    

      }
      
    }
    else {
    
      // Geocode address using Google
    
    }
  
  }
  catch (e) { }

*/  
  return false;

}


function processCheckout(strMethod, blnPopup){

  var strOpts = '';
  var blnAsync = false;
  
  procType = 'checkout';

  try {
    switch (strMethod){
      case 'CC' :
        strOpts = '&CCTYPE=' + document.getElementById('ccType').selectedIndex;
        strOpts = strOpts + '&CCNUM=' + document.getElementById('ccNumber').value;
        var strDate = GetSelectValue(document.getElementById('ccExpMonth')) + GetSelectValue(document.getElementById('ccExpYear'));
        strOpts = strOpts + '&EXPDATE=' + strDate;
        strOpts = strOpts + '&AMOUNT=' + stripCharsNotInBag(document.getElementById('cartTotal').innerHTML,'0123456789.');
        strOpts = strOpts + '&CVV2=' + document.getElementById('ccId').value;

        break;


      case 'CHK' :
      /*
        strOpts = '';
        ind = document.getElementById('x_bank_acct_type').selectedIndex;
        strOpts = '&ACCTTYPE=' + document.getElementById('x_bank_acct_type').options[ind].text;
        strOpts = strOpts + '&ABA=' + document.getElementById('x_bank_aba_code').value;
        strOpts = strOpts + '&ACCTNUM=' + document.getElementById('x_bank_acct_num').value;
        strOpts = strOpts + '&BANKNAME=' + document.getElementById('x_bank_name').value;
        strOpts = strOpts + '&ACCTNAME=' + document.getElementById('x_bank_acct_name').value;
        strOpts = strOpts + '&AMOUNT=' + document.getElementById('x_amount_1').value;

        */  
        break;

      case 'PO':
        //No Processing required
        break;
        
      default :
        hidePopWin(false);
        return false;

    }

    strOpts = strOpts + '&CUSTID=' + customerNumber; //document.getElementById('customerID').value;
    strOpts = strOpts + '&COMPANY=' + document.getElementById('billingCompany').value;
    strOpts = strOpts + '&FNAME=' + document.getElementById('billingFirstName').value;
    strOpts = strOpts + '&LNAME=' + document.getElementById('billingLastName').value;
    strOpts = strOpts + '&ADDR=' + document.getElementById('billingAddress1').value;
    strOpts = strOpts + '&CITY=' + document.getElementById('billingCity').value;
    strOpts = strOpts + '&STATE=' + GetSelectValue(document.getElementById('cboBillingState'));
    strOpts = strOpts + '&ZIP=' + document.getElementById('billingZip').value;
    strOpts = strOpts + '&PHONE=' + document.getElementById('billingPhone').value;
    strOpts = strOpts + '&FAX=';
    strOpts = strOpts + '&EMAIL=' + document.getElementById('billingEmail').value;
    strOpts = strOpts + '&ORDER=' + cart; //document.getElementById('cartID').value;


    strOpts = '&AUTHTYPE=' + strMethod + strOpts;

    if ( strMethod != 'PO' ) {
      document.body.style.cursor='wait';
      // Now Send the Data
      var loc = document.URL.toString().toLowerCase();
      loc = loc.substring(0,loc.indexOf('customerscripts'));
      strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=payauth' + strOpts, blnAsync, false, false);
    }
    else {
      strResponse = 'true|PO|none|';  
    }
    
    if ( !blnAsync ) {
      processAuthReturn(strResponse, true);
      procType = '';
      blnDisabled = false;
    }

  }
  catch (e) {
    hidePopWin(false);
  }
  
  document.body.style.cursor='default';
  
  return true;
}

function processAuthReturn(strResults, blnPopUp){

  var aryResponse = strResults.split('|',20);
  //var cart = document.getElementById('cartID').value;
  var strOrder = '';
  var strTest = '';

  try {
    if ( aryResponse[0].toString().toLowerCase() != 'true' ){
      if ( blnPopUp ) {
        hidePopWin(false);
      }
      
      showPopWin('../Includes/ajaxFunctions.aspx?type=orderproblem', '', 520, 350, null);

    }
    else{
      strOrder = createOrder(cart, Trim(aryResponse[1]), Trim(aryResponse[2]), true);

    }

  }
  catch (e) {
    //TODO
    hidePopWin(false);
  }
  
  document.body.style.cursor='default';
  return true;
  
}

function itemNavigate(item) {
  
  if (item.toLowerCase()=='giftwrap') return;

  try {
      parent.window.hs.close();
  }
  catch (e) {
    try {
      parent.window.hs.close(parent.window.document.getElementById('cartLink'));
    }
    catch (e) { }
  }

  var opts = '../Includes/ajaxFunctions.aspx?type=itemdetail&item=' + item + '&display=highslide';
  parent.window.displayInline('itemdetail',opts);
  
}

function addGiftWrap() {
  
  addToCart('giftwrap',0,1);
  displayInline('giftwrap','../CustomerScripts/page.aspx?page=giftWrap');
  
  return true;
}

function updateCartNotes() {

  var notes = document.getElementById('txtGiftMessage').value;

  if (notes!='') {
    strResponse = xmlHTTPCall('../Includes/ajaxFunctions.aspx?type=updatenotes&notes='+notes, false,false,false);
    parent.window.hs.close();
    parent.window.displayInlineCart();
  }
  return true;
}

function redirectHome(returnVal){

  var loc = 'http://' + GetDomain();
  location.replace(loc+'/CustomerScripts/page.aspx?page=index');
  
}

function showCheckoutMessage(strMethod, modWin){

  var fastCheckout = 0;

  try {
    if (modWin+'' != 'undefined' && modWin != null && modWin != '' ){
      showPopWin('', modWin, 250, 110, null);
    }
    
    if (fastCheckout==1 || fastCheckout==true) {
      var cart = document.getElementById('cartID').value;
      setTimeout("createOrder(" + cart.toString() + ", '', '', true);",300);
    }
    else
      var timer = setTimeout("processCheckout('"+strMethod+"',true);",300);
    //processCheckout(strMethod,true);
  }
  catch (e) {
  
  }
  

}

function processCheckout(strMethod, blnPopup){

  var strOpts = '';
  var blnAsync = false;
  
  procType = 'checkout';

  try {

    switch (strMethod)
    {
      case 'CC' :
        strOpts = '&CCTYPE=' + document.getElementById('ccType').selectedIndex;
        strOpts = strOpts + '&CCNUM=' + document.getElementById('ccNumber').value;
        var strDate = GetSelectValue(document.getElementById('ccExpMonth')) + GetSelectValue(document.getElementById('ccExpYear'));
        strOpts = strOpts + '&EXPDATE=' + strDate;
        strOpts = strOpts + '&AMOUNT=' + stripCharsNotInBag(Trim(document.getElementById('cartTotal').innerHTML),'0123456789.');
        strOpts = strOpts + '&CVV2=' + document.getElementById('ccId').value;

        break;


      case 'CHK' :
      /*
        strOpts = '';
        ind = document.getElementById('x_bank_acct_type').selectedIndex;
        strOpts = '&ACCTTYPE=' + document.getElementById('x_bank_acct_type').options[ind].text;
        strOpts = strOpts + '&ABA=' + document.getElementById('x_bank_aba_code').value;
        strOpts = strOpts + '&ACCTNUM=' + document.getElementById('x_bank_acct_num').value;
        strOpts = strOpts + '&BANKNAME=' + document.getElementById('x_bank_name').value;
        strOpts = strOpts + '&ACCTNAME=' + document.getElementById('x_bank_acct_name').value;
        strOpts = strOpts + '&AMOUNT=' + document.getElementById('x_amount_1').value;

        */  
        break;

      case 'PO':
        //No Processing required
        break;
        
      default :
        hidePopWin(false);
        return false;

    };


    strOpts = strOpts + '&CUSTID=' + customerNumber ;
    strOpts = strOpts + '&COMPANY=' + document.getElementById('billingCompany').value;
    strOpts = strOpts + '&FNAME=' + document.getElementById('billingFirstName').value;
    strOpts = strOpts + '&LNAME=' + document.getElementById('billingLastName').value;
    strOpts = strOpts + '&ADDR=' + document.getElementById('billingAddress1').value;
    strOpts = strOpts + '&CITY=' + document.getElementById('billingCity').value;
    strOpts = strOpts + '&STATE=' + GetSelectValue(document.getElementById('cboBillingState'));
    strOpts = strOpts + '&ZIP=' + document.getElementById('billingZip').value;
    strOpts = strOpts + '&PHONE=' + document.getElementById('billingPhone').value;
    strOpts = strOpts + '&FAX=';
    strOpts = strOpts + '&EMAIL=' + document.getElementById('billingEmail').value;
    strOpts = strOpts + '&ORDER=' + cart;


    strOpts = '&AUTHTYPE=' + strMethod + strOpts;

    if ( strMethod != 'PO' ) {
      document.body.style.cursor='wait';

      // Now Send the Data
      var loc = document.URL.toString().toLowerCase();
      loc = loc.substring(0,loc.indexOf('customerscripts'));
      strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=payauth' + strOpts, blnAsync, false, false);
    }
    else {
      strResponse = 'true|PO|none|';  
    }
    
    if ( !blnAsync ) {
      processAuthReturn(strResponse, true);
      procType = '';
      blnDisabled = false;
    }

  }
  catch (e) {
  //alert('processCheckout ' +e.message);
    hidePopWin(false);
  }
  
  document.body.style.cursor='default';
  
  return true;
}

function processAuthReturn(strResults, blnPopUp){

  var aryResponse = strResults.split('|',20);
  var strOrder = '';
  var strTest = '';

  try {

    if ( aryResponse[0].toString().toLowerCase() != 'true' ){
      if ( blnPopUp ) {
        hidePopWin(false);
      }
      
      showPopWin('../Includes/ajaxFunctions.aspx?type=orderproblem', '', 520, 350, null);

    }
    else{

      strOrder = createOrder(cart, Trim(aryResponse[2]), Trim(aryResponse[3]), true);

    }

  }
  catch (e) {
    hidePopWin(false);
  }
  
  document.body.style.cursor='default';
  return true;
  
}

function createOrder(cart, auth, ccref, blnPopUp){

  var strOpts = '';
  var strLocal = '';
  var shipToNumber = '';

  try {
    strOpts = strOpts + '&CART=' + eLinkUrl.encode(cart);
    strOpts = strOpts + '&BEML=' + eLinkUrl.encode(document.getElementById('billingEmail').value);
    strOpts = strOpts + '&BPH=' + eLinkUrl.encode(document.getElementById('billingPhone').value);
    strOpts = strOpts + '&BC=' + eLinkUrl.encode(document.getElementById('billingCompany').value)
    strOpts = strOpts + '&BNF=' + eLinkUrl.encode(document.getElementById('billingFirstName').value);
    strOpts = strOpts + '&BNL=' + eLinkUrl.encode(document.getElementById('billingLastName').value);
    strOpts = strOpts + '&BNI=' + eLinkUrl.encode(document.getElementById('billingInitial').value);
    strOpts = strOpts + '&BNG='
    strOpts = strOpts + '&BAD1=' + eLinkUrl.encode(document.getElementById('billingAddress1').value);
    strOpts = strOpts + '&BAD2=' + eLinkUrl.encode(document.getElementById('billingAddress2').value);
    strOpts = strOpts + '&BCTY=' + eLinkUrl.encode(document.getElementById('billingCity').value);
    strOpts = strOpts + '&BST=' + GetSelectValue(document.getElementById('cboBillingState'));
    strOpts = strOpts + '&BZIP=' + eLinkUrl.encode(document.getElementById('billingZip').value);
    try {
      shipToNumber = GetSelectValue(document.getElementById('shipToCBO'));
    }
    catch (e) {
      try {
        shipToNumber = document.getElementById('shipTo').value;
      }
      catch (e) {
        shipToNumber = '';
      }
    }
    if (shipToNumber==null) shipToNumber = '';
    strOpts = strOpts + '&ST=' + eLinkUrl.encode(shipToNumber);
    strOpts = strOpts + '&STN=' + eLinkUrl.encode(document.getElementById('shipToName').value);
    strOpts = strOpts + '&STAD1=' + eLinkUrl.encode(document.getElementById('shipToAddress1').value);
    strOpts = strOpts + '&STAD2=' + eLinkUrl.encode(document.getElementById('shipToAddress2').value);
    strOpts = strOpts + '&STCTY=' + eLinkUrl.encode(document.getElementById('shipToCity').value);
    strOpts = strOpts + '&STST=' + GetSelectValue(document.getElementById('cboShipToState'));
    strOpts = strOpts + '&STZIP=' + eLinkUrl.encode(document.getElementById('shipToZipCode').value);
    strOpts = strOpts + '&STPH=' + eLinkUrl.encode(document.getElementById('shipToPhone').value);
    strOpts = strOpts + '&STFAX='
    strOpts = strOpts + '&STEML=' + eLinkUrl.encode(document.getElementById('billingEmail').value);
    strOpts = strOpts + '&REQDT='
    strOpts = strOpts + '&CNDT='
    
    var shipVia = '';
    try {
      shipVia = document.getElementById('shipper'+GetRadioValue(getElementsByName('input','shipper'))).innerHTML;
    }
    catch (e) { }
    strOpts = strOpts + '&SHVIA=' + eLinkUrl.encode(shipVia);
    strOpts = strOpts + '&SHNT='
    strOpts = strOpts + '&PO=' + eLinkUrl.encode(document.getElementById('PONumber').value);
    strOpts = strOpts + '&FRT=' + document.getElementById('cartShipping').innerHTML;
    strOpts = strOpts + '&TX=' + stripCharsNotInBag(document.getElementById('cartTax').innerHTML,'0123456789.');
    strOpts = strOpts + '&HND=' + stripCharsNotInBag(document.getElementById('cartHandling').innerHTML,'0123456789.');
    strOpts = strOpts + '&CCNUM=' + document.getElementById('ccNumber').value;
    var strDate = "";
    try {
      strDate = GetSelectValue(document.getElementById('ccExpMonth')) + '/01/' + GetSelectValue(document.getElementById('ccExpYear'));
    }
    catch (e) { }
    strOpts = strOpts + '&EXPDATE=' + strDate;
    strOpts = strOpts + '&AMOUNT=' + stripCharsNotInBag(Trim(document.getElementById('cartTotal').innerHTML),'0123456789.');
    strOpts = strOpts + '&CVV2=' + Url.encode(document.getElementById('ccId').value);
    strOpts = strOpts + '&ATH=' + auth;
    strOpts = strOpts + '&REF=' + ccref;
    strOpts = strOpts + '&ABA='; // + document.getElementById('x_bank_aba_code').value;
    strOpts = strOpts + '&ACCTNUM='; // + document.getElementById('x_bank_acct_num').value;
    strOpts = strOpts + '&BANKNAME='; // + document.getElementById('x_bank_name').value;
    strOpts = strOpts + '&ACCTNAME='; // + document.getElementById('x_bank_acct_name').value;
    strOpts = strOpts + '&CCTYPE=' + document.getElementById('ccType').selectedIndex;
    strOpts = strOpts + '&PONAME=' + Url.encode(document.getElementById('POName').value);
    strOpts = strOpts + '&STC=' + Url.encode(document.getElementById('shipToFirstName').value + ' ' + document.getElementById('shipToLastName').value);
    var shipComplete = '1';
    try {
      if (document.getElementById('chkShipComplete').checked)
        shipComplete = '0';
    }
    catch (e) { }
    strOpts = strOpts + '&SCO=' + shipComplete;
    strOpts = strOpts + '&SHType=' + Url.encode(selectedShipRate);
    if (document.getElementById('ccNumber').value != "")
      strOpts = strOpts + '&Method=CC';
    else
      strOpts = strOpts + '&Method=PO';

    var loc = document.URL.toString().toLowerCase();
    loc = loc.substring(0,loc.indexOf('customerscripts'));
    strResponse = xmlHTTPCall(loc + 'Includes/ajaxFunctions.aspx?type=createorder' + strOpts, false, false, false);
    document.body.style.cursor='default';

    if ( blnPopUp )
      hidePopWin(false);

    var aryResponse = strResponse.split('|',20);
    if ( aryResponse[0].toString().toLowerCase() != 'true' ){
      showPopWin('../Includes/ajaxFunctions.aspx?type=orderproblem', '', 520, 350, null);
    }
    else{
      var orderDoc = '';
      if (aryResponse[2].indexOf('\\')!=-1)
        orderDoc = loc + 'Temp/' + GetFileName(aryResponse[2]);
      else
        orderDoc = aryResponse[2];

      if (orderDoc!='' && orderDoc.toLowerCase().indexOf('error')==-1)
        showPopWin(loc + 'Temp/' + GetFileName(aryResponse[2]), '', 650, 450, redirectHome);
      else
        setTimeout('redirectHome()',200);
    }
  
  }
  catch (e) {
    //TODO
    hidePopWin(false);
  }

  document.body.style.cursor='default';

  return true;

}

function displayOrder(order) {

  try {
    if ( !IsBlank(order))
    {

      /* Do not let them off the PopUp Window */
      strResponse = xmlHTTPCall('../Includes/ajaxFunctions.aspx?type=displayorder&order=' + order, false, false, false);

      var aryResponse = strResponse.split('|',20);

      if ( aryResponse[0].toString().toLowerCase() == 'true' ) {
        showPopWin(aryResponse[1],'', 700, 450, releaseCursor);
      }

    }

  }
  catch (e) {
    //TODO
  }
  
  document.body.style.cursor='default';
  blnDisabled = false;
  
  return false;
  
}

function salesTax(order) {

  var strResponse = '';
  var strOpts = '';
  var shipToNumber = '';

  try {
  
    if ( order != '' && order != null ) {
      strOpts = '&o=' + order;
      try {
        shipToNumber = GetSelectValue(document.getElementById('shipToCBO'));
      }
      catch (e) {
        try {
          shipToNumber = document.getElementById('shipToName').value;
        }
        catch (e) {
          shipToNumber = '';
        }
      }
      strOpts = strOpts + '&ST=' + shipToNumber;
      strOpts = strOpts + '&STN=' + document.getElementById('shipToFirstName').value + ' ' + document.getElementById('shipToLastName').value;
      strOpts = strOpts + '&STAD1=' + document.getElementById('shipToAddress1').value;
      strOpts = strOpts + '&STAD2=' + document.getElementById('shipToAddress2').value;
      strOpts = strOpts + '&STCTY=' + document.getElementById('shipToCity').value;
      strOpts = strOpts + '&STST=' + GetSelectValue(document.getElementById('cboShipToState'));
      strOpts = strOpts + '&STZIP=' + document.getElementById('shipToZipCode').value;
      try {
        strOpts = strOpts + '&FRT=' + document.getElementById('cartShipping').innerHTML;
      }
      catch (e) {
        strOpts = strOpts + '&FRT=0';
      }
      strOpts = strOpts + '&FNAME=' + document.getElementById('billingFirstName').value;
      strOpts = strOpts + '&LNAME=' + document.getElementById('billingLastName').value;
      strOpts = strOpts + '&ADDR=' + document.getElementById('billingAddress1').value;
      strOpts = strOpts + '&CITY=' + document.getElementById('billingCity').value;
      strOpts = strOpts + '&STATE=' + GetSelectValue(document.getElementById('cboBillingState'));
      strOpts = strOpts + '&ZIP=' + document.getElementById('billingZip').value;
      
      var loc = document.URL.toString().toLowerCase();
      var subLoc = loc.substring(0,loc.indexOf('customerscripts'));
      strResponse = xmlHTTPCall(subLoc + 'Includes/ajaxFunctions.aspx?type=salestax' + strOpts, false,false,false);

      var aryResponse = strResponse.split('|',20);

      if ( aryResponse[0] == 'true' ) {
        document.getElementById('cartTax').innerHTML = aryResponse[1];
        updateTotals();
      }
    }
  }
  catch(e) {
    // No Errors
  }
}

function updateTotals(){

  var dblTotal = 0;
  var dblHandling = 0;
  var dblTax = 0;
  var dblTemp = 0;
  var dblShipping = 0;
  var review = 0;

  try { 

    dblTotal = stripCharsNotInBag(document.getElementById('orderSubTotal').innerHTML,'0123456789.');
    dblHandling = stripCharsNotInBag(document.getElementById('cartHandling').innerHTML,'0123456789.');
    dblTax = stripCharsNotInBag(document.getElementById('cartTax').innerHTML,'0123456789.');

    dblHandling = 0;
    dblShipping = stripCharsNotInBag(document.getElementById('cartShipping').innerHTML,'0123456789.');  

    dblTotal = dblTotal * 1; // Convert to a number
    dblTax = dblTax * 1;
    dblShipping = dblShipping * 1; // Convert back to a number
    dblHandling = dblHandling * 1; // Convert back to a number

    dblTotal = dblTotal + dblShipping + dblHandling + dblTax;
    if ( review == 1) {
      dblShipping = dblShipping + dblHandling;
    }
    document.getElementById('cartTotal').innerHTML = formatDollar(dblTotal,true);

  }
  catch (e) { }
  
}

