window.onload = init;
window.onunload = writeCookies;

function init() {
    // If Firefox 3, make cartDiv stay fixed
    if (navigator.appName == "Netscape") {

        if (navigator.userAgent.indexOf("Firefox/") != -1) {
            if (navigator.userAgent.split("Firefox/")[1].charAt(0) == "3") {
                document.getElementById("shop").style.direction = "rtl";
                var wrapper = document.getElementById("itemsWrapper");
                wrapper.style.position = "absolute";
                wrapper.style.left     = "0px";
                wrapper.style.direction = "ltr";
                document.getElementById("cartDiv").style.position = "fixed";
            }
        }
    } // End ugly questionable hack

    readCookies();
}

function readCookies() {

    var pairs = getSplitCookie();
    
    if (pairs == null) { return; }
    
    for (var i = 0; i < pairs.length; i++) {
        var nameValue = pairs[i].split("=");
        var name = nameValue[0]; // Probably catNr
        var value = nameValue[1]; // Probably quantity
        // Assumes name is a catNr and checks that it's still is for sale
        var itemName = document.getElementById(name + "name");
        if (itemName != null) {
            // Adds item to cart
            for (var j = 0; j < value; j++) { add(name, itemName.value); }
        }
        // If not checks if name is the currencyCode
        else if (name == "currencyCode") { 
            if (value == "undefined" || value == "0") { 
                document.getElementById("cartLocation").value = "0";
                toggleDisabled(true, true);
                return; 
            }
            document.getElementById("cartLocation").value = value;
            setLocation(value);
        }
    }
    
    var location = document.getElementById("cartLocation");
    if (location.value == "0") { location.focus(); }
}

function getSplitCookie() { return document.cookie.split("; "); }

function writeCookies() {
    // Erases older cookie
    eraseCookies();

    var cart = getCart();
    // If cart not empty:
    if (cart.options[0].value != "0") {

        // Writes currencyCode to cookie
        document.cookie = "currencyCode=" + currencyCode;
    
        // Loops through cart
        for (var i = 0; i < cart.options.length; i++) {
            var catNr = cart.options[i].value;
            var amount = cart.options[i].text.split(" // ")[1];
            
            // Writes cart item to cookie
            document.cookie = catNr + "=" + amount;
        }
    }
    else if (document.getElementById("cartLocation").value != "locationHelpText") {
        // Writes currencyCode to cookie
        document.cookie = "currencyCode=" + currencyCode;
    }

}

function eraseCookies() {
    var pairs = getSplitCookie();
    if (pairs != null) { 
        var expDate = new Date();
        expDate.setTime(expDate.getTime() - 1);
        for (var i = 0; i < pairs.length; i++) {
            document.cookie = pairs[i].split("=")[0] + "=; expires=" + expDate.toGMTString();
        }
    }
}



var totItems = 0; // Total number of items in cart
var currencyCode;

function add(catNr, itemName) {
    
    if (document.getElementById("cartLocation").value == "0") { return false; }

    var inCart = document.getElementById(catNr + "inCart");
    if (document.getElementById("emptyCart") != null) { makeCartNotEmpty();  }
    
    // If item not already in cart
    if (inCart == null) {
        
        // The item to be added
        var addItem   = document.createElement("option");
        addItem.value = catNr;
        addItem.id    = catNr + "inCart";
		
		var text = document.createTextNode(itemName + " // 1");
		addItem.appendChild(text);
		
		getCart().appendChild(addItem); // Adds item to dropdown cart 
		
		updateIcons("add", catNr); // Adds icon
    }
    else {
        var quantity = parseInt(inCart.text.split(" // ")[1]) + 1;
        // Updates quantity
        inCart.text = itemName + " // " + quantity;
    }
    
    totItems++;
    
    var price = getItemPrice(catNr);
    
    flashCartDiv(flashCartColor);
    updateTotalNrOfItems("add");
    updateTotalAmount("add", price);
    getCart().value = catNr;
    toggleDisabled(false, false);
}

