﻿/************
Product
************/
function Product(itemId, name, price) 
{
    this.itemId = itemId;
    this.name = name;
    this.price = price;
}


//CONSTRUCTOR
//cart uses the cookie as storage for items
//the cookie has 2 main data stores.
//  1) the actual products with their information. the id of the product is the cookie name, and the name and price are concatonated
//      with a pipe (|) for transport.
//  2) an "index" which is a pipe delimited listing of all the product ids. This is used for retrieving items and knowing what's in the cart 
function Cart()
{   
    this.cookie = new Cookie("cart");
    this.hasItems = !!this.cookie.index;
    
    if (!this.hasItems)
    {
        this.itemCount = 0;
        this.totalPrice = 0;
    }
    else
    {
        this.itemCount = this.getItemCount();
        this.totalPrice = this.getTotalPrice();
    }
}

//ADD
Cart.prototype.add = function(product)
{   
        
    if (!this.cookie[product.itemId])//only do it if it doesn't exist already
    {
        this.itemCount++;
        
        this.totalPrice += parseFloat(product.price);
                
        this.cookie[product.itemId] = product.name + '|' + product.price;
        if (this.cookie.index)
            this.cookie.index += product.itemId + '|';//putting a pipe on both sides to make removal robust
        else
            this.cookie.index = '|' + product.itemId + '|';;
                
        this.cookie.store(365,'/');//save for 1 yr, use site-wide
                
        this.updateTotals();
        
        //talk to google analytics
        try { pageTracker._trackPageview('/Store/PutItemInCart'); }
        catch(e) { ; }
        
        return this.insertItemIntoDisplay(product); //returns the delete link for binding
        
    }    
}

//REMOVE
Cart.prototype.remove = function(node, product)
{
    delete this.cookie[product.itemId];
    
    if (this.cookie.index) //should always be true
        this.cookie.index = this.cookie.index.replace('|' + product.itemId + '|', '|');//grabbing both to insure nuking '2' doesn't kill '32'.
        
    this.itemCount--;
    this.totalPrice -= parseFloat(product.price);
    
    this.cookie.store(365,'/');

    this.updateTotals();
    
    if (node)//only if a node was passed in
        document.getElementById('cartexpanded').removeChild(node.parentNode);
    
    if (this.itemCount == 0)
    {
        this.close();
        this.clear();
    }

}

//RETRIEVE
//returns an array of all the products
Cart.prototype.retrieve = function()
{
    if (this.cookie.index)
    {
        var wholeCart = new Array();
        var indexArray = this.cookie.index.split('|');//make array;
        indexArray.shift();
        indexArray.pop(); //nuke bogus first and last elements
        
        for (var i = 0; i< indexArray.length; i++)
        {
            //dig through the cookie and find trio of values for (each) product 
            var itemId = indexArray[i];
            var tmpArr = this.cookie[itemId].split('|');
            var name = tmpArr[0];
            var price = tmpArr[1];
            
            //load an array with all the elements
            wholeCart.push(new Product(itemId, name, price));
        }
        
        return wholeCart;
    }
        else return null;
}

//CLEAR
Cart.prototype.clear = function()
{
    this.itemCount = 0;
    this.totalPrice = 0.0;
    this.cookie.remove('/');
    //clear cookie
}

//POPULATE THE CART READOUT ON THE PAGE
Cart.prototype.populateDisplay = function()
{
    var items = this.retrieve();
    if (items)
    {
    
        elms = $$('add');
        //set all the icons already in the cart to the "added" state
        for (var j = 0; j < items.length; j++)
        {
            var el;
            el = this.insertItemIntoDisplay(items[j]);
            //wiring up the delete icon/link
            YUE.addListener(el,'click', CartBroker.remove);

            //console.log(items[j].itemId);            
            for (var k = 0; k < elms.length; k++)
            {
                if (elms[k].getAttribute('itemid') == items[j].itemId)
                {
                    CartBroker.changeIcon(elms[k]);
                    YUE.addListener(el,'click', CartBroker.changeIconBack, elms[k], true);                             
                }           
            }
        }
    }
    
    this.updateTotals();
}


/////////////////UTILITIES/////////////////////////

Cart.prototype.updateTotals = function()
{
    if ($('cartcount'))//only do this if the cart UI is there
    {
        var count = this.itemCount ? this.itemCount : "0";
        count = count == "1" ? count + " item" : count + " items";
        $('cartcount').innerHTML = count;
        
        var total = this.totalPrice ? this.formatCurrency(this.getTotalPrice()) : "$0.00";
        $('carttotal').innerHTML = total;
    }
}


