Function.prototype.bind = function(context) {
   var fn = this;
   return function() {
      return fn.apply(context, arguments);
   };
}

function DepositForm()
{
    this.el = {
        form: document.getElementById('frmDeposit'),
        city: document.getElementById('slcCity'),
        blckDpsrName: document.getElementById('blckDepositName'),
        dpsrName: document.getElementById('slcDepositName'),
        blckCurr: document.getElementById('blckCurr'),
        curr: document.getElementById('slcСurr'),
        blckCurrInf: document.getElementById('blckCurrInf'),
        blckCurrErr: document.getElementById('blckCurrErrBlock'),
        errCurr: document.getElementById('blckCurrErr'),
        currMsg: document.getElementById('blckCurrMsg'),
        blckTerm: document.getElementById('blckTerm'),
        term: document.getElementById('txtTerm'),
        blckTermInf: document.getElementById('blckTermInf'),
        blckTermFixed: document.getElementById('blckTermFixed'),
        termFixed: document.getElementById('slcTerm'),
        blckErrTerm: document.getElementById('blckErrTermBlock'),
        errTerm: document.getElementById('blckErrTerm'),
        blckDeposit: document.getElementById('blckDeposit'),
        deposit: document.getElementById('txtDeposit'),
        blckDpstInf: document.getElementById('blckDepositInf'),
        blckMultyDpst: document.getElementById('blckMultyDeposit'),
        dpstRur: document.getElementById('txtRurDeposit'),
        dpstUsd: document.getElementById('txtUsdDeposit'),
        dpstEur: document.getElementById('txtEurDeposit'),
        blckDpstRurInf: document.getElementById('blckRurDepositInf'),
        blckDpstUsdInf: document.getElementById('blckUsdDepositInf'),
        blckDpstEurInf: document.getElementById('blckEurDepositInf'),
        blckErrDeposit: document.getElementById('blckErrDepositBlock'),
        errDeposit: document.getElementById('blckErrDeposit'),
        blckRate: document.getElementById('blckRateBlock'),
        rate: document.getElementById('blckRate'),
        blckFinalSum: document.getElementById('blckFinalSum'),
        finalSum: document.getElementById('finalSum'),
        blckIncome: document.getElementById('blckIncome'),
        income: document.getElementById('income'),
        blckInfo1: document.getElementById('blckInfo1'),
        blckInfo2: document.getElementById('blckInfo2'),
        rurIncome: document.getElementById('rurIncome'),
        blckRurInfo1: document.getElementById('blckRurInfo1'),
        blckRurInfo2: document.getElementById('blckRurInfo2'),
        usdIncome: document.getElementById('usdIncome'),
        blckUsdInfo1: document.getElementById('blckUsdInfo1'),
        blckUsdInfo2: document.getElementById('blckUsdInfo2'),
        eurIncome: document.getElementById('eurIncome'),
        blckEurInfo1: document.getElementById('blckEurInfo1'),
        blckEurInfo2: document.getElementById('blckEurInfo2'),

        button: document.getElementById('btnCalculate'),
        blckErr: document.getElementById('blckErrTermBlock'),
        err: document.getElementById('blckErrTerm')
    }
    /*
    var s = '';
    for (var i in this.el) {
        s += i + ": " + this.el[i] + "; ";
    }
    alert(s);
    */

    this.data = {};
    this.employee = 0;
    this.cities = this.cities || {};
    this.branches_deposites = this.branches_deposites || {};
    this.deposites = this.deposites || {};
    this.rates = this.rates || {};
    this.deposit = 0;
    this.curr = 0;
    this.rate = 0;
    this.bankRate = this.bankRate || {rur: 18, usd: 9, eur: 9};
    this.currName = {rur: 'рублей РФ', usd: 'долларов США', eur: 'евро'};
    this.currName2 = {rur: 'рубли РФ', usd: 'доллары США', eur: 'евро'};
    this.el.form.reset();
    for (var i in this.cities) {
        this.el.city.options[this.el.city.options.length] = new Option(this.cities[i].name, this.cities[i].id, false, false);
    }
    this.el.form.onsubmit = function() {return false};
    this.el.city.onchange = this.hndlCity.bind(this);
    this.el.dpsrName.onchange = this.hndlDpsrName.bind(this);
    this.el.curr.onchange = this.setSumInf.bind(this);
    this.el.button.onclick = this.checkForm.bind(this);
}
DepositForm.prototype.hndlCity = function(event)
{
    this.el.button.disabled = true;
    this.el.button.parentNode.className = 'button dis';
    var city_val = this.el.city.options[this.el.city.selectedIndex].value;
    if ('0' == city_val) {
        /* Если город не выбран скрываем все поля и сбрасываем все значения */
        this.hide(this.el.blckDpsrName, this.el.blckCurr, this.el.blckCurrInf, this.el.blckTerm,
            this.el.blckTermFixed, this.el.blckErrTerm, this.el.blckDeposit, this.el.blckMultyDpst,
            this.el.blckErrDeposit, this.el.blckRate, this.el.blckFinalSum, this.el.blckIncome, this.el.income, this.el.rurIncome, this.el.usdIncome, this.el.eurIncome,
            this.el.blckInfo1, this.el.blckRurInfo1, this.el.blckUsdInfo1, this.el.blckEurInfo1,
            this.el.blckInfo2, this.el.blckRurInfo2, this.el.blckUsdInfo2, this.el.blckEurInfo2, this.el.blckErr);
        this.data = {};
    } else if (!this.data.city_id || this.data.city_id != city_val) {
        /* Cкрываем все поля кроме выбора вклада */
        this.show(this.el.blckDpsrName);
        this.hide(this.el.blckCurr, this.el.blckCurrInf, this.el.blckTerm,
            this.el.blckTermFixed, this.el.blckErrTerm, this.el.blckDeposit, this.el.blckMultyDpst,
            this.el.blckErrDeposit, this.el.blckRate, this.el.blckFinalSum, this.el.blckIncome, this.el.income, this.el.rurIncome, this.el.usdIncome, this.el.eurIncome,
            this.el.blckInfo1, this.el.blckRurInfo1, this.el.blckUsdInfo1, this.el.blckEurInfo1,
            this.el.blckInfo2, this.el.blckRurInfo2, this.el.blckUsdInfo2, this.el.blckEurInfo2, this.el.blckErr);
        /* Cбрасываем все значения кроме города вклада */
        this.data = {
            city_id: city_val,
            branch_id: this.cities[city_val].branch_id
        };
        this.data.city_id = city_val;
        /* Формируе список вкладов */
        this.el.dpsrName.options.length = 0;
        this.el.dpsrName.options[0] = new Option('Выбрать', 0, false, false);
        for (var i in this.branches_deposites[this.data.branch_id]) {
            this.el.dpsrName.options[this.el.dpsrName.options.length] = new Option(
                this.deposites[this.branches_deposites[this.data.branch_id][i]].name,
                this.deposites[this.branches_deposites[this.data.branch_id][i]].id,
                false, false);
        }
    }
}
DepositForm.prototype.hndlDpsrName = function(event)
{
    var i, dpst_val = this.el.dpsrName.options[this.el.dpsrName.selectedIndex].value;
    this.hide(this.el.blckCurr, this.el.blckCurrInf, this.el.blckTerm, this.el.blckTermFixed,
        this.el.blckErrTerm, this.el.blckDeposit, this.el.blckMultyDpst, this.el.blckErrDeposit,
        this.el.blckRate, this.el.blckFinalSum, this.el.blckIncome, this.el.income,
        this.el.rurIncome, this.el.usdIncome, this.el.eurIncome,
        this.el.blckInfo1, this.el.blckRurInfo1, this.el.blckUsdInfo1, this.el.blckEurInfo1,
        this.el.blckInfo2, this.el.blckRurInfo2, this.el.blckUsdInfo2, this.el.blckEurInfo2, this.el.blckErr);
    if ('0' == dpst_val) {
        this.data = {
            city_id: this.data.city_id,
            branch_id: this.data.branch_id
        };
    } else {
        this.data.dpst_id = dpst_val;
        this.data.deposit = this.deposites[dpst_val]; // Текщий вклад
        /* Определение валюты вклада */
        if (this.data.deposit.multy_curr) {
            this.hide(this.el.blckCurr);
            this.show(this.el.blckCurrInf);
            this.el.currMsg.innerHTML = 'Валюта вклада – одновременно рубли РФ, доллары США и Евро'
        } else if (1 == this.data.deposit.curr_list_sum) {
            this.hide(this.el.blckCurr);
            this.show(this.el.blckCurrInf);
            this.el.currMsg.innerHTML = 'Валюта вклада – ' +
                (this.data.deposit.curr_list.rur ? 'рубли РФ' : (this.data.deposit.curr_list.rur ? 'доллары США' : 'Евро'));
        } else {
            this.hide(this.el.blckCurrInf);
            this.show(this.el.blckCurr);
            this.el.curr.options.length = 0;
            this.el.curr.options[0] = new Option('Выбрать', 0, false, false);
            for (i in this.currName2) {
                if (this.data.deposit.curr_list[i]) {
                    this.el.curr.options[this.el.curr.options.length] = new Option(this.currName2[i], i, false, false);
                }
            }
        }
        /* Сумма вклада */
        if (this.data.deposit.multy_curr) {
            this.hide(this.el.blckDeposit);
            this.show(this.el.blckMultyDpst);
        } else {
            this.hide(this.el.blckMultyDpst);
            this.show(this.el.blckDeposit);
        }
        /* Срок вклада */
        this.show(this.el.term);
        if (this.data.deposit.max_term > 0 || 1 == this.data.deposit.term_count) {
            this.show(this.el.blckTerm, this.el.blckTermInf);
            this.hide(this.el.blckTermFixed);
            if (this.data.deposit.max_term > 0) {
                this.el.blckTermInf.innerHTML = 'от ' + this.data.deposit.min_term + ' до ' + this.data.deposit.max_term  + ' дней';
            } else if (1 == this.data.deposit.term_count && this.data.deposit.min_term > 1) {
                this.hide(this.el.term);
                this.el.blckTermInf.innerHTML = this.data.deposit.min_term  + ' дней';
            }
        } else {
            this.show(this.el.blckTermFixed);
            this.hide(this.el.blckTerm, this.el.blckTermInf);
            this.el.termFixed.options.length = 0;
            this.el.termFixed.options[this.el.termFixed.options.length]
                = new Option('Выбрать', 0, false, false);
            for (i in this.data.deposit.term) {
               this.el.termFixed.options[this.el.termFixed.options.length]
                    = new Option(this.data.deposit.term[i], i, false, false);
            }
        }
        //this.show(this.el.button);
        this.el.button.disabled = false;
        this.el.button.parentNode.className = 'button';
        this.setSumInf();
    }
}

