/// <reference path="D:/SiteData/scripts/safemart.js"/>

Array.prototype.find = function(search){
 var i = 0;
 while (this[i] != search && i<this.length){
	++ i;
 }

 if (i==this.length){
	i= -1;
 }
 return (i);
}
if (typeof(Array.prototype.findAt) == "undefined")
{
    Array.prototype.findAt = function(needle, p_nStartLoc, p_cMatch, p_cExclusions){
     if (typeof(p_cMatch) == 'undefined') p_cMatch = 'exact';
     if (typeof(p_cExclusions) == 'undefined') p_cExclusions = '';

	    if (p_cExclusions.length > 0)
	    {
		    //	p_cExclusions = a string containing chars to remove from the search_string
		    //		before performing the compare. For example, to remove all instances
		    //		of "a', "b", and "c" p_cExclusions would equal "abc".
    		
		    var regExp = eval('/['+p_cExclusions+']/g');
	    }
	    else
	    {
		    var regExp = null;
	    }
    	
     var i = p_nStartLoc;

     if (p_cMatch == 'exact'){
	    for (i=p_nStartLoc; i<this.length; i++)
	    {
		    var l_cSearch = this[i];
    		
		    if (regExp != null)
		    {
			    //alert(l_cSearch);
			    l_cSearch = l_cSearch.replace(regExp,"");
			    //alert(l_cSearch);
		    }
    		
		    if (l_cSearch != null)
		    {
			    if (l_cSearch == needle) break;
		    }
	    }
     }
     else if (p_cMatch == 'contains'){
	    for (i=0; i<this.length; i++){
		    if (this[i] != null){
			    var v_numtostr = this[i].toString()
			    if (v_numtostr.indexOf(needle) != -1) break;
		    }
	    }
     }
     else if (p_cMatch == 'containswhole'){
	    for (i=0; i<this.length; i++){
		    if (this[i] != null){
			    var v_numtostr = this[i].toString()
			    if (parseInt(needle) == parseInt(this[i])) break;
		    }
	    }
     }

     else if (p_cMatch == 'containsround'){
	    for (i=0; i<this.length; i++){
		    if (this[i] != null){
			    var v_numtostr = this[i].toString()
			    if (Math.round(parseFloat(needle)) == Math.round(parseFloat(this[i]))) break;
		    }
	    }
     }

     if (i==this.length){
	    i= -1;
     }
     return (i);
    }
}


// base checkout object "Class"
Checkout = new Object();

// Customer Object
Checkout.Customer = new Safemart.Person();
Checkout.Customer.ChampionStatus = ""; /// Extended from Base Class
Checkout.Customer.Ship.State = "";/// Set a default value
Checkout.Customer.Ship.StateDomestic = "";/// Extended from Base Class
Checkout.Customer.Ship.StateCanada = "";/// Extended from Base Class
Checkout.Customer.Ship.StateInternational = "";/// Extended from Base Class
Checkout.Customer.Ship.Country = "";/// Set a default value
Checkout.Customer.Ship.CountryInternational = ""; /// Extended from Base Class
Checkout.Customer.Bill.State = "";/// Set a default value
Checkout.Customer.Bill.StateDomestic = "";/// Extended from Base Class
Checkout.Customer.Bill.StateCanada = "";/// Extended from Base Class
Checkout.Customer.Bill.StateInternational = "";/// Extended from Base Class
Checkout.Customer.Bill.Country = "";/// Set a default value
Checkout.Customer.Bill.CountryInternational = ""; /// Extended from Base Class

Checkout.ShowSidebar = true;
/*
Checkout.Customer.Ship.State = "AL"; /// Set a default value
Checkout.Customer.Ship.StateDomestic = "AL"; /// Extended from Base Class
Checkout.Customer.Ship.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Ship.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Ship.Country = "US"; /// Set a default value
Checkout.Customer.Ship.CountryInternational = "US"; /// Extended from Base Class
Checkout.Customer.Bill.State = "AL"; /// Set a default value
Checkout.Customer.Bill.StateDomestic = "AL"; /// Extended from Base Class
Checkout.Customer.Bill.StateCanada = ""; /// Extended from Base Class
Checkout.Customer.Bill.StateInternational = ""; /// Extended from Base Class
Checkout.Customer.Bill.Country = "US"; /// Set a default value
Checkout.Customer.Bill.CountryInternational = "US"; /// Extended from Base Class
*/

Safemart.FetchBackBase = function()
{
    var _Enabled = false;
    var _Url = "https://pixel.fetchback.com/serve/fb/pdc?cat=&name=landing&sid=1347";
    var _Frame = "uiFetchbackPixel"

    this.Abandon = function(productList)
    {
        if (_Enabled)
        {
            var Pixel = document.getElementById(_Frame);
            if (Pixel != null)
            {
                Pixel.src = _Url + "&abandon_products=" + productList;
            }
        }
    }

    this.Purchase = function(productList)
    {
        if (_Enabled)
        {
            var Pixel = document.getElementById(_Frame);
            if (Pixel != null)
            {
                Pixel.src = _Url + "&purchase_products=" + productList;
            }
        }
    }
}

Checkout.FetchBack = new Safemart.FetchBackBase();
Checkout.FetchBack.FetchBackPurchaseList = "";

Safemart.PayPalBase = function()
{
    var _Enabled = true;
    var _GetDetailReturnHandler;
    var _PlaceOrderReturnHandel;
    var _ErrorResponse = "";
    var _ValidShipping = "true";
    var _ShippingAddress = "";
    var _ShipTotal = 0;


    this.Enabled = function()
    {
        return _Enabled;
    }

    this.DoCheckout = function()
    {
        _Notification("checkout");
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
        wsi._Soap.AddCall("PayPalCheckout", _DoCheckoutCallback, aParameters);

    }

    var _Notification = function(whichOverlay)
    {

        if (document.getElementById("PayPalPanel") == null)
        {
            var PayPalPanel = document.createElement("div");
            document.body.appendChild(PayPalPanel);
            PayPalPanel.setAttribute('id', "PayPalPanel");
            PayPalPanel.setAttribute('visibility', 'hidden');
            PayPalPanel.setAttribute('style', 'background-color:white');

            //<div class="hd" id="eBillCaption" ></div>
            YAHOO.example.container.PayPalPanel = new YAHOO.widget.Panel("PayPalPanel",
			     { fixedcenter: true,
			         visible: false,
			         width: "400px",
			         height: "150px",
			         zIndex: 1000,
			         close: false,
			         modal: true,
			         effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: .5 }
			     });
            YAHOO.example.container.PayPalPanel.render();
        }

        var PayPalDiv = document.getElementById("PayPalPanel")
        switch (whichOverlay)
        {
            case "checkout":
                PayPalDiv.innerHTML = "<div class='bd' style='background-color:white;'><br /><br /><center>Preparing your cart for PayPal.<br /><img src='/img/images/progress.gif' alt='' style='padding-top:10px;'></center><br /><br /></div>";
                break;

            case "placeorder":
                PayPalDiv.innerHTML = "<div class='bd' style='background-color:white;'><br /><br /><center>Submitting order.<br /><img src='/img/images/progress.gif' alt='' style='padding-top:10px;'></center><br /><br /></div>";
                break;
        }
        YAHOO.example.container.PayPalPanel.show();
    }

    var _HideNotification = function()
    {
        YAHOO.example.container.PayPalPanel.hide();
    }
    var _DoCheckoutCallback = function(returnValue)
    {
        if (returnValue.indexOf("Error") > -1)
        {
            _HideNotification();
            returnValue = returnValue.replace("Error: ", "");
            alert(returnValue);
        }
        else
        {
            document.location.href = returnValue;
        }

    }

    this.GetDetails = function(returnHandler)
    {
        _GetDetailReturnHandler = returnHandler;
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
        wsi._Soap.AddCall("PayPalGetDetails", _GetDetailCallback, aParameters);
    }

    var _GetDetailCallback = function(returnValue)
    {


        var isSuccessful = true;
        if (returnValue.indexOf("Error") > -1)
        {
            _ErrorResponse = returnValue.replace("Error: ", "");
            isSuccessful = false;
        }
        else
        {
            //_PreAuthReturn = getDomAdapter().parseXml(returnValue);
            if ('undefined' != typeof ActiveXObject)
            {
                // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                _ShippingAddress = new ActiveXObject("Microsoft.XMLDOM");
                _ShippingAddress.loadXML(returnValue);

            }
            else
            {
                _ShippingAddress = getDomAdapter().parseXml(returnValue);
            }
            _ValidShipping = _ShippingAddress.getElementsByTagName("validshipping")[0].firstChild.nodeValue;
            _ShipTotal = _ShippingAddress.getElementsByTagName("shiptotal")[0].firstChild.nodeValue;

        }

        _GetDetailReturnHandler(isSuccessful);
    }

    this.ValidShipping = function()
    {
        return _ValidShipping;
    }

    this.ShipTotal = function()
    {
        return _ShipTotal;
    }

    this.Address1 = function()
    {
        return _ShippingAddress.getElementsByTagName("address1")[0].firstChild.nodeValue;
    }

    this.Address2 = function()
    {
        if (_ShippingAddress.getElementsByTagName("address2")[0].firstChild == null)
        {
            return "";
        }
        else
        {
            return _ShippingAddress.getElementsByTagName("address2")[0].firstChild.nodeValue;
        }
    }

    this.City = function()
    {
        return _ShippingAddress.getElementsByTagName("city")[0].firstChild.nodeValue;
    }

    this.State = function()
    {
        return _ShippingAddress.getElementsByTagName("state")[0].firstChild.nodeValue;
    }

    this.Zip = function()
    {
        return _ShippingAddress.getElementsByTagName("zip")[0].firstChild.nodeValue;
    }

    this.Country = function()
    {
        return _ShippingAddress.getElementsByTagName("country")[0].firstChild.nodeValue;
    }

    this.PlaceOrder = function(returnHandler, shipId, shipAmount, tax, orderTotal)
    {
        _Notification("placeorder");
        _PlaceOrderReturnHandel = returnHandler;
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
        aParameters.Add("shipId", shipId);
        aParameters.Add("shipTotal", shipAmount);
        aParameters.Add("tax", tax);
        aParameters.Add("cartTotal", orderTotal);

        wsi._Soap.AddCall("PayPalMakePayment", _PlaceOrderCallback, aParameters);
    }

    var _PlaceOrderCallback = function(returnValue)
    {
        _HideNotification();
        /*
        var isSuccessful = true;
        if (returnValue.indexOf("ERROR") > -1)
        {
        _ErrorResponse = returnValue.replace("ERROR:", "");
        isSuccessful = false;
        }
        */
        _PlaceOrderReturnHandel(returnValue);
    }

    this.ErrorResponse = function()
    {
        return _ErrorResponse;
    }
}

Checkout.PayPal = new Safemart.PayPalBase();
Checkout.PayPalOrder = false;

/// Extend the base class to handle PayPal orders with the cart.
Checkout.PayPal.OrderConfirmed = function()
{
    if (Checkout.PayPal.ValidShipping().toLowerCase() == "false")
    {
        Checkout.PayPal.PlaceOrder(Checkout.PayPal.PlaceOrderReturn, Checkout.Customer.Ship.Type, Checkout.Customer.Ship.Cost, Checkout.Cart.Tax, Checkout.Cart.Total);
    }
    else
    {
        Checkout.PayPal.PlaceOrder(Checkout.PayPal.PlaceOrderReturn, "", Checkout.Customer.Ship.Cost, Checkout.Cart.Tax, Checkout.Cart.Total);
    }
}

Checkout.PayPal.PlaceOrderReturn = function(returnValue)
{
    /// go to the thank you page
    
    Checkout.PlaceOrderReturnValue = returnValue;
    Checkout.PlaceOrderReturn2()
}

/// Create eBillMe Constructor
Safemart.eBillme = function()
{
     var _Enabled = true;
     var _PreAuthReturn = "";
     var _Preauthrefid = "";
     var _Acceptancepageurl = "";
     var _Authstatus = "";
     var _ConfirmationPageUrl = "";
     var _OrderNumber = "";
     var _AccountNumber = "";
     
     this.Enabled = function()
     {
        return _Enabled;
     }
     
     this.Enable = function(enable)
     {
        _Enabled = enable;
     }

    this.GetConfirmationPageUrl = function()
    {
        return _ConfirmationPageUrl;
    }
    
    this.GetAccountNumber = function()
    {
        return _AccountNumber;
    }
    
    this.GetOrderNumber = function()
    {
        return _OrderNumber;
    }
    
    var _DisplayTerms = function()
    {
//alert("display Terms\r" + _Preauthrefid + "\r" + _Acceptancepageurl + "\r" + _Authstatus);
     
        if (document.getElementById("eBillmePanel") == null)
        {
            var eBillmePanel = document.createElement("div");
            document.body.appendChild(eBillmePanel);
		    eBillmePanel.setAttribute('id', "eBillmePanel");
		    eBillmePanel.setAttribute('visibility', 'hidden');
    		
		    //<div class="hd" id="eBillCaption" ></div>
		    YAHOO.example.container.eBillmePanel = new YAHOO.widget.Panel("eBillmePanel",
			     { fixedcenter:true,
				    visible:false,
				    width:"820px",
				    height:"620px",
				    zIndex:1000,
				    close: false,
				    modal: true, 
				    effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:.5} } );
            YAHOO.example.container.eBillmePanel.render();
        }
        
        var eBillDiv = document.getElementById("eBillmePanel")
        eBillDiv.innerHTML = '<div class="bd" style="background-color:white;"><iframe id="acceptance" src="'+_Acceptancepageurl+'&next=https://www.safemart.com/checkout/ebillmenext.htm&back=https://www.safemart.com/checkout/ebillmeback.htm&merchant=safemart" width="800px" height="600px" frameborder="0" ></iframe></div>';
        YAHOO.example.container.eBillmePanel.show();
    
    }

    var _CloseTerms = function()
    {
        YAHOO.example.container.eBillmePanel.hide();
    }
    this.CloseTerms = function()
    {
        _CloseTerms();
    }
    
    this.PreAuthorizeReturn = function(returnValue)
    {  
        
        //_PreAuthReturn = getDomAdapter().parseXml(returnValue);
        if ('undefined' != typeof ActiveXObject)
        {
           // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            _PreAuthReturn = new ActiveXObject("Microsoft.XMLDOM");
            _PreAuthReturn.loadXML(returnValue);
            
        }
        else
        {
            _PreAuthReturn = getDomAdapter().parseXml(returnValue);
        }
//alert(_PreAuthReturn.xml);
//alert(_PreAuthReturn.getElementsByTagName("preauthrefid")[0].firstChild.nodeValue);
//alert(_PreAuthReturn.getElementsByTagName("acceptancepageurl")[0].firstChild.nodeValue);
//alert(_PreAuthReturn.getElementsByTagName("authstatus")[0].firstChild.nodeValue);
        
        /*
        _Preauthrefid = _PreAuthReturn.childNodes[0].childNodes[0].firstChild.nodeValue;
        _Acceptancepageurl = _PreAuthReturn.childNodes[0].childNodes[1].firstChild.nodeValue;
        _Authstatus = _PreAuthReturn.childNodes[0].childNodes[2].childNodes[0].firstChild.nodeValue;
        */
        _Preauthrefid = _PreAuthReturn.getElementsByTagName("preauthrefid")[0].firstChild.nodeValue;
        _Acceptancepageurl = _PreAuthReturn.getElementsByTagName("acceptancepageurl")[0].firstChild.nodeValue
        _Authstatus = _PreAuthReturn.getElementsByTagName("authstatus")[0].firstChild.nodeValue;
//alert("preauthorder() return authorization status: " + _Authstatus + "\r\n\r\npreauthorder() response:\r\n" + returnValue);                
        if (_Authstatus == "WAIT")
        {
            _DisplayTerms();
        }
        else
        {
            alert("Sorry, you have not been approved to use the eBillme option. Please select another payment option");
        }
    }
    
    this.Authorize = function(returnHandler)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("preauthrefid", _Preauthrefid);

        wsi._Soap.AddCall("Authorize_eBillme", returnHandler, aParameters);  

    }
    
    this.AuthorizeReturn = function(returnValue)
    {
        //var AuthReturn = getDomAdapter().parseXml(returnValue);
        
        
        if ('undefined' != typeof ActiveXObject)
        {
           // _XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            var AuthReturn = new ActiveXObject("Microsoft.XMLDOM");
            AuthReturn.loadXML(returnValue);
            
        }
        else
        {
            var AuthReturn = getDomAdapter().parseXml(returnValue);
        }
        
        _ConfirmationPageUrl = AuthReturn.getElementsByTagName("confirmationpageurl")[0].firstChild.nodeValue;
        _OrderNumber = AuthReturn.getElementsByTagName("ordernumber")[0].firstChild.nodeValue;
        _AccountNumber = AuthReturn.getElementsByTagName("accountnumber")[0].firstChild.nodeValue;
        
        _CloseTerms();
//alert(returnValue);
        Checkout.PlaceOrder();
    }

}


