﻿var reCalcForTotalMethod = $.isFunction(reCalcForTotalMethod) ? reCalcForTotalMethod : $.noop;

(function ($) {
    $.fn.setIntTotPrice = function (origPrice, sourceCurrency, applyMarkUp) {
        this.each(function () {
            $(this).attr('mu', applyMarkUp ? 'true' : 'false');
            $(this).attr('origPrice', origPrice);
            $(this).attr('curr', sourceCurrency);
        });
    }
    $.fn.setPrice = function (origPrice, sourceCurrency, applyMarkUp) {
        this.each(function () {
            if (origPrice < 5)
                $(this).attr('fixed', 'true');
            $(this).attr('mu', applyMarkUp ? 'true' : 'false');
            $(this).attr('origPrice', (origPrice < 5 ? 1 : origPrice));
            $(this).attr('curr', sourceCurrency);
        });
    }
    $.fn.setTotalPrice = function (collection, possibleTotalItem, ApplyMarkUp, reCalc, callback) {
        reCalcForTotalMethod = reCalc;
        var totalItem = this;
        var data = "";
        for (var i in collection) {
            if (data.indexOf(collection[i].CurrencyCode) == -1 && collection[i].CurrencyCode != null)
                data += collection[i].CurrencyCode + ',';
        }
        if (data != "")
            data = data.substring(0, data.length - 1);
        var targetCC = $('#currencySelector').val();
        var targetSym = $('#currencySelector option:selected').attr('symbol');
        if (typeof (targetCC) != 'string' || targetCC.length == 0) {
            targetCC =  $("#DCC").html();
            targetSym = $("#DCS").html();
        }
        // Construct a JSON list to send to the server...
        var args = JSON.stringify({ sourceCurrencyCodes: data, targetCurrencyCode: targetCC });

        // Call the server via an ajax call with the data we have prepared...
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: getExchangeRatesPath,
            data: args,
            dataType: 'json',
            success: function (data) {
                if (data.d.success == true) {
                    var total = 0.0; var possibleTotal = 0.0;
                    for (var i1 in data.d.exchangeRates) {
                        for (var i2 in collection) {
                            if (collection[i2].CurrencyCode == data.d.exchangeRates[i1].source) {
                                var subtotal = collection[i2].Amount;
                                var subPosTotal = collection[i2].PossibleAmount;
                                if (collection[i2].Amount > 5)
                                    subtotal *= data.d.exchangeRates[i1].exchangeRate;
                                if (collection[i2].PossibleAmount > 5)
                                    subPosTotal *= data.d.exchangeRates[i1].exchangeRate;
                                if (ApplyMarkUp && data.d.exchangeRates[i1].source != targetCC) {
                                    if (collection[i2].Amount > 5)
                                        subtotal *= (data.d.exchangeRates[i1].markUp + 1.0);
                                    if (collection[i2].PossibleAmount > 5)
                                        subPosTotal *= (data.d.exchangeRates[i1].markUp + 1.0);
                                }
                                total += subtotal;
                                possibleTotal += subPosTotal;
                            }
                        }
                    }
                    totalItem.setIntTotPrice(total, targetCC, false);
                    possibleTotalItem.setIntTotPrice(possibleTotal, targetCC, false);
                    if ($.isFunction(callback))
                        callback(total);
                }
            },
            error: function (data) {
                return false;
            }
        });
    }
    $.getPrice = function (origPrice, sourceCurrency, applyMarkUp) {
        var res = '<span mu="' + (applyMarkUp ? 'true' : 'false') + '" origPrice="' + origPrice + '" curr="' + sourceCurrency + '"></span>';
        return res;
    }

    jQuery.fn.setCurrencySpans = function (callback) {
        // Now deal with the prices on screen already - we need to ajax the exchange rates first, so
        // we get the exchange rates requires to parse the page:
        var data = "";
        $('span[curr]').add('option[curr]').each(function (index, item) {
            var code = item.attributes['curr'].nodeValue;
            if (data.indexOf(code) == -1 && code != null)
                data += code + ',';
        });
        if (data != "")
            data = data.substring(0, data.length - 1);

        var targetCC = $('#currencySelector').val();
        var targetSym = $('#currencySelector option:selected').attr('symbol');
        if (typeof (targetCC) != 'string' || targetCC.length == 0) {
            targetCC =  $("#DCC").html();
            targetSym = $("#DCS").html();
        }
        // Construct a JSON list to send to the server...
        var args = JSON.stringify({ sourceCurrencyCodes: data, targetCurrencyCode: targetCC });

        // Call the server via an ajax call with the data we have prepared...
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: getExchangeRatesPath,
            data: args,
            dataType: 'json',
            success: function (data) {
                if (data.d.success == true) {
                    for (var i in data.d.exchangeRates) {
                        $('span[curr="' + data.d.exchangeRates[i].source + '"]').add('option[curr="' + data.d.exchangeRates[i].source + '"]').each(function (index, item) {
                            var price = $(item).attr('origPrice');
                            if (price != 1) {
                                if ($(item).attr('fixed') != 'true') {
                                    price = price * data.d.exchangeRates[i].exchangeRate;
                                    if ($(item).attr('mu') == 'true')
                                        price *= (1.0 + data.d.exchangeRates[i].markUp);
                                }
                                price = Math.round(price);
                            }
                            else
                                price = 1.0;
                            if ($(item).attr('numOnly') == 'true')
                                $(this).text(price.toFixed(0));
                            else
                                $(this).text(/*targetCC + ' ' + */targetSym + ' ' + price.toFixed(0));
                            if ($.isFunction(callback))
                                callback();
                        });
                    }
                }
            },
            error: function (data) {
                return false;
            }
        });
    };
})(jQuery);

