/*
    Greetings from Thijsy Wijsy from Wax Interactive!
    Do not try to cheat the Almighty Paypal, for a manual check will make sure 
    you are paying exactly what you need to pay ;-)
*/

function addHiddenField (form, name, value)
{
    var cmd = document.createElement('input');
    cmd.type = 'hidden';
    cmd.name = name;
    cmd.value = value;
    form.appendChild(cmd);
}

var nTaxAmount = 19;
var Bestellen = new Object ();

Bestellen =
{
    'aCountries' : new Array (),
    'aDeliveryZones' : new Array (),
    'aDeliveryWeight' : new Array (),
    
    'config' : function ()
    {
        /*
            COUNTRIES (zone is used to calculate distance)
            Feel free to edit (make sure you save this file in UTF8!)
            
            (Parameters: sCountry, iZone, bHasTax)
        */
        Bestellen.addCountry('Nederland', 0, true);
        Bestellen.addCountry('België', 1, true);
        Bestellen.addCountry('Luxemburg', 2, false);
        Bestellen.addCountry('Duitsland', 3, false);
        Bestellen.addCountry('Frankrijk', 4, false);
        Bestellen.addCountry('Denemarken', 4, false);
        Bestellen.addCountry('Groot Brittanië', 4, false);
        Bestellen.addCountry('Oostenrijk', 4, false);
        Bestellen.addCountry('Zwitserland', 4, false);
        Bestellen.addCountry('Finland', 5, false);
        Bestellen.addCountry('Ierland', 5, false);
        Bestellen.addCountry('Italië', 5, false);
        Bestellen.addCountry('Noorwegen', 5, false);
        Bestellen.addCountry('Portugal', 5, false);
        Bestellen.addCountry('Spanje', 5, false);
        Bestellen.addCountry('Zweden', 5, false);
        Bestellen.addCountry('Bulgarijë', 6, false);
        Bestellen.addCountry('Estland', 6, false);
        Bestellen.addCountry('Griekenland', 6, false);
        Bestellen.addCountry('Hongarije', 6, false);
        Bestellen.addCountry('Letland', 6, false);
        Bestellen.addCountry('Litouwen', 6, false);
        Bestellen.addCountry('Polen', 6, false);
        Bestellen.addCountry('Romenië', 6, false);
        Bestellen.addCountry('Slovenië', 6, false);
        Bestellen.addCountry('Slowakije', 6, false);
        Bestellen.addCountry('Tjechië', 6, false);
        Bestellen.addCountry('Rusland', 7, false);
        Bestellen.addCountry('Turkije', 7, false);
        
        /*
            Deliviry zones
            Feel free to edit (make sure you save this file in UTF8!)
        */
        Bestellen.addDeliveryZone (0, new Array ( 7.95,  8.95, 10.95, 12.95, 13.95, 14.95,  16.95,  17.95,  18.95,  21.95,  22.95,  25.95,  28.95,  33.95,  41.95,  49.95,  54.95), 11.95);
        Bestellen.addDeliveryZone (1, new Array (10.95, 13.95, 16.95, 17.95, 19.95, 21.95,  22.95,  25.95,  28.95,  33.95,  36.95,  41.95,  45.95,  49.95,  54.95,  65.95,  70,95), 13.95);
        Bestellen.addDeliveryZone (2, new Array (13.95, 16.95, 19.95, 22.95, 25.95, 28.95,  33.95,  37.95,  41.95,  45.95,  48.95,  50.95,  51.95,  55.95,  69.95,  83.95,  89.95), 13.95);
        Bestellen.addDeliveryZone (3, new Array (26.95, 27.95, 30.95, 34.95, 37.95, 41.95,  48.95,  55.95,  62.95,  68.95,  75.95,  83.95,  99.95, 107.95, 124.95, 142.95, 159.95), 18.95);
        Bestellen.addDeliveryZone (4, new Array (26.95, 30.95, 35.95, 39.95, 43.95, 47.95,  55.95,  64.95,  73.95,  81.95,  90.95,  98.95, 107.95, 128.95, 150.95, 171.95, 192.95), 26.95);
        Bestellen.addDeliveryZone (5, new Array (30.95, 35.95, 40.95, 45.95, 51.95, 56.95,  67.95,  77.95,  88.95,  99.95, 109.95, 120.95, 130.95, 156.95, 184.95, 210.95, 237.95), 31.95);
        Bestellen.addDeliveryZone (6, new Array (33.95, 39.95, 46.95, 52.95, 59.95, 65.95,  78.95,  91.95, 104.95, 117.95, 130.95, 143.95, 155.95, 188.95 ,220.95, 252.95, 285.95), 35.95);
        Bestellen.addDeliveryZone (7, new Array (49.95, 57.95, 64.95, 72.95, 79.95, 87.95, 102.95, 118.95, 132.95, 147.95, 162.95, 177.95, 192.95, 230.95, 268.95, 306.95, 343.95), 40.95);
        
        /*
            Delivery weight
            Feel free to edit (make sure you save this file in UTF8!)
        */
        Bestellen.aDeliveryWeight = new Array (5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200);
    },
    
    'init' : function ()
    {
        // Initiliaze countries (and html select boxes)
        Bestellen.config ();
        Bestellen.addCountryOptions ();
        Bestellen.updateHtml ();
    },
    
    'updateHtml' : function ()
    {
        var elements = $$('div.product');
        for (var i = 0; i < elements.length; i++)
        {
            var el = elements[i].select('input');
            if (el.length >= 1)
            {
                l = el[0];

                l.onkeyup = function() 
                {
                    if (isInt(this.value)) 
                    {
                        calculate();
                        this.style.backgroundColor = "#ffffff";
                    } else {
                        this.style.backgroundColor = "#EA9B9B";
                    }
                    if (this.value == "") {
                        this.style.backgroundColor = "#ffffff";
                    }
                }
            }       
        }
    },
    
    'addCountry' : function (sName, iZone, bHasTax)
    {
        Bestellen.aCountries.push 
        ({
            'id' : Bestellen.aCountries.length, 
            'sName' : sName, 
            'iZone' : iZone, 
            'bHasTax' : bHasTax
        });
    },
    
    'addCountryOptions' : function ()
    {
        var select = $('toCountry');
        
        if (select)
        {
            Bestellen.aCountries.sort(Bestellen.doCountrySort);
            
            for (var i = 0; i < Bestellen.aCountries.length; i ++)
            {
                var v = Bestellen.aCountries[i];
                var field = new Option (v.sName, v.id);
                field.innerHTML = v.sName;
                if (v.id == 0)
                {
                    field.selected = true;
                }
                select.appendChild (field);
            }
        }
    },
    
    'addDeliveryZone' : function (id, aDeliveryCost, nExtraCost)
    {
        Bestellen.aDeliveryZones.push
        ({
            'id' : id,
            'aDeliveryCost' : aDeliveryCost,
            'nExtraCost' : nExtraCost, // If weight exceeds the above set packages, this is the extra cost / xx kilo
            'nExtraWeight' : 50 // xx kilo
        });
    },
    
    'getCountryTax' : function (id)
    {
        for (var i = 0; i < Bestellen.aCountries.length; i ++)
        {
            if (Bestellen.aCountries[i].id == id)
            {
                return Bestellen.aCountries[i].bHasTax;
            }
        }
        return true;
    },
    
    'getCountryFromId' : function (iCountry)
    {
        for (var i = 0; i < Bestellen.aCountries.length; i ++)
        {
            if (Bestellen.aCountries[i].id == iCountry)
            {
                return Bestellen.aCountries[i];
            }
        }
        return false;
    },
    
    'getDeliveryZoneFromId' : function (iZone)
    {
        for (var i = 0; i < Bestellen.aDeliveryZones.length; i ++)
        {
            if (Bestellen.aDeliveryZones[i].id == iZone)
            {
                return Bestellen.aDeliveryZones[i];
            }
        }
        return false;
    },
    
    /*
        Get the smallest price
    */
    'getDeliveryCostFromWeight' : function (zone, weight)
    {
        for (var i = 0; i < Bestellen.aDeliveryWeight.length; i ++)
        {
            if (weight <= Bestellen.aDeliveryWeight[i])
            {
                return zone.aDeliveryCost[i];
            }
        }
        
        // If that didn't work, take the heighest value and add aditional cost
        var i = Bestellen.aDeliveryWeight.length - 1;
        var basecost = zone.aDeliveryCost[i];
        
        var extraweight = weight - Bestellen.aDeliveryWeight[i];
        var extracost = (extraweight / zone.nExtraWeight) * zone.nExtraCost;
        
        return basecost + extracost;
    },
    
    'getDeliveryCost' : function (iCountry, weight)
    {
        var country = Bestellen.getCountryFromId (iCountry);
        if (country)
        {
            // Get delivery zones for this country
            var zones = Bestellen.getDeliveryZoneFromId (country.iZone);
            if (zones)
            {
                // Get zone from weight
                return Bestellen.getDeliveryCostFromWeight (zones, weight);
            }
            else
            {
                alert ('Delivery zone not found: '+country.iZone);
            }
        }
        else
        {
            alert ('Country not found: '+iCountry);
        }
    },
    
    // Overwrite sort equation
    'doCountrySort' : function (a, b)
    {
        return a.sName > b.sName;
    },
    
    'calculatePrice' : function ()
    {
        // fetch products
        var iCountry = $('toCountry').value;
        
        var tax = Bestellen.getCountryTax (iCountry) ? nTaxAmount : 0;
        
        var objects = $$('div.product');

        var aantal = 0;
        var totalPrice = 0;
        var totalWeight = 0;
        var totalTax = 0;
        
        for (var i = 0; i < objects.length; i ++)
        {       
            var name = objects[i].select('.productname');
            var amount = objects[i].select('input');
            var weight = objects[i].select('span.weight');
            
            if (weight.length == 1)
            {
                weight = parseFloat(weight[0].innerHTML);
            }
            else
            {
                weight = 0;
            }
            
            if (name.length == 1 && amount.length >= 1 && parseInt(amount[0].value) > 0)
            {
                aantal ++;
                
                amount = parseInt(amount[0].value);
                //var price = this.getProductPrice (objects[i], amount);
                var price = this.getProductPrice (objects[i], this.getTotalProductAmount ());
                
                totalWeight += (weight * amount);
                totalPrice += price * amount;
                totalTax += (price / 100) * tax * amount;
            }
        }
        
        var totalDelivery = Bestellen.getDeliveryCost (iCountry, totalWeight);
        
        var output = 
        {
            'nTotalBruto' : totalPrice,
            'nTotalTax' : totalTax,
            'nTotalDelivery' : totalDelivery,
            'nTotalNetto' : totalPrice + totalTax + totalDelivery
        };
        
        return output;
    },
    
    'getStaffelGroup' : function (objProduct)
    {
        var staffel = objProduct.select ('.staffelgroup');
        if (staffel.length == 1)
        {
            return parseInt(staffel[0].innerHTML);
        }
        return false;
    },
    
    'getStaffelProductAmount' : function (objProduct)
    {
        var totalAmount = 0;
        
        // Sum all products with this staffel group
        var staffelgroup = this.getStaffelGroup (objProduct);
        if (staffelgroup)
        {       
            var objects = $$('div.product');
            for (var i = 0; i < objects.length; i ++)
            {
                // Only add amount if staffel group is the same
                if (this.getStaffelGroup(objects[i]) == staffelgroup)
                {
                    var amount = objects[i].select('input');
                    if (amount.length == 1)
                    {
                        var a = parseInt (amount[0].value);
                        if (a > 0)
                        {
                            totalAmount += a;
                        }
                    }
                }
            }
        }
        else
        {
            var input = objProduct.select ('input');
            if (input.length == 1)
            {
                totalAmount += parseInt(input[0].value);
            }
        }
        
        return parseInt(totalAmount);
    },
    
    /*
        Returns the price of 1 product!
    */
    'getProductPrice' : function (objProduct)
    {
        var amount = this.getStaffelProductAmount (objProduct);
    
        // First: check for staffel!
        var spans = objProduct.select('span');
        for (var i = 0; i < spans.length; i ++)
        {
            var iSearch = spans[i].className.search (/staffel/);
            if (iSearch >= 0)
            {
                var substring = spans[i].className.substr (iSearch + 8);
                endString = substring.search (/]/);
                var range = substring.substr (0, endString);
                range = range.split ('-');

                if (range.length == 2)
                {
                    if (range[0] <= amount && range[1] >= amount)
                    {
                        return parseFloat (spans[i].innerHTML);
                    }
                }
                else
                {
                    if (range[0] <= amount)
                    {
                        return parseFloat (spans[i].innerHTML);
                    }
                }
            }
        }
        
        // Second: check for regular price
        price = objProduct.select('span.price');
        if (price.length == 1)
        {
            price = parseFloat (price[0].innerHTML);
        }
        return price;
    },
    
    'getTotalProductAmount' : function ()
    {
        var objects = $$('div.product');
        var totalAmount = 0;
        for (var i = 0; i < objects.length; i ++)
        {
            var amount = objects[i].select('input');
            if (amount.length >= 1)
            {
                var a = parseInt (amount[0].value);
                if (a > 0)
                {
                    totalAmount += a;
                }
            }
        }
        return totalAmount;
    },
    
    'fixNameForPaypal' : function (sName)
    {
        var sReturn = "";
        for (var i = 0; i < sName.length; i ++)
        {
            // Valid range of characters: 32 to 126
            if (sName.charCodeAt(i) > 31 && sName.charCodeAt(i) < 127)
            {
                sReturn += sName[i];
            }
        }
        return sReturn;
    },
    
    'sendPaypalForm' : function (toEmail)
    {
        // fetch products
        var iCountry = $('toCountry').value;
        
        var tax = Bestellen.getCountryTax (iCountry) ? nTaxAmount : 0;
        
        var objects = $$('div.product');
        
        var form = document.createElement('form');
        form.action = 'https://www.paypal.com/nl/cgi-bin/webscr';
        form.method = 'post';
        
        addHiddenField (form, 'cmd', '_cart');
        addHiddenField (form, 'upload', 1);
        addHiddenField (form, 'business', toEmail);
        addHiddenField (form, 'currency_code', 'EUR');

        var aantal = 0;
        var totalWeight = 0;
        
        for (var i = 0; i < objects.length; i ++)
        {      

            var name = objects[i].select('.productname');
            var amount = objects[i].select('input');
            var weight = objects[i].select('span.weight');

            if (weight.length == 1)
            {
                weight = parseFloat(weight[0].innerHTML);
            }
            else
            {
                weight = 0;
            }
            
            if (name.length == 1 && amount.length == 1 && parseInt(amount[0].value) > 0)
            {
				aantal ++;
				
				// product1 heeft 2 types in 1
				if(amount[0].id == 'txtProd1') {
					
					// eerste type ophalen
					amount = parseInt($('txtProd1_1').value);
					var price = this.getProductPrice (objects[i], this.getTotalProductAmount ());
					
					totalWeight += (weight * amount); 
					
					addHiddenField (form, 'item_name_'+aantal, this.fixNameForPaypal (name[0].innerHTML + ": aantal Scania"));
					addHiddenField (form, 'amount_'+aantal, Math.round(price * 100) / 100 );
					addHiddenField (form, 'quantity_'+aantal, amount);
					addHiddenField (form, 'tax_'+aantal, Math.round(((price / 100) * tax)*100) / 100);
					
					if (aantal > 1)
					{
						addHiddenField (form, 'shipping_'+aantal, 0);
					}
					
					addHiddenField (form, 'on0_' + aantal, 'Truck Merk');	
					
					aantal++;
					// 2e type ophalen
					amount = parseInt($('txtProd1_2').value);
					var price = this.getProductPrice (objects[i], this.getTotalProductAmount ());
					
					totalWeight += (weight * amount); 
					
					addHiddenField (form, 'item_name_'+aantal, this.fixNameForPaypal (name[0].innerHTML + ": aantal overige"));
					addHiddenField (form, 'amount_'+aantal, Math.round(price * 100) / 100 );
					addHiddenField (form, 'quantity_'+aantal, amount);
					addHiddenField (form, 'tax_'+aantal, Math.round(((price / 100) * tax)*100) / 100);
					
					if (aantal > 1)
					{
						addHiddenField (form, 'shipping_'+aantal, 0);
					}
					
					addHiddenField (form, 'on0_' + aantal, 'Truck Merk');				
										
				} else {
	
					amount = parseInt(amount[0].value);
					
					// Calculate right price (staffel korting)
					//var price = this.getProductPrice (objects[i], amount);
					var price = this.getProductPrice (objects[i], this.getTotalProductAmount ());
					
					totalWeight += (weight * amount);            	
		
					addHiddenField (form, 'item_name_'+aantal, this.fixNameForPaypal (name[0].innerHTML));
					addHiddenField (form, 'amount_'+aantal, Math.round(price * 100) / 100 );
					addHiddenField (form, 'quantity_'+aantal, amount);
					addHiddenField (form, 'tax_'+aantal, Math.round(((price / 100) * tax)*100) / 100);
					
					if (aantal > 1)
					{
						addHiddenField (form, 'shipping_'+aantal, 0);
					}
					
					addHiddenField (form, 'on0_' + aantal, 'Truck Merk');
					/*addHiddenField (form, 'os0_' + aantal, this.fixNameForPaypal ($('forTruck').value));*/				
				
				}                
            }
        }
        
        var shipping = Bestellen.getDeliveryCost (iCountry, totalWeight);
        addHiddenField (form, 'shipping_1', Math.round(shipping * 100) / 100);
        
        if (aantal > 0)
        {
            document.body.appendChild (form);
            form.submit ();
        }
    },
    
    'updateProduct1' : function () {
        
        var totalAmmount = 0;
        
        if($('txtProd1_1').value != "") {
        
            if(isInt($('txtProd1_1').value)) {
              $('txtProd1_1').style.backgroundColor = "#ffffff";
              totalAmmount += parseInt($('txtProd1_1').value);
            } else {
                this.style.backgroundColor = "#EA9B9B";
            }
                
        }
        
        if($('txtProd1_2').value != "") {
        
            if(isInt($('txtProd1_2').value)) {
            
             $('txtProd1_2').style.backgroundColor = "#ffffff";
             totalAmmount += parseInt($('txtProd1_2').value);
             $('txtProd3').value = $('txtProd1_2').value;
              
            } else {
                $('txtProd1_2').style.backgroundColor = "#EA9B9B";
            }
                
        }
        
        $('txtProd1').value = totalAmmount;
        calculate();
        
    }
}

Event.observe(window, 'load', Bestellen.init, false);
