/// <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 (!Array.prototype.findAt)
//{
    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 = "AL";/// 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";/// Default value
Checkout.Customer.Ship.CountryInternational = "US"; /// Extended from Base Class
Checkout.Customer.Bill.State = "AL";/// 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";/// Default value
Checkout.Customer.Bill.CountryInternational = "US"; /// Extended from Base Class

/*
Checkout.Customer = new Object();
Checkout.Customer.SalesRep = "";
Checkout.Customer.InternalID = "";
Checkout.Customer.Email = "";
Checkout.Customer.Password = "";
Checkout.Customer.PassConfirm = "";
Checkout.Customer.Ship = new Object();
Checkout.Customer.Ship.InternalId = "";
Checkout.Customer.Ship.FirstName = "";
Checkout.Customer.Ship.LastName = "";
Checkout.Customer.Ship.Company = "";
Checkout.Customer.Ship.AddressLine1 = "";
Checkout.Customer.Ship.AddressLine2 = "";
Checkout.Customer.Ship.City = "";
Checkout.Customer.Ship.State = "AL";
Checkout.Customer.Ship.Zip = "";
Checkout.Customer.Ship.Country = "US";
Checkout.Customer.Ship.Phone = "";
Checkout.Customer.Ship.Type = "";
Checkout.Customer.Ship.Cost = 0;
Checkout.Customer.Ship.Memo = "";
Checkout.Customer.Ship.Raw = "";


Checkout.Customer.Bill = new Object();
Checkout.Customer.Bill.InternalId = "";
Checkout.Customer.Bill.SameAsShip = true;
Checkout.Customer.Bill.FirstName = "";
Checkout.Customer.Bill.LastName = "";
Checkout.Customer.Bill.Company = "";
Checkout.Customer.Bill.AddressLine1 = "";
Checkout.Customer.Bill.AddressLine2 = "";
Checkout.Customer.Bill.City = "";
Checkout.Customer.Bill.State = "AL";
Checkout.Customer.Bill.Zip = "";
Checkout.Customer.Bill.Country = "US";
Checkout.Customer.Bill.Phone = "";

Checkout.Customer.CreditCard = new Object();
Checkout.Customer.CreditCard.CardsOnFile = new Array();
Checkout.Customer.CreditCard.InternalId = "";
Checkout.Customer.CreditCard.Type = "Visa";
Checkout.Customer.CreditCard.NameOnCard = "";
Checkout.Customer.CreditCard.Number = "";
Checkout.Customer.CreditCard.ExpirationMonth = "";
Checkout.Customer.CreditCard.ExpirationYear = "";
Checkout.Customer.CreditCard.CVV2 = "";
*/

Checkout.eBillme = new Object();

/// Create Cart Object
Checkout.Cart = new Object();
Checkout.Cart.EmptyText = "Your Cart is currently empty.";
Checkout.Cart.IsEmpty = true;
Checkout.Cart.Weight = 0;
Checkout.Cart.SubTotal = 0;
Checkout.Cart.Total = 0;
Checkout.Cart.Tax = 0;
Checkout.Cart.PromotionCode = "";
Checkout.Cart.Discount = "";
Checkout.Cart.DiscountValue = 0;
Checkout.Cart.DiscountType = "";
Checkout.Cart.Raw = "";

Checkout.TaxRate = 6.3;

Checkout.Init = function()
{
    if (document.getElementById("CheckoutPage") != null)
    {
       Checkout.Load();
    }
    
}

Checkout.Load = function()
{

    /// 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");
        }
    }
    
    /// Set Progress graphics.
    Checkout.SetProgress();   
    
     
}

//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.Login = function()
{
    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";
	    document.getElementById("CheckoutNotificationMessage").innerHTML = "<br /><br /><center>Login in progress...</center><br /><br />";
        YAHOO.example.container.panel1.show();
    
        wsi._Soap.AddCall("CustomerLogin", Checkout.Customer.LoginReturn, aParameters);
    }
    else if (Checkout.Customer.Email.length == 0)
    {
        document.getElementById("LoginMessage").innerHTML = "An email address is required for login";
        document.getElementById("LoginMessage").style.color = "Red";
    }
    else
    {
        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)
{
    YAHOO.example.container.panel1.hide();/// close notificaion window.
    if (returnData.substring(0,5) == "error")
    {
        document.getElementById("LoginMessage").innerHTML = returnData.substring(7);
        document.getElementById("LoginMessage").style.color = "Red";
        
    }
    else
    {
   
        document.getElementById("substepLogin").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;
            }
            else 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("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"))
        }        
        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"))
            }
            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);
