function extend(Child, Parent)
{
    var F = function() { };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.superclass = Parent.prototype;
}

var programStandard = function (completion)
{
    this.name = 'Кредит «Универсальный»';
    this.codeName = 'standard';
    this.programType = 1;
    
    this.price = Math.round(completion.price);
    this.completionPrice = Math.round(completion.price);
    this.metallicPrice = completion.CostColorMetalic;
    this.metallicPriceUSD = completion.CostColorMetallicUSD;
    this.completion = completion;
    
    this.ltv = 0.85;
}

programStandard.prototype.init = function(startData, programSwitch)
{
    if (typeof programSwitch == 'undefined')
    {
        programSwitch = false;
    }
    this.termMin = 12;
    this.termMax = 60;
    this.firstPayMin = 15;
    this.firstPayMax = 100;
    this.ltv = 0.85;
    
    $('#CalcCredit input[name=onSumCredit]').attr('disabled', false);
    facade.program.setTerm(60);
    facade.program.setFirstPay(15);
    facade.program.commission = 6000;
    this.insurance = 0;
    
    if (!programSwitch)
    {
        facade.program.currency = 'rub';
        this.USDRate = false;
    }
    
    facade.page.sliderTerm.slider('option', 'disabled', false);
    facade.page.sliderTermInner.slider('option', 'disabled', false);
    facade.page.sliderFirstPay.slider('option', 'disabled', false);

    if (!programSwitch)
    {
        $('#currency_selector_rub').attr('checked', true);
        $('.currency_label').html('Руб');
        $('#metallic_off').attr('checked', true);
    }
    
    $('#onSumCredit_off').attr('checked', true);
    $('#CalcCredit input[name=SumCreditCur]').val('').attr('disabled', true);
    $('#CalcCredit input[name=SumCreditRate]').val('').attr('disabled', true);
    $('#LsTerm').hide();
    
    $('#FormExchangeRate').show();
    $('.standard_field').show();
    $('.additional_field').hide();
    $('.program50_field').hide();
    $('.so_sign').hide();
    $('.disclaimer p').hide();
    $('#so_notice_standart').show();
    
    
    $('#TotalIntegCost').val(Math.round(parseFloat(this.price)));
    
    if ((typeof startData != 'undefined') && startData)
    {
        this.setData(startData);
    }
    facade.program.calc();
    facade.program.bindEvents();
    
}


programStandard.prototype.setData = function(data)
{
    facade.program.setTerm(data.term);
    facade.program.setFirstPay(data.firstPay);
    
    if (data.color == 1)
    {
        $('#metallic_on').attr('checked', true);
    }
    
    if (data.insurance > 0)
    {
        facade.program.insurance = data.insurance;
        $('#onSumCredit_on').attr('checked', true);
        $('#CalcCredit input[name=SumCreditCur]').val((data.insurance * data.price / 100).toFixed(2)).attr('disabled', false);
        $('#CalcCredit input[name=SumCreditRate]').val(parseFloat(data.insurance).toFixed(2)).attr('disabled', false);
    }
    
    if (data.currency != facade.program.currency)
    {
        facade.program.currency = data.currency;
        
        if(facade.program.currency == 'usd')
        {
            $('#currency_selector_usd').attr('checked', true);
            $('.currency_label').html('USD');
        }
        else if (facade.program.currency == 'rub')
        {
            $('#currency_selector_rub').attr('checked', true);
            $('.currency_label').html('Руб');
        }
    }
}

