﻿
window.addEvent('domready', function() {
    writeCartSummary();
})

function writeCartSummary()
{
    if (Cookie.read("shoppingCart"))
    {
       // alert(Cookie.read("shoppingCart"));
        $('itemCount').set('text', '');
        $('totalPrice').set('text', '');
        
        var totalPrice = 0.00;
        var itemCount = 0;

        var shoppingCart = Cookie.read("shoppingCart");

        var itemArray = shoppingCart.split('~&~');

        for (var i = 0; i < itemArray.length ; i++)
        {
            var eachItem = new Array();
            eachItem = itemArray[i].split(':~:');

            var price = eachItem[2];
            var numItems = eachItem[3];
            itemCount = (itemCount + parseInt(numItems));
            totalPrice = (totalPrice + ((+price) * numItems));            
        }
        $('itemCount').set('text', 'items: ' + itemCount);
        $('totalPrice').set('text', '£' + totalPrice.toFixed(2));
        
        if($('shoppingCart'))
        {
            if($('checkoutForm'))
            {
                $('itemsTable').set("html", "<table><tr><th>product</th><th>price</th><th>quantity</th><th>line price</th></tr>"+getItemRows(itemArray)+"</table>","<p id='subTotal'>sub-total: £"  +totalPrice.toFixed(2) + "</p>");
                var listItemArray = $('cartTotal').getChildren('li');
                listItemArray[0].set('text','Items £' +totalPrice.toFixed(2));
                countryChange();
            }
            else
            {
                $('itemsTable').set("html", "<table id='shoppingCart' cellpadding='0' cellspacing='0'><tr><th>product</th><th>price</th><th>quantity</th><th colspan=2>line price</th></tr>"+getItemRows(itemArray)+"</table>","<div id='cartNav'><p id='subTotal'>sub-total: £"  +totalPrice.toFixed(2) + "</p>"+"<p><a href='/users/checkout-address.aspx' title='checkout' class='checkoutButton'>checkout</a><a href='#' onclick='updateCart(); return false' title='Update cart' id='updateCart'>Update</a></p></div>");   
            }
        }
    }
    else
    {
        if($('shoppingCart'))
        {
            var anchorArray = $('shoppingCart').getElements('a');
            for (var i = 0; i < anchorArray.length ; i++)
            {
                anchorArray[i].toggleClass('inactiveCart');
            }           
        }
    }
}

function getItemRows(itemArray)
{
    var itemRows = "";
    for (var i = 0; i < itemArray.length ; i++)
    {
        var eachItem = new Array();
        eachItem = itemArray[i].split(':~:');

        var itemDescription = eachItem[1];
        var price = eachItem[2]  * 1;
        var numItems = eachItem[3];
        var itemLink = eachItem[4];
        var linePrice = ((+numItems) * (+price))
        itemRows += "<tr><td class='productRangeName'><a href='"+itemLink+"' title='"+itemDescription+"'>"+itemDescription+"</a></td><td class='productRangePrice'>&pound;"+ price.toFixed(2) +"</td><td class='productRangeBuy'><input type='text' value='"+numItems+"' /></td><td>&pound;"+ linePrice.toFixed(2)+"</td><td class='productDelete'><a href='#' onclick='removeItem("+i+"); return false' title=''>remove</a></td></tr>";
    }
    return itemRows;
}

function updateCart()
{
    if (Cookie.read("shoppingCart"))
    {
        var oldShoppingCart = Cookie.read("shoppingCart");
        var itemArray = oldShoppingCart.split('~&~');
        var itemAmounts = $('itemsTable').getElements('input');

        var newShoppingCart = "";

        for (var i = 0; i < itemArray.length ; i++)
        {
            var eachItem = new Array();
            eachItem = itemArray[i].split(':~:');
            eachItem[3] = itemAmounts[i].get('value');
            
            if(i == 0)
            {
                newShoppingCart =  eachItem[0]+ ":~:" + eachItem[1]+ ":~:" + eachItem[2]+ ":~:" + eachItem[3]+ ":~:" + eachItem[4];
            }
            else
            {
                newShoppingCart += "~&~" + eachItem[0]+ ":~:" + eachItem[1]+ ":~:" + eachItem[2]+ ":~:" + eachItem[3]+ ":~:" + eachItem[4];
            }
        }
        Cookie.write("shoppingCart",newShoppingCart,{});
        writeCartSummary();
    }
}

function removeItem(itemIndex)
{
    var oldShoppingCart = Cookie.read("shoppingCart");
    var newShoppingCart = "";
    var itemArray = oldShoppingCart.split('~&~');
    if(itemArray.length == 1)
    {
        emptyCart()
    }
    else
    {
        var firstItem = true;    
        for (var i = 0; i < itemArray.length ; i++)
        {
            if(i != itemIndex)
            {
                if(firstItem)
                {
                    newShoppingCart = itemArray[i];
                    firstItem = false;
                }
                else
                {
                    newShoppingCart += "~&~" + itemArray[i];
                }
            }
            else
            {
							var eachItem = new Array();
							eachItem = itemArray[i].split(':~:');
							if(Cookie.read(eachItem[0]))
							{
								Cookie.dispose(eachItem[0],{});
							}
            }
        }
        Cookie.write("shoppingCart",newShoppingCart,{});
        writeCartSummary();
    }       
}