Checkout.eBillme = new Safemart.eBillme();


/// Create Cart Object
Checkout.Cart = new Object();
Checkout.Cart.Name = "";
Checkout.Cart.EmptyText = "Your Cart is currently empty.";
Checkout.Cart.IsEmpty = true;
Checkout.Cart.Weight = 0;
Checkout.Cart.NoFreeShipWeight = 0;
Checkout.Cart.FlatRateShip = 0;
Checkout.Cart.NoShipping = 1;
/// Default is 1 - most items will ship in one package.
/// Items that do not qualify for free shipping usually:
///  - weight more
///  - Ship seperatly
/// Therefore, the PieceCount will be incremented for
/// each item that does not qualify for free shipping.
Checkout.Cart.PieceCount = 0;
Checkout.Cart.SubTotal = 0;
Checkout.Cart.Total = 0;
Checkout.Cart.Qty = 0;
Checkout.Cart.Tax = 0;
Checkout.Cart.PromotionCode = "";
Checkout.Cart.Discount = "";
Checkout.Cart.DiscountValue = 0;
Checkout.Cart.DiscountType = "";
Checkout.Cart.Raw = "";
Checkout.Cart.Mode = "Server"; /// Cookie based cart in incomplete. Client side is finish, server side has not been started.

Checkout.TaxRate = 6.3;

Checkout.Init = function()
{
    if (document.getElementById("CheckoutPage") != null)
    {
    /*
        var QueryString = new Safemart.QueryString();
        var PayPalReturn = QueryString.Find("paypalreturn");

        if (PayPalReturn != null && PayPalReturn == "success")
        {
            Checkout.PayPal.GetDetails(Checkout.Load);
        }
        else
        {
            Checkout.Load();
        }
        */

        /// Auto-Load
        Checkout.Load();
    }
}

Checkout.Load = function(entry)
{
    if (typeof (entry) == "undefined") entry = "";
    /*
    /// reset all input fields
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)
    {
    if (inputs[i].type.toLowerCase() != "button")
    {
    inputs[i].value = inputs[i].getAttribute("defaultvalue")

            if (inputs[i].type.toLowerCase() == "radio" && inputs[i].getAttribute("defaultchecked") == 'true')
    {
    inputs[i].checked = true;
    }
    }
    }

    /// reset all Selects
    var inputs = document.getElementsByTagName("select");
    for (var i = 0; i < inputs.length; i++)
    {
    if (inputs[i].getAttribute("defaultvalue") == "")
    {
    inputs[i].value = "";

        }
    else
    {
    inputs[i].value = inputs[i].getAttribute("defaultvalue");
    }
    }
    */
    var uiPayPalBtn = document.getElementById("uiPayPalBtn");
    var uiPaypalOr = document.getElementById("uiPaypalOr");

    if (Checkout.PayPal.Enabled())
    {
        if (uiPayPalBtn != null) uiPayPalBtn.style.display = "block";
        if (uiPaypalOr != null) uiPaypalOr.style.display = "block";
    }
    else
    {
        if (uiPayPalBtn != null) uiPayPalBtn.style.display = "none";
        if (uiPaypalOr != null) uiPaypalOr.style.display = "none";
    }

    var QueryString = new Safemart.QueryString();
    var PayPalReturn = QueryString.Find("paypalreturn");

    if (Checkout.PayPal.Enabled() && PayPalReturn != null && PayPalReturn == "success")
    {
        Checkout.PayPalOrder = true;
        //Checkout.PayPal.GetDetails(Checkout.PayPal.GetDetailsReturnHandler);
        Checkout.PayPal.GetDetails(Checkout.GetPayPalDetailReturn);
    }
    else
    {
        Checkout.InitializeUI(entry);
    }


    /// Set Progress graphics.


    //Checkout.HideAllSteps()
    //Checkout.ShowStep("stepPayment");



    /// Google Analytics - page tracking
    /// Not Currently tracking on page load
    //pageTracker._trackPageview("/Checkout/"+Checkout.GoogleAnalyticsSteps[0]);     
    //pageTracker._trackPageview("/Checkout/"+Checkout.GoogleAnalyticsSteps[1]);     
}

Checkout.InitializeUI = function(entry)
{
    if (entry != "")
    {
        Checkout.HideSubstep("substepChooseCheckout");
        Checkout.ShowSubstep("substepConfidence");


        if (document.getElementById("sidebar-Caption") != null)
        {
            document.getElementById("sidebar-Caption").innerHTML = "Buy with Confidence:";
        }
    }

    if (entry == "PayPalConfirmOrder")
    {

        Checkout.Customer.Ship.AddressLine1 = Checkout.PayPal.Address1();
        Checkout.Customer.Ship.AddressLine2 = Checkout.PayPal.Address2();
        Checkout.Customer.Ship.City = Checkout.PayPal.City();
        Checkout.Customer.Ship.State = Checkout.PayPal.State();
        Checkout.Customer.Ship.Zip = Checkout.PayPal.Zip();
        Checkout.Customer.Ship.Country = Checkout.PayPal.Country();


        if (Checkout.PayPal.ValidShipping().toLowerCase() == "false")
        {

            Checkout.Customer.Ship.GetMethods();

            document.getElementById("PayPalShippingMsg").style.display = "block";
            document.getElementById("uiShippingPrevBtn").style.display = "none";
            Checkout.ShowStep("stepShippingOptions");
        }
        else
        {
            Checkout.Customer.Ship.Cost = Checkout.RoundMoney(Checkout.PayPal.ShipTotal());
            Checkout.ShowStep("stepPayPalConfirmation");
        }
        Checkout.SetTotals();
    }
    else if (entry == "ProceedWithCheckout")
    {
        //Checkout.ShowStep("stepAddress");
        Checkout.NextStep();
    }
    else
    {/// Default entry
        Checkout.ActivateStep("stepCart");
        //Checkout.ActivateStep("stepAddress");


        Checkout.ShowSubstep("substepChooseCheckout");


        /// Track login for Google Analytics
        Checkout.Google.TrackSubPage(0);

        Checkout.SetProgress();


    }

    if (Checkout.Cart.NoShipping)
    {
        /// the shipping address step will be skipped, don't set defaults.
    }
    else
    {
        /// Set default values 
        Checkout.Customer.Ship.State = "AL";
        Checkout.Customer.Ship.StateDomestic = "AL";
        Checkout.Customer.Ship.Country = "US";
        Checkout.Customer.Ship.CountryInternational = "US";

    }

    Checkout.Customer.Bill.State = "AL";
    Checkout.Customer.Bill.StateDomestic = "AL";
    Checkout.Customer.Bill.Country = "US";
    Checkout.Customer.Bill.CountryInternational = "US";

    if (Checkout.Cart.NoShipping)
    {
        /// Don't let the user go to the shipping address step.
        document.getElementById("uiBillingOptionsPrevBtn").style.display = "none";
        document.getElementById("uiBillLogin").style.display = ""; /// return to default
        document.getElementById("uiBIllingEmail").style.display = ""; /// retunr to default

    }

    if (Checkout.ShowSidebar)
    {
        Checkout.ShowSubstep("sidebar");
    }

    Checkout.ShowSubstep("uiTotalBox");
    Checkout.ShowSubstep("CartRef");


}

Checkout.GetPayPalDetailReturn = function(successful)
{
    if (successful)
    {
        Checkout.InitializeUI("PayPalConfirmOrder");
    }
    else
    {
        Checkout.InitializeUI("");
        alert(Checkout.PayPal.ErrorResponse());
    }

}

//document.body.onload = Checkout.onLoad;



Checkout._NewCard = function()
{
    var Card = new Object();
    Card.InternalId = "";
    Card.Default = false;
    Card.Type = "";
    Card.NameOnCard = "";
    Card.Number = "";
    Card.Expiration = "";
    
    return Card;
}

Checkout.Customer.ShowLogin = function()
{
    //
    document.getElementById("CheckoutNotificationCaption").innerHTML = "Enter Account Login";
    document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("LoginOverlay").innerHTML.replace("_#Msg#_",'<span id="LoginMessage" style="color:red"></span>');
    YAHOO.example.container.panel1.show();
    
}

Checkout.Customer.HideLogin = function()
{
    YAHOO.example.container.panel1.hide(); /// close notificaion window.
}

Checkout.Customer.Login = function()
{
    //YAHOO.example.container.panel1.hide(); /// close the login overlay.

    if (Checkout.Customer.Email.length > 0 && Checkout.Customer.Password.length > 0)
    {
        //document.getElementById("LoginMessage").innerHTML = "Login in progress...";
        //document.getElementById("LoginMessage").style.color = "Blue";

        SessionID = (wsi._Cookie.GetCrumb("SessionID") == null ? "" : wsi._Cookie.GetCrumb("SessionID"));

        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionID", SessionID);
        aParameters.Add("email", Checkout.Customer.Email);
        aParameters.Add("password", Checkout.Customer.Password);

        document.getElementById("CheckoutNotificationCaption").innerHTML = "Customer Login";
        // SHILL 11/17/08 document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Login in progress...</center><br /><br />";
        document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Processing Login<br /><img src='/img/images/progress.gif' alt=''></center><br /><br />";

        YAHOO.example.container.panel1.show();

        wsi._Soap.AddCall("CustomerLogin", Checkout.Customer.LoginReturn, aParameters);
    }
    else if (Checkout.Customer.Email.length == 0)
    {
        //alert("An email address is required for login");
        document.getElementById("LoginMessage").innerHTML = "An email address is required for login";
        //document.getElementById("LoginMessage").style.color = "Red";
    }
    else
    {
        //alert("A password is required for login");
        document.getElementById("LoginMessage").innerHTML = "A password is required for login";
        //document.getElementById("LoginMessage").style.color = "Red";
    }

    //<div class="hd" id="CheckoutNotificationCaption" ></div>
    //<div class="bd"  id="CheckoutNotificationMessage" ><div>



}

