﻿Hardcore.Cart = function()
{
    var _key; //UniqueIdentifier
    var xmlCart;
    var _divmain;
    var _dialog;
    var _loading;
    var _cookie;
    var m_UseBillAsShpAddr;
    var _divbilling;
    var _divshipping;
    var _divverify;
    var _divreceipt;
    var _iframe;
    var _usebrowserhistory;
    var _ccNumber;
    var _ccMonth;
    var _ccYear;
    var _ccCID;
    var _newUserPwd;

    var _orderCreated;
    
    Ext.onReady(this.Initialize.createDelegate(this));
    
}

Ext.extend(Hardcore.Cart, Ext.util.Observable,
{
    Initialize : function()
    {
        this.addEvents({"onData": true});
        _divmain = Ext.get('divMC');
        this._loading = Ext.get('loading');
        m_UseBillAsShpAddr = false;
        
        this._divbilling = Ext.get('divBilling');
        this._divshipping = Ext.get('divShipping');
        this._divverify = Ext.get('divVerifyOrder');
        this._divreceipt = Ext.get('divOrderReceipt');
        this._iframe = Ext.get('iFrame');
        this._usebrowserhistory = false;
        this._orderCreated = false;
    },
        
    Dialog: function(d)
    {
        this._dialog = d;
    },

    SetKey : function(key)
    {
        this._key = key;
        this.SetCartCookie();
    },

    GetCartCookie : function()
    {
        if (!this._cookie)
        {
           this._cookie = new Utility.Cookie();
        }
        this._key = this._cookie.Read("HardcoreCart");
    },
        
    SetCartCookie : function()
    {
        if (!this._cookie)
        {
           this._cookie = new Utility.Cookie();
        }
        this._cookie.Set("HardcoreCart", this._key);
    },
    
    DeleteCartCookie : function()
    {
        if (!this._cookie)
        {
           this._cookie = new Utility.Cookie();
        }
        this._cookie.Delete("HardcoreCart");
    },
        
    Create: function()
    {
        //Creates an empty cart returning the Key
        //Functions.ShowLoader(true);
        Hardcore.AjaxAPI.Cart.Create(this.Create_process.createDelegate(this));
    },
    
    Create_process: function (response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            this._key = response.value;
            this.SetCartCookie();
        }
        //Functions.ShowLoader(false);
    },
    
    Get: function(isEditable, fillFloater, screenId)
    {
        //if(this._loading)
        //Functions.ShowLoader(true);
            
        var contextObj = {varFillFloater: fillFloater, varScreenID: screenId}
        
        //if we are not editable, disable the shipping dropdown
        if (isEditable == false)
            document.getElementById("ddlShippingOptions").disabled = "disabled";
        
        if (screenId && screenId == 'checkout')
        {
            //call a different callback for the checkout page
            Hardcore.AjaxAPI.Cart.Get(this._key, isEditable, null, this.GetForCheckout_process.createDelegate(this), contextObj);
        }
        else
        {
            Hardcore.AjaxAPI.Cart.Get(this._key, isEditable, null, this.Get_process.createDelegate(this), contextObj);
        }
    },
        
    Get_process: function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            xmlCart = response.value.documentElement;
            
            if (xmlCart.tagName == 'CartEmpty')
            {
                //show cartempty div
                var d;
                d = Ext.get('divShoppingCart');
                if(d)
                    d.dom.className = 'hide';
                d = Ext.get('divEmptyCart');
                if(d)
                    d.dom.className = '';
            }
            else
            {
                var d
                d = Ext.get('divShoppingCart');
                if(d)
                    d.dom.className = '';                
                d = Ext.get('divEmptyCart');
                if(d)
                    d.dom.className = 'hide';
                
                
                for (var i = 0, child; child = xmlCart.childNodes[i]; i++)
                {
                    if (child.nodeName == 'Line')
                    {
                        this.BuildLine(child);
                    }
                    else if (child.nodeName == 'CartMessage')
                    {
                        this.BuildCartMessage(child);
                    }
                    else if (child.nodeName == 'SubTotal')
                    {
                        this.BuildSubTotal(child);
                    }
                    else if (child.nodeName == 'Tax')
                    {
                        this.BuildTax(child);
                    }
                    else if (child.nodeName == 'GrandTotal')
                    {
                        this.BuildTotal(child);
                    }     
                    else if (child.nodeName == 'ShippingPrice')
                    {
                        this.BuildShippingHandlingPrice(child);
                    }
                    else if (child.nodeName == 'ShippingItemID')
                    {
                        this.BuildShippingHandlingMethod(child);
                    }
                    else if (child.nodeName == 'SummaryContent' && (response.context != null && response.context.varFillFloater == true))
                    {
                        this.BuildOrderSummaryFloater(child);
                    }
                }
            }
        }
        
        //Functions.ShowLoader(false);

    },
    GetForCheckout_process : function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
        
            var xmlCart = response.value.documentElement;
            
            if (xmlCart.tagName == 'CartEmpty')
            {
                //show the empty cart div
                var dEC = Ext.get('divEmptyCart');
                if(dEC)
                    dEC.removeClass('hide');
            }
            else
            {
                //hide the emptycart
                var dMC = Ext.get('divMainCheckout');
                if(dMC)
                    dMC.removeClass('hide');

                cart.CheckoutAddressRetrieve();
                
                for (var i = 0, child; child = xmlCart.childNodes[i]; i++)
                {
                    if (child.nodeName == 'Line')
                    {
                        this.BuildLine(child);
                    }
                    else if (child.nodeName == 'CartMessage')
                    {
                        this.BuildCartMessage(child);
                    }
                    else if (child.nodeName == 'SubTotal')
                    {
                        this.BuildSubTotal(child);
                    }
                    else if (child.nodeName == 'Tax')
                    {
                        this.BuildTax(child);
                    }
                    else if (child.nodeName == 'GrandTotal')
                    {
                        this.BuildTotal(child);
                    }     
                    else if (child.nodeName == 'ShippingPrice')
                    {
                        this.BuildShippingHandlingPrice(child);
                    }
                    else if (child.nodeName == 'SummaryContent' && (response.context != null && response.context.varFillFloater == true))
                    {
                        this.BuildOrderSummaryFloater(child);
                    }
                }
                                
                //if we are logged in hide the Create Account div
                cookie = new Utility.Cookie();
                var v = cookie.Read("HardcoreCustomer");
                if (v != null)
                {
                    document.getElementById("divPassword").className = "hide";
                }                
            }
        }
    },
        
    UpdateLine: function(Line, ProductID, Quantity, OverrideQuantity, showDialogOnAdd)    
    {
        if (Quantity != "")
        {
            if (Quantity > 0)
            {
                //Functions.ShowLoader(true);
                
                var context = {varShowDialogOnAdd: showDialogOnAdd, varLine: Line}
                Hardcore.AjaxAPI.Cart.Update(this._key, Line, ProductID, Quantity, OverrideQuantity, this.UpdateLine_process.createDelegate(this), context);
            }
        }
    },
    
    UpdateLine_process: function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            var x;
            
            //set cart cookie
            x = Ext.DomQuery.selectNode("CartID", response.value);
            if(x != null && x.firstChild != null)
            this.SetKey(x.firstChild.nodeValue);
            
            
            //update the subTotal
            x = Ext.DomQuery.selectNode("SubTotal", response.value);
            this.BuildSubTotal(x);
            
            //update the Total
            x = Ext.DomQuery.selectNode("GrandTotal", response.value);
            this.BuildTotal(x);

            //update the shipping price
            x = Ext.DomQuery.selectNode('ShippingPrice', response.value);
            this.BuildShippingHandlingPrice(x);
            
            //update the changed line
            x = Ext.DomQuery.select("Line", response.value);
            
            for (var i = 0; i < x.length; i++)
            {
                for (var a = 0; a < x[i].attributes.length; a++)
                {
                    if (x[i].attributes[a].name == "Number")
                    {
                        var lineNum = x[i].attributes[a].value;
                        if (lineNum == response.context.varLine)
                        {
                            this.BuildLine(x[i]);
                            break;
                        }
                    }
                }
            }
            
            
            if(response.context.varShowDialogOnAdd == true)
            {
                d.Message("Item Added to Cart", "The Item was added to your cart.");
            }
        }
        
        //Functions.ShowLoader(false);
    },
    
    RemoveLine : function(Line)
    {
        //Functions.ShowLoader(true);
        
        var context = {line: Line};
        
        Hardcore.AjaxAPI.Cart.Remove(this._key, Line, this.RemoveLine_process.createDelegate(this), context);
    },
    
    RemoveLine_process : function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            xmlCart = response.value.documentElement;
            
            if (xmlCart.tagName == 'CartEmpty')
            {
                //show cartempty div
                var d;
                d = Ext.get('divShoppingCart');
                d.dom.className = 'hide';
                d = Ext.get('divEmptyCart');
                d.dom.className = '';
            }
            else
            {
                var removeline = Ext.get('divLine' + response.context.line);
                removeline.dom.parentNode.removeChild(removeline.dom);
                
                //update the shipping price
                x = Ext.DomQuery.selectNode('ShippingPrice', response.value);
                this.BuildShippingHandlingPrice(x);
                
                //update the price
                var x = Ext.DomQuery.selectNode("SubTotal", response.value);
                this.BuildSubTotal(x);
                
                //update the Total
                x = Ext.DomQuery.selectNode("GrandTotal", response.value);
                this.BuildTotal(x);        
            }
        }
        //Functions.ShowLoader(false);  
    },
    
    UpdateConfigured: function(productID, xml, line)
    {
        //Functions.ShowLoader(true);
        if (line == null)
            line == "";
            
        Hardcore.AjaxAPI.Cart.UpdateConfigured(this._key, line, productID, Xml.ToString(xmlConfigComponents), this.UpdateConfigured_process.createDelegate(this));
    },
    
    UpdateConfigured_process : function(response)
    {
        //Functions.ShowLoader(false);
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            this.SetKey(response.value);
		  location.href = "ShoppingCart.aspx";
		//Changed on 12/3/2008 - page redirects to shopping cart page now - John Schjolberg
		//d.Message('Saved To Cart', 'Your configuration was successfully saved to your cart.');
        }
    },
    
    UpdateShippingMethod: function(shippingMethodValue)
    {
        //Functions.ShowLoader(true);
        Hardcore.AjaxAPI.Cart.UpdateShippingMethod(this._key, shippingMethodValue, this.Get_process.createDelegate(this));        
    },
    
    HandleError: function(response)
    {
        this._dialog.Message('Error', 'There was an error message from the AJAX call:\n\n' + response.error.Message);
    },
    
    HandleOrderError : function(xError)
    {
        var sError = "";
        for (var i = 0, child; child = xError.childNodes[i]; i++)
        {
            if (child.nodeName == 'Error')
            {
                sError += child.firstChild.nodeValue + '</br>';
            }
        }
        d.Message('Order Validation Error', sError);    
    },
    
    BuildCartMessage : function(child)
    {
        var divCartMessage = Ext.get('divCartMessage');
        if(child != null && child.firstChild != null)
            divCartMessage.update(child.firstChild.nodeValue);
    },
    
    BuildLine: function (xml)
    {
        var ID = Xml.GetNamedValue(xml, 'Number', '');
        var divLine = Ext.get('divLine' + ID);

        if (divLine == null)
        {
            divLine = new Ext.Element(document.createElement('div'));
            divLine.update(Xml.GetNamedValue(xml, 'content', ''));
            _divmain.appendChild(divLine.dom);
        }
        else
        {
            var parent = divLine.up('div');
            parent.update(Xml.GetNamedValue(xml, 'content', ''));
        }
    },
    
    BuildSubTotal: function (child)
    {
        var divSubTotal = Ext.get('divSubTotal');
        if (divSubTotal)
        {
            if(child != null && child.firstChild != null)
                divSubTotal.update(child.firstChild.nodeValue);
        }
    },

    BuildTax: function (child)
    {
        var divTax = Ext.get('divTax');
        if (divTax)
        {
            if(child != null && child.firstChild != null)
                divTax.update(child.firstChild.nodeValue);
        }
    },
    
    BuildShippingHandlingPrice : function (child)
    {
        var divShippingPrice = Ext.get('divShippingPrice');
        if (divShippingPrice)
        {
            if(child != null && child.firstChild != null)
                divShippingPrice.update(child.firstChild.nodeValue);
        }
    },
    
    BuildShippingHandlingMethod : function (child)
    {
        if(child != null && child.firstChild != null)
            document.getElementById("ddlShippingOptions").value = child.firstChild.nodeValue;
    },
        
    
    
    
    
    
    BuildTotal : function (child)
    {
        var divTotalPrice = Ext.get('divTotalPrice');
        if (divTotalPrice)
        {
            if(child != null && child.firstChild != null)
                divTotalPrice.update(child.firstChild.nodeValue);
        }
    },
    
    BuildOrderSummaryFloater : function (child)
    {
        var divOrderSummary = Ext.get('divOrderSummary');
        if (divOrderSummary)
        {
            if(child != null && child.firstChild != null)
                divOrderSummary.update(child.firstChild.nodeValue);
        }
    },
    
    /* ui section */
    CheckoutAddressRetrieve : function()
    {    
        //Functions.ShowLoader(true);
        Hardcore.AjaxAPI.Cart.CartAddressRetrieve(this._key, this.CheckoutAddressRetrieve_process.createDelegate(this));
    },
    CheckoutAddressRetrieve_process: function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            Form.PopulateUserFields(response.value.documentElement);
        }
                    
        //Functions.ShowLoader(false);
    },    
    
    UseAsShippingChange : function(o)
    {
        if (o.checked)
            m_UseBillAsShpAddr = true;
        else
            m_UseBillAsShpAddr = false;
    },
    
    ClearShippingFields : function()
    {    
        //clear the shipping fields
        document.getElementById("sTitle").value = '';
        document.getElementById("sCompanyName").value = '';
        document.getElementById("sFirstName").value = '';
        document.getElementById("sMI").value = '';
        document.getElementById("sLastName").value = '';
        document.getElementById("sStAddress1").value = '';
        document.getElementById("sStAddress2").value = '';
        document.getElementById("sApt").value = '';
        document.getElementById("sCity").value = '';
        document.getElementById("sState").value = '';
        document.getElementById("sCountry").value = '';
        document.getElementById("sZip").value = '';
        document.getElementById("sPhone").value = '';
        document.getElementById("sAltPhone").value = '';
    },
        
    FillShipAddrFromBilling : function()
    {
        document.getElementById("sTitle").value = document.getElementById("bTitle").value;
        document.getElementById("sCompanyName").value = document.getElementById("bCompanyName").value;
        document.getElementById("sFirstName").value = document.getElementById("bFirstName").value;
        document.getElementById("sMI").value = document.getElementById("bMI").value;
        document.getElementById("sLastName").value = document.getElementById("bLastName").value;
        document.getElementById("sStAddress1").value = document.getElementById("bStAddress1").value;
        document.getElementById("sStAddress2").value = document.getElementById("bStAddress2").value;
        document.getElementById("sApt").value = document.getElementById("bApt").value;
        document.getElementById("sCity").value = document.getElementById("bCity").value;
        document.getElementById("sState").value = document.getElementById("bState").value;
        document.getElementById("sCountry").value = document.getElementById("bCountry").value;
        document.getElementById("sZip").value = document.getElementById("bZip").value;
        document.getElementById("sPhone").value = document.getElementById("bPhone").value;
        document.getElementById("sAltPhone").value = document.getElementById("bAltPhone").value ;        
    },
    
    UpdateCartInfo : function(formXml)
    {      
        Hardcore.AjaxAPI.Cart.UpdateInfo(this._key, formXml, this.UpdateCartInfo_process.createDelegate(this));
    },
    
    UpdateCartInfo_process: function(response)
    {
        if (response.error)
            this.HandleError(response);
    },    
        
    MoveToBillingScreen : function(step)
    {
        //Functions.ShowLoader(true);
        this.MoveToStep(step, true);
        //Functions.ShowLoader(false);
    },
    
    MoveToShipScreen : function(step)
    {
        //Functions.ShowLoader(true);
        
        //validate fields
        if (Validator.BillingScreen() == false)
        {
            //Functions.ShowLoader(false);
            return false;
        }
        
        this.UpdateCart();
        
        if (document.getElementById("sUseBillingAddress").checked == true)
            this.FillShipAddrFromBilling();
        
        this.MoveToStep(step, true);            
        
        //Functions.ShowLoader(false);
    },
    
    MoveToVerifyScreen : function(step)
    {
        //Functions.ShowLoader(true);
        
        var contextObj = {varStep: step}
                
        
        //validate fields
        if (Validator.ShippingScreen() == false)
        {
            //Functions.ShowLoader(false);
            return false;
        }

        this.UpdateCart();
        
        Functions.ShowLoader(true);
        
        //retrieve the cart for validation
        this._ccNumber = document.getElementById('txtbCCNum').value;
        this._ccNumber = this._ccNumber.replace('-', '');
        this._ccMonth = document.getElementById('ccExpMonth').value;
        this._ccYear = document.getElementById('ccExpYr').value;
        this._newUserPwd = document.getElementById('bPwd').value;
        this._ccCID = document.getElementById('txtbCID').value;
        
        Hardcore.AjaxAPI.Cart.GetVerified(this._key, this._ccNumber, this._ccMonth, this._ccYear, this._ccCID, this.MoveToVerifyScreenGetVerfied_process.createDelegate(this), contextObj);

    },
    MoveToVerifyScreenGetVerfied_process : function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            //check for successful validation
            var retVal;           
            
            for (var a = 0; a < response.value.firstChild.attributes.length; a++)
            {
                if (response.value.firstChild.attributes[a].name == "Success")
                {
                    retVal = response.value.firstChild.attributes[a].value;
                    break;
                }
            }
                
            
            if (retVal == 0)
            {
                //report failure
                this.HandleOrderError(Ext.DomQuery.selectNode("ErrorData", response.value));
            }
            else
            {
                var x;        
                //update the price
                x = Ext.DomQuery.selectNode("SubTotal", response.value);
                this.BuildSubTotal(x); 
                //update the Total
                x = Ext.DomQuery.selectNode("GrandTotal", response.value);
                this.BuildTotal(x);                            
                //update the Tax
                x = Ext.DomQuery.selectNode("Tax", response.value);
                this.BuildTax(x); 
                //Update the Shipping and Handling
                x = Ext.DomQuery.selectNode("SH", response.value);
                this.BuildShippingHandlingPrice(x); 
                
                this.MoveToStep(response.context.varStep, true);                
            }
        }
        
        //Functions.ShowLoader(false);
        
    },
    
    MoveToOrderReceipt : function(step)
    {
        //Functions.ShowLoader(true);
        
        //place order
        cart.OrderCreate(step);        
    },

    OrderCreate : function(step)
    {
        //Functions.ShowLoader(true);
        
        var contextObj = {varStep: step}
        
        var updateAcct = true;
        var customer = cookie.Read("HardcoreCustomer");
        if (customer != null)
        {
            updateAcct = false;
        }  

        //retrieve the cart
        Hardcore.AjaxAPI.Cart.OrderCreate(this._key, false, false, this._ccNumber, this._ccMonth, this._ccYear, this._ccCID, this._newUserPwd, updateAcct, this.OrderCreate_process.createDelegate(this), contextObj);               
    },
    OrderCreate_process: function(response)
    {
        if (response.error)
        {
            this.HandleError(response);
        }
        else
        {
            //check for success
            var retVal;
            for (var a = 0; a < response.value.firstChild.attributes.length; a++)
            {
                if (response.value.firstChild.attributes[a].name == "Success")
                {
                    retVal = response.value.firstChild.attributes[a].value;
                    break;
                }
            }
            
            if (retVal == 0)
            {
                //report failure
                this.HandleOrderError(Ext.DomQuery.selectNode("ErrorData", response.value));
            }
            else
            {
                this._orderCreated = true;
                
                this.DeleteCartCookie();
                
                var ob;

                
                //get order number
                var ordNum = Ext.DomQuery.selectNode("OrderNumber", response.value);
                if(ordNum != null && ordNum.firstChild != null)
                {
                    ob = Ext.get('divOrderReceipt');
                    var s = ob.dom.innerHTML;
                    s = s.replace("*order*", ordNum.firstChild.nodeValue);
                    ob.update(s);                
                }
                
                ob = Ext.get('divOrderReceipt');
                ob.dom.className = '';
                
                this.MoveToStep(response.context.varStep, true);
            }
        }
        //Functions.ShowLoader(false);
    },     
    
    UpdateCart : function()
    {
        var x = Form.getFormElementsXML('formfield', 'true');
        this.UpdateCartInfo(x);
    },
    
    UncheckUseBillingAddr : function()
    {
        document.getElementById("sUseBillingAddress").checked = false;
    },
    
    MoveToStep : function(target, AddToHistory)
    {  
        this._divbilling.dom.className = 'hide';
        this._divshipping.dom.className = 'hide';
        this._divverify.dom.className = 'hide';
        var stepImage;
        //var imgSteps = document.getElementById("imgSteps");
        
        if (target == 1)
        {
            //show the summary div
            var summ = Ext.get("divOrderSummary");
            summ.dom.className = 'FormRight';

            stepImage = "../Resources/Images/CheckoutBilling.png";
            //imgSteps.useMap = "#mapStep1";
            this._divbilling.dom.className = '';
        }
        else if (target == 2)
        {
            //show the summary div
            var summ = Ext.get("divOrderSummary");
            summ.dom.className = 'FormRight';
            
            this._divshipping.dom.className = '';
            this._divshipping.scrollIntoView();
        }
        else if (target == 3)
        {
            var poButton = Ext.get('iNext3');
            poButton.dom.className = '';
            //hide the summary div
            var summ = Ext.get("divOrderSummary");
            summ.dom.className = 'hide';

            var imgBottomVerify = document.getElementById('imgBottomVerify');
            imgBottomVerify.className = '';
            var imgBottomReceipt = document.getElementById('imgBottomReceipt');
            imgBottomReceipt.className = 'hide';
            
            this._divverify.dom.className = '';
            this._divverify.scrollIntoView();
        }
        else if (target == 4)
        {
            var poButton = Ext.get('iNext3');
            poButton.dom.className = 'hide';

//            poButton = Ext.get('iBack3');
//            poButton.dom.className = 'hide';
            
            var imgBottomVerify = document.getElementById('imgBottomVerify');
            imgBottomVerify.className = 'hide';
            var imgBottomReceipt = document.getElementById('imgBottomReceipt');
            imgBottomReceipt.className = '';
            
            this._divverify.dom.className = '';
            this._divverify.scrollIntoView();
        }

        this.ShowStepImage(target);
        
        this._usebrowserhistory = false;
        
        if (AddToHistory == true)
        {
            this._iframe.dom.src = 'CartHistory.htm?' + target;
        }
    },
    
    ShowStepImage : function(target) 
    {
        var img1 = document.getElementById("imgStep1");
        var img2 = document.getElementById("imgStep2");
        var img3 = document.getElementById("imgStep3");
        var img4 = document.getElementById("imgStep4");
        
        img1.className = "hide";
        img2.className = "hide";
        img3.className = "hide";
        img4.className = "hide";
        
        if (target == 1)
        {
            img1.className = "";
        }
        else if (target == 2)
        {
            img2.className = "";
        }
        else if (target == 3)
        {
            img3.className = "";
        }
        else if (target == 4)
        {
            img4.className = "";
        }
    },
    
    IFrameCallback : function(step)
    {
        if (this._orderCreated == false)
        {
            if (this._usebrowserhistory == true)
            {
                this.MoveToStep(step, false);
            }
            this._usebrowserhistory = true;
        }
    }    
});