function addItem(itemID, priceP, thisObject)
{
    var numItems = 1;
    var price = priceP.substring(1);
    var itemLink;
    var itemDescription;

		if($('pcBuilderCost'))
		{
				numItems = 1;
        price = $('pcBuilderCostIncVat').getElement('span').get('text');
        var foundCart = true;
        var x = 1;
        while(foundCart)
        {
					if(Cookie.read("CustomPC-"+x))
					{
						x++;
					}
					else
					{
						foundCart = false;
					}
        }
				itemID = "CustomPC-" + x;
        itemLink = "display-build.aspx?customBuild=" + itemID;
        itemDescription = itemID + " - £" + price;
        createCustomPCCookie(itemID);
		}
    else if($(thisObject).getParent('div').getProperty('id') == "productDetails")
    {
				numItems = $(thisObject).getParent('li').getPrevious('li').getElement('input').get('value');
        itemLink = document.URL.toLocaleString();
        itemDescription = $('productDetails').getElement('h2').get('text');
    }
    else
    { 
				numItems = $(thisObject).getPrevious('input').get('value');
        itemLink = $(thisObject).getParent('tr').getElement('a').get('href');
        itemDescription = $(thisObject).getParent('tr').getElement('a').get('text');
    }
    
    price = price.replace(',','');

    if(numItems < 1)
    {
        numItems = 1;
    }

    
    if (Cookie.read("shoppingCart"))
    {
        var shoppingCart = Cookie.read("shoppingCart");     
    
        //break existing cookie up into individual items in array
        var itemArray = shoppingCart.split('~&~');

        //initialise new cookie
        var newShoppingCart = "";
        
        var existingItem = -1;
        for (var i = 0; i < itemArray.length ; i++)
        {
            //break up item into separate parts
            var eachItem = new Array();
            eachItem = itemArray[i].split(':~:');
            
            //check to see if this item is already in the shopping basket
            if(eachItem[0] == itemID)
            {
                existingItem = i;
            }
        }
        
        if(existingItem >= 0)
        {
            //break up item into separate parts
            var eachItem = new Array();
            eachItem = itemArray[existingItem].split(':~:');
            
            itemArray[existingItem] = itemID + ":~:" + itemDescription + ":~:" + price + ":~:" + (parseInt(numItems) + parseInt(eachItem[3])) + ":~:" + itemLink;
            for (var i = 0; i < itemArray.length ; i++)
            {
                if(i==0)
                {
                    newShoppingCart = itemArray[i];
                }
                else
                {
                    newShoppingCart += "~&~" + itemArray[i];
                }
            }
            Cookie.write("shoppingCart",newShoppingCart,{});       
        }
        else
        {
            shoppingCart += "~&~" + itemID + ":~:" + itemDescription + ":~:" + price + ":~:" + numItems + ":~:" + itemLink;
            Cookie.write("shoppingCart",shoppingCart,{});       
        }
        writeCartSummary();
    }
    else
    {
        Cookie.write("shoppingCart",itemID + ":~:" + itemDescription + ":~:" + price + ":~:" + numItems+ ":~:" + itemLink,{});       
        writeCartSummary();
    }
    
		if($('pcBuilderCost'))
		{
		    //window.location = "https://www.meshtechnology.co.uk/shopping-cart.aspx";
		    window.location = "http://www.meshtechnology.co.uk/shopping-cart.aspx";
		}
		else
		{
			$(thisObject).addClass('addedProduct');
			(function(){ $(thisObject).removeClass('addedProduct'); }).delay(2000);
		}
}

function emptyCart()
{
    if (Cookie.read("shoppingCart"))
    {
        Cookie.dispose("shoppingCart",{});
				var cookiePresent = true;
				var i = 1;
				var cookieName = "CustomPC-"+i.toString();
				while(cookiePresent)
				{
					if(Cookie.read(cookieName))
					{
						Cookie.dispose(cookieName,{});
						i++;
						cookieName = "CustomPC-"+i.toString();
					}
					else
					{
						cookiePresent = false;
					}
				}
				
        $('itemCount').set('text', 'items: 0');
        $('totalPrice').set('text', '£0.00');
        if($('shoppingCart'))
        {
            var anchorArray = $('shoppingCart').getElements('a');
            for (var i = 0; i < anchorArray.length ; i++)
            {
                anchorArray[i].toggleClass('inactiveCart');
            }
            
            $('itemsTable').set('html', '<p>Your Cart is empty</p>'); 
        }
    } 
    var mySlide = new Fx.Slide('toggled');
    mySlide.slideOut();
}