Checkout.Customer.LoginReturn = function(returnData)
{
    if (returnData.substring(0, 5) == "error")
    {
        Checkout.Customer.ShowLogin();
        document.getElementById("LoginMessage").innerHTML = returnData.substring(7);
        document.getElementById("LoginMessage").style.color = "Red";

    }
    else
    {
        Checkout.Customer.HideLogin();
        
        //document.getElementById("substepCart").style.display = "none";
        //Checkout.ShowStep(Checkout.Steps[1]);

        var Rows = returnData.split("||");

        for (var iRow = 0; iRow < Rows.length; iRow++)
        {
            var Fields = Rows[iRow].split("|");

            if (Rows[iRow].indexOf("Customer|") > -1)
            {
                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Checkout.Customer.InternalID(Values[1]);
                            break;

                        case "FirstName":
                            Checkout.Customer.Ship.FirstName = Values[1];
                            break;

                        case "LastName":
                            Checkout.Customer.Ship.LastName = Values[1];
                            break;

                        case "CompanyName":
                            Checkout.Customer.Ship.Company = Values[1];
                            break;

                        case "Email":
                            Checkout.Customer.Email = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("isShip=True") > 0)
            {
                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {

                        case "InternalId":
                            Checkout.Customer.Ship.InternalId = Values[1];
                            break;

                        case "Addressee":
                            Checkout.Customer.Ship.Company = Values[1];
                            break;

                        case "Attention":
                            // Override the Customer First and Last Name
                            var l_nDelimiter = Values[1].indexOf(' ');
                            var First = Values[1].substring(0, l_nDelimiter)
                            var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                            Checkout.Customer.Ship.FirstName = First;
                            Checkout.Customer.Ship.LastName = Last;
                            break;

                        case "Address1":
                            Checkout.Customer.Ship.AddressLine1 = Values[1];
                            break;

                        case "Address2":
                            Checkout.Customer.Ship.AddressLine2 = Values[1];
                            break;

                        case "City":
                            Checkout.Customer.Ship.City = Values[1];
                            break;

                        case "State":
                            Checkout.Customer.Ship.State = Values[1];
                            break;

                        case "Zip":
                            Checkout.Customer.Ship.Zip = Values[1];
                            break;

                        case "Country":
                            Checkout.Customer.Ship.Country = Values[1];
                            break;

                        case "Phone":
                            Checkout.Customer.Ship.Phone = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("isBill=True") > 0 && Rows[iRow].indexOf("isShip=True") > 0)
            {
                Checkout.Customer.Bill.SameAsShip = true;
            }
            
            if (Rows[iRow].indexOf("isBill=True") > 0)
            {
                Checkout.Customer.Bill.SameAsShip = false;

                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Checkout.Customer.Bill.InternalId = Values[1];
                            break;

                        case "Addressee":
                            Checkout.Customer.Bill.Company = Values[1]
                            break;

                        case "Attention":
                            var l_nDelimiter = Values[1].indexOf(' ');
                            var First = Values[1].substring(0, l_nDelimiter)
                            var Last = Values[1].substring(l_nDelimiter + 1, Values[1].length);

                            Checkout.Customer.Bill.FirstName = First;
                            Checkout.Customer.Bill.LastName = Last;
                            break;

                        case "Address1":
                            Checkout.Customer.Bill.AddressLine1 = Values[1];
                            break;

                        case "Address2":
                            Checkout.Customer.Bill.AddressLine2 = Values[1];
                            break;

                        case "City":
                            Checkout.Customer.Bill.City = Values[1];
                            break;

                        case "State":
                            Checkout.Customer.Bill.State = Values[1];
                            break;

                        case "Zip":
                            Checkout.Customer.Bill.Zip = Values[1];
                            break;

                        case "Country":
                            Checkout.Customer.Bill.Country = Values[1];
                            break;

                        case "Phone":
                            Checkout.Customer.Bill.Phone = Values[1];
                            break;
                    }
                }
            }

            if (Rows[iRow].indexOf("Card|") > -1)
            {
                Checkout.Customer.CreditCard.CardsOnFile[Checkout.Customer.CreditCard.CardsOnFile.length] = Checkout._NewCard();
                Card = Checkout.Customer.CreditCard.CardsOnFile[Checkout.Customer.CreditCard.CardsOnFile.length - 1];

                for (var iFields = 0; iFields < Fields.length; iFields++)
                {
                    var Values = Fields[iFields].split("=");
                    switch (Values[0])
                    {
                        case "InternalId":
                            Card.InternalId = Values[1];
                            break;

                        case "isDefault":
                            if (Values[1] == "true")
                            {
                                Card.Default = true;
                            }
                            break;

                        case "Type":
                            Card.Type = Values[1];
                            break;

                        case "NameOnCard":
                            Card.NameOnCard = Values[1];
                            break;

                        case "Number":
                            Card.Number = Values[1];
                            break;

                        case "Expiration":
                            Card.Expiration = Values[1];
                            break;
                    }
                }
            }
        }


        // Update the Shipping Fields
        document.getElementById("txtShipFirstName").value = Checkout.Customer.Ship.FirstName;
        document.getElementById("txtShipLastName").value = Checkout.Customer.Ship.LastName;
        document.getElementById("txtShipCompanyName").value = Checkout.Customer.Ship.Company;
        document.getElementById("txtCustomerEmail").value = Checkout.Customer.Email;
        document.getElementById("txtCustomerBillEmail").value = Checkout.Customer.Email;
        document.getElementById("txtShipAddress1").value = Checkout.Customer.Ship.AddressLine1;
        document.getElementById("txtShipAddress2").value = Checkout.Customer.Ship.AddressLine2;
        document.getElementById("txtShipCity").value = Checkout.Customer.Ship.City;
        if (Checkout.Customer.Ship.Country == "US")
        {
            Checkout.Customer.Ship.StateDomestic = Checkout.Customer.Ship.State;
            //document.getElementById("optShipStateProvince").value = Checkout.Customer.Ship.State;
        }
        else if (Checkout.Customer.Ship.Country == "CA")
        {
            Checkout.Customer.Ship.StateCanada = Checkout.Customer.Ship.State;
            //document.getElementById("optShipStateProvince_Canada").value = Checkout.Customer.Ship.State;
        }
        else
        {
            Checkout.Customer.Ship.StateInternational = Checkout.Customer.Ship.State;
            //document.getElementById("txtShipStateProvince").value = Checkout.Customer.Ship.State;
        }
        Checkout.SetStateField("Ship");

        document.getElementById("txtShipZipPostalCode").value = Checkout.Customer.Ship.Zip;
        document.getElementById("optShipCountryId").value = Checkout.Customer.Ship.Country;
        if (Checkout.Customer.Ship.Country != "US")
        {
            Checkout.Customer.Ship.CountryInternational = Checkout.Customer.Ship.Country;
            Checkout.ToggleCountryField("Ship");
        }

        if (Checkout.Customer.Ship.Phone.length > 0)
        {
            ClearInputExample(document.getElementById("txtShipPhoneNumber"))

            var PhoneNumber = Checkout.Customer.Ship.Phone;
            PhoneNumber = PhoneNumber.replace("-", " ").replace("(", "").replace(")", "");
            var PhoneArray = PhoneNumber.split(" ");

            document.getElementById("txtShipPhoneArea").value = PhoneArray[0];
            document.getElementById("txtShipPhonePrefix").value = PhoneArray[1];
            document.getElementById("txtShipPhoneSuffix").value = PhoneArray[2];



        }
        document.getElementById("txtShipPhoneNumber").value = Checkout.Customer.Ship.Phone;

        // Update the Bill to Fields
        if (!Checkout.Customer.Bill.SameAsShip)
        {
            document.getElementById("txtBillSameAsShipNo").click();
            document.getElementById("txtBillFirstName").value = Checkout.Customer.Bill.FirstName;
            document.getElementById("txtBillLastName").value = Checkout.Customer.Bill.LastName;
            document.getElementById("txtBillCompanyName").value = Checkout.Customer.Bill.Company;
            document.getElementById("txtBillAddress1").value = Checkout.Customer.Bill.AddressLine1;
            document.getElementById("txtBillAddress2").value = Checkout.Customer.Bill.AddressLine2;
            document.getElementById("txtBillCity").value = Checkout.Customer.Bill.City;
            if (Checkout.Customer.Bill.Country == "US")
            {
                Checkout.Customer.Bill.StateDomestic = Checkout.Customer.Bill.State;
                //document.getElementById("optBillStateProvince").value = Checkout.Customer.Bill.State;
            }
            else if (Checkout.Customer.Bill.Country == "CA")
            {
                Checkout.Customer.Bill.StateCanada = Checkout.Customer.Bill.State;
                //document.getElementById("optBillStateProvince_Canada").value = Checkout.Customer.Bill.State; 
            }
            else
            {
                Checkout.Customer.Bill.StateInternational = Checkout.Customer.Bill.State;
                //document.getElementById("txtBillStateProvince").value = Checkout.Customer.Bill.State;
            }
            Checkout.SetStateField("Bill");

            document.getElementById("txtBillZipPostalCode").value = Checkout.Customer.Bill.Zip;
            document.getElementById("optBillCountryId").value = Checkout.Customer.Bill.Country;
            if (Checkout.Customer.Bill.Country != "_unitedStates")
            {
                Checkout.Customer.Bill.CountryInternational = Checkout.Customer.Bill.Country;
                Checkout.ToggleCountryField("Bill");
            }

            if (Checkout.Customer.Bill.Phone.length > 0)
            {
                ClearInputExample(document.getElementById("txtBillPhoneNumber"))

                var PhoneNumber = Checkout.Customer.Bill.Phone;
                PhoneNumber = PhoneNumber.replace("-", " ").replace("(", "").replace(")", "");
                var PhoneArray = PhoneNumber.split(" ");

                document.getElementById("txtBillPhoneArea").value = PhoneArray[0];
                document.getElementById("txtBillPhonePrefix").value = PhoneArray[1];
                document.getElementById("txtBillPhoneSuffix").value = PhoneArray[2];
            }
            document.getElementById("txtBillPhoneNumber").value = Checkout.Customer.Bill.Phone;

        }
    }
}

Checkout.Customer.Ship.GetMethods = function()
{
    
    var aParameters = new wsi._Parameters();
    //aParameters.Add("firstName",Checkout.Customer.Ship.FirstName);
    //aParameters.Add("lastName",Checkout.Customer.Ship.LastName);
    //aParameters.Add("company",Checkout.Customer.Ship.Company);
    aParameters.Add("addressLine1", Checkout.Customer.Ship.AddressLine1);
    aParameters.Add("addressLine2", Checkout.Customer.Ship.AddressLine2);
    aParameters.Add("city", Checkout.Customer.Ship.City);
    aParameters.Add("state", Checkout.Customer.Ship.State);
    aParameters.Add("zip", Checkout.Customer.Ship.Zip);
    aParameters.Add("country", Checkout.Customer.Ship.Country);
    //aParameters.Add("phone",Checkout.Customer.Ship.Phone);
    aParameters.Add("weight", Checkout.Cart.Weight);
    aParameters.Add("noFreeShipWeight", Checkout.Cart.NoFreeShipWeight);
    aParameters.Add("pieceCount", Checkout.Cart.PieceCount);
    //alert("weight "+Checkout.Cart.Weight);
    wsi._Soap.AddCall("GetShippingMethods", Checkout.Customer.Ship.MethodsReturn, aParameters);
}

Checkout.Customer.Ship.MethodsReturn = function(returnData)
{
    //alert(returnData);
    Checkout.Customer.Ship.Raw = returnData;

    /// reset Ship properties
    Checkout.Customer.Ship.Cost = 0;
    // SHILL 09-22-2008
    // Don't clear the Shipping Type. 
    // If the customer changes item qty the shipping
    //  is re-caculated without changing the type
    //    Checkout.Customer.Ship.Type = "";

    document.getElementById("ShipMethodMessage").innerHTML = "";

    if (returnData.substring(0, 5) == "error")
    {
        alert(returnData.substring(7));
    }
    else
    {
        var aShipMethods = returnData.split("||")

        var ShipTable = "";
        ShipTable += '<table border="0" width="500px" cellspacing="0" cellpadding="4px">';
        if (Checkout.Cart.NoFreeShipWeight > 0 || Checkout.Cart.FlatRateShip > 0)
        {
            ShipTable += '<tr>' +
                            '<td colspan="2" style="text-align:right;">' +
                                 "<span style='position:relative;'>" +
                                    "<span id='NoFreeShipOverlayLink' class='CheckoutLink' onmouseover='Checkout.ShowNoFreeShippingOverlay();' onmouseout='Checkout.HideNoFreeShippingOverlay();'>" +
                                        "Why don't I see a free shipping option?" +
                                    "</span>" +
                                "</span>" +
                            '</td>' +
                            '</tr>'
        }

        ShipTable += '<tr>' +
                        '<td style="border-bottom:solid 1px black;">' +
                        '<b>Shipping Method</b>' +
                        '</td>' +
                        '<td style="border-bottom:solid 1px black;">' +
                        '<b>Price</b>' +
                        '</td>' +
                        '</tr>';

        /// reset Ship Cost    
        Checkout.Customer.Ship.Cost = 0;

        /// Default cost for Premium and Ground Shipping
        var PremiumShipCost = 11.75;
        var GroundShipCost = 5.99;

        if (Checkout.Cart.FlatRateShip > 0 || Checkout.Cart.NoFreeShipWeight > 0)
        {
            var NoFreeShipCost = 0;

            if (Checkout.Cart.NoFreeShipWeight > 0)
            {
                var NoFreeRowNum = aShipMethods.findAt("NOFREE_FEDEX_GROUND", 0, "contains");

                if (NoFreeRowNum > -1)
                {
                    NoFreeShipCost = parseFloat(aShipMethods[NoFreeRowNum].split("|")[1]);
                }
            }
            //alert(NoFreeShipCost);
            GroundShipCost = parseFloat(Checkout.Cart.FlatRateShip) + NoFreeShipCost;
        }

        /// California residents get upgraded to 2day air for the cost of ground.
        if (Checkout.Cart.SubTotal >= 100.00)
        {
            Cali2dayAirCost = 0;
        }
        else
        {
            var Cali2dayAirCost = GroundShipCost;
        }

        if (Checkout.Customer.Ship.Type == "2926" || Checkout.Customer.Ship.Type == "1785")
        {
            /// If the subtotal is greater that $99 the order qualifies for free shipping
            /// and all items qualify for free shipping
            /// and all items are not Flat rate shipping items
            if (Checkout.Cart.SubTotal >= 100.00 && Checkout.Cart.NoFreeShipWeight == 0 && Checkout.Cart.FlatRateShip == 0)
            {
                var ShipType = "2926";
            }
            else
            {
                var ShipType = "1785";
            }
        }
        else
        {
            var ShipType = Checkout.Customer.Ship.Type;
        }

        if (Checkout.Customer.Ship.Country == "US")
        {

            // Only the Continental US
            if (Checkout.Customer.Ship.State != "AK" && Checkout.Customer.Ship.State != "HI")
            {


                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "2925")
                {/// Apply free shipping - customer entered a coupon
                    PremiumShipCost = 0;
                }

                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "1785")
                {/// Apply free shipping - customer entered a coupon
                    GroundShipCost = 0;
                }


                if (ShipType == "2925")
                {
                    Checkout.Customer.Ship.Cost = PremiumShipCost;
                }
                else if (ShipType == "2926")
                {
                    Checkout.Customer.Ship.Cost = 0;
                }
                else if (ShipType == "1785")
                {
                    Checkout.Customer.Ship.Cost = GroundShipCost;
                }

                /// If the cart contains items that do not qualify for free shipping
                /// or if the cart contains flat rate shipping items
                ///     - do not include the option for premium shipping
                ///     - do not include the option for free shipping
                if (Checkout.Cart.NoFreeShipWeight == 0 && Checkout.Cart.FlatRateShip == 0)
                {
                    ShipTable += '<tr>' +
                                '<td>' +
                                '       <input id="ShipMethod_Premium" type="radio" name="ShippingOption" value="2925|' + PremiumShipCost + '" ' + (ShipType == '2925' || ShipType.length == 0 ? 'checked="checked"' : '') + ' />Premium - Delivered in 3 days' +
                                '    </td>' +
                                '    <td>' +
                                '        ' + Checkout.ToMoney(PremiumShipCost) +
                                '    </td>' +
                                '</tr>';

                    ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_Ground" type="radio" name="ShippingOption" ' + (ShipType == '2926' || ShipType == '1785' ? 'checked="checked"' : '') + ' value="' + (Checkout.Cart.SubTotal >= 100.00 ? "2926|0.00" : "1785|" + GroundShipCost) + '" />' +
                                         (Checkout.Cart.SubTotal >= 100.00 ? "Free Shipping - " : "") + "Ground Service" +
                                '    </td>' +
                                '    <td>' +
                                        (Checkout.Cart.SubTotal >= 100.00 ? "$0.00" : Checkout.ToMoney(GroundShipCost)) +
                                '    </td>' +
                                '</tr>';
                }
                else
                {
                    var ShipLabel = "";
                    if (Checkout.Cart.FlatRateShip > 0)
                    {
                        ShipLabel = "Flat Rate Shipping";
                    }
                    else
                    {
                        ShipLabel = "Ground Service";
                    }

                    ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_Ground" type="radio" name="ShippingOption" ' + (ShipType == '1785' ? 'checked="checked"' : '') + ' value="1785|' + GroundShipCost + '" />' +
                                         ShipLabel +
                                '    </td>' +
                                '    <td>' +
                                        Checkout.ToMoney(GroundShipCost) +
                                '    </td>' +
                                '</tr>';
                }

            }

            // All 50 States
            var iFedExStdOvernight = aShipMethods.findAt("STANDARD_OVERNIGHT|", 0, "contains");
            var iFedExPriOvernight = aShipMethods.findAt("PRIORITY_OVERNIGHT|", 0, "contains");
            var iFedExTwoDay = aShipMethods.findAt("FEDEX_2_DAY|", 0, "contains");
            //alert(iFedExTwoDay);
            if (iFedExTwoDay > -1)
            {
                /// Default Cost for FedeEx 2day air
                var ShipCost = parseFloat(aShipMethods[iFedExTwoDay].split("|")[1]);
                var TwoDayAirName = "FedEx 2-Day Air";

                /// California gets Free upgrade - 2nd day air for the cost of ground
                if (Checkout.Cart.FlatRateShip == 0 && Checkout.Customer.Ship.Country == "US" && Checkout.Customer.Ship.State == "CA")
                {
                    var ShipCost = Cali2dayAirCost;
                    var TwoDayAirName = "FedEx 2-Day Air - <span style='color:red;'>California Special Only</span>";
                }

                if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == "9")
                {/// Apply free shipping - customer entered a coupon
                    ShipCost = 0;
                }

                if (ShipType == "9")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '    <td>' +
                                '        <input id="ShipMethod_FEDEX_2_DAY" type="radio" name="ShippingOption" ' + (ShipType == '9' ? 'checked="checked"' : '') + ' value="9|' + ShipCost + '" />' + TwoDayAirName +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExStdOvernight > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExStdOvernight].split("|")[1]);


                if (ShipType == "1786")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_STANDARD_OVERNIGHT" type="radio" name="ShippingOption" ' + (ShipType == '1786' ? 'checked="checked"' : '') + ' value="1786|' + ShipCost + '" />FedEx Standard Overnight' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExPriOvernight > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExPriOvernight].split("|")[1]);

                if (ShipType == "2923")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_"PRIORITY_OVERNIGHT" type="radio" name="ShippingOption" ' + (ShipType == '2923' ? 'checked="checked"' : '') + '  value="2923|' + ShipCost + '" />FedEx Priority Overnight' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }
        }
        else
        {
            var iFedExEco = aShipMethods.findAt("INTERNATIONAL_ECONOMY|", 0, "contains");
            var iFedExPri = aShipMethods.findAt("INTERNATIONAL_PRIORITY|", 0, "contains");
            var iFedExGrd = -1;

            /// Canadians don't get a ground option
            if (Checkout.Customer.Ship.Country != "CA")
            {
                var iFedExGrd = aShipMethods.findAt("FEDEX_GROUND|", 0, "contains");
            }
            
            if (iFedExGrd > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExGrd].split("|")[1]);

                if (ShipType == "1785" || ShipType.length == 0)
                {
                    ShipType = "1785"
                    Checkout.Customer.Ship.Type = "1785";

                    Checkout.Customer.Ship.Cost = ShipCost;
                }


                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_FEDEX_GROUND" type="radio" name="ShippingOption" ' + (ShipType == '1785' ? 'checked="checked"' : '') + ' value="1785|' + ShipCost + '" />FedEx Ground' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExEco > -1)
            {

                var ShipCost = parseFloat(aShipMethods[iFedExEco].split("|")[1]);

                /// Canadians pay 50% on the shipping rate
                if (Checkout.Customer.Ship.Country == "CA")
                {
                    ShipCost /= 2;
                }

                if (ShipType == "1787" || (iFedExGrd == -1 && ShipType.length == 0))
                {
                    ShipType = "1787"
                    Checkout.Customer.Ship.Type = "1787";

                    Checkout.Customer.Ship.Cost = ShipCost;
                }


                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_INTERNATIONAL_ECONOMY" type="radio" name="ShippingOption" ' + (ShipType == '1787' ? 'checked="checked"' : '') + ' value="1787|' + ShipCost + '" />International Economy' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }

            if (iFedExPri > -1)
            {
                var ShipCost = parseFloat(aShipMethods[iFedExPri].split("|")[1]);

                /// Canadians pay 50% on the shipping rate
                if (Checkout.Customer.Ship.Country == "CA")
                {
                    ShipCost /= 2;
                }

                if (ShipType == "2924")
                {
                    Checkout.Customer.Ship.Cost = ShipCost;
                }

                ShipTable += '<tr>' +
                                '   <td>' +
                                '        <input id="ShipMethod_INTERNATIONAL_PRIORITY" type="radio" name="ShippingOption" ' + (ShipType == '2924' ? 'checked="checked"' : '') + ' value="2924|' + ShipCost + '" />International Priority' +
                                '    </td>' +
                                '    <td>' + Checkout.ToMoney(ShipCost) +
                                '    </td>' +
                                '</tr>';
            }
        }

        ShipTable += '<tr>' +
                    '   <td colspan="2" style="border-top:solid 1px black;">' +
                    '    &nbsp;</td>' +
                    '</tr>' +
                    '</table>';

        document.getElementById("ShipMethods").innerHTML = ShipTable;
        if (document.getElementsByName("ShippingOption").length > 0)
        {
            //document.getElementsByName("ShippingOption")[0].checked = true;
        }
        else
        {
            document.getElementById("ShipMethods").innerHTML = "<span style='color:red;'>There are no shipping options available for your location. Please use the Previous button to check you shipping address.</span>";
        }

        Checkout.SetTotals();

    }
}