programStandard.prototype.bindEvents = function()
{
    $('#PageCalcForm').unbind().submit(function(){ return false; });
    $('#PageCalcForm input:not(.credit_program_selector,.bot_but,.bot_but_r,.bot_but_r_comp)').unbind();
    facade.page.sliderFirstPay.unbind('slidestop');
    facade.page.sliderTerm.unbind('slidestop');
    facade.page.sliderTermInner.unbind('slidestop');
    
    $('#CalcCredit input[name=TermCredit]').change(function()
    {
        facade.program.setTerm($(this).val());
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=FirstPayRate]').change(function()
    {
        facade.program.setFirstPay($(this).val());
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=FirstPayCur]').change(function()
    {
        facade.program.setFirstPay( 100 * $(this).val() / facade.program.price );
        facade.program.calc();
    });
    
    $('#TotalIntegCost').change(function()
    {
        facade.program.price = $(this).val();
        $('#CalcCredit input[name=FirstPayCur]').val((facade.program.price * facade.program.firstPay / 100).toFixed(2));
        $('#program50_FirstPayCur').html((facade.program.price * facade.program.firstPay / 100).toFixed(2));
        $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2));
        $('#metallic_off').attr('checked', true);
        facade.program.calc();
    });
    
    facade.page.sliderTerm.bind('slidestop', function()
    {
        facade.program.setTerm(facade.page.sliderTerm.slider('value'));
        facade.program.calc();
    });
    
    facade.page.sliderTermInner.bind('slidestop', function()
    {
        facade.program.setTerm(facade.page.sliderTermInner.slider('value'));
        facade.program.calc();
    });
    
    facade.page.sliderFirstPay.bind('slidestop', function()
    {
        facade.program.setFirstPay(facade.page.sliderFirstPay.slider('value'));
        facade.program.calc();
    });
    
    $('.compl_check').change(function() {
        facade.program.completion = facade.car.completions[$(this).val()];
        facade.program.price = facade.car.completions[$(this).val()].price;
        facade.program.completionPrice = facade.program.price;
        facade.program.metallicPrice = facade.car.completions[$(this).val()].CostColorMetalic;
        facade.program.metallicPriceUSD = facade.car.completions[$(this).val()].CostColorMetallicUSD;
        $('#metallic_off').attr('checked', true);
        
        if (facade.program.currency == 'usd')
        {
            facade.program.currency = 'rub';
            facade.program.changeCurrency('usd');
        }
        else
        {
            $('#TotalIntegCost').val(Math.round(facade.program.price));
            $('#CalcCredit input[name=FirstPayCur]').val((facade.program.price * facade.program.firstPay / 100).toFixed(2));
            $('#program50_FirstPayCur').html((facade.program.price * facade.program.firstPay / 100).toFixed(2));
            $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2));
            facade.program.calc();
        }
    });
    
    $('#FormExchangeRate input[name=curr_selector]').change(function() {
        var currency = 'usd';
        
        if ($(this).attr('id') == 'currency_selector_rub')
        {
            currency = 'rub';
        }
        
        if ($(this).attr('id') == 'currency_selector_usd')
        {
            currency = 'usd';
        }
        
        facade.program.changeCurrency(currency);
    });
    
    $('#FormCostColor input[name=CostColor]').change(function(){
        if ($(this).val() == '1')
        {
            if (facade.program.currency == 'rub')
            {
                facade.program.price = parseInt(facade.program.completionPrice) + parseInt(facade.program.metallicPrice);
            }
            else if (facade.program.currency == 'usd')
            {
                facade.program.price = parseInt(facade.program.completionPrice) + parseInt(facade.program.metallicPriceUSD);
            }
        }
        else
        {
            facade.program.price = facade.program.completionPrice;
        }
        
        $('#TotalIntegCost').val(Math.round(facade.program.price));
        $('#CalcCredit input[name=FirstPayCur]').val((facade.program.price * facade.program.firstPay / 100).toFixed(2));
        $('#program50_FirstPayCur').html((facade.program.price * facade.program.firstPay / 100).toFixed(2));
        $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2));
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=onSumCredit]').change(function(){
        if ($(this).attr('id') == 'onSumCredit_off')
        {
            facade.program.insurance = 0;
            $('#CalcCredit input[name=SumCreditCur]').val('').attr('disabled', true);
            $('#CalcCredit input[name=SumCreditRate]').val('').attr('disabled', true);
        }
        
        if ($(this).attr('id') == 'onSumCredit_on')
        {
            facade.program.insurance = 10;
            $('#CalcCredit input[name=SumCreditRate]').val(facade.program.insurance).attr('disabled', false);
            $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2)).attr('disabled', false);
        }
        
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=SumCreditRate]').change(function()
    {
        facade.program.insurance = $(this).val();
        $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2));
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=SumCreditCur]').change(function()
    {
        facade.program.insurance =  $(this).val() / facade.program.price * 100;
        $('#CalcCredit input[name=SumCreditRate]').val(facade.program.insurance.toFixed(2));
        facade.program.calc();
    });
    
    $('#CalcCredit input[name=BackPayRate]').change(function(){
        if (typeof facade.program.checkBackPayRate != 'undefined')
        {
            facade.program.calc();
        }
    });
    
    $('#CalcCredit input[name=TermCreditTransformer]').change(function(){
        if ($(this).attr('id') == 'term_credit_transformer_48')
        {
            facade.program.setTerm(48);
        }
        
        if ($(this).attr('id') == 'term_credit_transformer_60')
        {
            facade.program.setTerm(60);
        }
        
        facade.program.calc();
    });
}

