﻿/*

    CART OBJECT LITERAL
    isbn: string
    title: string
    


*/







Cart = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/
    handlingFee: 10,


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/
    
    add: function()
    {
        //Validate isbn
        if(typeof arguments[0] ==  'undefined' || typeof arguments[0] != 'string')
        {
            throw new Error('Cart.add() constructor expects argument 1 to be of \'string\' type');
        }
        
        //Validate quantity
        if(typeof arguments[1] ==  'undefined' || isNaN(arguments[1]))
        {
            throw new Error('Cart.add() constructor expects argument 2 to be of \'number\' type');
        }
        
        //Validate purchase type
        if(typeof arguments[2] ==  'undefined' || typeof arguments[2] != 'string')
        {
            throw new Error('Cart.add() constructor expects argument 3 to be of \'string\' type');
        }
        
        var isbn = arguments[0];
        var quantity = arguments[1];
        var purchaseType = arguments[2];
        var inspection = arguments[3];
        
        //Search for item details
        var itemSearch = new OnixItemSearch(isbn,'CartAdd');
		//If item loaded
		if(itemSearch.loaded)
		{
		    var item = new OnixItem('series',itemSearch.tsIndex[0],quantity);
		    if(purchaseType == 'B' && !item.isItemAvailable())purchaseType = 'R';
		    item.purchaseType = purchaseType;	
		    item.inspection = inspection;	    
		    this.items.push(item);
		    this.save();
		}
        
            
    },
    
    load: function()
    {
        //Array used for LOG
        var vars = new Array();
        
        this.items = new Array();
        var oCookie = (DH.getCookie('mac_sec_cart')) ? DH.getCookie('mac_sec_cart').split('|') : null;
        if(oCookie)
        {
            for(var i = 0; i < oCookie.length; i++)
            {
                var isbn = oCookie[i].split('_')[0];
                var purchaseType = oCookie[i].split('_')[1].substring(1);
                var inspection = oCookie[i].split('_')[1].substring(0,1);
                var quantity = parseInt(oCookie[i].split('_')[2]);
                
                vars.push(isbn + '_' + inspection + purchaseType + '_' + quantity);
                
                //Search for item details
                var itemSearch = new OnixItemSearch(isbn,'CartLoad');
                //If item loaded
		        if(itemSearch.loaded)
		        {
		            var item = new OnixItem('series',itemSearch.tsIndex[0],quantity);
		            item.purchaseType = purchaseType;
		            item.inspection = (inspection == 'I') ? true : null;
		            this.items.push(item);
		        }
            }  
        }   
        if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Cart.load() - items in cookie',vars); 
    },
    
    save: function()
    {
        var vars = new Array();
        
        //If there are no items in cart delete cookie
        if(this.items.length == 0)
        {
            var cookieExpires = new Date();
            cookieExpires.setTime(cookieExpires.getTime() - (1 * 60 * 60 * 1000 ));
            DH.setCookie('mac_sec_cart','',cookieExpires,'/');
            if(Secondary._LOG_ENABLED)LOG.printH1('Cart.save() - cookie deleted');
        } else { //If there are items in cart
            for(var i = 0; i < this.items.length; i++)
            {
                var inspection = (this.items[i].inspection) ? 'I' : 'B';
                vars.push(this.items[i].isbn + '_' + inspection + this.items[i].purchaseType + '_' + this.items[i].quantity);
            }
            
            if(vars.length > 0)
            {
                var cookieExpires = new Date();
                cookieExpires.setTime(cookieExpires.getTime() + (1 * 60 * 60 * 1000 ));
                //cookieExpires.setDate(cookieExpires.getDate() + 2);
                DH.setCookie('mac_sec_cart',vars.join('|'),cookieExpires,'/');
                
                if(vars.length > 0 && Secondary._LOG_ENABLED)LOG.printULwithH1('Cart.save() - items being saved in cookie',vars);
                
            }
        }
    },
    
    remove: function(isbn)
    {
        if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - START - length of items = ' + this.items.length);
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].isbn == isbn)
            {
                //if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - removing ' + isbn);
                var item = this.items[i];
                this.items.splice(i,1);
            }
        } 
        //if(Secondary._LOG_ENABLED)LOG.printH1('Cart.remove() - END - length of items = ' + this.items.length);
        this.save();
        return item;
    },
    
    isItemInCart: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return true;
        }
        return false;
    },
    
    getItemWithISBN: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return this.items[i];
        }
        return null;
    },
    
    getItemCount: function()
    {
        var quantity = 0;
        for(var i = 0; i < this.items.length; i++)
        {
            quantity += this.items[i].quantity;
        }
        return quantity;    
    },
    
    getItemQuantity: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].hasSameISBN(isbn))return this.items[i].quantity;
        }
        return 0;
    },
    
    isItemBeingInspected: function(isbn)
    {
        var item = this.getItemWithISBN(isbn);
        if(item && item.purchaseType == 'I')
        {
            return true;
        } else {
            return false;
        }
    },
    
    setPurchaseType: function(isbn,purchaseType)
    {
        var item = this.getItemWithISBN(isbn);
        
        if(item)
        {
            switch(purchaseType)
            {
                case 'I'://Inspect item
                    item.quantity = 1;
                    item.purchaseType = purchaseType;
                    break;
                case 'B'://Buy item
                    item.checkAvailability(item.quantity);
                    item.purchaseType = purchaseType;
                    if(!item.isItemAvailable())item.purchaseType = 'R';
                    break;
                default:
            }                    
        }
        this.save();
    },
    
    setQuantity: function(isbn,quantity)
    {
        var item = this.getItemWithISBN(isbn);
        
        if(item)
        {
            if(quantity > 0)
            {
                item.quantity = quantity;
                item.checkAvailability(quantity);
                item.purchaseType = 'B';
                if(!item.isItemAvailable())item.purchaseType = 'R';
                this.save();
            } else {
                this.remove(isbn);
            }
        }
        
    },
    
    updateItem: function(isbnOrItem,oParent)
    { 
        var item = (typeof isbnOrItem == 'string') ? this.getItemWithISBN(isbnOrItem) : isbnOrItem;
        if(item)
        {
            var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
            if(isOnixProductPage)//If it is a book page
            {
                item.attachOnixProductForm(oParent);
            } else {//If it is an index page
                item.attachSeriesIndex1Item(oParent);
            }    
        }
    },
    
    hasItems: function()
    {
        if(this.items.length > 0)
        {
            return true;
        } else {
            return false;
        }
    },
    
    hasInspectedItems: function()
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType == 'I')return true;
        }
        return false;
    },
    
    hasOnlyItemsInStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType != 'B')return false;
        }
        return true;
    },
    
        hasOnlyItemsOutOfStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType == 'B' || this.items[i].purchaseType == 'I')return false;
        }
        return true;
    },

        removeItemsOutOfStock: function()
    {
        if(this.items.length == 0)return false;
        
        for(var i = 0; i < this.items.length; i++)
        {
        if(this.items[i].purchaseType != 'B') this.remove(this.items[i].isbn);
        }
        return true;
    },
   
 
    getTotal: function()
    {
        var total = 0;
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].purchaseType != 'I')
            {
                total += (this.items[i].price * this.items[i].quantity);
            }
        }
        
        //Check if handling fee must be added to total
        if(Checkout && (Checkout.step == 3 || Checkout.step == 4) && CheckoutCookie)
        {
            var oCookie = new CheckoutCookie('checkout_step1'); 
            var payType = oCookie.getVarValue('PayType');
            if(payType && payType == '2')//if payment is credit card
            {
                total += this.handlingFee;
            }
        }
        
        return total;
    },
    
    getItemTotal: function(isbn)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            if(this.items[i].isbn == isbn)
            {
                if(this.items[i].purchaseType != 'I')
                {
                    return (this.items[i].price * this.items[i].quantity);
                }
            }
        }
        return 0;
    },
    
    attachMiniCart: function(oParent)
    {
        var isOnixProductPage = (Secondary && Secondary.pageType && Secondary.pageType == 'onixProduct') ? true : null;
        
        var isOnixIndexPage = (Secondary && Secondary.section && Secondary.section == 'Library'
                               && Secondary.subsection && Secondary.subsection == 'Onix') ? true : null;
                               
        var isOnixSearchPage = (Secondary && Secondary.section && Secondary.section == 'Library'
                               && Secondary.subsection && Secondary.subsection == 'Search') ? true : null;
        
        var miniCart = document.getElementById('miniCart');
        if(!miniCart)
        {
            //Create cart holder
            miniCart = document.createElement('div');
            miniCart.setAttribute('id','miniCart');
            //variable to determine whether to attach to parent or not at the end of this
            var parentNecessary = true;
        } else {
            miniCart.innerHTML = '';
        }
        
        var ul = document.createElement('ul');
        
        //Create add button
        var li = document.createElement('li');
        if(isOnixProductPage || isOnixIndexPage || isOnixSearchPage)
        {
            var tag = document.createElement('a');                          
            tag.className = 'add';
            tag.appendChild(document.createTextNode('Add to order'));
            tag.setAttribute('href','#');
            //Attach event to element
            DH.addEvent(tag,'click',OnixItem_AddItems);
        } else {
            var tag = document.createElement('span');
            tag.className = 'add';
            tag.appendChild(document.createTextNode('Add to order'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Create view order button
        var li = document.createElement('li');
        if(this.hasItems())
        {
            var tag = document.createElement('a');
            tag.appendChild(document.createTextNode('View order'));
            tag.setAttribute('href','/secondary31/site/articleIDs/514829CC98A98DA3CA257557001A4C52?open&template=domSecondary');
        } else {
            var tag = document.createElement('span');
            tag.appendChild(document.createTextNode('View order'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Create checkout button
        var li = document.createElement('li');
        if(this.hasItems())
        {
            var tag = document.createElement('a');
            tag.appendChild(document.createTextNode('Checkout'));
            //tag.setAttribute('href','/secondary/site/libraries/checkout');
            tag.setAttribute('href','/secondary31/site/articleIDs/8BBB301D7E16233BCA257555001631ED?open&template=domSecondary');
        } else {
            var tag = document.createElement('span');
            tag.appendChild(document.createTextNode('Checkout'));
        }
        li.appendChild(tag);
        ul.appendChild(li);
        
        //Attach link list to miniCart
        miniCart.appendChild(ul);
        
        //Attach cart heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Shopping Summary'));
        miniCart.appendChild(h3);
        
        //Attach number of items
        var p = document.createElement('p');
        p.setAttribute('id','miniCartCount');
        p.appendChild(document.createTextNode('No. of items: ' + this.getItemCount()));
        miniCart.appendChild(p);
        
        //Attach total
        var p = document.createElement('p');
        p.setAttribute('id','miniCartTotal');
        p.appendChild(document.createTextNode('Total: $' + this.getTotal().toFixed(2)));
        miniCart.appendChild(p);
        
        if(parentNecessary)oParent.appendChild(miniCart);
    },
    
    attachSummaryTableHead: function(oTable)
    {
        var tr = document.createElement('tr');
        //var headings = ['ISBN','Title','RRP','e-Club Price','Quantity','Inspect','Buy','Total','Available',' '];
        var headings = ['ISBN','Title','RRP','Quantity','Inspect','Buy','Total','Available',' '];
        for(var i = 0; i < headings.length; i++)
        {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(headings[i]));
            if(i == (headings.length - 1))th.className = 'last';
            tr.appendChild(th);
        }
        var thead = document.createElement('thead');
        thead.appendChild(tr);
        oTable.appendChild(thead);
    },
    
    attachSummaryTableHeadCheckoutStep3: function(oTable)
    {
        var tr = document.createElement('tr');
        //var headings = ['ISBN','Title','RRP','e-Club Price','Quantity','Inspect','Buy','Total','Available'];
        var headings = ['ISBN','Title','RRP','Quantity','Inspect','Buy','Total','Available'];
        for(var i = 0; i < headings.length; i++)
        {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(headings[i]));
            if(i == (headings.length - 1))th.className = 'last';
            tr.appendChild(th);
        }
        var thead = document.createElement('thead');
        thead.appendChild(tr);
        oTable.appendChild(thead);
    },
    
    attachSummaryTable: function(oParent)
    {
        var oTable = document.createElement('table');
        
        var caption = document.createElement('caption');
        caption.appendChild(document.createTextNode('Summary'));
        oTable.appendChild(caption);
        
        this.attachSummaryTableHead(oTable);
        
        var tbody = document.createElement('tbody');
        
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachSummaryRow(tbody);    
        }
        
        //Attach total
        var tr = document.createElement('tr');
        tr.className = 'last';
        for(var i = 0; i < 9; i++)
        {
            if(i == 8)
            {
                var td =document.createElement('td');
                //td.setAttribute('colspan','2');
                td.className = 'total';
                td.appendChild(document.createTextNode('$' + this.getTotal().toFixed(2)));
            } else if(i == 7) {
                var td = document.createElement('td');  
                td.className = 'summaryTitle';
                td.appendChild(document.createTextNode('Total:'));
            } else {
                var td = document.createElement('td');
                if(i == 6)td.style.borderRightWidth = '1px';
                var img = document.createElement('img');
                img.src = 'templates/layout/$file/spacer.gif';
                td.appendChild(img);
                //td.setAttribute('colspan','1'); 
            }
            tr.appendChild(td);  
        }
        tbody.appendChild(tr);
        oTable.appendChild(tbody);
        oParent.appendChild(oTable);
    },
    
    attachSummaryTableCheckoutStep3: function(oParent)
    {
        var oTable = document.createElement('table');
        
        var caption = document.createElement('caption');
        caption.appendChild(document.createTextNode('Summary'));
        oTable.appendChild(caption);
        
        this.attachSummaryTableHeadCheckoutStep3(oTable);
        
        var tbody = document.createElement('tbody');
        
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachSummaryRowCheckoutStep3(tbody);    
        }
        
        //Attach total
        var tr = document.createElement('tr');
        tr.className = 'last';
        for(var i = 0; i < 8; i++)
        {
            if(i == 7)
            {
                var td =document.createElement('td');
                //td.setAttribute('colspan','2');
                td.className = 'total';
                td.appendChild(document.createTextNode('$' + this.getTotal().toFixed(2)));
            } else if(i == 6) {
                var td = document.createElement('td');  
                td.className = 'summaryTitle';
                td.appendChild(document.createTextNode('Total:'));
            } else {
                var td = document.createElement('td');
                if(i == 5)td.style.borderRightWidth = '1px';
                var img = document.createElement('img');
                img.src = 'templates/layout/$file/spacer.gif';
                td.appendChild(img);
                //td.setAttribute('colspan','1'); 
            }
            tr.appendChild(td);  
        }
        tbody.appendChild(tr);
        oTable.appendChild(tbody);
        oParent.appendChild(oTable);
    },
    
    attachSummary: function(oParent)
    {   
        oParent.innerHTML = '';
        
        //alert(this.items[0].value);
        
        if(this.items.length > 0)
        {
           this.attachSummaryTable(oParent);
           
           //Attach buttons
           var fieldset = document.createElement('fieldset');
           
           //If it is not check out
           if(!Checkout || Checkout.step != 1)
           {
               //Attach continue shopping button
               var oInput = document.createElement('input');
               oInput.setAttribute('type','button');
               oInput.setAttribute('value','Continue shopping');
               oInput.setAttribute('tabindex','1');
               oInput.className = 'button';
               var ContinueShoppingBtn_onClick = function(oEvent)
               {
                    var target = DH.stopEvent(oEvent);
                    history.go(-1);
               };
               DH.addEvent(oInput,'click',ContinueShoppingBtn_onClick);
               fieldset.appendChild(oInput);
               
               //Attach check out button
               if(this.hasItems())
               {
                   var oInput = document.createElement('input');
                   oInput.setAttribute('type','button');
                   oInput.setAttribute('value','Checkout now');
                   oInput.setAttribute('tabindex','2');
                   oInput.className = 'button';
                   var CheckoutNowBtn_onClick = function()
                   {
                        window.location = '/secondary31/site/articleIDs/8BBB301D7E16233BCA257555001631ED?open&template=domSecondary';
                   };
                   DH.addEvent(oInput,'click',CheckoutNowBtn_onClick);
                   fieldset.appendChild(oInput);
               }
               oParent.appendChild(fieldset);
            }
        } else {
            var p = document.createElement('p');
            p.appendChild(document.createTextNode('There are no items in the cart.'));
            p.className = 'noItems';
            oParent.appendChild(p);
        }
    },
    
    attachSummaryCheckoutStep3: function(oParent)
    {
        oParent.innerHTML = '';
        
        if(this.items.length > 0)
        {
            this.attachSummaryTableCheckoutStep3(oParent);
        } else {
            var p = document.createElement('p');
            p.appendChild(document.createTextNode('There are no items in the cart.'));
            p.className = 'noItems';
            oParent.appendChild(p);
        }
    },
    
    attachCheckoutHiddenInputs: function(oForm)
    {
        for(var i = 0; i < this.items.length; i++)
        {
            this.items[i].attachCheckoutHiddenInputs(oForm,i);
        };
    },

    init: function()
    {
        this.load();    
    }

}

