var docvars = null;


// Read URL GET variables and put them into the global docvars collection.
function getDocvars() {
    docvars = new Array();
    tmp = location.search.substr(1).split('&');
    for (i = 0; i < tmp.length; ++i) {
        pair = tmp[i].split('=');
        docvars[String(pair[0])] = String(pair[1]);
    }
}

// Get the value of the specified form element
function getValue(id) {
    var e, result;
    e = document.getElementById(String(id));
    if (!e)
        document.write("Error: element not found (" + String(id) + ").");
    result = validateInput(e.value);
    e.value = dot2comma(result);
    return result;
}

// Format a number for German users (using a comma as decimal separator)
function dot2comma(v) {
    v = (String)(v);
    return v.replace(/\./g, ',');
}

// Rounds a money value, using exactly two decimal places (adding zeroes where necessary).
function roundMoney(v) {
    var result;

    result = (String)(Math.round(v * 100.0) / 100.0);

    dotindex = result.indexOf('.');
    if (dotindex < 0)
        return result + '.00';

    fracpart = result.length - 1 - dotindex;
    switch (fracpart) {
        case 0:
            return result + '00';
        case 1:
            return result + '0';
        default:
            return result;
    }

    return result;
}

// Validates a numeric input (very simple validation)
function validateInput(val) {
    val = val.replace(/,/g, '.');
    val = Number(val);
    return val;
}

// These variables hold the result of the calculation for the 3 available tariffs.
// Fuelcost is identical in all tariffs, totalcost is the tariff-specific part of 
// the total price (everything except fuel).
var totalcost;
var kmcost;
var timecost;
var fuelcost;
var drivecost;
var creditedfeecost;

// Calculates the total cost.
function calc() {
    // First, we read the relevant tariff settings from the document.
    var isbusiness = (Number)(document.getElementById("privat_business").value);
    var hasopnv = (Number)(document.getElementById("opnv_yesno").value);
    if (isbusiness)
        hasopnv = 0;

    // Read the driving pattern inputs:
    // Kilometers per car class
    var kms = new Array();
    for (i = 0; i < number_of_carclasses; ++i)
        kms[i] = getValue('km.' + i);

    // ...and hours per car class per time zone
    var hours = new Array();
    for (i = 0; i < number_of_carclasses; ++i) {
        hours[i] = new Array();
        for (j = 0; j < number_of_timezones; ++j)
            hours[i][j] = getValue('hours.' + i + '.' + j);
    }

    // Calculate the fuel cost
    fuelcost = 0;
    for (i = 0; i < number_of_carclasses; ++i)
        fuelcost += fuelprice[isbusiness][i] * kms[i];

    // Calculate the kilometer costs
    kmcost = new Array();
    for (t = 0; t < number_of_tariffs; ++t) {
        kmcost[t] = 0.0;
        for (c = 0; c < number_of_carclasses; ++c)
            kmcost[t] += kmprice[isbusiness][t][c] * kms[c];
    }

    // Calculate the time costs
    timecost = new Array();
    for (t = 0; t < number_of_tariffs; ++t) {
        timecost[t] = 0.0;
        for (z = 0; z < number_of_timezones; ++z)
            for (c = 0; c < number_of_carclasses; ++c)
            timecost[t] += hourrate[isbusiness][t][c][z] * hours[c][z];
    }

    // Now we can calculate the total cost, and find out which tariff is the cheapest
    totalcost = new Array();
    drivecost = new Array();
    creditedfeecost = new Array();
    cheapest = -1;
    for (t = 0; t < number_of_tariffs; ++t) {
        if ((hasopnv || (t == 0)) && (isbusiness == 0)) {
            totalcost[t] = Math.max(monthlyfee[isbusiness][t], kmcost[t]);
        }
        else {
            totalcost[t] = monthlyfee[isbusiness][t] + kmcost[t];
        }
        drivecost[t] = kmcost[t] + timecost[t];
        totalcost[t] += timecost[t];
        creditedfeecost[t] = totalcost[t] - drivecost[t];

        if ((cheapest < 0) || ((Number)(totalcost[t]) < (Number)(totalcost[cheapest]))) {
            cheapest = t;
        }
    }

    // Finally, feed the calculated values back into the document.
    for (t = 0; t < 3; ++t) {
        var cn = "";

        if (totalcost[t] == totalcost[cheapest])
            cn = "cheapest";

        document.getElementById("tarifheader." + t).className = cn;
        document.getElementById("kosten." + t).className = cn;
        document.getElementById("kosten_pf." + t).className = cn;
        document.getElementById("kosten_total." + t).className = cn;

        document.getElementById("kosten." + t).innerHTML = dot2comma(roundMoney(drivecost[t]));
        document.getElementById("kosten_pf." + t).innerHTML = dot2comma(roundMoney(drivecost[t] + fuelcost));
        document.getElementById("kosten_total." + t).innerHTML = dot2comma(roundMoney(totalcost[t] + fuelcost));

        document.getElementById("tarifheader." + t).innerHTML = tariff_name[isbusiness][t];
    }

    document.getElementById("mwst").innerHTML = vat_text[isbusiness];
    (isbusiness ?
			"Alle Preise sind <strong>exklusiv</strong> 19% gesetzl. MwSt." :
			"Alle Preise sind <strong>inklusiv</strong> 19% gesetzl. MwSt.");

    document.getElementById("fuelcost").innerHTML = dot2comma(roundMoney(fuelcost));

    var tbl = document.getElementById("result_table");
    if (tbl.style)
        tbl.style.display = "";
}