programStandard.prototype.setTerm = function(term)
{
    _self = facade.program;
    
    if (facade.program.term == term)
    {
        return true;
    }
    
    
    if (term > _self.termMax)
    {
        term = _self.termMax;
    }
    else if (term < _self.termMin)
    {
        term = _self.termMin;
    }
    
    facade.program.term = term;
    facade.page.sliderTerm.slider('value', term);
    facade.page.sliderTermInner.slider('value', term);
    $('#CalcCredit input[name=TermCredit]').val(term);
    
    return true;
}

programStandard.prototype.setFirstPay = function(firstPay)
{
    _self = facade.program;
    
    if (facade.program.firstPay == firstPay)
    {
        return true;
    }
    
    if (firstPay > _self.firstPayMax)
    {
        firstPay = _self.firstPayMax;
    }
    else if (firstPay < _self.firstPayMin)
    {
        firstPay = _self.firstPayMin;
    }
    
    var _loanAmount = _self.price * (1 - firstPay / 100) + (_self.price * _self.insurance / 100);
    var recount = false;
    if ((_self.currency == 'rub') && (_loanAmount < 90000))
    {
        targetLoanAmount = 90000;
        recount = true;
    }
    else if ((_self.currency == 'usd') && (_loanAmount < 3000))
    {
        targetLoanAmount = 3000;
        recount = true;
    }
    
    if (recount)
    {
        firstPay = Math.floor(100 + _self.insurance - (100 / _self.price) * targetLoanAmount);
    }
    
    facade.program.firstPay = firstPay;
    facade.page.sliderFirstPay.slider('value', firstPay);
    $('#CalcCredit input[name=FirstPayRate]').val(parseFloat(firstPay).toFixed(2));
    $('#CalcCredit input[name=FirstPayCur]').val((this.price * firstPay / 100).toFixed(2));
    $('#program50_FirstPayCur').html((this.price * firstPay / 100).toFixed(2));
    
    
    return true;
}

