﻿// Currency Functions
var dollar = 0;
var sterling = 1;
var euro = 0;

function pageLoad() {

   getRates();
    // Get current currency
    $.ajax({
        type: "POST",
        url: '/methods/methods.aspx/getCurrency',
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data = JSON.parse(data.d);
            Currency = data.currency;
            $('.currencyConverter li').removeClass('selected');
            $('.currencyConverter li a.' + Currency).parent().addClass('selected');
            // Once we have the selected currenct run currency conversion
            setPrices();
        }
    });

    //Setup currency coversion buttons function
    $('.currencyConverter a').each(function() {
        $(this).click(function() {
            $('.currencyConverter a').parent().removeClass('selected');
            $(this).parent().addClass('selected');
            //Work out which button was pressed
            Currency = $(this).attr('class');
            $.ajax({
                type: "POST",
                url: '/methods/methods.aspx/setCurrency',
                data: '{"currency":"' + Currency + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) { }
            });
            //Run the actual conversion
            setPrices();
            return false;
        });
    });
}


function getRates(){
    //Get the exchange rates
    $.ajax({
        type: "POST",
        url: '/methods/methods.aspx/getRates',
        async: false,
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            result = JSON.parse(data.d);
            rates = result.rates;
            dollar = rates.Dollar;
            euro = rates.Euro;
        }
    });
    
    
}

// Function to do currency conversion for all prices on page. Takes string of row to limit replace to certain area on page
function setPrices(row) {
    var Symbol;
    if (euro == 0) {
        getRates();
    }
    //Some vars to store prices temporarily
    var OriginalPrice;
    var NewPrice;
    var Rate

    switch (Currency) {
        case "dollar":
            Rate = dollar;
            Symbol = "$";
            break;
        case "sterling":
            Rate = sterling;
            Symbol = "£";
            break;
        case "euro":
            Rate = euro;
            Symbol = "€";
            break;
    }
    if (row == undefined) {
        row = "";
    }

    //Go through each element with a class of price
    $(row + ' .currency, .totalRow .currency').each(function() {
        //Otherwise, the original price should be part of the class

        OriginalPrice = parseFloat($(this).find('.original').html());

        NewPrice = OriginalPrice * Rate;
        if (NewPrice > 1000) {
            $(this).find('.original').next().html(Symbol + CommaFormatted(NewPrice.toFixed(2).toString()));
        }
        else {
            $(this).find('.original').next().html(Symbol + NewPrice.toFixed(2));
        }
        
    });
}


//Comma format a number
function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) {
        return '';
    }
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) {
        a.unshift(n);
    }
    n = a.join(delimiter);
    if (d.length < 1) {
        amount = n;
    }
    else {
        amount = n;
    }
    amount = minus + amount;
    return amount;
}
