﻿exPub = new Object;

// Currency conversion functionality.
exPub.getCurrencyInfo = (function () {
    var CurrencyInfo = null;
    var getCurrencyInfo = function (callBack) {
        if (CurrencyInfo === null) {
            $.ajax({
                url: '/Currencies/GetExchangeRates',
                type: "GET",
                success: function (data) {
                    var exchangeInfo = data;
                    rates = exchangeInfo.query.results.rate;
                    if (exchangeInfo.query.results.rate.Rate === "0.00") {
                        callBack(new Object, true);
                        return;
                    }
                    if (rates[0] == undefined) {
                        rates = [];
                        rates[0] = exchangeInfo.query.results.rate;
                    }
                    CurrencyInfo = new Object;
                    CurrencyInfo.BaseCurrency = rates[0].id.slice(0, 3);
                    CurrencyInfo.ExchangeCurrencies = [];
                    for (var i = 0; i < rates.length; i++) {
                        var Currency = new Object;
                        Currency.Name = rates[i].id.slice(3, 6);
                        Currency.Rate = parseFloat(rates[i].Rate);
                        CurrencyInfo.ExchangeCurrencies[i] = Currency;
                    }
                    callBack(CurrencyInfo, false);
                }
            });
        }
    }
    return getCurrencyInfo;
})();

exPub.InitCurrencyConverter = (function () {
    var CurrencyInfo = null;
    var Retries = 0;
    var DialogName = "CurrencyExchange";
    var DialogSelector = "#" + DialogName;
    var NoInfoAvailable = true;
    var decimalPlaces = 0;
    var theDialog = null;

    // number formatting function
    // copyright Stephen Chapman 24th March 2006, 10th February 2007
    // permission to use this function is granted provided
    // that this copyright notice is retained intact
    function formatNumber(num, dec, thou, pnt, curr1, curr2, n1, n2) {
        var x = Math.round(num * Math.pow(10, dec));
        if (x >= 0) n1 = n2 = '';

        var y = ('' + Math.abs(x)).split('');
        var z = y.length - dec;

        if (z < 0) z--;

        for (var i = z; i < 0; i++)
            y.unshift('0');

        y.splice(z, 0, pnt);
        if (y[0] == pnt) y.unshift('0');

        while (z > 3) {
            z -= 3;
            y.splice(z, 0, thou);
        }

        var r = curr1 + n1 + y.join('') + n2 + curr2;
        return r;
    }

    function CreateTemplate() {
        var tmpl = '<script id="' + DialogName + '" type="text/html">' +
                        '<div class="ShowConversion">' +
                           "{{each(i, Currency) ExchangeCurrencies }}" +
                                '<div class="ConversionItem">' +
                                    "${Currency.Name}: ${Currency.ConvertedValue}<br/>" +
                                '</div>' +
                            "{{/each}}" +
                        '</div>' +
                    '</script>';
        $(tmpl).insertAfter("#outpage");
    };

    function ConversionInfo(BaseInfo, BaseValue) {
        var ConversionInfo = new Object;
        ConversionInfo.BaseCurrency = BaseInfo.BaseCurrency;
        ConversionInfo.BaseValue = BaseValue;
        ConversionInfo.ExchangeCurrencies = [];
        for (var i = 0; i < BaseInfo.ExchangeCurrencies.length; i++) {
            var Currency = new Object;
            Currency.Name = BaseInfo.ExchangeCurrencies[i].Name;
            Currency.Rate = BaseInfo.ExchangeCurrencies[i].Rate;
            ConvertedNumber = BaseInfo.ExchangeCurrencies[i].Rate * BaseValue;
            Currency.ConvertedValue = formatNumber(ConvertedNumber, decimalPlaces, ' ', '', '', '', '-', '');
            ConversionInfo.ExchangeCurrencies[i] = Currency;
        }
        return ConversionInfo;
    };

    function HandelEvent(item) {
        if (NoInfoAvailable) return;
        var BaseValue = parseFloat($(item).attr("id"));
        var Info = ConversionInfo(CurrencyInfo, BaseValue);
        $(".ShowConversion").dialog("close");
        $("#CurrencyExchange").tmpl(Info).insertAfter(item);
        $(".ShowConversion").dialog({
            title: $(item).html(),
            heigt: "auto",
            width: "180",
            closeOnEscape: false,
            modal: false,
            draggable: true,
            resizable: true,
            autoOpen: true,
            create: function (event, ui) {
                if(theDialog === null){
                    theDialog = $(this);
                    $('div.ui-dialog-content')
                    .each(function (index) {
                        if (!$(this).hasClass("ShowConversion")) {
                            $(this).bind("dialogclose", function (event, ui) {
                                $(theDialog).dialog("close");
                            });
                        }
                    })
                }
                else
                    theDialog = $(this);
            },
            close: function (event, ui) {
                $(this).remove();
            }
        });
        var ItemHight = $(".ConversionItem").outerHeight();
        var DialogHeadingHight = $(".ui-dialog-titlebar").outerHeight();
        $(".ShowConversion").dialog({ height: CurrencyInfo.ExchangeCurrencies.length * ItemHight + DialogHeadingHight + 20 })
        $(".ShowConversion").dialog("widget").position({
            my: 'left',
            at: 'right',
            of: item
        });
        $(".ShowConversion").dialog("open");
    };

    function Initialize() {
        $(".CurrencyConverter").live("click", function (e) {
            if (CurrencyInfo === null) {
                exPub.getCurrencyInfo(
                    (function (item) {
                        return function (CInfo, NoInfo) {
                            CreateTemplate();
                            CurrencyInfo = CInfo;
                            NoInfoAvailable = NoInfo;
                            HandelEvent(item);
                        }
                    })(this));
                return;
            }
            HandelEvent(this);
        })
    };

    return Initialize;
})();