programStandard.prototype.calc = function()
{
    _self = this;
    _self.updateInterestRate();
    _self.loanAmount = _self.price * (1 - _self.firstPay / 100) + (_self.price * _self.insurance / 100);
    
    // max pay in persent
    _self.checkCredit();
    
    var response = $.ajax(
    {
        url: 'calc.php?action=calcStandardCredit',
        type: 'post',
        data: {loanAmount:_self.loanAmount, term: _self.term, interestRate: _self.interestRate, commission: _self.commission},
        dataType: 'json',
        success: _self.onCalcSuccess
    });
}
programStandard.prototype.checkCredit = function()
{
    if (typeof _self.ltv != 'undefined')
    {
        if ( (_self.loanAmount / _self.price) > _self.ltv )
        {
            /*
            $('#CalcCredit input[name=onSumCredit]').attr('disabled', true);
            $('#CalcCredit input[name=SumCreditCur]').val('').attr('disabled', true);
            $('#CalcCredit input[name=SumCreditRate]').val('').attr('disabled', true);
            $('#onSumCredit_off').attr('checked', true);
            */
            
            alert (
                'Cумма кредита не может превышать ' + ( _self.ltv * 100  ) + '% от стоимости автомобиля'
                + ', пожалуйста поменяйте условия (страховку в сумме кредита или первоначальный взнос) '
            );
            $('#CalcCredit input[name=onSumCredit]:last').click().change();
            
            _self.insurance = 0;
            
            _self.loanAmount = _self.price * (1 - _self.firstPay / 100) + (_self.price * _self.insurance / 100);
        }
        else
        {
            $('#CalcCredit input[name=onSumCredit]').attr('disabled', false);
            $('#CalcCredit input[name=SumCreditCur]').attr('disabled', false);
            $('#CalcCredit input[name=SumCreditRate]').attr('disabled', false);
        }
    }
    
}


programStandard.prototype.onCalcSuccess = function(data)
{
    _self = facade.program;
    
    _self.monthlyPay = data.monthlyPay.toFixed(2);
    _self.totalPay = (_self.monthlyPay * _self.term).toFixed(2);
    _self.totalPayRate = (_self.totalPay - _self.loanAmount).toFixed(2);
    _self.summCredit = (_self.loanAmount).toFixed(2);
    
    
    $('#InterestRate').html(_self.interestRate);
    $('#SummCredit').html(formatDigit(_self.summCredit));
    $('#Commission').html(formatDigit(_self.commission));
    $('#MonthlyPay').html(formatDigit(_self.monthlyPay));
    $('#VisualMonthlyPay').html(formatDigit(_self.monthlyPay));
    $('#TotalPay').html(formatDigit(_self.totalPayRate));
}

programStandard.prototype.updateInterestRate = function()
{
    _self = this;
    
    if (_self.currency == 'usd')
    {
        _self.interestRate = 9.0;
    }
    else if (_self.currency == 'rub')
    {
        if (_self.term < 13)
        {
            if (_self.firstPay < 20)
            {
                _self.interestRate = 15.0;
            }
            else if (_self.firstPay < 30)
            {
                _self.interestRate = 13.0;
            }
            else if (_self.firstPay < 40)
            {
                _self.interestRate = 12.5;
            }
            else
            {
                _self.interestRate = 9.5;
            }
        }
        else if (_self.term < 37)
        {
            if (_self.firstPay < 20)
            {
                _self.interestRate = 16.0;
            }
            else if (_self.firstPay < 30)
            {
                _self.interestRate = 14.0;
            }
            else if (_self.firstPay < 40)
            {
                _self.interestRate = 13.5;
            }
            else
            {
                _self.interestRate = 12.5;
            }
        }
        else
        {
            if (_self.firstPay < 20)
            {
                _self.interestRate = 16.5;
            }
            else if (_self.firstPay < 30)
            {
                _self.interestRate = 15.0;
            }
            else if (_self.firstPay < 40)
            {
                _self.interestRate = 14.5;
            }
            else
            {
                _self.interestRate = 13.5;
            }
        }
    }
}