//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 width="95%" cellspacing="0" cellpadding="4px">'+
                        '<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;

        if (Checkout.Customer.Ship.Type == "2926" || Checkout.Customer.Ship.Type == "1785")
        {
            /// If the subtotal is greater that $99 the order qualifies for free shipping
            if (Checkout.Cart.SubTotal >= 100.00)
            {
                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")
            {
                var PremiumShipCost = 11.75;
                var GroundShipCost = 5.99;
           
                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;
                }
                

                
                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>'+
                                '<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>';
                                
                                
            }
        
            // 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");
            
            if (iFedExTwoDay > -1)
            {  
                var ShipCost = parseFloat(aShipMethods[iFedExTwoDay].split("|")[1]); 
            
                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+'" />FedEx 2-Day Air'+
                                '    </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 = 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]);
            
                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]);
            
                       
                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
    {
        document.location.href = "https://"+document.domain+"/checkout.htm"
    }
}

Checkout.Cart.Get = function()
{
    var SessionID = wsi._Cookie.GetCrumb("SessionID");

    if (SessionID != null)
    {
        var aParameters = new wsi._Parameters();
        aParameters.Add("sessionID",SessionID);

        wsi._Soap.AddCall("GetCart", Checkout.Cart.GetReturn, aParameters);
    }
    else
    {
        Checkout.Cart.GetReturn(null)
    }
    
    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
    if (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";
        //document.getElementById("lblSalesRep").style.display = "inline";
        //document.getElementById("optSalesRep").style.display = "inline";
        
    }
    
}

Checkout.Cart.LineItemTemplate = ""+
        "<tr id='_#GroupId#_'>"+
            "<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 width='55px' rowspan='2' valign='top' style='padding-top:10px;padding-right:10px;'>"+
                "<img src='_#ImgLocation#_' width='50px' height='50px' />"+
            "</td>"+
            "<td width='1000px' colspan='2' valign='top'>"+
                "<span>item# _#Sku#_</span>"+
            "</td>"+
         "</tr>"+
         "<tr>"+
            "<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' onclick='Checkout.Cart.ChangeItemQty(\"_#GroupId#_\", \"Qty_#GroupId#_\");'>Update</span>"+
                "<br /><span class='CheckoutLink' onclick='Checkout.Cart.RemoveItem(\"_#GroupId#_\");'>Remove</span>"+
            "</td>"+
            "<td align='right' valign='top'>"+
                "<span id='Price_#GroupId#_'>_#Price#_</span>"+
                "&nbsp&nbsp<span id='Total_#GroupId#_'>_#Total#_</span>"+
            "</td>"+
        "</tr>";
        

Checkout.ItemToRemove = "";

Checkout.Cart.RemoveItem = function(groupId)
{
    Checkout.ItemToRemove = groupId;
    var Message = document.getElementById("RemoveCartItemNotification").innerHTML;
    //Message = Message.Replace(/_#RemoveItemTitle_#/g, title);
    
    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 (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);
        }
    }
}

Checkout.Cart.ChangeItemQty = function(groupId, qtyField)
{
    var SessionID = wsi._Cookie.GetCrumb("SessionID");

    var Qty = document.getElementById(qtyField).value

    document.getElementById("CartItems").innerHTML = "Updating Quantity...";

    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);
    }
}

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;
        
    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("||");
        
        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 TotalPrice = 0;
            var BaseQty = 0;

           
            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>

                if (ItemProperties[1] == "0")
                {
                    
                    
                    ItemHTML = ItemHTML.replace(/_#GroupId#_/g, ItemProperties[0]);
                    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]);
                   
                    UnitPrice += parseFloat(ItemProperties[5]);
                    BaseQty = parseInt(ItemProperties[4]);
                }
                else
                {
                    if (CustomizationsHTML.length == 0)
                    {
                        CustomizationLink = "View&nbsp;Options";
                                        
                    }
                    else
                    {
                        CustomizationsHTML += "<br />";
                    }
                    
                    CustomizationsHTML += ItemProperties[3];
                    
                    UnitPrice +=  (parseInt(ItemProperties[4])/BaseQty)*parseFloat(ItemProperties[5]);
                }
                
                //UnitPrice += parseFloat(ItemProperties[5]);
                //TotalPrice += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);
                    
                Checkout.Cart.Weight += parseInt(ItemProperties[4])*parseFloat(ItemProperties[6]);
                //Checkout.Cart.SubTotal += parseFloat(ItemProperties[4])*parseFloat(ItemProperties[5]);

            }
           
            TotalPrice += UnitPrice * BaseQty;
            Checkout.Cart.SubTotal += TotalPrice;
                  
            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;
        }
        
        document.getElementById("CartItems").innerHTML = "<table border='0' width='100%' cellspacing='0' cellpadding='0'>"+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))
        //document.getElementById("CardMessage").innerHTML = 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) == "S")
        {
            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);
        }
    }
      
    Checkout.SetTotals();
}

