﻿var payback = {
    conversionRate: 1.15,

    start: function() {
        var button = $('.input .calculate');
        if (button.length > 0) {
            button.click(payback.click);
            $('a.pound').click(function() { payback.setCurrency('pound'); return false; });
            $('a.euro').click(function() { payback.setCurrency('euro'); return false; });
            payback.loadUrl();
        }
    },

    click: function() {
        var quantity = $('#quantity').val();
        var hoursPerDay = $('#hoursperday').val();
        var daysPerWeek = $('#daysperweek').val();
        var weeksPerYear = $('#weeksperyear').val();
        var cost = $('#cost').val();
        var lampChangeTime = $('#lampchangetime').val();
        var labourRate = $('#labourrate').val();
        var numberOfStaff = $('#numberofstaff').val();
        var additionalEquipment = $('#additionalequipment').val();
        var productLifeSpanHoursTenThou = 10000;
        var productLifeSpanYearsTenThou = productLifeSpanHoursTenThou / (hoursPerDay * daysPerWeek * weeksPerYear);
        var productLifeSpanHours = 50000;
        var productLifeSpanYears = productLifeSpanHours / (hoursPerDay * daysPerWeek * weeksPerYear);
        var lampChangesThroughLife = $('#lampchangesthroughlife').text();
        var lampsPerLuminaire = $('#lampsperluminaire').text();
        var costPerLamp = parseFloat($('#costperlamp_pound').text().substring(1));
        var ledCostThroughLife, cflCostThroughLife;

        // validation
        var isValid = true;
        if (isNaN(quantity) || quantity == 0)
            isValid = false;
        if (isNaN(hoursPerDay) || hoursPerDay == 0)
            isValid = false;
        if (isNaN(daysPerWeek) || daysPerWeek == 0)
            isValid = false;
        if (isNaN(weeksPerYear) || weeksPerYear == 0)
            isValid = false;
        if (isNaN(cost) || cost == 0)
            isValid = false;
        if (isNaN(lampChangeTime) || lampChangeTime == 0)
            isValid = false;
        if (isNaN(labourRate) || labourRate == 0)
            isValid = false;
        if (isNaN(numberOfStaff) || numberOfStaff == 0)
            isValid = false;
        if (isNaN(additionalEquipment))
            isValid = false;

        if (!isValid) {
            alert('Please check your input');
            return false;
        }

        payback.saveUrl();

        $(new Array('cfl', 'led')).each(function(i, name) {
            var totalWatts = parseInt($('#' + name + "_totalwatts").text());
            var costThroughLife = (quantity * (totalWatts / 1000) * productLifeSpanHours * cost);
            var costPerYear = costThroughLife / productLifeSpanYears;

            $('#' + name + '_costthroughlife_pound').text(payback.formatCurrency(costThroughLife, '£'));
            $('#' + name + '_costthroughlife_euro').text(payback.formatCurrency(costThroughLife * payback.conversionRate, '€'));
            $('#' + name + '_costperyear_pound').text(payback.formatCurrency(costPerYear, '£'));
            $('#' + name + '_costperyear_euro').text(payback.formatCurrency(costPerYear * payback.conversionRate, '€'));

            if (name == 'led') ledCostThroughLife = costThroughLife;
            if (name == 'cfl') cflCostThroughLife = costThroughLife;
        });

        $('#cf1_lifespaninyears').text(roundNumber(productLifeSpanYears, 1));
        $('#cf1_lifespaninyearstenthou').text(roundNumber(productLifeSpanYearsTenThou, 1));

        var saving = cflCostThroughLife - ledCostThroughLife;
        var percentage = Math.round(100 * saving / cflCostThroughLife);
        $('#led_saving_pound').text(payback.formatCurrency(saving, '£'));
        $('#led_saving_euro').text(payback.formatCurrency(saving * payback.conversionRate, '€'));
        $('#led_percentage').text(percentage + '%');

        var cflTotalCostThroughLife = (lampChangesThroughLife * costPerLamp * lampsPerLuminaire * quantity) + (lampChangesThroughLife * quantity * (numberOfStaff * (labourRate / 60 * lampChangeTime))) + (lampChangesThroughLife * additionalEquipment);
        var cflTotalCostPerYear = cflTotalCostThroughLife / productLifeSpanYears;

        $('#cfltotalcostthroughlife_pound').text(payback.formatCurrency(cflTotalCostThroughLife, '£'));
        $('#cfltotalcostthroughlife_euro').text(payback.formatCurrency(cflTotalCostThroughLife * payback.conversionRate, '€'));
        $('#cfltotalcostperyear_pound').text(payback.formatCurrency(cflTotalCostPerYear, '£'));
        $('#cfltotalcostperyear_euro').text(payback.formatCurrency(cflTotalCostPerYear * payback.conversionRate, '€'));

        $('#saving_pound').text(payback.formatCurrency(cflTotalCostThroughLife, '£'));
        $('#saving_euro').text(payback.formatCurrency(cflTotalCostThroughLife * payback.conversionRate, '€'));

        var totalSavingThroughLife = saving + cflTotalCostThroughLife;
        var totalSavingPerYear = totalSavingThroughLife / productLifeSpanYears;

        $('#totalsavingthroughlife_pound').text(payback.formatCurrency(totalSavingThroughLife, '£'));
        $('#totalsavingthroughlife_euro').text(payback.formatCurrency(totalSavingThroughLife * payback.conversionRate, '€'));
        $('#totalsavingperyear_pound').text(payback.formatCurrency(totalSavingPerYear, '£'));
        $('#totalsavingperyear_euro').text(payback.formatCurrency(totalSavingPerYear * payback.conversionRate, '€'));

        payback.totalSavingPerYear = totalSavingPerYear;
        //payback.costChanged();
        return false;
    },

    saveUrl: function() {
        var hash = '#';
        hash += 'currency=' + ($('.form').hasClass('euro') ? 'euro' : 'pound');
        hash += ',quantity=' + $('#quantity').val();
        hash += ',hoursperday=' + $('#hoursperday').val();
        hash += ',daysperweek=' + $('#daysperweek').val();
        hash += ',weeksperyear=' + $('#weeksperyear').val();
        hash += ',cost=' + $('#cost').val();
        hash += ',lampchangetime=' + $('#lampchangetime').val();
        hash += ',labourrate=' + $('#labourrate').val();
        hash += ',numberofstaff=' + $('#numberofstaff').val();
        hash += ',additionalequipment=' + $('#additionalequipment').val();
        document.location = hash;
    },

    loadUrl: function() {
        var params = document.location.hash.substring(1).split(',');
        if (params.length > 1) {
            $(params).each(function(i, param) {
                var keyValue = param.split('=');
                switch (keyValue[0]) {
                    case 'currency':
                        $('.form').removeClass('pound').removeClass('euro').addClass(keyValue[1]);
                        break;
                    default:
                        $('#' + keyValue[0]).val(keyValue[1]);
                        break;
                }
            });
            payback.click();
        }
    },

    formatCurrency: function(num, symbol) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.round(num * 100 + 0.50000000001);
        num = Math.round(num / 100).toString();
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + symbol + num);
    },

    /*costChanged: function() {
    var quantity = $('#quantity').val();
    var cflTotalCapitalCost = parseInt($('#cflcost').val()) * quantity;
    var ledTotalCapitalCost = parseInt($('#ledcost').val()) * quantity;
    $('#cfl_capitalcost').text(payback.formatCurrency(cflTotalCapitalCost));
    $('#led_capitalcost').text(payback.formatCurrency(ledTotalCapitalCost));

        var paybackYears = (ledTotalCapitalCost - cflTotalCapitalCost) / payback.totalSavingPerYear;
    var pby = $('#paybackyears');
    pby.text(paybackYears.toFixed(1));
    if (isNaN(paybackYears) || paybackYears < 0)
    pby.text('');

    },*/

    setCurrency: function(currency) {
        var form = $('.form');
        form.removeClass('pound');
        form.removeClass('euro');
        form.addClass(currency);
        payback.saveUrl();
    },

    printOpened: function() {
        var height = $.browser.msie || $.browser.safari ? '148px' : '143px';
        $('.rwWindowContent iframe').height(height);
        //window.print();
    },

    printClosed: function(clientName, projectName) {
        //window.print();
        $('#clientname').text(clientName);
        $('#projectname').text(projectName);
        $('#printheader p').css('display', 'block');
        window.print();
    },

    sendOpened: function() {
        var height = '242px';
        $('.rwWindowContent iframe').height(height);
    }
};

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

$(payback.start);