Checkout.Cart.View = function()
{
    if (document.getElementById("CartItemCount") != null && document.getElementById("CartItemCount").innerHTML == "0")
    {
        alert("There are currently no items in your cart.");
    }
    else
    {
        if (document.domain == "quarantine.safemart.com")
        {
            document.location.href = "https://" + document.domain + "/checkout.htm"
        }
        else
        {
            document.location.href = "https://www.safemart.com/checkout.htm"
        }
    }
}

Checkout.Cart.Get = function()
{
    if (Checkout.Cart.Mode == "Server")
    {
        var SessionID = wsi._Cookie.GetCrumb("SessionID");

        if (SessionID != null)
        {
            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionID", SessionID + Checkout.Cart.Name);
            wsi._Soap.AddCall("GetCart", Checkout.Cart.GetReturn, aParameters);
        }
        else
        {
            Checkout.Cart.GetReturn(null)
        }
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.Cart.GetReturn(Checkout.CartProcessor.GetCart());
    }
    
    wsi.GetIP(Checkout.GetIPReturn);
}

Checkout.GetIPReturn = function(ip)
{
//alert(ip);

    Checkout.Customer.IP = ip
    
    ///192.168.253.1 = local.quarantine.safemart.com
    ///192.168.253.10 = local.www.safemart.com
    ///64.6.124.68 = Old Ocusafe Location - Moats building
    ///64.6.124.68 = New Ocusafe Location - Bertrand
        if (ip == "64.6.124.68" || ip == "64.6.124.16" || ip == "139.146.141.27" || ip == "192.168.253.1" || ip == "192.168.253.10")
        {   
            Checkout.Customer.InternalIP = true;
            document.getElementById("Internal").style.display = "block";
           
        }
}

Checkout.Cart.LineItemTemplate = "" +
         "<tr id='_#GroupId#_'>"+
            "<td width='55px' rowspan='2' valign='top' style='padding-top:10px;padding-right:10px;'>" +
                "<img src='_#ImgLocation#_' width='50px' height='50px' />" +
            "</td>" +
            "<td colspan='3' valign='top' style='padding-top:10px'>"+
                "<a href='_#ItemLocation#_'>_#ItemName#_</a>"+
                " &nbsp;"+
                "<span style='position:relative;'>"+
                    "<span id='OptionLink_#GroupId#_' class='CheckoutLink'"+
                        //" onmouseover='document.getElementById(\"Customizations_#GroupId#_\").style.display = \"block\";'"+
                        " onmouseover='YAHOO.example.container.overlay1.cfg.setProperty(\"context\", [\"OptionLink_#GroupId#_\",\"tl\",\"bl\"]); YAHOO.example.container.overlay1.setBody(document.getElementById(\"Customizations_#GroupId#_\").innerHTML);YAHOO.example.container.overlay1.show()'"+
                        //" onmouseout='document.getElementById(\"Customizations_#GroupId#_\").style.display = \"none\"' >_#CustomizationLink#_"+
                        " onmouseout='YAHOO.example.container.overlay1.hide()' >_#CustomizationLink#_"+
                    "</span>"+
                    "<div id='Customizations_#GroupId#_' style='display:none;z-index:1000;position:absolute;top:25px;left:-20px;padding:10px;background-color:white;border:solid 1px #c0c0c0;'>_#Customizations#_</div>"+
                "</span>"+
            "</td>"+
         "</tr>"+
         "<tr>"+
            "<td valign='top'>"+
                "<span>item# _#Sku#_</span>"+
            "</td>"+
            "<td valign='top'>"+
                "<input type='text'id='Qty_#GroupId#_' onkeyup='Checkout.ValidateQty(this);' onblur='Checkout.ValidateQty(this,true);' defaultvalue='_#Qty#_' value='_#Qty#_' size='1' maxlength='3' style='height:20px;' />"+
                "&nbsp;Qty"+
                "&nbsp;<span class='CheckoutLink' style='font-size:11px;' onclick='Checkout.Cart.ChangeItemQty(\"_#GroupId#_\", \"Qty_#GroupId#_\");'>Update</span>"+
                "&nbsp;<span class='CheckoutLink' style='font-size:11px;'  onclick='Checkout.Cart.RemoveItem(\"_#GroupId#_\",\"_#NsId#_\")'>Remove</span>" +
            "</td>"+
            "<td align='right' valign='top'>"+
                "<div style='_#PriceStyles#_'>"+
                    "<span id='Price_#GroupId#_'>_#Price#_</span>"+
                    "&nbsp;&nbsp;&nbsp;&nbsp;<span id='Total_#GroupId#_'>_#Total#_</span>" +
                "</div>" +
                "<div style='display:_#DiscountDisplay#_;color:red;'>"+
                    "<span>(discounted)&nbsp&nbsp</span>"+
                    "<span id='DiscountPrice_#GroupId#_'>_#DiscountPrice#_</span>"+
                    "&nbsp;&nbsp;&nbsp;&nbsp;<span id='DiscountTotal_#GroupId#_'>_#DiscountTotal#_</span>" +                
                "</div>"+
                
            "</td>"+
        "</tr>";


Checkout.ItemToRemove = "";
Checkout.ItemToRemoveId = "";

Checkout.Cart.RemoveItem = function(groupId, netsuitId)
{
    Checkout.ItemToRemove = groupId;
    Checkout.ItemToRemoveId = netsuitId;
    
    var Message = document.getElementById("RemoveCartItemNotification").innerHTML;
    //Message = Message.Replace(/_#RemoveItemTitle_#/g, title);

    /// reset the smart money flag.
    /// after the remove, if the cart still contains the Smart Money Package.
    /// the flag will be set to true.
    Checkout.Cart.ContainsSmartMoneyPackage = false;

    /// Reset the eBillme enabled to true
    /// eBillme is disable when the cart contains the Smart Money package.
    Checkout.eBillme.Enable(true);

    document.getElementById("CheckoutNotificationCaption").innerHTML = "Remove from Cart";
    document.getElementById("CheckoutNotificationMessage").innerHTML = Message;
    YAHOO.example.container.panel1.show();
}

Checkout.RemoveItemConfirmed = function(removeItem)
{
    YAHOO.example.container.panel1.hide();

    if (removeItem)
    {
        groupId = Checkout.ItemToRemove;

        var SessionID = wsi._Cookie.GetCrumb("SessionID");

        document.getElementById("CartItems").innerHTML = "Removing Item from Cart...";

        if (Checkout.Cart.Mode == "Server")
        {
            if (SessionID != null)
            {
                var aParameters = new wsi._Parameters();
                aParameters.Add("sessionID", SessionID);
                aParameters.Add("groupId", groupId);


                wsi._Soap.AddCall("RemoveFromCart", Checkout.Cart.GetReturn, aParameters);

            }
            else
            {
                Checkout.Cart.GetReturn(null);
            }
        }
        else if (Checkout.Cart.Mode == "Cookie")
        {
            Checkout.Cart.GetReturn(Checkout.CartProcessor.RemoveFromCart(groupId));
        }
    }

    Checkout.FetchBack.Abandon(Checkout.ItemToRemoveId);
}

Checkout.Cart.ChangeItemQty = function(groupId, qtyField)
{
    var Qty = document.getElementById(qtyField).value
    document.getElementById("CartItems").innerHTML = "Updating Quantity...";
    
    if (Checkout.Cart.Mode == "Server")
    {
        var SessionID = wsi._Cookie.GetCrumb("SessionID");

        if (SessionID != null)
        {
            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionID",SessionID);
            aParameters.Add("groupId", groupId);
            aParameters.Add("qty", Qty);

            wsi._Soap.AddCall("ChangeCartQty", Checkout.Cart.GetReturn, aParameters);

         }
        else
        {
            Checkout.Cart.GetReturn(null);
        }
    }
    else if (Checkout.Cart.Mode == "Cookie")
    {
        Checkout.Cart.GetReturn(Checkout.CartProcessor.UpdateQty(groupId,Qty));
    }
}

Checkout.Cart.GetViewText = function()
{
    wsi.Cart.GetViewText();
}