programStandard.prototype.changeCurrency = function(currency)
{
    if (facade.program.currency == currency)
    {
        return true;
    }
    
    if (!facade.program.USDRate)
    {
        var response = $.ajax(
        {
            url: 'b.php?t=getUSDRate',
            data: {intName: facade.car.name},
            dataType: 'json',
            async: false,
            type: 'post'
        }).responseText;
        
        facade.program.USDRate = $.parseJSON(response).USDRate;
    }
    
    if (currency == 'usd')
    {
        facade.program.commission = 200;
        $('.currency_label').html('USD');
    }
    else if (currency == 'rub')
    {
        facade.program.commission = 6000;
        $('.currency_label').html('Руб');
    }
    
    var rate = facade.program.USDRate;
    if (currency == 'usd')
    {
        rate = 1 / rate;
    }
    
    facade.program.currency = currency;
    if ($('#metallic_on').attr('checked'))
    {
        facade.program.price = facade.program.completionPrice * rate + parseFloat(currency == 'rub' ? facade.program.metallicPrice : facade.program.metallicPriceUSD);
    }
    else
    {
        facade.program.price = facade.program.price * rate;
    }
    facade.program.completionPrice = facade.program.completionPrice * rate;
    
    $('#TotalIntegCost').val(Math.round(facade.program.price));
    $('#CalcCredit input[name=FirstPayCur]').val((facade.program.price * facade.program.firstPay / 100).toFixed(2));
    $('#program50_FirstPayCur').html((facade.program.price * facade.program.firstPay / 100).toFixed(2));
    if (facade.program.insurance > 0)
    {
        $('#CalcCredit input[name=SumCreditCur]').val((facade.program.price * facade.program.insurance / 100).toFixed(2));
    }
    facade.program.calc();
}


programStandard.prototype.print = function()
{
    _self = facade.program;
    href = 'currency=' + _self.currency;
    href += '&credit=' + escape(_self.name);
    href += '&programType=' + _self.programType;
    href += '&carName=' + escape(facade.car.name);
    href += '&carImage=' + facade.car.image;
    href += '&price=' + Math.round(_self.price);
    href += '&completion=' + escape($(_self.completion.name).html());
    href += '&color=' + escape($('#metallic_on').attr('checked') ? 'металлик' : 'не металлик');
    href += '&firstPay=' + (_self.firstPay * _self.price / 100).toFixed(2);
    href += '&insurance=' + (_self.insurance * _self.price / 100).toFixed(2);
    href += '&term=' + _self.term;
    href += '&interestRate=' + _self.interestRate;
    href += '&commission=' + _self.commission;
    href += '&summCredit=' + _self.summCredit;
    
    if (_self.programType == 1)
    {
        href += '&monthlyPay=' + _self.monthlyPay;
        href += '&totalPayRate=' + _self.totalPayRate;
    }
    else if (_self.programType == 2)
    {
        href += '&monthlyPay1=' + _self.monthlyPay1;
        href += '&totalPayRate1=' + _self.totalPayRate1;
        href += '&monthlyPay2=' + _self.monthlyPay2;
        href += '&totalPayRate2=' + _self.totalPayRate2;
    }
    
    if (typeof _self.endLoanAmount != 'undefined')
    {
        href += '&endLoanAmount=' + parseFloat(_self.endLoanAmount).toFixed(2);
    }
    
    window.open('print.php?' + href, 'displayWindow', 'width=768,height=900,status=no,toolbar=no,menubar=no');
}

programStandard.prototype.exportData = function()
{
    _self = facade.program;
    
    var data =
    {
        currency: _self.currency,
        credit: _self.name,
        programType: _self.programType,
        carName: facade.car.name,
        carImage: facade.car.image,
        price: Math.round(_self.price),
        completion: $(_self.completion.name).html(),
        color: ($('#metallic_on').attr('checked') ? 1 : 0),
        firstPay: parseFloat(_self.firstPay * _self.price / 100).toFixed(2),
        firstPayRate: parseFloat(_self.firstPay).toFixed(2),
        insurance: parseFloat(_self.insurance * _self.price / 100).toFixed(2),
        insuranceRate: parseFloat(_self.insurance).toFixed(2),
        term: _self.term,
        interestRate: _self.interestRate,
        commission: _self.commission,
        summCredit: _self.summCredit
    }
    
    if (_self.programType == 1)
    {
        data.monthlyPay = _self.monthlyPay;
        data.totalPayRate = _self.totalPayRate;
    }
    else if (_self.programType == 2)
    {
        data.monthlyPay1 = _self.monthlyPay1;
        data.monthlyPay2 = _self.monthlyPay2;
        data.totalPayRate1 = _self.totalPayRate1;
        data.totalPayRate2 = _self.totalPayRate2;
    }
    
    return data;
}