function updateIcons(action, catNr) {
    var iconsDiv = document.getElementById("cartIcons");
    
    if (action == "add") {
        var icon = document.createElement("img");
        icon.src = "graphics/catalogue/" + catNr + ".jpg";
        icon.id  = catNr + "icon";
        icon.onclick = function() {
                          document.getElementById("cartDropDown").value = catNr;
                       };
        
        iconsDiv.appendChild(icon); // Adds icon above drop-down
    }
    else if (action == "remove") {
        var icon = document.getElementById(catNr + "icon");
        
        icon.parentNode.removeChild(icon); // Removes icon
    }
    else if (action == "clear") { iconsDiv.innerHTML = ""; }
}

function getItemPrice(catNr) { 
return parseInt(document.getElementById(catNr + "price" + currencyCode).value); 
}

function updateTotalNrOfItems(action) {
    var total = document.getElementById("cartNrOfItems");
    var totalInt = parseInt(total.innerHTML);
    
    if (action == "add") { total.innerHTML = totalInt + 1;  }
    else if (action == "remove") { total.innerHTML = totalInt - 1; }
    else if (action == "clear") { total.innerHTML = 0; }
}

function updateTotalAmount(action, price) {
    var total = document.getElementById("cartTotalAmount");
    var totalInt = parseInt(total.innerHTML);
    
    if (action == "add") { total.innerHTML = totalInt + price;  }
    else if (action == "remove") { total.innerHTML = totalInt - price; }
    else if (action == "clear") { total.innerHTML = 0; }
}


function makeCartNotEmpty() { getCart().innerHTML = ""; }
function makeCartEmpty() {
	var emptyCart   = document.createElement("option");
    emptyCart.value = "0";
    emptyCart.id    = "emptyCart";
	var text = document.createTextNode("Your cart is empty.");
	emptyCart.appendChild(text);

	getCart().innerHTML = "";
	getCart().appendChild(emptyCart);
}

function getCart() { return document.getElementById("cartDropDown"); }
function getCartForm() { return document.getElementById("cartForm"); }


function setLocation(currencyCode) {
    // Sets currencyCode
    document.getElementById("currency_code").value = currencyCode;
    
    this.currencyCode = currencyCode;

    // Shows price below items
    var items = getElementsByClass("shopItems");
    for (var i = 1; i < items.length; i++) {
        var nr = serialize(i);
        var price = document.getElementById("int" + nr + "price" + currencyCode).value;
        var priceTag = document.getElementById("price" + nr);
        priceTag.innerHTML = currencyCode + " " + price;
    }
        
    //Enables add to cart buttons
    toggleDisabled(false, true);
        
    // Removes drop downs help text if needed
    var helpText = document.getElementById("locationHelpText");
    if (helpText != null) { helpText.parentNode.removeChild(helpText); }
    
    // Updates total price
    var totalPrice = document.getElementById("cartTotalAmount");
    
    if (totalPrice.innerHTML != "0") {
        totalPrice.innerHTML = 0;
        // Loops through cart
        var cart = getCart();
        for (var i = 0; i < cart.options.length; i++) {
            var item = cart.options[i];
            var text = item.text.split(" // ");
            var amount = parseInt(text[1]);
            var price = parseInt(document.getElementById(item.value + "price" + currencyCode).value);
            
            // Updates total price
            totalPrice.innerHTML = parseInt(totalPrice.innerHTML) + price * amount;
        }
    }
    
    document.getElementById("cartTotalCurrency").innerHTML = currencyCode;
}

function serialize(nr) {
    nr = "00" + nr;
    nr = nr.substring(nr.length-3, nr.length);
    return nr;
}

