﻿var Currency = {
    txtFromId: "#txtCurFrom",
    txtToId: "#txtCurTo",
    cboFrom: "#cboCurFrom",
    cboTo: "#cboCurTo",
    toChangeId: "",
    FromLastValue: 1,
    ToLastValue: 1,
    curCurrency: 1.4,
    txtChangeFrom: function(sender) {
        if (sender.value.length > 0) {
            var doubl = parseFloat(sender.value);
            if (isNaN(doubl)) {
                sender.value = this.FromLastValue;
                //alert('Not a number');
            }
            else
                this.FromLastValue = doubl;
            $(this.txtToId).val((this.curCurrency * this.FromLastValue).toFixed(2));
            //sender.value = this.FromLastValue.toString();
        }
    },
    txtChangeTo: function(sender) {
        if (sender.value.length > 0) {
            var doubl = parseFloat(sender.value);

            if (isNaN(doubl)) {
                sender.value = this.ToLastValue;
                //                alert(Not);
            }
            else
                this.ToLastValue = doubl;
            $(this.txtFromId).val(((1 / this.curCurrency) * this.ToLastValue).toFixed(2));
            //sender.value = this.FromLastValue.toString();
        }
    },
    cboChange: function(sender) {
        var change = this.cboFrom;
        var mySender = sender.id;
        if (mySender.indexOf('From') > 0) {
            change = this.cboTo;

        }
        if (sender.value == $(change).val()) {
            if (sender.value == 'USD')
                $(change).val('EUR');
            else
                $(change).val('USD');

        }
        this.getNewCurrency("#" + sender.id);

    },
    getNewCurrency: function(myToChangeId) {
        this.disableControls();
        var fromCurrency = $(this.cboFrom).val();
        var toCurrency = $(this.cboTo).val();
        this.toChangeId = myToChangeId;
        $.post("Ajax/Convert.ashx", { 'from': fromCurrency, 'to': toCurrency, 'number': 1 }, function(data) {
            Currency.enableControls();
            var doubl = parseFloat(data);
            if (isNaN(doubl) || doubl == 0) {
                //alert('Problem getting rate, recieved: ' + data);
            }
            else {
                Currency.curCurrency = doubl;
                Currency.refresh();
            }
        }, "text");

    },
    disableControls: function() {
        $("#CurrContainer :input").attr("disabled", "disabled");
    },
    enableControls: function() {
        $("#CurrContainer :input").attr("disabled", "");
    },
    refresh: function() {

        if (this.toChangeId == this.cboTo)
            $(this.txtToId).val((this.curCurrency * this.FromLastValue).toFixed(2));
        else if (this.toChangeId == this.cboFrom)
            $(this.txtFromId).val(((1 / this.curCurrency) * this.ToLastValue).toFixed(2));
        else
            alert(ss);
        this.toChangeId = "";
    }
};