Checkout.Cart.GetReturn = function(returnValue)
{

    Checkout.Cart.Raw = returnValue;

    /// both Cart.RemoveItem and Cart.UpdateQty return to this funtion.
    /// call GetViewText to update the cart view in the header
    Checkout.Cart.GetViewText();

    /// reset the weigth and  subtotal
    Checkout.Cart.Weight = 0;
    Checkout.Cart.SubTotal = 0;

    /// Reset No Free Shipping weight
    Checkout.Cart.NoFreeShipWeight = 0;
    Checkout.Cart.PieceCount = 0;

    /// Reset Flat Rate Shipping
    Checkout.Cart.FlatRateShip = 0;

    /// Reset the No Shipping flag
    Checkout.Cart.NoShipping = 1;

    if (returnValue == null || returnValue.length == 0)
    {
        document.getElementById("CartItems").innerHTML = Checkout.Cart.EmptyText;
        Checkout.Cart.IsEmpty = true;
    }
    else if (returnValue.substring(0, 5) == "error")
    {
        document.getElementById("CartItems").innerHTML = returnValue;
        Checkout.Cart.IsEmpty = true;
    }
    else
    {
        Checkout.Cart.IsEmpty = false;

        var CartArray = returnValue.split("||");
        //alert(CartArray.join("\r\n\r\n"));        
        var Groups = new Array();
        var GroupMap = new Array();

        for (var iItems = 0; iItems < CartArray.length; ++iItems)
        {
            var ItemProperties = CartArray[iItems].split("|");

            var GroupNumber = Groups.findAt(ItemProperties[0], 0)

            if (GroupNumber == -1)
            {
                Groups[Groups.length] = ItemProperties[0];
                GroupMap[GroupMap.length] = "" + iItems; /// It must be a string
            }
            else
            {
                GroupMap[GroupNumber] += "," + iItems;
            }
        }



        var ItemListHTML = "";

        //for (var iItems=0; iItems<CartArray.length; ++iItems)
        for (var iGroups = 0; iGroups < Groups.length; iGroups++)
        {

            var ThisGroup = GroupMap[iGroups]
            /*
            //if (GroupMap[iGroups] == 0)
            if (GroupMap[iGroups].indexOf(",") == -1)
            { // split doesn't work if value = 0
            var GroupIds = new Array();
            GroupIds[0] = GroupMap[iGroups];
            }
            else
            {
            var GroupIds = GroupMap[iGroups].split(",");
            }
            */
            var GroupIds = GroupMap[iGroups].split(",");

            var ItemHTML = Checkout.Cart.LineItemTemplate;
            var CustomizationLink = "";
            var CustomizationsHTML = "";
            var UnitPrice = 0;
            var UnitDiscountPrice = 0;
            var TotalPrice = 0;
            var BaseQty = 0;

            /// Clear the FetchBack Purchase List
            Checkout.FetchBack.FetchBackPurchaseList = "";

            for (var iItems = 0; iItems < GroupIds.length; ++iItems)
            {
                //var ItemProperties = CartArray[iItems].split("|");
                var ItemProperties = CartArray[parseInt(GroupIds[iItems])].split("|");
                // Examples:
                // MAINPRODUCT|907|PRODUCTNAME|1|299.00|1.00
                // BUNDLE|757|3M Double Sided Tape - 1" Squares|4|2.00|1.00
                // <ParentID>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>|<CouponPrice>|<Coupon>|<No Free Shipping>|<Flat Rate Shipping>
                // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>|<CouponPrice>|<Coupon>|<No Free Shipping>|<Flat Rate Shipping>|<Non Shippable>


                if (ItemProperties[2] == "76495")
                {
                    Checkout.Cart.ContainsSmartMoneyPackage = true;
                    Checkout.eBillme.Enable(false);
                }


                if (ItemProperties[1] == "0")
                {

                    Checkout.FetchBack.FetchBackPurchaseList += ItemProperties[2];

                    ItemHTML = ItemHTML.replace(/_#GroupId#_/g, ItemProperties[0]);
                    ItemHTML = ItemHTML.replace(/_#NsId#_/g, ItemProperties[2]);
                    ItemHTML = ItemHTML.replace(/_#ImgLocation#_/g, ItemProperties[8]);
                    ItemHTML = ItemHTML.replace(/_#ItemLocation#_/g, ItemProperties[9]);
                    ItemHTML = ItemHTML.replace(/_#ItemName#_/g, ItemProperties[3]);
                    ItemHTML = ItemHTML.replace(/_#Sku#_/g, ItemProperties[7]);
                    ItemHTML = ItemHTML.replace(/_#Qty#_/g, ItemProperties[4]);

                    var DiscountPrice = parseFloat(ItemProperties[10]);
                    var ReqularPrice = parseFloat(ItemProperties[5]);

                    UnitDiscountPrice += DiscountPrice;
                    UnitPrice += ReqularPrice;

                    BaseQty = parseInt(ItemProperties[4]);
                    Checkout.Cart.Qty += BaseQty;

                    if (ItemProperties[14] == "false")
                    {
                        Checkout.Cart.NoShipping = 0;
                    }
                }
                else
                {
                    if (CustomizationsHTML.length == 0)
                    {
                        CustomizationLink = "View&nbsp;Options";

                    }
                    else
                    {
                        CustomizationsHTML += "<br />";
                    }

                    CustomizationsHTML += ItemProperties[3];

                    var DiscountPrice = parseFloat(ItemProperties[10]);
                    var ReqularPrice = parseFloat(ItemProperties[5]);

                    UnitDiscountPrice += (parseInt(ItemProperties[4]) / BaseQty) * DiscountPrice;
                    UnitPrice += (parseInt(ItemProperties[4]) / BaseQty) * ReqularPrice;
                }

                //UnitPrice += parseFloat(ItemProperties[5]);
                //TotalPrice += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);

                var ItemQty = parseInt(ItemProperties[4]);
                var ItemWeight = parseFloat(ItemProperties[6]);
                var IsItemNoFreeShip = ItemProperties[12].toLowerCase();
                var ItemFlatShipRate = parseFloat(ItemProperties[13]);
                Checkout.Cart.Weight += ItemQty * ItemWeight;

                /// Use Flat Rate shipping over "No Free Shipping"
                if (ItemFlatShipRate == 0)
                {
                    if (IsItemNoFreeShip == "true")
                    {
                        Checkout.Cart.NoFreeShipWeight += ItemQty * ItemWeight;
                        Checkout.Cart.PieceCount += ItemQty;
                    }
                }
                else
                {
                    Checkout.Cart.FlatRateShip += ItemQty * ItemFlatShipRate;
                }
                //Checkout.Cart.SubTotal += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);

            }
            //alert("NoShippingWeight " + Checkout.Cart.NoFreeShipWeight + "\r\nPieceCount " + Checkout.Cart.PieceCount + "\r\nFlatRateShipping " + Checkout.Cart.FlatRateShip);
            /// This section of code supports line item discounts.
            /// currenly line item discounts is disabled on the server.
            /// The code remains here should line item discounts be re-enabled.            
            if (UnitDiscountPrice > 0)
            { /// Set the discount price

                TotalPrice += UnitDiscountPrice * BaseQty;
                Checkout.Cart.SubTotal += TotalPrice;

                /// Strike through the Reqular price
                ItemHTML = ItemHTML.replace(/_#PriceStyles#_/g, "text-decoration: line-through;");

                /// Write-in the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountPrice#_/g, Checkout.ToMoney(UnitDiscountPrice));
                ItemHTML = ItemHTML.replace(/_#DiscountTotal#_/g, Checkout.ToMoney(TotalPrice));

                /// show the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountDisplay#_/g, "block");
            }
            else
            { /// Use the regular price
                TotalPrice += UnitPrice * BaseQty;
                Checkout.Cart.SubTotal += TotalPrice;

                /// Clear discount price
                ItemHTML = ItemHTML.replace(/_#DiscountPrice#_/g, "");
                ItemHTML = ItemHTML.replace(/_#DiscountTotal#_/g, "");

                /// hide the discount price
                ItemHTML = ItemHTML.replace(/_#DiscountDisplay#_/g, "none");

            }

            ItemHTML = ItemHTML.replace(/_#Price#_/g, Checkout.ToMoney(UnitPrice));
            ItemHTML = ItemHTML.replace(/_#Total#_/g, Checkout.ToMoney(TotalPrice));
            ItemHTML = ItemHTML.replace(/_#CustomizationLink#_/g, CustomizationLink);
            ItemHTML = ItemHTML.replace(/_#Customizations#_/g, CustomizationsHTML);

            // Add the item to the list
            ItemListHTML += ItemHTML;
        }

        var SessionId = wsi._Cookie.GetCrumb("SessionID");


        document.getElementById("CartRef").innerHTML = "Cart Reference: " + SessionId;


        document.getElementById("CartItems").innerHTML = "<table border='0' width='100%' cellspacing='0' cellpadding='0' style='padding-right:20px;'>" +
            ItemListHTML + "</table>";
    }

    if (Checkout.Customer.Ship.Zip.length > 0)
    {
        /// Update Shipping 
        Checkout.Customer.Ship.GetMethods();
    }

    Checkout.SetTotals();
    Checkout.Cart.ApplyCoupon();


}

Checkout.Cart.ApplyCoupon = function()
{
    
    //document.getElementById("CardMessage").innerHTML = ""

    /// Clear values
    /*
    if (Checkout.Cart.DiscountType != "")
    {
        Checkout.Cart.Discount = "";
        Checkout.Cart.DiscountValue = 0;
        Checkout.Cart.DiscountType = "";
        Checkout.Customer.Ship.MethodsReturn(Checkout.Customer.Ship.Raw);
    }
    */
    
    if (Checkout.Cart.PromotionCode.length > 0)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
        aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
        aParameters.Add("couponCode",Checkout.Cart.PromotionCode);

        wsi._Soap.AddCall("ValidateCoupon", Checkout.Cart.CouponReturn, aParameters);
    }
    else
    {
        /// Reset totals
        Checkout.SetTotals();
    }
}

Checkout.Cart.CouponReturn = function(returnValue)
{

    if (returnValue.substring(0,5) == "error")
    {
        alert(returnValue.substring(7))
    }
    else
    {
        Checkout.Cart.Discount = returnValue;
        if (returnValue.slice(0,1) == "$")
        {
            Checkout.Cart.DiscountValue = parseInt(returnValue.slice(1));
            Checkout.Cart.DiscountType = "$";
        }
        else if(returnValue.slice(-1) == "%")
        {
            Checkout.Cart.DiscountValue = parseInt(returnValue.slice(0,-1));
            Checkout.Cart.DiscountType = "%";
        }
        else if (returnValue.slice(0,1) == "#")
        {
            Checkout.Cart.DiscountValue = returnValue.slice(1);
            Checkout.Cart.DiscountType = "S";  
            Checkout.Customer.Ship.Type = Checkout.Cart.DiscountValue;  
            Checkout.Customer.Ship.MethodsReturn(Checkout.Customer.Ship.Raw);
            
            alert("Free shipping has been applied to your cart.");
        }
        else
        {/// display message
        /// This should only be called if using a Line Item Discounts.
            alert(returnValue);
        }
    }
    
    Checkout.SetTotals();
}

Checkout.Cart.ContainsSmartMoneyPackage = false;

/// Converts a float value to a Money String
Checkout.ToMoney = SWH.ToMoney;
/*
Checkout.ToMoney = function(value)
{

    // convert to string
    value = "" + value;
    
    if (value.indexOf(".") == -1)
    {
        value += ".00";
    }
    
    if (value.indexOf(".") < value.length - 3)
    {/// round to two decimals
        //value = Math.round(parseFloat(value)*100)/100
        
        value = Checkout.RoundMoney(value);
        
        /// Make the value a string again
        value = ""+value;
        
    }
       
    //alert(value + "  " + value.slice(-2,-1))
    if (value.slice(-2,-1) == ".")
    {/// second to last char is a . -- pad the value with zero.
        value += "0";
    }
   


    // add the $        
    value = "$" + value;
        
    return value;
}
*/

Checkout.RoundMoney = SWH.RoundMoney;
/*
Checkout.RoundMoney = function(value)
{
    return Math.round(parseFloat(value)*100)/100
}
*/

Checkout.SetTotals = function()
{
    /// CheckoutTotal will be null if the page load is not complete 
    if (document.getElementById("CheckoutTotal") != null)
    {
        var Discount = 0;
        
        if (Checkout.Cart.DiscountType == "$")
        {
            Discount = Checkout.Cart.DiscountValue;
        }
        else if (Checkout.Cart.DiscountType == "%")
        {
            Discount = Checkout.RoundMoney((Checkout.Cart.DiscountValue / 100) * Checkout.Cart.SubTotal);
        }
        
        if (document.getElementById("CheckoutDiscount") != null)
        {
            if (Discount > 0)
            {
                document.getElementById("CheckoutDiscount").style.color = "red";
            }
            else
            {
                    document.getElementById("CheckoutDiscount").style.color = "black";
            }
        }
        
        var ShipText = ""
        if (Checkout.Cart.DiscountType == "S" && Checkout.Cart.DiscountValue == Checkout.Customer.Ship.Type)
        {
            ShipText = "(Free)"
        }
        
        var Taxes = 0;
        if (
             (Checkout.Customer.Bill.SameAsShip == true && Checkout.Customer.Ship.Country == "US" && Checkout.Customer.Ship.State == "KS")
             ||
             (Checkout.Customer.Bill.SameAsShip == false && Checkout.Customer.Bill.Country == "US" && Checkout.Customer.Bill.State == "KS")
            )
        {
            Taxes = (Checkout.TaxRate / 100) * Checkout.Cart.SubTotal;
        }
        
        
        document.getElementById("CheckoutSubTotal").innerHTML = Checkout.ToMoney(Checkout.Cart.SubTotal);
        document.getElementById("CheckoutDiscount").innerHTML = (Discount > 0 ? "-" : "")+Checkout.ToMoney(Discount);
        document.getElementById("CheckoutDiscountText").innerHTML = (Discount > 0 ? "(" + Checkout.Cart.Discount + ")" : "");
        document.getElementById("CheckoutShippingCost").innerHTML = Checkout.ToMoney(Checkout.Customer.Ship.Cost);
        document.getElementById("CheckoutFreeShippingText").innerHTML = ShipText;
        
        Checkout.Cart.Tax = Taxes;
        document.getElementById("CheckoutTax").innerHTML = Checkout.ToMoney(Taxes);
        
        Checkout.Cart.Total = (Checkout.Cart.SubTotal - Discount) + Checkout.Customer.Ship.Cost + Taxes
        document.getElementById("CheckoutTotal").innerHTML = Checkout.ToMoney(Checkout.Cart.Total);
    }
}

Checkout.GoogleCheckout = function()
{
    if (Checkout.Cart.IsEmpty)
    {
        alert(Checkout.Cart.EmptyText);
    }
    else
    {
        var _sSessionId = wsi._Cookie.GetCrumb("SessionID");
        document.location.href = "/checkout/GoogleCheckout.aspx?id="+_sSessionId;
    }
}

Checkout.EnableSmartMoneyOptions = function()
{
    
}

Checkout.PlaceOrder = function()
{

    if (Checkout.Cart.NoShipping)
    {
        Checkout.Customer.Bill.SameAsShip = false
    }
    
   /// Reset the Message
   document.getElementById("CardMessage").innerHTML = ""
   
   
   var aParameters = new wsi._Parameters();
//window.status = Checkout.Customer.InternalID();
    aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID") + Checkout.Cart.Name);
    aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
    aParameters.Add("customer_SalesRep", Checkout.Customer.SalesRep);
    aParameters.Add("customer_Email", Checkout.Customer.Email);
    aParameters.Add("customer_Password", Checkout.Customer.Password);
    
    aParameters.Add("ship_InternalId", Checkout.Customer.Ship.InternalId);
    aParameters.Add("ship_FirstName", Checkout.Customer.Ship.FirstName);
    aParameters.Add("ship_LastName", Checkout.Customer.Ship.LastName);
    aParameters.Add("ship_Company", Checkout.Customer.Ship.Company);
    aParameters.Add("ship_AddressLine1", Checkout.Customer.Ship.AddressLine1);
    aParameters.Add("ship_AddressLine2", Checkout.Customer.Ship.AddressLine2);
    aParameters.Add("ship_City", Checkout.Customer.Ship.City);
    aParameters.Add("ship_State", Checkout.Customer.Ship.State);
    aParameters.Add("ship_Zip", Checkout.Customer.Ship.Zip);
    aParameters.Add("ship_Country", Checkout.Customer.Ship.Country);
    aParameters.Add("ship_Phone", Checkout.Customer.Ship.Phone);
    aParameters.Add("ship_Type", Checkout.Customer.Ship.Type);
    aParameters.Add("ship_Cost", Checkout.Customer.Ship.Cost);
    aParameters.Add("ship_Memo", Checkout.Customer.Ship.Memo);

    aParameters.Add("bill_InternalId", Checkout.Customer.Bill.InternalId);
    aParameters.Add("bill_SameAsShip", (Checkout.Customer.Bill.SameAsShip ? "true" : "false"));
    aParameters.Add("bill_FirstName", Checkout.Customer.Bill.FirstName);
    aParameters.Add("bill_LastName", Checkout.Customer.Bill.LastName);
    aParameters.Add("bill_Company", Checkout.Customer.Bill.Company);
    aParameters.Add("bill_AddressLine1", Checkout.Customer.Bill.AddressLine1);
    aParameters.Add("bill_AddressLine2", Checkout.Customer.Bill.AddressLine2);
    aParameters.Add("bill_City", Checkout.Customer.Bill.City);
    aParameters.Add("bill_State", Checkout.Customer.Bill.State);
    aParameters.Add("bill_Zip", Checkout.Customer.Bill.Zip);
    aParameters.Add("bill_Country", Checkout.Customer.Bill.Country);
    aParameters.Add("bill_Phone", Checkout.Customer.Bill.Phone);

    aParameters.Add("card_InternalId", Checkout.Customer.CreditCard.InternalId);
    aParameters.Add("card_Type", Checkout.Customer.CreditCard.Type);
    aParameters.Add("card_NameOnCard", Checkout.Customer.CreditCard.NameOnCard);
    aParameters.Add("card_Number", Checkout.Customer.CreditCard.Number);
    aParameters.Add("card_ExpirationMonth", Checkout.Customer.CreditCard.ExpirationMonth);
    aParameters.Add("card_ExpirationYear", Checkout.Customer.CreditCard.ExpirationYear);
    aParameters.Add("card_CVV2", Checkout.Customer.CreditCard.CVV2);
    aParameters.Add("promotionCode", Checkout.Cart.PromotionCode);
    aParameters.Add("championStatus", Checkout.Customer.ChampionStatus);
    aParameters.Add("paymentMethod", Checkout.Customer.PaymentMethod());
    aParameters.Add("eBillMeAccount", Checkout.eBillme.GetAccountNumber());
    aParameters.Add("eBillMeOrderId", Checkout.eBillme.GetOrderNumber());
    aParameters.Add("ssn", Checkout.Customer.SSN);
    
 
    wsi._Soap.AddCall("PlaceOrder", Checkout.PlaceOrderReturn, aParameters);  

    /// HasAccount == false verifies that HasAccount is NOT true and NOT null
    if (Checkout.Customer.HasAccount() == false && Checkout.Customer.InternalID().length == 0)//  Checkout.Customer.Email.indexOf("safemart.com") > -1)
    {
        Checkout.Notification_CreateAccount();
    }
    else
    {
        Checkout.Notificaton_SubmitOrder();
    }
}

Checkout.CreatingPassword = false;
Checkout.SavePassword = false;

Checkout.Notification_CreateAccount = function()
{
    Checkout.CreatingPassword = true;

   
    document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
	document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("CreatAccountNotification").innerHTML;
    YAHOO.example.container.panel1.show();
}

Checkout.Notification_CreateAccount_GetPassword = function()
{
    Checkout.CreatingPassword = true;

    document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
    document.getElementById("CheckoutNotificationMessage").innerHTML = document.getElementById("GetPasswordNotification").innerHTML;
    YAHOO.example.container.panel1.show();
}

Checkout.Notification_CreatAccountReturn = function(returnValue)
{


    var PasswordConfirmed = true;
    var PasswordValid = true;

    if (returnValue != 'save')
    {// do not save the password.
        Checkout.Customer.Password = "";
        Checkout.Customer.PassConfirm = "";
    }
    else
    {
        Checkout.SavePassword = true;

        PasswordConfirmed = (Checkout.Customer.Password == Checkout.Customer.PassConfirm ? true : false)
        PasswordValid = Checkout.Customer.ValidatePassword();
        //window.status = PasswordConfirmed + " " + PasswordValid;        
        if (!PasswordConfirmed || !PasswordValid)
        {
            if (!PasswordConfirmed)
            {
                //document.getElementById("CreateAccountMsg").innerHTML = "Your Password Confirmation is different than your Password. Please re-type your Password.";
                alert("Your Password Confirmation is different than your Password. Please re-type your Password.");
            }
            else
            {
                //document.getElementById("CreateAccountMsg").innerHTML = "Your password must be at least 6 characters long and contain one number.";
                alert("Your password must be at least 6 characters long and contain one number.");
            }
            /*            
            document.getElementById("CreateAccountMsg").style.color = "red";
            document.getElementById("txtAccountPassword").value = "";
            document.getElementById("txtAccountPassConfirm").value = "";
            
            Checkout.Customer.Password = "";
            Checkout.Customer.PassConfirm = "";
            */

        }
    }

    if (PasswordConfirmed && PasswordValid)
    {
        Checkout.CreatingPassword = false;

        if (Checkout.PlaceOrderReturnValue.length > 0)
        {
            Checkout.Notificaton_SubmitOrder();
            Checkout.PlaceOrderReturn2();
        }
        else
        {
            Checkout.Notificaton_SubmitOrder();
        }
    }
}

Checkout.ChangePassword = function()
{
    var aParameters = new wsi._Parameters();
    aParameters.Add("customer_InternalID", Checkout.Customer.InternalID());
    aParameters.Add("customer_Email", Checkout.Customer.Email);
    aParameters.Add("customer_Password", Checkout.Customer.Password);
    
    wsi._Soap.AddCall("ChangeCustomerPassword", Checkout.ChangePasswordReturn, aParameters); 
}

Checkout.ChangePasswordReturn = function(returnValue)
{
    //alert(returnValue);
}
Checkout.Notificaton_SubmitOrder = function()
{
    document.getElementById("CheckoutNotificationCaption").innerHTML = "Submitting Order";
    document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Submitting your order.<br /><img src='/img/images/progress.gif' alt=''></center><br /><br />";
    YAHOO.example.container.panel1.show();
}

Checkout.PlaceOrderReturnValue = "";

Checkout.PlaceOrderReturn = function(returnValue)
{
    Checkout.PlaceOrderReturnValue = returnValue;
    
    if (!Checkout.CreatingPassword)
    {
        Checkout.PlaceOrderReturn2();
    }
    
}

Checkout.PlaceOrderReturn2 = function()
{
    var returnValue = Checkout.PlaceOrderReturnValue;

    YAHOO.example.container.panel1.hide(); /// close notificaion window.


    if (returnValue.indexOf("InternalId=") > -1)
    {
        Checkout.Customer.InternalID(returnValue.substring(returnValue.indexOf("InternalId=") + 11));
        returnValue = returnValue.substring(0, returnValue.indexOf("InternalId=") - 1);
    }

    if (returnValue.indexOf("Order created successfully") > -1)
    {

        Checkout.FetchBack.Purchase(Checkout.FetchBack.FetchBackPurchaseList);

        if (Checkout.Customer.InternalID().length > 0 && Checkout.SavePassword)
        {
            document.getElementById("CardMessage").innerHTML = "Creating User account...";
            Checkout.ChangePassword();
        }

        var _cOrderId = "";
        /// Strip off the order id
        if (returnValue.indexOf("OrderId=") > -1)
        {
            _cOrderId = returnValue.substring(returnValue.indexOf("|OrderId=") + 9);
            returnValue = returnValue.substring(0, returnValue.indexOf("OrderId=") - 1);
        }



        if (_cOrderId.length > 0)
        {
            Checkout.Google.Analytics(_cOrderId);
        }

        var ConfiramtionUrl = ""
        if (Checkout.eBillme.GetConfirmationPageUrl().length > 0)
        {
            ConfiramtionUrl = "&confirmationpageurl=" + Checkout.eBillme.GetConfirmationPageUrl();
        }

        var Host = ""
        /// The Quarantine site does not allow non-secure pages.
        if (document.location.host.toLowerCase().indexOf("quarantine") == -1)
        {
            Host = "http://" + document.location.host;
        }

        var ThankYou = "";
        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            ThankYou = "thank-you-sm.htm";
        }
        else
        {
            ThankYou = "thank-you.htm";
        }

        document.location.href = Host + "/" + ThankYou + "?orderId=" + _cOrderId + "&total=" + Checkout.RoundMoney(Checkout.Cart.Total) + "&qty=" + Checkout.Cart.Qty + ConfiramtionUrl;
    }
    else
    {
        if (Checkout.PayPalOrder)
        {
            document.getElementById("PayPalMessage").innerHTML = returnValue.replace("Error: ", "");
        }
        else
        {
            document.getElementById("CardMessage").innerHTML = returnValue.replace("Error: ", "");
        }
    }
}

Checkout.Google = new Object();
Checkout.Google.SubPageVisited = new Array();
Checkout.Google.TrackSubPage = function(subPage)
{
//alert(Checkout.Google.SubPageVisited[subPage]);
    if (Checkout.Google.SubPageVisited[subPage] != true)
    {

        /// Mark sub page visited.
        Checkout.Google.SubPageVisited[subPage] = true;
        
        /// Google Analytics - page tracking
        if (Checkout.Customer.InternalID().length == 0)
        {/// The customer is NOT logged in
            pageTracker._trackPageview("/Checkout/"+Checkout.GoogleAnalyticsSteps[subPage]);
            //window.status = "/Checkout/"+Checkout.GoogleAnalyticsSteps[subPage]; 
//alert("/Checkout/"+Checkout.GoogleAnalyticsSteps[subPage]);
        }
        else
        {/// The customer is  logged in
        
            /// Do not track Shipping Address for authenticated customers
            if (subPage != 1)
            {
                pageTracker._trackPageview("/Checkout/"+Checkout.GoogleAnalyticsReturnCustSteps[subPage]); 
                //window.status = "/Checkout/"+Checkout.GoogleAnalyticsReturnCustSteps[subPage];
//alert("/Checkout/"+Checkout.GoogleAnalyticsReturnCustSteps[subPage]);
            }
        }
    }
}
Checkout.Google.Analytics = function(orderId)
{
    var _Enable = true;
    
    if (_Enable)
    {
        pageTracker._addTrans(
        orderId,                           // Order ID
        "",                                // Affiliation
        "" + Checkout.Cart.Total,          // Total
        "" + Checkout.Cart.Tax,            // Tax
        "" + Checkout.Customer.Ship.Cost,  // Shipping
        Checkout.Customer.Ship.City,       // City
        Checkout.Customer.Ship.State,      // State
        Checkout.Customer.Ship.Country     // Country
        );

        var CartArray = Checkout.Cart.Raw.split("||");

        for (var iItems=0; iItems<CartArray.length; ++iItems)
        {
            
            var ItemProperties = CartArray[iItems].split("|");
            // <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>

              pageTracker._addItem(
                orderId,           // Order ID
                ItemProperties[7], // SKU
                ItemProperties[3], // Product Name
                "",                // Category
                ItemProperties[5], // Price
                ItemProperties[4]  // Quantity
              );
        }

        pageTracker._trackTrans();
    }
}
  
Checkout.CurrentStep = 0; //skip the login step
Checkout.Progress = 0; // start with the shipping address

Checkout.Steps = new Array();
Checkout.Steps[0] = "stepCart";
Checkout.Steps[1] = "stepAddress";
Checkout.Steps[2] = "stepBillingAddress";
Checkout.Steps[3] = "stepShippingOptions";
Checkout.Steps[4] = "stepPayment";

Checkout.GoogleAnalyticsSteps = new Array();
Checkout.GoogleAnalyticsSteps[0] = "Cart";
Checkout.GoogleAnalyticsSteps[1] = "ShippingAddress";
Checkout.GoogleAnalyticsSteps[2] = "BillingAddress";
Checkout.GoogleAnalyticsSteps[3] = "ShippingMethods";
Checkout.GoogleAnalyticsSteps[4] = "BillingInformation";

Checkout.GoogleAnalyticsReturnCustSteps = new Array();
Checkout.GoogleAnalyticsReturnCustSteps[0] = "ReturnCustCart";
Checkout.GoogleAnalyticsReturnCustSteps[1] = "ReturnCustShippingAddress";
Checkout.GoogleAnalyticsReturnCustSteps[2] = "ReturnCustBillingAddress";
Checkout.GoogleAnalyticsReturnCustSteps[3] = "ReturnCustShippingMethods";
Checkout.GoogleAnalyticsReturnCustSteps[4] = "ReturnCustBillingInformation";

Checkout.NextStep = function()
{
    /// If there are no products requiring shipping, skip the shipping address and go to billing
    if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep + 1] == "stepAddress")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    /// if the next step is the billing address
    /// and the billing address is the same as the shipping
    //// skip the billing address step.
    else if (Checkout.Steps[Checkout.CurrentStep + 1] == "stepBillingAddress"
        && Checkout.Customer.Bill.SameAsShip)
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    else if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep + 1] == "stepShippingOptions")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 2]);
    }
    else
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep + 1]);
    }
}

Checkout.PrevStep = function()
{
    /// if the previous step is the billing address
    /// and the billing address is the same as the shipping
    //// go to the shipping address step.
    if (!Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep - 1] == "stepBillingAddress"
        && Checkout.Customer.Bill.SameAsShip)
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 2]);
    }
    else if (Checkout.Cart.NoShipping && Checkout.Steps[Checkout.CurrentStep - 1] == "stepShippingOptions")
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 2]);
    }
    else
    {
        Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep - 1]);
    }
}