DepositForm.prototype.setSumInf = function()
{
    this.getCurr();
    this.hide(this.el.blckDpstInf, this.el.blckDpstRurInf, this.el.blckDpstUsdInf, this.el.blckDpstEurInf);
    if (!this.data.deposit) {
        return;
    }
    if (this.data.deposit.multy_curr) {
        this.show(this.el.blckDpstRurInf, this.el.blckDpstUsdInf, this.el.blckDpstEurInf);
        this.el.blckDpstRurInf.innerHTML = 'от ' + num_format(this.data.deposit.min_rursum);
        this.el.blckDpstUsdInf.innerHTML = 'от ' + num_format(this.data.deposit.min_usdsum);
        this.el.blckDpstEurInf.innerHTML = 'от ' + num_format(this.data.deposit.min_eursum);
    } else if (this.data.curr) {
        this.show(this.el.blckDpstInf);
        this.el.blckDpstInf.innerHTML = 'от ' + num_format(this.data.deposit['min_' + this.data.curr + 'sum']);
    }
}

DepositForm.prototype.getCurr = function()
{
    this.data.curr = false;
    if (!this.data.deposit.multy_curr && this.data.deposit.curr_list_sum > 1 ) {
        this.data.curr = 0 == this.el.curr.options.selectedIndex ? false : this.el.curr.options[this.el.curr.options.selectedIndex].value;
    } else if (!this.data.deposit.multy_curr) {
        for (i in this.data.deposit.curr_list) {
            if (this.data.deposit.curr_list[i]) {
                this.data.curr = i;
            }
        }
    }
}

