﻿/*
# -*- coding: utf-8 -*-
#   $Author: nic $
#   $Date: 2008-01-25 19:22:33 +0000 (Fri, 25 Jan 2008) $
#   $Rev: 364 $
#   $URL: http://lilleymania.webfactional.com/svnlunar/lunartics/trunk/source/lunartics/public/javascript/shopping.js $
#   $Id: shopping.js 364 2008-01-25 19:22:33Z nic $
#
*/

function invalidateCache() {
    var data = "";
	var opt = {
		method: 'post',
		postBody: data,
		on404: function(t) { // Handle 404
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},
		onFailure: function(t) { // Handle other errors
			alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}
	new Ajax.Request("/admin/invalidateCache", opt);
	return false;
}

// Add a product to the shopping basket
function addToBasket(code, uniqueno, elementToUpdate, elementToHighlight) {
	var data = 'code='+code+"&uniqueno="+uniqueno;
	var opt = {
		method: 'post',
		postBody: data,
		onSuccess: function(t) {
            var basket = eval('('+ t.responseText +')').basket;
            var fragment = createSubNavFragment(basket);
            if ($("basketsummary").style.display == "none") {
                $("basketsummary").style.display = "";
            }
			updateElement('tobasket', 'basketsummary', fragment);
			invalidateCache();
			if (elementToUpdate != undefined) {
                updateElement(elementToUpdate, undefined, getQuantity(basket, code, uniqueno));
            }
		},
		on404: function(t) { // Handle 404
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},
		onFailure: function(t) { // Handle other errors
			alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}
	new Ajax.Request("/shop/addtobasket", opt);
	return false;
}

// Remove a product from the shopping basket
function removeFromBasket(code, uniqueno, qty, elementToUpdate, elementToHighlight) {
    var data = 'code='+code+"&uniqueno="+uniqueno+"&qty="+qty;
    var opt = {
        method: 'post',
        postBody: data,
        onSuccess: function(t) {
            var basket = eval('('+ t.responseText +')').basket;
            if (elementToUpdate != undefined) {
                updateElement(elementToUpdate, undefined, getQuantity(basket, code, uniqueno));
                var removeRow = true;
                for (var i = 0; i < basket.length; i++) {
                    var item = basket[i];
                    if (item.ProductTypeCode == code && item.ProductUniqueNo == uniqueno) {
                        removeRow = false;
                        break;
                    }
                }
                if (basket.length == 0 || removeRow) {
                    var row = $(elementToHighlight);
                    var body = row.parentNode;
                    body.deleteRow(row.rowIndex-1);
                    if (body.rows.length == 0) {
                        replaceDivWithEmptyBasket(body);
                        $("basketsummary").style.display = "none";
                        invalidateCache();
                    }
                }
            }
            if (basket.length > 0) {
                var subNavFrag = createSubNavFragment(basket);
                updateElement('tobasket', 'basketsummary', subNavFrag);
            }
        },
        on404: function(t) { // Handle 404
            alert('Error 404: location "' + t.statusText + '" was not found.');
        },
        onFailure: function(t) { // Handle other errors
            alert('Error ' + t.status + ' -- ' + t.statusText);
        }
    }
    new Ajax.Request("/shop/removefrombasket", opt);
    return false;
}

function updateSubNav(basket) {
    var fragment = createSubNavFragment(basket);
    updateElement('tobasket', undefined, fragment);
}

function getLength(basket) {
    var length = 0;
    for (var i = 0; i < basket.length; i++) {
        var item = basket[i];
        length += parseFloat(item.Quantity);
    }
    return length;
}

function getQuantity(basket, code, uniqueno) {
    var length = 0;
    for (var i = 0; i < basket.length; i++) {
        var item = basket[i];
        if (item.ProductUniqueNo == uniqueno && item.ProductTypeCode == code) {
            length = parseFloat(item.Quantity);
            break;
        }
    }
    return length;
}

function createSubNavFragment(basket) {
    var length = getLength(basket);
    var text = "Lunartics";
    if (length == 1)
        text = "Lunartic";
    var fragment = "You have " + length + " " + text + " in your basket";
    return fragment;
}

// updates an element with the number of items
function updateElement(element, elementToHighlight, fragment) {
    $(element).innerHTML = fragment;
    if (elementToHighlight != undefined) {
	   new Effect.Shake($(elementToHighlight));
    }
}

function increaseQuantity(code, uniqueno, tr, td) {
	addToBasket(code, uniqueno, td, tr);
}

function decreaseQuantity(code, uniqueno, tr, td) {
	removeFromBasket(code, uniqueno, 1, td, tr);
}

function removeRow(code, uniqueno, tr) {
    removeFromBasket(code, uniqueno, 9999);
	var row = $(tr);
    var body = row.parentNode;
    body.deleteRow(row.rowIndex-1);
    if (body.rows.length == 0) {
        replaceDivWithEmptyBasket(body);
        $("basketsummary").style.display = "none";
        invalidateCache();
    }
}

function replaceDivWithEmptyBasket(body) {
    var div = body.parentNode.parentNode;
    div.innerHTML = "Your basket is empty<div class='proceed'><input type='button' class='btn' onclick='window.location.href = \"/shop/catalogue\";' title='Go to the shop' value='Go to the shop...'/></div>";
}

function calculateShippingAndVAT(destination, totalprice, products) {
    var delivery = 0;
    var vat = 0;
    var taxRate=document.getElementsByName("checkout-flow-support.merchant-checkout-flow-support.tax-tables.default-tax-table.tax-rules.default-tax-rule-1.rate");
    var taxArea=document.getElementsByName("checkout-flow-support.merchant-checkout-flow-support.tax-tables.default-tax-table.tax-rules.default-tax-rule-1.tax-area.postal-area.country-code");
    var shippingTaxed=document.getElementsByName("checkout-flow-support.merchant-checkout-flow-support.tax-tables.default-tax-table.tax-rules.default-tax-rule-1.shipping-taxed");
    shippingTaxed[0].value = "true";
    taxRate[0].value = "0.175";
    
    if (destination=="UK") {
        if (totalprice > 0 && totalprice < 10)
            delivery = "2.50";
        else if(totalprice > 10 && totalprice < 30)
            delivery = "3.95";
        else if(totalprice > 30 && totalprice < 50)
            delivery = "4.95";
        else if(totalprice > 50 && totalprice < 70)
            delivery = "5.95";
        else if(totalprice > 70)
            delivery = "0.00";
    }
    else if(destination=="Europe") {
        if (totalprice > 0 && totalprice < 10)
            delivery = "4.00";
        else if(totalprice > 10 && totalprice < 30)
            delivery = "6.00";
        else if(totalprice > 30 && totalprice < 50)
            delivery = "8.00";
        else if(totalprice > 50 && totalprice < 70)
            delivery = "10.00";
        else if(totalprice > 70)
            delivery = "0.00";
    }
    else if(destination=="World") {
        taxRate[0].value = "0.00";
        shippingTaxed[0].value = "false";
        if (totalprice > 0 && totalprice < 10)
            delivery = "6.00";
        else if(totalprice > 10 && totalprice < 30)
            delivery = "8.00";
        else if(totalprice > 30 && totalprice < 50)
            delivery = "10.00";
        else if(totalprice > 50 && totalprice < 70)
            delivery = "12.00";
        else if(totalprice > 70)
            delivery = "0.00";
        $("vat").innerHTML = "£0.00";
    }
    if (shippingTaxed[0].value == "true") {
        vat = iterateBasket(products);
        vat += half_up_rounding(parseFloat(delivery), 17.5);
        vat = vat.toFixed(2);
        if (vat > 0) {
            $("vat").innerHTML = "£"+vat;
        }
    }
    
    var overall = totalprice+parseFloat(delivery)+parseFloat(vat);
    overall = overall.toFixed(2);
    var els = document.getElementsByName("ship_method_price_1");
    if (delivery=="0.00") {
        $("delivery").innerHTML = "Free";
        $(els[0]).value = "0.00";
    }
    else {
        $("delivery").innerHTML = "£"+delivery;
        $(els[0]).value = delivery;
    }
    $("total").innerHTML = "£"+overall;
}

function iterateBasket(products) {
    var vat = 0;
    for (var n in products) {
        if (products.hasOwnProperty(n)) {
            product = products[n];
            vat += half_up_rounding( (parseFloat(product.Price) * parseFloat(product.Quantity) ), 17.5);
        }
    }
    return vat;
}

function half_up_rounding(value, tax) {
    var tmp = (tax / 100 * (value));
    return round(tmp, 2);
}

function round(rval, rpl) {
    var p = parseFloat(Math.pow(10,rpl));
    rval = rval * p;
    var tmp = Math.round(rval);
    return parseFloat(tmp/p);
}

function processOrder() {
    var data = "total="+$("total").innerHTML.substr(1);
	var opt = {
		method: 'post',
		postBody: data,
		onSuccess: function(t) {
            $("google-checkout").submit();
        },
		on404: function(t) { // Handle 404
			alert('Error 404: location "' + t.statusText + '" was not found.');
		},
		onFailure: function(t) { // Handle other errors
			alert('Error ' + t.status + ' -- ' + t.statusText);
		},
		onComplete: function(t) {
            invalidateCache();
        }
	}
	new Ajax.Request("/shop/processorder", opt);
	return false;
}