Checkout.ShowStep = function(showThis)
{
    if (showThis != "stepAddress")
    {
        document.location.hash = "checkouttop";
    }
    
    Checkout.CollapseStep(Checkout.Steps[Checkout.CurrentStep]);
    Checkout.CurrentStep = Checkout.Steps.find(showThis);

    var ThisStep = document.getElementById(showThis);
    var ThisCaption = document.getElementById(showThis + "-Caption");
    var ThisBody = document.getElementById(showThis + "-Body");
    var ThisExpandImage = document.getElementById(showThis + "-ExpandImage");

    // Show the Step
    ThisStep.style.display = "block";
    ThisCaption.style.display = "block";
    ThisBody.style.display = "block";

    // Set the expand image
    if (showThis == "stepCart")
    {
        //ThisExpandImage.src = "../graphics/minus_compact.png"
    }

    Checkout.SetProgress();

    Checkout.Google.TrackSubPage(Checkout.CurrentStep);
}

Checkout.ActivateStep = function(activateThis)
{
    var ThisStep = document.getElementById(activateThis);
    var ThisCaption = document.getElementById(activateThis + "-Caption");
    var ThisBody = document.getElementById(activateThis + "-Body");

    // Show the Step
    ThisStep.style.display = "block";
    ThisCaption.style.display = "block";
    ThisBody.style.display = "block";

}

Checkout.SetProgress = function()
{

    var ActiveGraphic = (Checkout.CurrentStep < 2 ? 1 : Checkout.CurrentStep - 1)

    // Set the current step active
    if (Checkout.CurrentStep > 0)
    {
        var ThisProgress = document.getElementById("Progress" + ActiveGraphic);
        //if (ThisProgress.innerHTML.length == 0 || ThisProgress.innerHTML.indexOf("inactive") > -1)
        if (ThisProgress.src.indexOf("inactive") > -1)
        {
            //ThisProgress.innerHTML = "<img src='/graphics/cart-progress" + ActiveGraphic + "-active.gif'>";
            ThisProgress.src = "/graphics/cart-progress" + ActiveGraphic + "-active.gif";
        }
    }

    // Set the next steps inactive
    for (var i = ActiveGraphic + 1; i < 4; ++i)
    {
        var ThisProgress = document.getElementById("Progress" + i);
        if (ThisProgress.innerHTML.indexOf("inactive") == -1)
        {
            //ThisProgress.innerHTML = "<img src='/graphics/cart-progress" + i + "-inactive.gif'>";
            ThisProgress.src = "/graphics/cart-progress" + i + "-inactive.gif";
        }
    }

    Checkout.Progress = Checkout.CurrentStep;
}

Checkout.CollapseStep = function(hideThis)
{
    var ThisStep = document.getElementById(hideThis);
    var ThisCaption = document.getElementById(hideThis + "-Caption");
    var ThisBody = document.getElementById(hideThis + "-Body");
    var ThisExpandImage = document.getElementById(hideThis + "-ExpandImage");

    ThisStep.style.display = "none";
    //ThisBody.style.display = "none";

    // Set the expand image
    //ThisExpandImage.src = "../graphics/plus_compact.png"

    // Always collapse the Login
    document.getElementById("stepCart-Body").style.display = "none";
    //document.getElementById("stepLogin-ExpandImage").src = "../graphics/plus_compact.png";
}