// For business customers, blur the OPNV dropdown, since business tariffs do not have any OPNV discount.
// Also, adjust the page title to reflect the change.
function check_opnv_blur() {
    var isbusiness = Number(document.getElementById("privat_business").value);
    var e = document.getElementById("opnv_settings");
    var t = document.getElementById("title");
    if (isbusiness) {
        e.style.visibility = "hidden";
    }
    else {
        e.style.visibility = "visible";
    }
    document.getElementById("title").firstChild.nodeValue = page_title[isbusiness];
    document.title = page_title[isbusiness];

    for (t = 0; t < number_of_tariffs; ++t)
        document.getElementById("tarifheader." + t).innerHTML = tariff_name[isbusiness][t];
}

function get_business() {
    return Number(document.getElementById("privat_business").value);
}

function set_business(val) {
    if (get_business() != val) {
        document.getElementById("privat_business").value = (val ? 1 : 0);
        check_opnv_blur();
    }
}

function set_business_private() {
    var baseloc = window.location.href.split('?');
    var newloc = 'about:blank';
    if (get_business())
        newloc = baseloc[0] + '?type=business';
    else
        newloc = baseloc[0] + '?type=private';
    if (newloc != window.location.href)
        window.location = newloc;
}


function subscribe() {
    var uri = 'http://customer.greenwheels.com/public/registration_customer.aspx?';
    uri += 'org=' + String(organisation);
    uri += '&lang=' + language;
    uri += '&company=' + (get_business() ? 'true' : 'false');
    uri += '&utm_campaign=inschrijven';
    uri += '&utm_medium=green_button';
    if (language == 'nl')
        uri += '&utm_source=public_GWnl_' + (get_business() ? 'b' : 'p') + '_tarieven_vergelijker';
    else
        uri += '&utm_source=public_GWde_' + (get_business() ? 'b' : 'p') + '_tarifentscheidung';
    window.location = uri;
}

// General initialization...
function init() {
    getDocvars();
    
    var tbl = document.getElementById("result_table");
    if (tbl.style)
        tbl.style.display = "none";

    switch (docvars["type"]) {
        case 'business':
            set_business(1);
            break;
        case 'private':
            set_business(0);
            break;
        default:
            newloc = window.location.href.split('?') + '?type=private';
            document.write('Please wait for automatic redirection, or use <a href="' + newloc + '">this link</a> to go to the correct page.');
            window.location = newloc;
            break;
    }

    if (!get_business()) {
        switch (docvars["discount"]) {
            default:
            case 'yes':
                document.getElementById("opnv_yesno").value = 1;
                break;
            case 'no':
                document.getElementById("opnv_yesno").value = 0;
                break;
        }
    }

    e = document.getElementById("fuel_date_long");
    if (e)
        e.innerHTML = fuel_date_long;

    e = document.getElementById("fuel_date_short");
    if (e)
        e.innerHTML = fuel_date_short;
}