DepositForm.prototype.checkForm = function()
{
    var i, valid = true;
    this.data.sum = 0;
    this.data.term = 0;
    this.data.term_id = 0;
    this.data.rurSum = 0;
    this.data.usdSum = 0;
    this.data.eurSum = 0;
    this.getCurr();
    this.hide(this.el.blckCurrErr, this.el.blckErrTerm, this.el.blckErrDeposit, this.el.blckRate,
        this.el.blckFinalSum, this.el.blckIncome, this.el.income, this.el.rurIncome, this.el.usdIncome, this.el.eurIncome,
        this.el.blckInfo1, this.el.blckRurInfo1, this.el.blckUsdInfo1, this.el.blckEurInfo1,
        this.el.blckInfo2, this.el.blckRurInfo2, this.el.blckUsdInfo2, this.el.blckEurInfo2, this.el.blckErr);
    /* Проверить валюту */
    if (!this.data.deposit.multy_curr && this.data.deposit.curr_list_sum > 1 && 0 == this.el.curr.options.selectedIndex) {
        this.show(this.el.blckCurrErr);
        this.el.errCurr.innerHTML = 'Не выбрана валюта вклада';
        this.el.curr.focus();
        valid = false;
    }
    /* Проверить сумму */
    if (this.data.curr || this.data.deposit.multy_curr) {
        if (!this.data.deposit.multy_curr) {
            var min_sum = this.data.deposit['min_'+this.data.curr+'sum'];
            var sum = this.el.deposit.value;
            if (sum < min_sum) {
                this.show(this.el.blckErrDeposit);
                this.el.errDeposit.innerHTML = 'Минимальная сумма вклада ' + min_sum + ' ' + this.currName[this.data.curr];
                this.el.deposit.focus();
                valid = false;
            } else if (this.data.deposit['max_'+this.data.curr+'sum'] > 0 && sum > this.data.deposit['max_'+this.data.curr+'sum']) {
                this.show(this.el.blckErrDeposit);
                this.el.errDeposit.innerHTML = 'Максимальная сумма вклада ' + this.data.deposit['max_'+this.data.curr+'sum'] + ' ' + this.currName[this.data.curr];
                this.el.deposit.focus();
                valid = false;
            } else {
                this.data.sum = sum * 1;
            }
        } else {
            var rur_sum =  this.el.dpstRur.value * 1;
            var usd_sum =  this.el.dpstUsd.value * 1;
            var eur_sum =  this.el.dpstEur.value * 1;
            if (rur_sum < this.data.deposit.min_rursum || usd_sum < this.data.deposit.min_usdsum || eur_sum < this.data.deposit.min_eursum) {
                this.show(this.el.blckErrDeposit);
                this.el.errDeposit.innerHTML = 'Минимальная сумма вклада ' + this.data.deposit.min_rursum
                    + ' рублей, ' + this.data.deposit.min_usdsum + ' долларов США и '
                    + this.data.deposit.min_eursum + ' евро';
                if (rur_sum < this.data.deposit.min_rursum) {
                    this.el.dpstRur.focus();
                } else if (usd_sum < this.data.deposit.min_usdsum) {
                    this.el.dpstUsd.focus();
                } else {
                    this.el.dpstEur.focus();
                }
                valid = false;
            } else if ( (this.data.deposit.max_rursum > 0 && rur_sum > this.data.deposit.max_rursum )
                || (this.data.deposit.max_usdsum > 0 && usd_sum > this.data.deposit.max_usdsum )
                || (this.data.deposit.max_eursum > 0 && eur_sum > this.data.deposit.max_eursum )
            ) {
                this.show(this.el.blckErrDeposit);
                this.el.errDeposit.innerHTML = 'Максимальная сумма вклада ' + this.data.deposit.max_rursum
                    + ' рублей, ' + this.data.deposit.max_usdsum + ' долларов США и '
                    + this.data.deposit.max_eursum + ' евро';
                this.el.deposit.focus();
                valid = false;
            } else {
                this.data.rur_sum = rur_sum * 1;
                this.data.usd_sum = usd_sum * 1;
                this.data.eur_sum = eur_sum * 1;
            }
        }
    }
    /* Проверить срок вклада */
    if (this.data.deposit.max_term) {
        var term = this.el.term.value;
        if ('' == term) {
            this.show(this.el.blckErrTerm);
            this.el.errTerm.innerHTML = "Не указан срок вклада";
            this.el.term.focus();
            valid = false;
        } else if (term < this.data.deposit.min_term || term > this.data.deposit.max_term) {
            this.show(this.el.blckErrTerm);
            this.el.errTerm.innerHTML = "Указан недопустимый срок вклада";
            this.el.term.focus();
            valid = false;
        } else {
            this.data.term = term * 1;
        }
    } else if (1 == this.data.deposit.term_count) {
        var term = 1 == this.data.deposit.min_term ? this.el.term.value : this.data.deposit.min_term;
        if (term < this.data.deposit.min_term) {
            this.show(this.el.blckErrTerm);
            this.el.errTerm.innerHTML = "Cрок вклада не может быть меньше " + this.data.deposit.min_term + " дней";
            this.el.term.focus();
            valid = false;
        } else {
            this.data.term = term * 1;
        }
    } else {
        if (0 == this.el.termFixed.selectedIndex) {
            this.show(this.el.blckErrTerm);
            this.el.errTerm.innerHTML = "Не выбран срок вклада";
            this.el.termFixed.focus();
            valid = false;
        } else {
            this.data.term_id = this.el.termFixed.options[this.el.termFixed.selectedIndex].value;
            this.data.term = this.el.termFixed.options[this.el.termFixed.selectedIndex].text * 1;
        }
    }
    if (valid) {
        this.calculate();
    }
}
DepositForm.prototype.calculate = function()
{
    if (! this.rates[this.data.deposit.id]) {
        alert('Ошибка. Не определены ставки по вкладу');
        return;
    }
    if (!this.data.term_id) {
        for (var i in this.data.deposit.term) {
            //s += i + " - " + this.deposit.term[i] + ";";
            if ( this.data.deposit.term[i] <= this.data.term &&
                (!this.data.term_id || this.data.deposit.term[i] > this.data.deposit.term[this.data.term_id])
            ) {
                this.data.term_id = i;
            }
        }
    }
    if (this.data.deposit.multy_curr) {
        this.data.rur_sum_id = this.getSumId('rur', this.data.rur_sum);
        this.data.usd_sum_id = this.getSumId('usd', this.data.usd_sum);
        this.data.eur_sum_id = this.getSumId('eur', this.data.eur_sum);
        this.data.rur_rate = this.rates[this.data.deposit.id][this.data.term_id][this.data.rur_sum_id]['rur'];
        this.data.usd_rate = this.rates[this.data.deposit.id][this.data.term_id][this.data.usd_sum_id]['usd'];
        this.data.eur_rate = this.rates[this.data.deposit.id][this.data.term_id][this.data.eur_sum_id]['eur'];
        this.show(this.el.blckRate);
        this.el.rate.innerHTML = this.data.rur_rate + "% в рублях РФ.<br>"
            + this.data.usd_rate + "% в долларах США.<br>"
            + this.data.eur_rate + "% в евро";

        this.show(this.el.blckIncome, this.el.rurIncome, this.el.usdIncome, this.el.eurIncome);

        var rur_income = this.calculateIncome(this.data.rur_sum, this.data.term, this.data.rur_rate, this.data.curr);
        var usd_income = this.calculateIncome(this.data.usd_sum, this.data.term, this.data.usd_rate, this.data.curr);
        var eur_income = this.calculateIncome(this.data.eur_sum, this.data.term, this.data.eur_rate, this.data.curr);
        this.el.rurIncome.innerHTML = num_format(rur_income) + " " + this.currName['rur'];
        this.el.usdIncome.innerHTML = num_format(usd_income) + " " + this.currName['usd'];
        this.el.eurIncome.innerHTML = num_format(eur_income) + " " + this.currName['eur'];

        this.data.rur_rate > this.bankRate['rur']  ? this.show(this.el.blckRurInfo2) : this.show(this.el.blckRurInfo1);
        this.data.usd_rate > this.bankRate['usd']  ? this.show(this.el.blckUsdInfo2) : this.show(this.el.blckUsdInfo1);
        this.data.eur_rate > this.bankRate['eur']  ? this.show(this.el.blckEurInfo2) : this.show(this.el.blckEurInfo1);

        this.show(this.el.blckFinalSum);
        this.el.finalSum.innerHTML = num_format(rur_income + this.data.rur_sum) + " " + this.currName['rur'] + '<br>'
            + num_format(usd_income + this.data.usd_sum) + " " + this.currName['usd'] + '<br>'
            + num_format(eur_income + this.data.eur_sum) + " " + this.currName['eur'];
    } else {
        var income;
        this.data.sum_id = this.getSumId(this.data.curr, this.data.sum);        
        this.data.rate = this.rates[this.data.deposit.id][this.data.term_id][this.data.sum_id][this.data.curr];
        this.show(this.el.blckRate);
        this.el.rate.innerHTML = this.data.rate + "%";

        this.show(this.el.blckIncome, this.el.income);
        income = this.calculateIncome(this.data.sum, this.data.term, this.data.rate, this.data.curr);
        this.el.income.innerHTML = num_format(income) + " " + this.currName[this.data.curr];
        this.show(this.el.blckFinalSum);
        this.el.finalSum.innerHTML = num_format(income + this.data.sum) + " " + this.currName[this.data.curr];
        this.data.rate > this.bankRate[this.data.curr]  ? this.show(this.el.blckInfo2) : this.show(this.el.blckInfo1);
    }
}
DepositForm.prototype.getSumId = function(curr, sum)
{
    var sum_id = 0;
    for (var i in this.data.deposit[curr+'sum']) {
        if (this.data.deposit[curr+'sum'][i] <= sum && (!sum_id || this.data.deposit[curr+'sum'][i] > this.data.deposit[curr+'sum'][sum_id])) {
            sum_id = i;
        }
    }
    return sum_id;
}
DepositForm.prototype.calculateIncome = function(sum, term, rate, curr)
{
    if (rate > this.bankRate[curr]) {
        //var r = 'rur' == cur ? this.bankRate[curr] - 5 : this.bankRate[curr];
        return this.data.deposit.getIncone(sum, term, rate) - 0.35 * (this.data.deposit.getIncone(sum, term, rate) - this.data.deposit.getIncone(sum, term, this.bankRate[curr]));
    } else {
        return this.data.deposit.getIncone(sum, term, rate);
    }
}
DepositForm.prototype.hide = function()
{
    for (var i = 0; i < arguments.length; i++) {
        addClass(arguments[i], 'hide');
    }
}
DepositForm.prototype.show = function()
{
    for (var i = 0; i < arguments.length; i++) {
        removeClass(arguments[i], 'hide');
    }
}