Checkout.ToggleStep = function(toggleThis)
{

    var ThisBody = document.getElementById(toggleThis+"-Body");
    
    if (ThisBody.style.display == "none")
    {
        Checkout.ShowStep(toggleThis);
    }
    else
    {
        Checkout.CollapseStep(toggleThis);
    }

}

Checkout.SetStateField = function(toggleThis)
{
    if (toggleThis == "Ship")
    {

        var sAddress = Checkout.Customer.Ship;            
    }
    else
    {
        var sAddress = Checkout.Customer.Bill;
    }
//alert(sAddress.Country)
    switch(sAddress.Country)
    {
        case "US":
            document.getElementById("txt"+toggleThis+"StateProvince").style.display = "none";
            document.getElementById("div"+toggleThis+"StateProvince").style.display = "block";
            //document.getElementById("opt"+toggleThis+"StateProvince").style.display = "inline";
            document.getElementById("div"+toggleThis+"StateProvince_Canada").style.display = "none";
            
            //document.getElementById("opt"+toggleThis+"StateProvince").value = sAddress.State;
            document.getElementById("opt"+toggleThis+"StateProvince").value = sAddress.StateDomestic;
            sAddress.State = sAddress.StateDomestic;
            break;
        
        
        case "CA":
            document.getElementById("txt"+toggleThis+"StateProvince").style.display = "none";
            document.getElementById("div"+toggleThis+"StateProvince").style.display = "none";
            //document.getElementById("opt"+toggleThis+"StateProvince").style.display = "none";
            document.getElementById("div"+toggleThis+"StateProvince_Canada").style.display = "block";
            //document.getElementById("opt"+toggleThis+"StateProvince_Canada").value = sAddress.State;
            
            document.getElementById("opt"+toggleThis+"StateProvince_Canada").value = sAddress.StateCanada;
            sAddress.State = sAddress.StateCanada;
            break;
            
        default:
            document.getElementById("txt"+toggleThis+"StateProvince").style.display = "block";
            document.getElementById("div"+toggleThis+"StateProvince").style.display = "none";
            document.getElementById("div"+toggleThis+"StateProvince_Canada").style.display = "none";
            //document.getElementById("txt"+toggleThis+"StateProvince").value = sAddress.State;  
            
            document.getElementById("txt"+toggleThis+"StateProvince").value = sAddress.StateInternational;
            sAddress.State = sAddress.StateInternational;
            break;
            
        
    }
}

Checkout.ToggleCountryField = function(toggleThis)
{

   
    if (toggleThis == "Ship")
    {

        var Address = Checkout.Customer.Ship;            
    }
    else
    {
        var Address = Checkout.Customer.Bill;
    }
        
    if (document.getElementById("lbl"+toggleThis+"CountryID").style.display != "none")
    {/// Change to International
    
    
        /// Save State
        switch(Address.Country)
        {
            case "CA":
                Address.StateCanada = Address.State;
                break;
                
            case "US":
                Address.StateDomestic = Address.State;
                break;
                
            default:
                Address.StateInternational = Address.State;
                break;
        }
        
         /// Restore International Country
        Address.Country = Address.CountryInternational;
        
/*
        /// Restore State
        switch(Address.Country)
        {
            case "CA":
                Address.State = Address.StateCanada;
                break;
                
            case "US":
                Address.State = Address.StateDomestic;
                break;
                
            default:
                Address.State = Address.StateInternational;
                break;
        }
        */
             
        
        
        document.getElementById("lbl"+toggleThis+"CountryID").style.display = "none";
        document.getElementById("txt"+toggleThis+"CountryID").style.display = "block";
        //document.getElementById("lnk"+toggleThis+"CountryToggle").innerHTML = "Click Here for Domestic Addresses";
        document.getElementById("lbl"+toggleThis+"StateProvince").innerHTML = "State/Province";
        document.getElementById("lbl"+toggleThis+"ZipPostalCode").innerHTML = "Zip/Postal Code";
        
        /// SHILL 9/15/08 Added 
        /// Switch to international Phone field
        document.getElementById("Domestic"+toggleThis+"Phone").style.display = "none";
        document.getElementById("International"+toggleThis+"Phone").style.display = "block";
        document.getElementById("txt"+toggleThis+"PhoneNumber").value = Address.Phone;
        /// End Added
        
    }
    else
    {/// Change to Domestic
    
        /// Save International Country
        Address.CountryInternational = Address.Country;
        /// Change to US
        Address.Country = "US";
        
        /// Save Internationl State
        if (Address.CountryInternational == "CA")
        {
            Address.StateCanada = Address.State;
        }
        else
        {
            Address.StateInternational = Address.State;
        }
        /// Restore Domestic State
        //Address.State = Address.StateDomestic;
            
            
        document.getElementById("lbl"+toggleThis+"CountryID").style.display = "block";
        document.getElementById("txt"+toggleThis+"CountryID").style.display = "none";  
        //document.getElementById("lnk"+toggleThis+"CountryToggle").innerHTML = "Click Here for International Addresses";
        document.getElementById("lbl"+toggleThis+"StateProvince").innerHTML = "State";
        document.getElementById("lbl"+toggleThis+"ZipPostalCode").innerHTML = "Zip Code";
        //document.getElementById("txt"+toggleThis+"StateProvince").value = document.getElementById("opt"+toggleThis+"StateProvince").value;

        /// SHILL 9/15/08 Added
        /// Switch to domestic phone format
        document.getElementById("Domestic"+toggleThis+"Phone").style.display = "block";
        document.getElementById("International"+toggleThis+"Phone").style.display = "none";
        Checkout.UpdatePhone(toggleThis);
        /// End Added
    }
    
    Checkout.SetStateField(toggleThis);
}

Checkout.HideAllSteps = function()
{
    for(var i=0; i<Checkout.Steps.length; i++)
    {
        document.getElementById(Checkout.Steps[i]).style.display = "none";
    }
}

Checkout.ShowSubstep = function(subStep)
{
    document.getElementById(subStep).style.display = "block";
}

Checkout.HideSubstep = function(subStep)
{
    document.getElementById(subStep).style.display = "None";
}

Checkout.ShowEbillmeSubstep = function()
{
    Checkout.HideSubstep('substepCardInfo');
    Checkout.ShowSubstep('substepEbillme');
    document.getElementById("uiSubmitBtn").style.display = "none";
}

Checkout.ShowCreditCardSubstep = function()
{
    Checkout.HideSubstep('substepEbillme');
    Checkout.ShowSubstep('substepCardInfo');
    document.getElementById("uiSubmitBtn").style.display = "inline";
}

/// Check for empty data 
Checkout.CheckEmpty = function(requiredFieldsArray, requiredDataArray, failureField, failureMessage)
{
    var EmptyFound = false
    for (var i=0; i<requiredDataArray.length; i++)
    {

        if(requiredDataArray[i].length == 0)
        {
            document.getElementById(failureField).innerHTML = failureMessage;
            EmptyFound = true
        }
    }
    
    if (!EmptyFound) document.getElementById(failureField).innerHTML = "";
    
    return EmptyFound;
}

Checkout.ValidZip = function(zip, country, failureField)
{
    zip = zip.toUpperCase();
    var regex = /((^\d{5}([- |]\d{4})?$)|(^[A-Z]\d[A-Z][- |]\d[A-Z]\d$))/;
    var Valid = false;
    var CountryLong = ""
      
    if (country.length > 0)
    {
        switch(country)
        {
            case "US" :
                /// 55555
                /// 55555-5555
                if (zip.search(/^\d{5}(-\d{4})?$/) != -1)
                {
                    Valid = true;
                }
                CountryLong = "US";
                
                break;
                
            case "CA" :
                /// X5X 5X5
                /// X5X-5X5
                /// X5X5X5
                if (zip.search(/^[A-Z]{1}\d{1}[A-Z]{1}[ |-]*\d{1}[A-Z]{1}\d{1}$/) != -1)
                {
                    Valid = true;
                }
                CountryLong = "Canadian";
                break;
                
            default:
                Valid = true;
                break;
        }
        
        /// If invalid return the message.
        if (Valid) 
        {
            document.getElementById(failureField).innerHTML = "";
        }
        else
        {
            document.getElementById(failureField).innerHTML = "Please enter a valid " + CountryLong + " zip code.";
        }
        
    }


    return Valid;
}

Checkout.FormHandler = new Safemart.FormHandler("","","");

Checkout.UpdatePhone = function(what)
{
    var Phone
    Phone = document.getElementById("txt"+what+"PhoneArea").value;
    Phone += document.getElementById("txt"+what+"PhonePrefix").value;
    Phone += document.getElementById("txt"+what+"PhoneSuffix").value;
    
    if (what == "Ship")
    {
        Checkout.Customer.Ship.Phone = Phone;
    }
    else if (what == "Bill")
    {
        Checkout.Customer.Bill.Phone = Phone;
    }
    
}

Checkout.ValidateStepAddress = function()
{

    var Validated = true;

    var FieldCount = 0

    var RequiredFields = new Array();
    RequiredData = new Array();

    RequiredData[FieldCount] = Checkout.Customer.Ship.FirstName;
    RequiredFields[FieldCount++] = "txtShipFirstName";

    RequiredData[FieldCount] = Checkout.Customer.Ship.LastName;
    RequiredFields[FieldCount++] = "txtShipLastName";

    RequiredData[FieldCount] = Checkout.Customer.Ship.AddressLine1;
    RequiredFields[FieldCount++] = "txtShipAddress1";

    RequiredData[FieldCount] = Checkout.Customer.Ship.City;
    RequiredFields[FieldCount++] = "txtShipCity";

    RequiredData[FieldCount] = Checkout.Customer.Ship.Zip;
    RequiredFields[FieldCount++] = "txtShipZipPostalCode";

    if (Checkout.Customer.Ship.Country != "US")
    {
        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            Validated = false;
            document.getElementById("Shipmessage").innerHTML = document.getElementById("SmUsOnlyMessage").innerHTML;
        }

        RequiredData[FieldCount] = Checkout.Customer.Ship.Phone;
        RequiredFields[FieldCount++] = "txtShipPhoneNumber";
    }

    if (!Checkout.Customer.InternalIP)
    {
        RequiredData[FieldCount] = Checkout.Customer.Email;
        RequiredFields[FieldCount++] = "txtCustomerEmail";
    }

    //RequiredFields[6] = Checkout.Customer.Ship.Country;

    if (Checkout.Customer.Ship.Country == "CA")
    {
        RequiredData[FieldCount] = Checkout.Customer.Ship.State;
        RequiredFields[FieldCount++] = "txtShipStateProvince";
    }

    /// Stop checking if invalid data has already been found.
    if (Validated)
    {
        var FailureMessage = "All required fields must be completed."

        if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "Shipmessage", FailureMessage))
        {// all required fields not empty   

            if (!Checkout.ValidZip(Checkout.Customer.Ship.Zip, Checkout.Customer.Ship.Country, "Shipmessage"))
            {// invalid Zip
                Validated = false;
                //document.getElementById("Shipmessage").innerHTML = Checkout.Customer.Bill.InvalidPhoneMsg;
            }

            if (!Checkout.Customer.InternalIP)
            {
                if (!Checkout.Customer.IsEmailValid())
                { /// invalid email
                    Validated = false;
                    document.getElementById("Shipmessage").innerHTML = "Please include a valid email address.";
                }
            }

            /// validate Phone if US
            if (Checkout.Customer.Ship.Country == "US")
            {
                if (!Checkout.Customer.Ship.IsPhoneValid())
                { /// invalid Phone
                    document.getElementById("Shipmessage").innerHTML = Checkout.Customer.Ship.InvalidPhoneMsg;
                    Validated = false;
                }
            }


        }
        else
        {
            Validated = false;
        }
    }
    //document.getElementById("Shipmessage").innerHTML += "  " + Checkout.Customer.Ship.State + "-" + Checkout.Customer.Ship.Country
    if (Validated)
    {
        Checkout.Customer.Ship.GetMethods();

        if (document.getElementById("ShippingOptionsDisclamer") != null)
        {
            if (Checkout.Customer.Ship.Country == "CA")
            {
                document.getElementById("ShippingOptionsDisclamer").style.display = "block";
            }
            else
            {
                document.getElementById("ShippingOptionsDisclamer").style.display = "none";
            }
        }
        var aParameters = new wsi._Parameters();
        aParameters.Add("email", Checkout.Customer.Email);
        wsi._Soap.AddCall("HasAccountCheck", Checkout.Customer.HasAccountCheckReturn, aParameters);

        Checkout.NextStep();
    }
}

Checkout.ValidateStepBillingAddress = function()
{
    //window.status = "ID" +   Checkout.Customer.InternalID();
    
    var Validated = true;
    //if(!Checkout.Customer.Bill.SameAsShip)
    //{

    var FieldCount = 0

    var RequiredFields = new Array();
    var RequiredData = new Array();

    RequiredData[FieldCount] = Checkout.Customer.Bill.FirstName;
    RequiredFields[FieldCount++] = "txtBillFirstName";

    RequiredData[FieldCount] = Checkout.Customer.Bill.LastName;
    RequiredFields[FieldCount++] = "txtBillLastName";

    RequiredData[FieldCount] = Checkout.Customer.Bill.AddressLine1;
    RequiredFields[FieldCount++] = "txtBillAddress1";

    RequiredData[FieldCount] = Checkout.Customer.Bill.City;
    RequiredFields[FieldCount++] = "txtBillCity";

    RequiredData[FieldCount] = Checkout.Customer.Bill.Zip;
    RequiredFields[FieldCount++] = "txtBillZipPostalCode";

    if (Checkout.Customer.Bill.Country != "US")
    {
        RequiredData[FieldCount] = Checkout.Customer.Bill.Phone;
        RequiredFields[FieldCount++] = "txtBillPhoneNumber";
    }
    
    if (Checkout.Cart.NoShipping && !Checkout.Customer.InternalIP)
    {
        RequiredData[FieldCount] = Checkout.Customer.Email;
        RequiredFields[FieldCount++] = "txtCustomerBillEmail";
    }

    if (Checkout.Customer.Bill.Country == "CA")
    {
        RequiredData[FieldCount] = Checkout.Customer.Bill.State;
        RequiredFields[FieldCount++] = "txtBillStateProvince";
    }

    var FailureMessage = "All required fields must be completed."

    if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "BillMessage", FailureMessage))
    {
        
        if (!Checkout.ValidZip(Checkout.Customer.Bill.Zip, Checkout.Customer.Bill.Country, "BillMessage"))
        {// invalid Zip
            document.getElementById("BillMessage").innerHTML =  "Please include a valid Zip Code.";
            Validated = false;
        }

        /// validate Phone if US
        if (Checkout.Customer.Bill.Country == "US")
        {
            if (!Checkout.Customer.Bill.IsPhoneValid())
            { /// invalid Phone
                document.getElementById("BillMessage").innerHTML = Checkout.Customer.Bill.InvalidPhoneMsg;
                Validated = false;
            }
        }

        if (Checkout.Cart.NoShipping && !Checkout.Customer.InternalIP)
        {
            if (!Checkout.Customer.IsEmailValid())
            { /// invalid email
                Validated = false;
                document.getElementById("BillMessage").innerHTML = "Please include a valid email address.";
            }
        }
    }
    else
    {
        Validated = false;
    }

    //}
    
    /// if all fields validate
    if (Validated)
    {
        Checkout.SetTotals();
        Checkout.NextStep();
    }
}