//returns the delete link (trash can) for binding 
Cart.prototype.insertItemIntoDisplay = function(product)
{
    /* MODEL
    <div class="cartitem">    
        <span class="cartitemdelete"><a href="#"><img src="/images/trash.gif" /></a></span>
        <span class="cartitemname"><p><a href="#">Red Fire Truck</a></p></span>
        <span class="cartitemprice">$4.95</span>
    </div>
    */
    var c = document.getElementById('cartexpanded');
    var el = document.createElement('div');
    el.className = "cartitem";
    var inner = "<span class='cartitemdelete' itemid='" 
        + product.itemId + "' itemname='" 
        + product.name + "' itemprice='" 
        + product.price + "'><a href='#'><img src='/images/trash.gif' /></a></span>"
    inner += "<span class='cartitemname'><p><a href='/Store/Product/" 
        + product.itemId + "'>" 
        + product.name + "</a></p></span>"
    inner += "<span class='cartitemprice'>" 
        + product.price + "</span>"
    el.innerHTML = inner;
    c.appendChild(el);
    
    return el.firstChild; //going to need it to bind events to
}

Cart.prototype.getItemCount = function()
{
    return this.arrayOfIndex().length;
}
    
Cart.prototype.getTotalPrice = function()
{
    var arr = this.arrayOfIndex();
    var total = 0.0;
    for(var i = 0; i< arr.length; i++)
    {
        total += parseFloat(this.cookie[arr[i]].split('|')[1],10);
    }
    
    return total;
}

Cart.prototype.arrayOfIndex = function()
{
    var indexArray = this.cookie.index.split('|');//make array;
    indexArray.shift();
    indexArray.pop(); //nuke bogus first and last elements
    return indexArray;
}

Cart.prototype.formatCurrency = function(n) 
{
	var n = n.toString().replace(/\$|\,/g,'');
	var dblValue = parseFloat(n);

	var blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	var dblValue = Math.floor(dblValue*100+0.50000000001);
	var intCents = dblValue%100;
	var strCents = intCents.toString();
	var dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

Cart.prototype.open = function()
{
    show($('cartexpanded'));
    show($('cartclose'));
    hide($('cartopen'));
}

Cart.prototype.close = function()
{
    hide($('cartexpanded'));
    hide($('cartclose'));
    show($('cartopen'));
}

/*/////////                                                 ///////////
            CartBroker - this is the interface to the cart
//////////                                                 //////////*/

var CartBroker =
{
    init: function()
    {
        window.cart = new Cart();
        cart.populateDisplay();
        YUE.addListener($('cartopen'), 'click', cart.open);
        YUE.addListener($('cartclose'), 'click', cart.close);
        YUE.addListener($$('add'), 'click', CartBroker.add, cart);        
        
        //YUE.addListener($$('cartitemdelete'), 'click', CartBroker.remove, cart);
    },
    add: function(e)
    {
        var product = new Product(this.getAttribute('itemid'),this.getAttribute('itemname'),this.getAttribute('itemprice').substring(1));
        var deleteLink = cart.add(product) //el is delete link (in the cart display) of the item added
        if (deleteLink)//add happened and hadn't happened already. 
        {        
            YUE.addListener(deleteLink,'click', CartBroker.remove);//wiring up the delete icon/link
            YUE.addListener(deleteLink,'click', CartBroker.changeIconBack, this, true);
            
            //create object to be animated indicating adding something to cart
            var el = document.createElement('div');
            document.body.appendChild(el);
            el.className = "carttraveler";
            YUD.setXY(el,YUD.getXY(this));
            
            CartBroker.changeIcon(this);      
            
            var anim = new YAHOO.util.Motion(el, { points: { to: YUD.getXY('cartopen') } },1);
            anim.animate();

            //nuke traveler
            setTimeout(function() {document.body.removeChild(el)},1000);            
        }
      
        YUE.stopEvent(e);
    },
    remove: function(e)
    {
        var product = new Product(this.getAttribute('itemid'),this.getAttribute('itemname'),this.getAttribute('itemprice').substring(1));    
        cart.remove(this, product);
        YUE.stopEvent(e);
    },
    changeIcon: function(el)
    {
        //update display to show item is "in cart"
        //if parentNode == span, it's the abbreviated display like on the store homepage and needs diff treatment
        if (el.parentNode.nodeName != "SPAN")
            YUD.setStyle(el, 'background-image', 'url(/images/icons/incart.gif)');

        YUD.setStyle(el, 'text-decoration','none');
        YUD.setStyle(el, 'cursor','text');
        el.innerHTML = el.parentNode.nodeName == "SPAN" ? "<img src='/images/icons/incart.gif' />" : "In Cart";
    },
    changeIconBack: function()
    {
        if (this.parentNode.nodeName != "SPAN")
            YUD.setStyle(this, 'background-image', 'url(/images/icons/addtocart.gif)');
        
        YUD.setStyle(this, 'text-decoration','underline');
        YUD.setStyle(this, 'cursor','pointer');
        this.innerHTML = this.parentNode.nodeName == "SPAN" ? "<img src='/images/icons/addtocart.gif' />" : "Add to Cart";
    }
};

//start the party
YUE.onDOMReady(CartBroker.init);