function prepareForSubmit() {
    var currencyCode = document.getElementById("currency_code").value;

    // Checks that location is selected
    if (currencyCode == "0") {
        alert("Please select your destination.");
        document.getElementById("cartLocation").focus();
        return false;
    }
    else {
        
        
        // Loops through cart
        var cart = getCart();
        for (var i = 0; i < cart.options.length; i++) {
            // Creates Paypal fields
            
            var paypalIndex = i + 1;
            var option = getCart().options[i];
            var catNr = option.value;
            var itemArray = option.text.split(" // ");
            var itemName = itemArray[0];
            var itemQuantity = itemArray[1];
            var itemAmount = 
                document.getElementById(catNr + "price" + document.getElementById("currency_code").value).value;
            
            var cartForm = getCartForm();
        
            var item_name   = document.createElement("input");
                item_name.type  = "hidden";
                item_name.name  = "item_name_" + paypalIndex;
                item_name.id    = "item_name_" + paypalIndex;
                item_name.value = itemName;
            var item_number   = document.createElement("input");
                item_number.type  = "hidden";
                item_number.name  = "item_number_" + paypalIndex;
                item_number.id    = "item_number_" + paypalIndex;
                item_number.value = catNr;
            var quantity   = document.createElement("input");
                quantity.type  = "hidden";
                quantity.name  = "quantity_" + paypalIndex;
                quantity.id    = "quantity_" + catNr;
                quantity.value = itemQuantity;
            var amount   = document.createElement("input");
                amount.type  = "hidden";
                amount.name  = "amount_" + paypalIndex;
                amount.id    = "amount_" + paypalIndex;
                amount.value = itemAmount;
        
            // Adds fields to form
            cartForm.appendChild(item_name);
            cartForm.appendChild(item_number);
            cartForm.appendChild(quantity);
            cartForm.appendChild(amount);
    
        }
        return true;
    }
}

function removeSelected() {
    
    if (getCart().options[0].value == "0") { return false; }
    
    var item = getCart().options[getCart().selectedIndex];
    var catNr = item.value;
    
    var itemArray = item.text.split(" // ");
    var quantity = parseInt(itemArray[1]);
    
    var price = getItemPrice(catNr);
    
    totItems--;

    if(quantity > 1) {
        quantity--;
        // Sets correct amount in cart
        item.text = itemArray[0] + " // " + quantity;
    }
    else {
        // Removes item from cart
        deleteElement(item);
        updateIcons("remove", catNr); // Removes icon
        
        if (totItems == 0) { 
            makeCartEmpty(); 
            eraseCookies();
            toggleDisabled(true, false);
        }

    }
    flashCartDiv(flashCartColor);
    updateTotalNrOfItems("remove");
    updateTotalAmount("remove", price);
}

function clearCart() {
    if (getCart().options[0].value == "0") { return false; }
    
    var cart = getCart();
    for (var i = 0; i < cart.options.length; i++) {
        deleteElement(document.getElementById(cart.options[i].value + "inCart"));
    }
    totItems = 0;
    
    flashCartDiv(flashCartColor);
    updateTotalNrOfItems("clear");
    updateTotalAmount("clear");
    
    makeCartEmpty();
    eraseCookies();
    updateIcons("clear");
    
    toggleDisabled(true, false);
}


function deleteElement(element) { 
    element.parentNode.removeChild(element);
    if (element != null) { element.id = ""; }
}

var flashCartColor = "#ddaa55";

function getCartDiv() { return document.getElementById("cartDiv"); }

function flashCartDiv(color) {
    var cartDiv = getCartDiv();
    changeDivBgColor(cartDiv, color);
    
    // Changes bgColor back to transparent after second parameter ms
    window.setTimeout(function() { changeDivBgColor(cartDiv, ""); }, 100);
}
function changeDivBgColor(div, color) { div.style.backgroundColor = color; }

function toggleDisabled(state, addButtons) {
    
    var elements;
    
    if (addButtons) { elements = getElementsByClass("addButtons"); }
    else { elements = getElementsByClass("cartDisabledElements"); }
    
    // Toggles the elements' disabled status
    for (var i = 0; i < elements.length; i++) { elements[i].disabled = state; }
}



// Function below written by Dustin Diaz
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\\\s)"+searchClass+"(\\\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


