Checkout.ValidateShippingOptions = function()
{
    /// Clear previous values
    Checkout.Customer.Ship.Type = "";
    Checkout.Customer.Ship.Cost = 0;

    // Validate fields

    // if all fields validate

    for (var i = 0; i < document.getElementsByName("ShippingOption").length; i++)
    {
        if (document.getElementsByName("ShippingOption")[i].checked)
        {
            var ShipValue = document.getElementsByName("ShippingOption")[i].value;
            var ShipArray = ShipValue.split("|");
            Checkout.Customer.Ship.Type = ShipArray[0];
            Checkout.Customer.Ship.Cost = parseFloat(ShipArray[1]);
        }
    }
    //alert(Checkout.Customer.Ship.Type.length);

    if (Checkout.Customer.Ship.Type.length == 0)
    {
        document.getElementById("ShipMethodMessage").innerHTML = "Please select a shipping options.";
    }
    else
    {
        Checkout.SetTotals();

        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            document.getElementById("uiSsnLabel").style.display = "block";
            document.getElementById("uiSnn").style.display = "block";
        }

        if (Checkout.eBillme.Enabled() == false)
        {
            document.getElementById("uiBillingMethods-ebillme").style.display = "none";
            document.getElementById("uiEbillmeLogo").style.display = "none";
            document.getElementById("uiEbillmeLink").style.display = "none";
            document.getElementById("uiBillingMethods-cc").style.display = "none";
            Checkout.ShowSubstep('substepCardInfo');
            document.getElementById("uiSubmitBtn").style.display = "inline";
        }
        else
        {
            document.getElementById("uiBillingMethods-ebillme").style.display = "inline";
            document.getElementById("uiEbillmeLogo").style.display = "inline";
            document.getElementById("uiEbillmeLink").style.display = "inline";
            document.getElementById("uiBillingMethods-cc").style.display = "inline";

            //Checkout.HideSubstep("substepCardInfo");
            //Checkout.HideSubstep("substepEbillme");
        }

        if (Checkout.PayPalOrder)
        {
            Checkout.HideSubstep("stepShippingOptions");
            Checkout.ShowStep("stepPayPalConfirmation");
        }
        else
        {
            Checkout.NextStep();
        }
    }
}


Checkout.ShowNoFreeShippingOverlay = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["NoFreeShipOverlayLink", "tl", "tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("NoFreeShipOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}


Checkout.HideNoFreeShippingOverlay = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ShowCVV2 = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["Whatiscvv2","tl","tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("CvvOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}


Checkout.HideCVV2 = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ShowWhySSN = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["uiWhySnn","tl","tr"]);
    YAHOO.example.container.overlay1.setBody(document.getElementById("WhySnnOverlay").innerHTML);
    YAHOO.example.container.overlay1.show();
}

Checkout.HideWhySSN = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ValidateCreditCard = function()
{


    if (!Checkout.eBillme.Enabled())
    {
        Checkout.Customer.PaymentMethod("cc");
    }

    if (Checkout.Customer.PaymentMethod() == "")
    {
        document.getElementById("CardMessage").innerHTML = "Please select a payment method.";
    }
    else if (Checkout.Customer.PaymentMethod() == "eBillMe")
    {
        if (Checkout.Customer.Email.length > 0)
        {
            /*
            EbillmePreAuthorize(string sessionId, string customer_Email, string ship_FirstName, string ship_LastName,
                        string ship_Company, string ship_AddressLine1, string ship_AddressLine2, string ship_City, string ship_State,
                        string ship_Zip, string ship_Country, string ship_Phone, string ship_Type, string ship_Cost, string bill_SameAsShip,
                        string bill_FirstName, string bill_LastName, string bill_Company, string bill_AddressLine1, string bill_AddressLine2,
                        string bill_City, string bill_State, string bill_Zip, string bill_Country, string bill_Phone, string totalPrice)
            */  
            
       
            var aParameters = new wsi._Parameters();
            aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
            aParameters.Add("customer_Email", Checkout.Customer.Email);
            
            aParameters.Add("ship_FirstName", Checkout.Customer.Ship.FirstName);
            aParameters.Add("ship_LastName", Checkout.Customer.Ship.LastName);
            aParameters.Add("ship_Company", Checkout.Customer.Ship.Company);
            aParameters.Add("ship_AddressLine1", Checkout.Customer.Ship.AddressLine1);
            aParameters.Add("ship_AddressLine2", Checkout.Customer.Ship.AddressLine2);
            aParameters.Add("ship_City", Checkout.Customer.Ship.City);
            aParameters.Add("ship_State", Checkout.Customer.Ship.State);
            aParameters.Add("ship_Zip", Checkout.Customer.Ship.Zip);
            aParameters.Add("ship_Country", Checkout.Customer.Ship.Country);
            aParameters.Add("ship_Phone", Checkout.Customer.Ship.Phone);
            aParameters.Add("ship_Type", Checkout.Customer.Ship.Type);
            aParameters.Add("ship_Cost", Checkout.Customer.Ship.Cost);
            aParameters.Add("bill_SameAsShip", (Checkout.Customer.Bill.SameAsShip ? "true" : "false"));
            aParameters.Add("bill_FirstName", Checkout.Customer.Bill.FirstName);
            aParameters.Add("bill_LastName", Checkout.Customer.Bill.LastName);
            aParameters.Add("bill_Company", Checkout.Customer.Bill.Company);
            aParameters.Add("bill_AddressLine1", Checkout.Customer.Bill.AddressLine1);
            aParameters.Add("bill_AddressLine2", Checkout.Customer.Bill.AddressLine2);
            aParameters.Add("bill_City", Checkout.Customer.Bill.City);
            aParameters.Add("bill_State", Checkout.Customer.Bill.State);
            aParameters.Add("bill_Zip", Checkout.Customer.Bill.Zip);
            aParameters.Add("bill_Country", Checkout.Customer.Bill.Country);
            aParameters.Add("bill_Phone", Checkout.Customer.Bill.Phone);
            aParameters.Add("totalPrice", Checkout.RoundMoney(Checkout.Cart.Total));
       
            wsi._Soap.AddCall("PreAuthorize_eBillme", Checkout.eBillme.PreAuthorizeReturn, aParameters); 
        }
        else
        {
            alert("An email address is required to use the eBillme option.");
        } 
    }
    else
    {
        var RequiredFields = new Array();
        RequiredFields[0] = "txtFirstNameOnCard";
        RequiredFields[1] = "txtCardNumber";
        RequiredFields[2] = "intMonth";
        RequiredFields[3] = "intYear";
        //RequiredFields[4] = "txtCWCode";
        
        RequiredData = new Array();
        RequiredData[0] = Checkout.Customer.CreditCard.NameOnCard;
        RequiredData[1] = Checkout.Customer.CreditCard.Number;
        RequiredData[2] = Checkout.Customer.CreditCard.ExpirationMonth;
        RequiredData[3] = Checkout.Customer.CreditCard.ExpirationYear;
        RequiredData[4] = Checkout.Customer.CreditCard.CVV2;
        
        if (Checkout.Cart.ContainsSmartMoneyPackage)
        {
            RequiredData[5] = Checkout.Customer.SSN;
        }

        var FailureMessage = "All required fields must be completed."
        
        if (!Checkout.CheckEmpty(RequiredFields, RequiredData, "CardMessage", FailureMessage))
        {
            var PasswordGood = (Checkout.Customer.Password == Checkout.Customer.PassConfirm ? true : false)
            var SsnGood = (!Checkout.Cart.ContainsSmartMoneyPackage || Checkout.Customer.IsSsnValid() ? true : false)

            if (!SsnGood)
            { /// Invalid SSN
                document.getElementById("CardMessage").innerHTML = "Invalid Social security number. Please re-type your SSN.";
            }
            else if (Checkout.Customer.InternalID().length == 0 && !PasswordGood)
            { /// The password and the confirmed password do not match.
              /// Customers who are logged in are not prompted to create an account
            
                document.getElementById("CardMessage").innerHTML = "Your Password Confirmation is different than your Password. Please re-type your Password.";
                document.getElementById("txtAccountPassword").value = "";
                document.getElementById("txtAccountPassConfirm").value = "";
                
                Checkout.Customer.Password = "";
                Checkout.Customer.PassConfirm = "";
                

            }
            else
            { /// Passed validation
                Checkout.PlaceOrder();
            }
        }
    }
 }


Checkout.ValidateQty = function(what, checkBlank)
{
    if (typeof(checkBlank) == "undefined") checkBlank = false;
    
    var MainProductQty = what.value;
    if (MainProductQty.match(/[^0-9]/))
    {
        /// Strip all non numeric characters
        what.value = MainProductQty.replace(/[^0-9]/g, "");
    }
    
    /// Don't allow 0 Qty
    if (MainProductQty == "0")
    {
        what.value = "1";
    }
    
    if (checkBlank)
    {
        if (what.value.length == 0)
        {
            what.value = what.getAttribute("defaultvalue");
        }
    }
}

// The following functions could be used globally

function ClearInputExample(who)
{
    if(who.style.fontStyle == 'italic')
    {
        who.value='';
        who.style.color='black';
        who.style.fontStyle='normal';
    }
}


var CartProcessor = function()
{

    /// Cart Items are saved in this format
    /// <GroupId>|<ParentId>|<NetSuiteID>|<Title>|<Qty>|<Unit Price>|<Unit Weight>|<SKU>|<Img>|<URL>

    /// <summary>
    /// Add a Product to the Cart
    /// </summary>
    /// <param name="item">The product to be added</param>
    this.AddToCart = function(item)
    {
        /// Get the current cart
        var CartData = this.GetCart();
        
        /// If the cart is not empty add a delimiter
        if (CartData.length > 0)
        {
            CartData += "||";
        }
        
        /// Add the item to the cart
        CartData += item;
        
        /// Save the cart
        SaveCart(CartData);
        
        /// Return the cart
        return CartData;
    }
    
    /// <summary>
    /// Update the Qty for a Product
    /// </summary>
    /// <param name="groupId">The Group Id for the product to be updated</param>
    /// <param name="qty">The new Quantity</param>
    /// <returns>The Cart Data</returns>
    this.UpdateQty = function(groupId, qty)
    {
        /// Get the current cart
        var CartData = this.GetCart();
        
        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");
            
            /// To hold the array position of the main item
            var FoundMain = null;
            var BaseQty = null;
            
            /// Search for the Main item
            for (var i=0; i<ItemArray.length; ++i)
            {
                /// Split the Item
                var ItemProperties = ItemArray[i].split("|");
            
                if (ItemProperties[0] == groupId && ItemProperties[1] == "0")
                {
                    /// Store the Main item
                    FoundMain = i
                    BaseQty = ItemProperties[4];
                    break;    
                }
            }
            
            if (FoundMain != null)
            {
                if (qty.length > 0)
                {
                
                    for (var i=0; i<ItemArray.length; ++i)
                    {
                        /// Split the Item
                        var ItemProperties = ItemArray[i].split("|");
                            
                        if (ItemProperties[0] == groupId)
                        {
                            /// Get the new Qty
                            var NewQty = null;
                            if (ItemProperties[1] == "0")
                            {
                                NewQty = qty;
                            }
                            else
                            {
                                NewQty = (ItemProperties[4] / BaseQty) * qty;
                            }
                            
                            /// Update the Qty
                            ItemProperties[4] = NewQty;
                            
                            /// Push the update back into the array.
                            ItemArray[i] = ItemProperties.join("|");
                            
                            /// Save the cart
                            CartData = ItemArray.join("||")
                            SaveCart(CartData);  
                        }
                    }
                }
                else
                {
                    /// Remove zero Qty items
                    CartData = RemoveFromCart(groupId);
                }
            }
        }
        
        return CartData;
    }
    
    /// <summary>
    /// Get the Sub-Total of all items in the cart. Addons are included in the Sub-Total.
    /// </summary>
    this.CartTotal = function()
    {
        /// Get the current cart
        var CartData = this.GetCart();
        
        var Total = 0;
        
        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");
            
            /// Get the Cart Total
            
            for (var iItems=0; iItems<ItemArray.length; ++iItems)
            {
                /// Split the Item
                var ItemProperties = ItemArray[iItems].split("|");
            
                var Qty = ItemProperties[4]
                var UnitPrice = ItemProperties[5]
                
                /// Add Item price to total
                Total += parseFloat(UnitPrice) * parseInt(Qty);

            }
        }
        
        /// Convert the total to money
        Total = SWH.ToMoney(Total,false);
        
        /// String the 
        /// Return the total
        return Total;
        
    }
    
    /// <summary>
    /// Get the number of items in the cart. Addons are excluded from the count
    /// </summary>
    this.CartQty = function()
    {
        /// Get the current cart
        var CartData = this.GetCart();
        var Qty = 0;
       
        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");
            
            /// Get the Cart Qty
            for (var iItems=0; iItems<ItemArray.length; ++iItems)
            {
                /// Split the Item
                var ItemProperties = ItemArray[iItems].split("|");
                
                /// Do not include Addons in the Qty count
                if (ItemProperties[1] == 0)
                {
                    Qty += parseInt(ItemProperties[4]);
                }
            }
        }
        /// Return the Qty
        return Qty;
    }
    
    /// <summary>
    /// Get a comma deliminted list of Id
    /// </summary>
    this.GetIdList = function()
    {
    
    }
    
    /// <summary>
    /// Remove a Product from the cart.
    /// </summary>
    /// <param name="groupId">The Group Id for the product to be removed</param>
    this.RemoveFromCart = function(groupId)
    {
        /// Get the current cart
        var CartData = this.GetCart();
        
        /// Is the cart is empty?
        if (CartData.length > 0)
        {
            var ItemArray = CartData.split("||");
            
            /// Search for items in reverse order.
            for (var i=ItemArray.length-1; i<=0; --i)
            {
                /// Split the Item
                var ItemProperties = ItemArray[i].split("|");
            
                if (ItemProperties[0] == groupId)
                {
                    ItemArray.splice(Found,1);
                }
            }
            

            if (ItemArray.length == 0)
            {
                /// Empty cart
                this.ClearCart();
            }
            else
            {
                CartData = ItemArray.join("||")
                SaveCart(CartData);           
            }
        }
        
        return CartData;
    }
    
    /// <summary>
    /// Remove all Products from the Cart.
    /// </summary>
    this.ClearCart = function()
    {
        SaveCart("");
    }
       
    /// <summary>
    /// Get all the Products from the Cart.
    /// </summary>
    this.GetCart = function()
    {
        var CartData = (wsi._Cookie.GetCrumb("cart") == null ? "" : wsi._Cookie.GetCrumb("cart"));
//alert("GetCart\r\n\r\n"+CartData);
        return CartData
    }
    
    /// <summary>
    /// Commit the Cart to Cookies. The previous value will be over-writen.
    /// </summary>
    /// <param name="cartData">The new Cart</param>
    var SaveCart = function(cartData)
    {
        wsi._Cookie.SaveCrumb("cart", cartData);
    }
}

if (Checkout.Cart.Mode == "Cookie")
{
    Checkout.CartProcessor = new CartProcessor();
}
else
{
    Checkout.CartProcessor = null;
}