/// Converts a float value to a Money String
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 = function(value)
{
    return Math.round(parseFloat(value)*100)/100
}

Checkout.SetTotals = function()
{
    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 (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.PlaceOrder = function()
{
   /// Reset the Message
   document.getElementById("CardMessage").innerHTML = ""
   
   
   var aParameters = new wsi._Parameters();
//window.status = Checkout.Customer.InternalID();
    aParameters.Add("sessionId", wsi._Cookie.GetCrumb("SessionID"));
    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);
 
    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.eBillme.PreAuthorizeReturn = function(returnValue)
{
//alert(returnValue);
}

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_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.";
            }
            else
            {
                document.getElementById("CreateAccountMsg").innerHTML = "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.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)
    {
        
        if (Checkout.Customer.InternalID().length > 0 && Checkout.SavePassword)
        {
            Checkout.ChangePassword();
        }
        
        if (returnValue.indexOf("OrderId=") > -1)
        {
            var _cOrderId = returnValue.substring(returnValue.indexOf("OrderId=")+8);
            returnValue =  returnValue.substring(0,returnValue.indexOf("OrderId=")-1);
        }
    
        Checkout.Google.Analytics(_cOrderId);
        document.location.href = "/thank-you.htm?orderId="+_cOrderId;
        /*
        Checkout.CurrentStep = 0;
        Checkout.HideAllSteps();
        document.getElementById("cartPreview").style.display = "none";
        document.getElementById("CheckoutHeader").style.display = "none";
        document.getElementById("Confirmation").style.display = "block";
        */
    }
    else
    {
        document.getElementById("CardMessage").innerHTML = returnValue;
    }
}

Checkout.Google = new Object();
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 = 1; //skip the login step
Checkout.Progress = 1; // start with the shipping address

Checkout.Steps = new Array();
Checkout.Steps[0] = "stepLogin";
Checkout.Steps[1] = "stepAddress";
Checkout.Steps[2] = "stepBillingAddress";
Checkout.Steps[3] = "stepShippingOptions";
Checkout.Steps[4] = "stepPayment";

Checkout.NextStep = function()
{
    Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep+1]);
}

Checkout.PrevStep = function()
{
    Checkout.ShowStep(Checkout.Steps[Checkout.CurrentStep-1]);
}

Checkout.ShowStep = function(showThis)
{
    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 == "stepLogin")
    {
        //ThisExpandImage.src = "../graphics/minus_compact.png"
    }
    
    Checkout.SetProgress();
}

Checkout.ActivateStep = function(activateThis)
{

}

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)
	    {
	        ThisProgress.innerHTML = "<img 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'>";
	    }
	}
	
	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");
    
    ThisBody.style.display = "none";
    
    // Set the expand image
    //ThisExpandImage.src = "../graphics/plus_compact.png"
    
    // Always collapse the Login
    document.getElementById("stepLogin-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";
}

/// 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 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")
    {
        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";
    }
        
    var Validated = true;

    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();

        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.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
                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;
                }
            }
        }
        else
        {
            Validated = false;
        }
    }
//document.getElementById("Billmessage").innerHTML += "  " + Checkout.Customer.Bill.State + "-" + Checkout.Customer.Bill.Country        
    // if all fields validate
    if (Validated)
    {
        Checkout.SetTotals();
        Checkout.NextStep();
    }
}

Checkout.ValidateShippingOptions = function()
{
    // 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();
        
        Checkout.NextStep();
    }
}

Checkout.ShowCVV2 = function()
{
    YAHOO.example.container.overlay1.cfg.setProperty("context", ["Whatiscvv2","tl","tr"]);
    YAHOO.example.container.overlay1.setBody("Visa, Mastercard, or Discover - the 3 digit number on the back of card.<br /><br />American Express - the 4 digit number on the front of card.");
    YAHOO.example.container.overlay1.show();
}

Checkout.HideCVV2 = function()
{
    YAHOO.example.container.overlay1.hide()
}

Checkout.ValidateCreditCard = function()
{
//Checkout.Customer.PaymentMethod("eBillMe")
    if (Checkout.Customer.PaymentMethod() == "eBillMe")
    {
        /*
        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)
        */  
        
       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);

   
        wsi._Soap.AddCall("PreAuthorize_eBillme", Checkout.eBillme.PreAuthorizeReturn, aParameters);  
    }
    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;

        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)

            if (Checkout.Customer.InternalID().length > 0 || PasswordGood)
            {
                Checkout.PlaceOrder();
            }
            else
            {
                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 = "";
                
            }
        }
    }
 }


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';
    }
}
