var konsultant = function(){
    this._templates = {};
};

konsultant.prototype.init = function(){
    var that = this;
    
    this._initTemplates();
    

    
    
    $(".konsultantB").click(function(){
        var data = {
            ofert_type: $(this).attr("data-ofert_type"),
            ofert_subtype: $(this).attr("data-ofert_subtype"),
            info: $(this).attr("data-info"),
            description: $(this).attr("data-description"),
            form: $(this).attr("data-form"),
            insId: $(this).attr("data-ins-id"),
            diffrentData:$(this).attr("data-diffrentData")
        };

        //****GA Tracking Code
        _gaq.push(['t2._trackPageview', '/lead/click/'+data['info']+'/'+data['ofert_type']+'/'+data['ofert_subtype']]);
        
        var tpl = that.markupTemplate(data.form, data);
        tpl.appendTo('body');
        $("body").find("#cctForm").overlay({
            load: true,
            closeOnClick: false,
            closeOnEsc: false,
            mask: {
        		color: '#f1f1f1',
        		loadSpeed: 200,
        		opacity: 0.9
        	},
            top:'center',
            onLoad: function(){
                //dodanie wyświetlania formularza
                            $('a.regulamin').click(function(){
                               var tpl = that.markupTemplate('regulaminTemplate',{});
                               tpl.appendTo('body');
                                   $('body').find('.mainDiv').overlay({
                                                load: true,
                                                closeOnClick: false,
                                                closeOnEsc: true,
                                                mask: {
                                            		color: '#f1f1f1',
                                            		loadSpeed: 200,
                                            		opacity: 0.9
                                            	},
                                                top:'center',
                                                onLoad: function(){
                                                   $(".mainDiv .close").click(function(){
                                                        var form = $('.mainDiv');
                                                        form.find('.close')
                                                   });
                                                },
                                                onClose: function(){
                                                    $("body").find(".formOpinions").remove();
                                                }
                                            });
                            $.post('/index.php?c=Partner&a=getRegulamin',{},function(msg){
                                $('.mainDiv').find('.regulamin').html(msg);
                            });
                        });
                //////
                var k1 = k2 = false; //zmienne do keyUp
                $("#cct-tel-1").keyup(function(){
                        if($("#cct-tel-1").val().length == 3 && k1 == false){
                            k1 = true;
                            $("#cct-tel-2").focus();
                        }
                        if($("#cct-tel-1").val().length < 3){
                            k1 = false;
                        }
                });
                
                $("#cct-tel-2").keyup(function(){
                    if($("#cct-tel-2").val().length == 3 && k2 == false){
                        k2 = true;
                        $("#cct-tel-3").focus();
                    }
                    if($("#cct-tel-2").val().length < 3){
                        k2 = false;
                    }
                });                
                
                $("#cctForm").find("#submitKonsultantB").click(function(){
                    var valid = true;
                    $("#cctForm").find('.borderRed').removeClass('borderRed');
                    var newsVar = 0;
                    if($('#cctForm').find("input[name=newsletter]:checked").length>0){
                        newsVar = 1;
                    }
                    _data = {
                        email: $("#cctForm").find("input[name=cct-email]").val(),
                        imie: $("#cctForm").find("input[name=cct-imie]").val(),
                        nazwisko: $("#cctForm").find("input[name=cct-nazwisko]").val(),
                        tel1: $("#cctForm").find("input[name=cct-tel-1]").val(),
                        tel2: $("#cctForm").find("input[name=cct-tel-2]").val(),
                        tel3: $("#cctForm").find("input[name=cct-tel-3]").val(),
                        miasto: $("#cctForm").find("input[name=cct-miasto]").val(),
                        pora_kontaktu: $("#cctForm").find("select[name=cct-pora_kontaktu]").val(),
                        kod_pocztowy: $("#cctForm").find("input[name=cct-kod_pocztowy]").val(),
                        pesel: $("#cctForm").find("input[name=cct-pesel]").val(),
                        newsletter: newsVar
                    };
                    if(!AC.utils.isEmail(_data.email)){
                        $("#cctForm").find("input[name=cct-email]").addClass('borderRed');
                        valid = false;
                    }
                    
                    /*if(_data.imie == ''){
                        $("#cctForm").find("input[name=cct-imie]").addClass('borderRed');
                        valid = false;
                    }*/
                    
                    /*if(_data.nazwisko == ''){
                        $("#cctForm").find("input[name=cct-nazwisko]").addClass('borderRed');
                        valid = false;
                    }*/
                    
                    if(isNaN(parseInt(_data.tel1)) || isNaN(parseInt(_data.tel2)) || isNaN(parseInt(_data.tel3))){
                        $("#cctForm").find("input[name=cct-tel-1], input[name=cct-tel-2], input[name=cct-tel-3]").addClass('borderRed');
                        valid = false;
                    }

                    var checkboxy = document.getElementsByName('przetwarzanie')
                    if(checkboxy.length>0){
                       if(!checkboxy[0].checked){
                            alert("Musisz wyrazić zgodę na przetwarzanie danych");
                            $("#cctForm").find("input[name=przetwarzanie]").addClass('borderRed');
                            valid = false;
                       }
                    }
                    data = AC.utils.mergeObjects(data, _data);
                    
                    if(!valid){return false;}
                    
                    $("body").find("#cctForm form").html('<p class="center paddedBig h2"><b>Proszę czekać</b><br/><br/><img src="/public/gfx/loaders/ajax-loader.gif" /></p>');
                    
                    $.getJSON('/index.php?c=Partner&a=createKonsultantLead', data, function(respond){
                        
                        //****GA Tracking Code
                        _gaq.push(['t2._trackPageview', '/lead/add/'+data['info']+'/'+data['ofert_type']+'/'+data['ofert_subtype']]);
                        
                        $("body").find("#cctForm form").html('<p class="center paddedBig h2"><b>' + respond.message + '</b></p>');
                    });
                    
                });
                
            },
            onClose: function(){
                $("body").find("#cctForm").remove();
            }
        });
        
    });
    
  
};

konsultant.prototype.markupTemplate = function(template, options){
    if(typeof(options) == 'undefined'){
        options = {};
    }
    return this._templates[template](options);
};


konsultant.prototype._initTemplates = function(options){
    var that = this;
    this._templates = {
    	advancedForm: function(options){
            var html = [
                '<div id="cctForm" class="paddedBig">',
                    '<form action="#" id="cct-form" method="post">',
                        '<h2 class="h1">Sprawdź bezpłatnie!</h1>',
                        '<p>Wypełnij formularz. Nasz konsultant zadzwoni w ciągu 24 godzin.</p>',
                        '<table>',
                            '<tbody>',
                                '<tr>',
                                    '<td class="padded"><label>Tel. kom.:</label></td>',
                                    '<td class="padded" style="white-space: nowrap;">',
                                        '<input type="text" maxlength="3" id="cct-tel-1" class="padded h3 center" name="cct-tel-1" style="margin-right: 10px; width: 45px;" />',
                                        '<input type="text" maxlength="3" id="cct-tel-2" class="padded h3 center" name="cct-tel-2" style="margin-right: 10px; width: 45px;" />',
                                        '<input type="text" maxlength="3" id="cct-tel-3" class="padded h3 center" name="cct-tel-3" style="width: 45px;" /><span style="padding: 0px 2px 0px 7px; color: red;">*</span>',
                                    '</td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded"><label for="cct-email">E-mail:</label></td>',
                                    '<td class="padded" style="white-space: nowrap;"><input type="text" id="cct-email" class="padded h3" name="cct-email" style="width:95%" /><span style="padding: 0px 2px 0px 7px; color: red;">*</span></td>',
                                '</tr>',
                            '</tbody>',
                        '</table>',
                        
                        '<p class="paddedBig center"><button type="button" class="buton formButFont" style="border:none;" id="submitKonsultantB">Sprawdź</button></p>',
                        
                        '<strong>Aby przyspieszyć kontakt możesz podać dodatkowe dane</strong>',
                        '<table>',
                            '<tbody>',
                                  '<tr>',
                                    '<td class="padded" style="width:100px"><label for="cct-imie">Imię:</label></td>',
                                    '<td class="padded" style="width:200px;"><input type="text" id="cct-imie" class="padded h3" name="cct-imie" style="width:95%" /></td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded"><label for="cct-nazwisko">Nazwisko:</label></td>',
                                    '<td class="padded"><input type="text" id="cct-nazwisko" class="padded h3" name="cct-nazwisko" style="width:95%" /></td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded" style="width:100px;">Miejscowość:</td>',
                                    '<td class="padded" style="width:200px;"><input type="text" class="padded" name="cct-miasto" style="width:95%;"/></td>',
                                '</tr><tr>',
                                    '<td class="padded">Kod pocztowy:</td>',
                                    '<td class="padded"><input type="text" class="padded" name="cct-kod_pocztowy" style="width:95%;"/></td>',
                                '</tr><tr>',
                                    '<td class="padded">Preferowana pora kontaktu:</td>',
                                    '<td class="padded">',
                                        '<select class="padded" name="cct-pora_kontaktu" id="cct-pora_kontaktu" style="width:95%;">',
                                            '<option value="dowolna">dowolna</option>',
                                            '<option value="rano">9.00 - 12.00</option>',
                                            '<option value="południe">12.00 - 15.00</option>',
                                            '<option value="wieczór">15.00 - 18.00</option>',
                                            '<option value="noc">18.00 - 20.00</option>',
                                        '</select>',
                                    '</td>',
                                '</tr><tr>',
                                    '<td class="padded">PESEL:</td>',
                                    '<td class="padded"><input type="text" class="padded" name="cct-pesel" style="width:95%;"/></td>',
                                '</tr>',
                            '</tbody>',
                        '</table>',
                        '<table style="font-size: 10px; color:#B0B0B0">',
                        '   <tr>',
                        '       <td><input type="checkbox" name="przetwarzanie" value="1" checked="checked" class="przetwarzanie"/>',
                        '       <td>Wyrażam zgodę na przetwarzanie moich danych osobowych na zasadach określonych w <a class="regulamin">regulaminie</a></td>',
                        '   </tr>',
                        '   <tr>',
                        '       <td><input type="checkbox" name="newsletter" value="1" checked="checked"/></td>',
                        '       <td>Zgodnie z ustawą z dnia 26.08.2002r. o świadczeniu usług drogą elektroniczną, obowiązującą od 10 marca 2003r. wyrażam zgodę na otrzymywanie informacji handlowych drogą elektroniczną.</td>',
                        '   </tr>',
                        '</table>',
                        '<input type="hidden" name="insId" value="{$insId}"/>',
                        '<input type="hidden" name="description" value="{$description}"/>',
                        '<input type="hidden" name="diffrentData" value="{$diffrentData}"/>',
                    '</form>',
                '</div>'
            ].join('');
            return $(AC.utils.parseTemplate(html, options));
        },
    	simpleForm: function(options){
            var html = [
                '<div id="cctForm" class="paddedBig">',
                    '<form action="#" id="cct-form" method="post">',
                        '<h2 class="h1">Sprawdź bezpłatnie!</h1>',
                        '<p>Wypełnij formularz. Nasz konsultant zadzwoni w ciągu 24 godzin.</p>',
                        '<table>',
                            '<tbody>',
                                '<tr>',
                                    '<td class="padded"><label>Tel. kom.:</label></td>',
                                    '<td class="padded" style="white-space: nowrap;">',
                                        '<input type="text" maxlength="3" id="cct-tel-1" class="padded h3" name="cct-tel-1" style="margin-right: 10px; width: 45px;" />',
                                        '<input type="text" maxlength="3" id="cct-tel-2" class="padded h3" name="cct-tel-2" style="margin-right: 10px; width: 45px;" />',
                                        '<input type="text" maxlength="3" id="cct-tel-3" class="padded h3" name="cct-tel-3" style="width: 45px;" /><span style="padding: 0px 2px 0px 7px; color: red;">*</span>',
                                    '</td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded"><label for="cct-email">E-mail:</label></td>',
                                    '<td class="padded" style="white-space: nowrap;"><input type="text" id="cct-email" class="padded h3" name="cct-email" style="width:95%" /><span style="padding: 0px 2px 0px 7px; color: red;">*</span></td>',
                                '</tr>',
                            '</tbody>',
                        '</table>',
                        '<p class="paddedBig center"><button type="button" class="padded gradientDark c-pointer h2" style="border:none;" id="submitKonsultantB">Sprawdź bezpłatnie</button></p>',
                        '<h2 class="h3">Aby przyspieszyć kontakt możesz podać dodatkowe dane</h2>',
                        '<table>',
                            '<tbody>',
                                '<tr>',
                                    '<td class="padded" style="width:100px"><label for="cct-imie">Imię:</label></td>',
                                    '<td class="padded" style="width:200px;"><input type="text" id="cct-imie" class="padded h3" name="cct-imie" style="width:95%" /></td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded"><label for="cct-nazwisko">Nazwisko:</label></td>',
                                    '<td class="padded"><input type="text" id="cct-nazwisko" class="padded h3" name="cct-nazwisko" style="width:95%" /></td>',
                                '</tr>',
                                '<tr>',
                                    '<td class="padded" style="width:100px;">Miejscowość:</td>',
                                    '<td class="padded" style="width:200px;"><input type="text" class="padded" name="cct-miasto" style="width:95%;"/></td>',
                                '</tr><tr>',
                                    '<td class="padded">Kod pocztowy:</td>',
                                    '<td class="padded"><input type="text" class="padded" name="cct-kod_pocztowy" style="width:95%;"/></td>',
                                '</tr><tr>',
                                    '<td class="padded">Preferowana pora kontaktu:</td>',
                                    '<td class="padded">',
                                        '<select class="padded" name="cct-pora_kontaktu" id="cct-pora_kontaktu" style="width:95%;">',
                                            '<option value="dowolna">dowolna</option>',
                                            '<option value="rano">9.00 - 12.00</option>',
                                            '<option value="południe">12.00 - 15.00</option>',
                                            '<option value="wieczór">15.00 - 18.00</option>',
                                            '<option value="noc">18.00 - 20.00</option>',
                                        '</select>',
                                    '</td>',
                                '</tr><tr>',
                            '<tbody>',
                        '</table>',
                        '<table style="font-size: 10px; color:#B0B0B0">',
                        '   <tr>',
                        '       <td><input type="checkbox" name="przetwarzanie" value="1" checked="checked" class="przetwarzanie"/>',
                        '       <td>Wyrażam zgodę na przetwarzanie moich danych osobowych na zasadach określonych w <a class="regulamin">regulaminie</a></td>',
                        '   </tr>',
                        '   <tr>',
                        '       <td><input type="checkbox" name="newsletter" value="1" checked="checked"/></td>',
                        '       <td>Zgodnie z ustawą z dnia 26.08.2002r. o świadczeniu usług drogą elektroniczną, obowiązującą od 10 marca 2003r. wyrażam zgodę na otrzymywanie informacji handlowych drogą elektroniczną.</td>',
                        '   </tr>',
                        '</table>',
                    '</form>',
                '</div>'
            ].join('');
            return $(AC.utils.parseTemplate(html, options));
        },
        regulaminTemplate: function(option){
          var html = [
            '<div class="mainDiv">',
            '<p><a class="close"></a></p>',
            '<div class="regulamin"><p class="center paddedBig h2"><b>Proszę czekać</b><br/><br/><img src="/public/gfx/loaders/ajax-loader.gif" /></p></div>',
            '</div>',
          ].join('');
          return $(AC.utils.parseTemplate(html, options));
        }
    };
};

AC.registerController(new konsultant);MultiCalc = function(){};

MultiCalc.prototype.init = function(){
    var that = this;    
    //box kredytow
    that.calcHipoteka();
    that.calcGotowka();
    that.calcSamochod();
    that.mainSelect();
    //box lokat
    that.calcLokata();
    //konta karty
    that.calcKarty();
    //kredyty firmowy
    that.calcFirma();
}

MultiCalc.prototype.bindEvents = function(){}

MultiCalc.prototype.mainSelect = function(){
    var that = this;
    that.showCalcCredit($('.select_calc_test').val()); //wyswietlenie domyslnego
    $('.select_calc_test').change(function(){
        that.showCalcCredit($(this).val());
    });
}

/* obsluga suwaka kredytow firmowych */
MultiCalc.prototype.calcFirma = function(){
    var that = this;
    //zczytanie watosci domyslnych
    var Value = $('.firmy form.calcform').find('input[name=value]').val();
    var Period = $('.firmy form.calcform').find('input[name=period]').val();
    //var Currency = $('.lokaty form.calcform').find('select[name=currency]').val();
    //slidery
    var sliderValue = $('.slider_value_kredyt_firmowy').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 5,
        max: 200,
        step: 5,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.firmy .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));            
        },               
        slide: function(event, ui){
            $('.firmy .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){            
            $('.firmy form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('firmy');
        }
    });
    
    var sliderValue = $('.slider_period_kredyt_firmowy').slider({ //slider dla czasu kredytowania
        range: 'min',
        min: 3,
        max: 10,
        step: 1,
        value: Period,
        animate: true,
        create: function(event, ui){
            $('.firmy .amount_period').html(Period);
        },               
        slide: function(event, ui){
            $('.firmy .amount_period').html(ui.value);
        },
        change: function(event, ui){
            $('.firmy form.calcform').find('input[name=period]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('firmy');
        }
    });
    that.changeRate('firmy');
    //obsluga linku
    $('#link_to_kredyty_firmowe').click(function(){
       var value = $('.firmy form.calcform').find('input[name=value]').val()*1000;
       var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
       var period = $('.firmy form.calcform').find('input[name=period]').val();
       var link = '/firma/kredyty-dla-firm?kwotaFormat='+value_format+'&warunki[kwota]='+value+'&warunki[kf_type]=0&warunki[kf_duration]='+period;
       location.href = link;
       return false; 
    });
}

/* obsluga suwaka lokat */
MultiCalc.prototype.calcLokata = function(){
    var that = this;
    //zczytanie watosci domyslnych
    var Value = $('.lokaty form.calcform').find('input[name=value]').val();
    var Period = $('.lokaty form.calcform').find('input[name=period]').val();
    //var Currency = $('.lokaty form.calcform').find('select[name=currency]').val();
    //slidery
    var sliderValue = $('.slider_value_lokaty').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 1,
        max: 50,
        step: 1,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.lokaty .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));            
        },               
        slide: function(event, ui){
            $('.lokaty .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){            
            $('.lokaty form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('lokaty');
        }
    });
    $('#period_lokaty').change(function(){
        $('.lokaty form.calcform').find('input[name=period]').val( $(this).val() ); 
        that.changeRate('lokaty');   
    });
    that.changeRate('lokaty');
    //obsluga linku
    $('#link_to_lokaty').click(function(){
       var value = $('.lokaty form.calcform').find('input[name=value]').val()*1000;
       var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
       var link = '/firma/kredyty-dla-firm?kwotaFormat='+value_format+'&warunki[kwota]='+value+'&warunki[kf_type]=0&warunki[kf_duration]=10';
       var link = 'inwestycje/lokaty/porownanie?warunki[investmentType]=-1&warunki[investmentType]=5&warunki[przedzial]=2&warunki[investmentLength]=12_3&investmentValueFormat='+value_format+'&warunki[investmentValue]='+value;
       location.href = link;
       return false; 
    });    
}

/* obsluga suwaków hipotek */
MultiCalc.prototype.calcHipoteka = function(){
    var that = this;
    //zczytanie watosci domyslnych
    var Value = $('.hipoteczne form.calcform').find('input[name=value]').val();
    var Period = $('.hipoteczne form.calcform').find('input[name=period]').val();
    var Currency = $('.hipoteczne form.calcform').find('select[name=currency]').val();
    //slidery
    var sliderValue = $('.slider_value_hipoteka').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 50,
        max: 500,
        step: 1,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.hipoteczne .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));            
        },               
        slide: function(event, ui){
            $('.hipoteczne .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){            
            $('.hipoteczne form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('hipoteczne');
        }
    });
    var sliderValue = $('.slider_period_hipoteka').slider({ //slider dla czasu kredytowania
        range: 'min',
        min: 10,
        max: 40,
        step: 5,
        value: Period,
        animate: true,
        create: function(event, ui){
            $('.hipoteczne .amount_period').html(Period);
        },               
        slide: function(event, ui){
            $('.hipoteczne .amount_period').html(ui.value);
        },
        change: function(event, ui){
            $('.hipoteczne form.calcform').find('input[name=period]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('hipoteczne');
        }
    });
    //koniec sliderow
    //obsluga zmiany waluty
    $('.hipoteczne .select_currency').change(function(){
        that.changeRate('hipoteczne');
    }) 
    that.changeRate('hipoteczne');
    //obsluga linku
    $('#link_to_hipoteczne').click(function(){
        var value = $('.hipoteczne form.calcform').find('input[name=value]').val()*1000;
        var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
        var property = value*(10/8);
        var propertyFormat = AC.utils.number_format(property, 0, ',', ' ').replace(" ", "+");
        var period = $('.hipoteczne form.calcform').find('input[name=period]').val();
        var currency = $('.hipoteczne .select_currency').val();
        if(currency == 0) currency = 1;
        var link = '/kredyty/hipoteczne/porownanie?propertyValueFormat='+propertyFormat+'&warunki[propertyValue]='+property+'&creditValueFormat='+value_format+'&warunki[creditValue]='+value+'&warunki[periodYear]='+period+'&warunki[currency_id]='+currency+'&warunki[rate_type]=1&warunki[nier_dzialka]=1&warunki[clientAge]=30';
        location.href = link;
        return false;
    });     
}

/* obsluga suwaków gotowkek */
MultiCalc.prototype.calcGotowka = function(){
    var that = this;
    //zczytanie watosci domyslnych
    var Value = $('.gotowkowe form.calcform').find('input[name=value]').val();
    var Period = $('.gotowkowe form.calcform').find('input[name=period]').val();
    //var Currency = $('.gotowkowe form.calcform').find('select[name=currency]').val();

    //slidery
    var sliderValue = $('.slider_value_gotowka').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 1,
        max: 120,
        step: 1,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.gotowkowe .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));
        },               
        slide: function(event, ui){
            $('.gotowkowe .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){
            $('.gotowkowe form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('gotowkowe');
        }
    });
    var sliderValue = $('.slider_period_gotowka').slider({ //slider dla czasu kredytowania
        range: 'min',
        min: 1,
        max: 7,
        step: 1,
        value: Period,
        animate: true,
        create: function(event, ui){
            $('.gotowkowe .amount_period').html(Period);
            $('.gotowkowe .amount_period_unit').html(' lat');
            if(Period==1){ $('.gotowkowe .amount_period_unit').html(' rok'); }
            if(Period==2 || Period==3 || Period==4 ){ $('.gotowkowe .amount_period_unit').html(' lata'); }             
        },               
        slide: function(event, ui){
            $('.gotowkowe .amount_period').html(ui.value);
            $('.gotowkowe .amount_period_unit').html(' lat');
            if(ui.value==1){ $('.gotowkowe .amount_period_unit').html(' rok'); }
            if(ui.value==2 || ui.value==3 || ui.value==4 ){ $('.gotowkowe .amount_period_unit').html(' lata'); }            
        },
        change: function(event, ui){
            $('.gotowkowe form.calcform').find('input[name=period]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('gotowkowe');
        }
    });
    //koniec sliderow
    //obsluga zmiany waluty
   /* $('#select_currency').change(function(){
        that.changeRate('gotowkowe');
    })*/ 
    that.changeRate('gotowkowe');
    //obsluga linku
    $('#link_to_gotowkowe').click(function(){
        var value = $('.gotowkowe form.calcform').find('input[name=value]').val()*1000;
        var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
        var period = $('.gotowkowe form.calcform').find('input[name=period]').val()*12;
        var link = '/kredyty/gotowkowe/porownanie?warunki[advanceSearchVisible]=&creditValueFormat='+value_format+'&warunki[creditValue]='+value+'&warunki[period]='+period+'&warunki[withoutCertificate]=-1';
        location.href = link;
        return false;
    });    
}
/* obsluga suwaków samochodowych */
MultiCalc.prototype.calcSamochod = function(){
    var that = this;
    //zczytanie watosci domyslnych
    var Value = $('.samochodowe form.calcform').find('input[name=value]').val();
    var Period = $('.samochodowe form.calcform').find('input[name=period]').val();
    var Currency = $('.samochodowe form.calcform').find('select[name=currency]').val();
    //slidery
    var sliderValue = $('.slider_value_samochod').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 10,
        max: 80,
        step: 1,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.samochodowe .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));           
        },               
        slide: function(event, ui){
            $('.samochodowe .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){            
            $('.samochodowe form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('samochodowe');
        }
    });
    var sliderValue = $('.slider_period_samochod').slider({ //slider dla czasu kredytowania
        range: 'min',
        min: 1,
        max: 10,
        step: 1,
        value: Period,
        animate: true,
        create: function(event, ui){
            $('.samochodowe .amount_period').html(AC.utils.number_format(Period, 0, ',', ' '));
            $('.samochodowe .amount_period_unit').html(' lat');
            if(Period==1){ $('.samochodowe .amount_period_unit').html(' rok'); }
            if(Period==2 || Period==3 || Period==4 ){ $('.samochodowe .amount_period_unit').html(' lata'); }            
        },               
        slide: function(event, ui){
            $('.samochodowe .amount_period').html(AC.utils.number_format(ui.value, 0, ',', ' '));
            $('.samochodowe .amount_period_unit').html(' lat');
            if(ui.value==1){ $('.samochodowe .amount_period_unit').html(' rok'); }
            if(ui.value==2 || ui.value==3 || ui.value==4 ){ $('.samochodowe .amount_period_unit').html(' lata'); }
        },
        change: function(event, ui){
            $('.samochodowe form.calcform').find('input[name=period]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('samochodowe');
        }
    });
    //koniec sliderow
    //obsluga zmiany waluty
    $('.samochodowe .select_currency').change(function(){
        that.changeRate('samochodowe');
    })
    that.changeRate('samochodowe');
    //obsluga linku
    $('#link_to_samochodowe').click(function(){
        var value = $('.samochodowe form.calcform').find('input[name=value]').val()*1000;
        var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
        var period = $('.samochodowe form.calcform').find('input[name=period]').val()*12;
        var currency = $('.samochodowe .select_currency').val();
        var link = '/kredyty/samochodowe/porownanie?warunki[advanceSearchVisible]=1&vehiclePriceFormat='+value_format+'&warunki[vehiclePrice]='+value+'&creditValueFormat='+value_format+'&warunki[creditValue]='+value+'&warunki[period]='+period+'&warunki[vehicleAge]=0&warunki[currency_id]='+currency;
        location.href = link;
        return false;
    });    
}
/* obsluga suwaka kart kredytowych */
MultiCalc.prototype.calcKarty = function(){
    var that = this;
    //.ui-slider-range{position:absolute;z-index:1;font-size: .7em;display:block;border:0;background-position:0 0;}
    //zczytanie watosci domyslnych
    var Value = $('.karty_kredytowe form.calcform').find('input[name=value]').val();
    var Period = $('.karty_kredytowe form.calcform').find('input[name=period]').val();
    var Currency = $('.karty_kredytowe form.calcform').find('select[name=currency]').val();
    //slidery
    var sliderValue = $('.slider_value_karty').slider({ //slider dla kwoty kredytu
        range: 'min',
        min: 1,
        max: 50 ,
        step: 1,
        value: Value,
        animate: true,
        create: function(event, ui){
            $('.karty_kredytowe .amount_credit').html(AC.utils.number_format(Value*1000, 0, ',', ' '));            
        },               
        slide: function(event, ui){
            $('.karty_kredytowe .amount_credit').html(AC.utils.number_format(ui.value*1000, 0, ',', ' '));
        },
        change: function(event, ui){            
            $('.karty_kredytowe form.calcform').find('input[name=value]').val(ui.value); //musi byc zapis wartoci do pola ukrytego
            that.changeRate('karty_kredytowe');
        }
    });
    //koniec sliderow
    //obsluga zmiany waluty
    $('#typ_karty_kredytowej').change(function(){
        $('.karty_kredytowe form.calcform').find('input[name=period]').val( $(this).val() );
        that.changeRate('karty_kredytowe');
    }) 
    that.changeRate('karty_kredytowe');
    
    //obsluga linku
    $('#link_to_karty').click(function(){
        var value = $('.konta_karty form.calcform').find('input[name=value]').val()*1000;
        var value_format = AC.utils.number_format(value, 0, ',', ' ').replace(" ", "+");
        var minicome = value*20/100;
        var minicome_format = AC.utils.number_format(minicome, 0, ',', ' ').replace(" ", "+");
        var card_type = $('.konta_karty form.calcform').find('input[name=period]').val();
        var link = '/konta-karty/karty-kredytowe/porownanie?minIncomeFormat='+minicome_format+'&warunki[pcc_minincome]='+minicome+'&maxCredLimFormat='+value_format+'&warunki[pcc_maxcredlim]='+value+'&warunki[pcc_thematic]='+card_type;
        location.href = link;
        return false;
    });    
    
}
/* odpalenie kalkulatora */
MultiCalc.prototype.changeRate = function(product){
    //pobranie wartosci z pol ukrytych
    $('.lCalc .loading').show();
    var credit = $('.'+product+' form.calcform').find('input[name=value]').val()*1000; //kwota musi byc przemnozona x1000
    var time = $('.'+product+' form.calcform').find('input[name=period]').val();
    var currency = $('.'+product+' form.calcform').find('select[name=currency]').val();

    //zlozenie urla w zaleznosci od produktu
    switch(product){
        case 'hipoteczne':
            var valid = (typeof(currency)=='undefined' || typeof(credit)=='undefined' || typeof(time)=='undefined') ? false : true; 
            var url = '&a=rechargeHipoteka&walutaKredytu='+currency+'&kwotaKredytu='+credit+'&okresKredytowania='+time;
        break;
        case 'gotowkowe':
            var valid = (typeof(credit)=='undefined' || typeof(time)=='undefined') ? false : true;
            var url = '&a=rechargeGotowka&kwotaKredytu='+credit+'&okresKredytowania='+time;
        break;
        case 'samochodowe':
            var valid = (typeof(currency)=='undefined' || typeof(credit)=='undefined' || typeof(time)=='undefined') ? false : true;
            var url = '&a=rechargeSamochod&walutaKredytu='+currency+'&kwotaKredytu='+credit+'&okresKredytowania='+time;
        break;
        case 'karty_kredytowe':
            var valid = (typeof(credit)=='undefined' || typeof(time)=='undefined') ? false : true;
            var url = '&a=rechargeKartyKredytowe&kwotaKredytu='+credit+'&typKarty='+time; //tutaj w zmiennej time jest typ karty
        break;
        case 'lokaty':
            var valid = (typeof(credit)=='undefined') ? false : true;
            var url = '&a=rechargeLokaty&kwotaInwestycji='+credit+'&okresInwestycji='+time;;
        break;
        case 'firmy':   
            var valid = (typeof(credit)=='undefined') ? false : true;
            var url = '&a=rechargeFirmy&kwotaKredytu='+credit+'&okresKredytowania='+time;
        break;            
        default: var valid = false;
    }

    if(valid){ //musza byc podane wszsytkie odpowiednie zmienne zeby odpalic jsona
        $.getJSON('/index.php?c=Calc'+url, {rand:Math.random()}, function(respond){
            switch(product){
                case 'firmy':
                case 'hipoteczne':
                case 'gotowkowe':
                case 'samochodowe':
                case 'karty_kredytowe':
                    $('.right .'+product+' span.min').text(AC.utils.number_format(respond.data.min, 0, ',', ' '));
                    $('.right .'+product+' span.max').text(AC.utils.number_format(respond.data.max, 0, ',', ' '));
                    $('.right .'+product+' span.save_month').text(AC.utils.number_format(respond.data.diff, 0, ',', ' '));
                    $('.right .'+product+' span.save_whole').text(AC.utils.number_format(respond.data.wholeDiff*1000, 0, ',', ' '));
                    break;
                case 'lokaty':
                
                    if(respond.data.max_bank!=0){
                        $('.right .'+product+' span.max_bank').text(AC.utils.number_format(respond.data.max_bank, 2, ',', ' ')+' %');
                    }else $('.right .'+product+' span.max_bank').text('brak danych');

                    if(respond.data.max_bez_podatku!=0){
                        $('.right .'+product+' span.max_bez_podatku').text(AC.utils.number_format(respond.data.max_bez_podatku, 2, ',', ' ')+' %');
                    }else $('.right .'+product+' span.max_bez_podatku').text('brak danych');

                    if(respond.data.max_polisolokaty!=0){
                        $('.right .'+product+' span.max_polisolokaty').text(AC.utils.number_format(respond.data.max_polisolokaty, 2, ',', ' ')+' %');
                    }else $('.right .'+product+' span.max_polisolokaty').text('brak danych');

                    if(respond.data.max_oszczednosciowe!=0){
                        $('.right .'+product+' span.max_oszczednosciowe').text(AC.utils.number_format(respond.data.max_oszczednosciowe, 2, ',', ' ')+' %');
                    }else $('.right .'+product+' span.max_oszczednosciowe').text('brak danych');

                    if(respond.data.max!=0){
                        $('.right .'+product+' span.max').text(AC.utils.number_format(respond.data.max, 0, ',', ' ')+' %');
                    }else $('.right .'+product+' span.max').text('brak danych');

                    $('.right .'+product+' span.save_month').text(AC.utils.number_format(respond.data.diff, 0, ',', ' '));
                    break;
                default:
            }
            $('.lCalc .loading').hide();
        });
    }
}

/* wyswietlenie odpowiedniego kalkulatora */
MultiCalc.prototype.showCalcCredit = function(calc){
    $('.kredyty').hide();
    $('div.'+calc).show();
}

AC.registerController(new MultiCalc);
$(document).ready(function(){
    $('.calculator_load').hide();    
});var calcUbSamochodu = function(){};

calcUbSamochodu.prototype.init = function(){
    var that = this;
    
    var d = new Date();
    var curr_year = d.getFullYear();
    for ( var i=(curr_year-9); i<=curr_year; i++ ) {
        var sel = (i == 1) ? "selected" : "";
        $('#select-08-01').
          append($("<option " + sel + "></option>").
          attr("value", i).
          text(i));
    }
    //that.getMarka($('#select-08-01').val());
    that.getType($('#select-08-00').val());    
    $('#select-08-00').change( function() { that.getType($(this).val()); });
    $('#select-08-01').change( function() { that.getMarka($(this).val()); });
    $('#select-08-02').change( function() { that.getModel($('#select-08-01').val(), $(this).val()); });
    $('#select-08-03').change( function() { that.calculate($('#select-08-01').val(), $('#select-08-02').val(), $(this).val());});
    
    this.bindEvents();
    
};

calcUbSamochodu.prototype.numer2currency = function(number) {
    var j = Math.floor(number/1000);
    return j + ' tys. zł';
};

calcUbSamochodu.prototype.bindEvents = function(){
    var that = this;
    $('#img_acoc_tooltip').tooltip({
        tip: '#tooltip_acoc_box',
        effect: 'fade',        
        position: '0 0',
        offset: [-1 -1],
        delay: 50
     });              
}

calcUbSamochodu.prototype.getType = function(typ) {
    $('#vis_ubezpieczenia .loading').show();
    var that = this;
    $('#select-08-01').find('option').remove().end();
    $.getJSON('/index.php?c=Calc&a=getType', {rand: Math.random(), type:typ}, function(respond){
        
        for ( var i=0; i<respond.data.year.length; i++ ) {
            var sel = ( respond.data.year[i].prod_od == 'TOYOTA' ) ? 'selected' : '';
            $('#select-08-01').
              append($("<option " + sel + "></option>").
              attr("value", respond.data.year[i].prod_od).
              text(respond.data.year[i].prod_od));
        }
        that.getMarka($('#select-08-01').val());
        return false;
    });    
}

calcUbSamochodu.prototype.getMarka = function(rocznik) {
    $('#vis_ubezpieczenia .loading').show();
    var that = this;
    $('#select-08-02').find('option').remove().end();
    $.getJSON('/index.php?c=Calc&a=getMarka', {rand: Math.random(), year:rocznik}, function(respond){
        for ( var i=0; i<respond.data.marki.length; i++ ) {
            var sel = ( respond.data.marki[i].marka == 'TOYOTA' ) ? 'selected' : '';
            $('#select-08-02').
              append($("<option " + sel + "></option>").
              attr("value", respond.data.marki[i].marka_id).
              text(respond.data.marki[i].marka));
        }
        that.getModel($('#select-08-01').val(), $('#select-08-02').val());
        return false;
    });
};

calcUbSamochodu.prototype.getModel = function(rocznik, marka) {
    $('#vis_ubezpieczenia .loading').show();
    var that = this;
    $('#select-08-03').find('option').remove().end();
    $.getJSON('/index.php?c=Calc&a=getModel', {rand: Math.random(), year:rocznik, marka_id:marka}, function(respond){
        for ( var i=0; i<respond.data.modele.length; i++ ) {
            var sel = ( respond.data.modele[i].model == 'Yaris' ) ? 'selected' : '';
            $('#select-08-03').
              append($("<option " + sel + "></option>").
              attr("value", respond.data.modele[i].model_id).
              text(respond.data.modele[i].model));
        }
        that.calculate($('#select-08-01').val(), $('#select-08-02').val(), $('#select-08-03').val());
        return false;
    });
};

calcUbSamochodu.prototype.calculate = function(rocznik, marka, model) {
    $('#vis_ubezpieczenia .loading').show();
    if(typeof(rocznik)!='undefined' && typeof(marka)!='undefined' && typeof(model)!='undefined'){ //zabezpieczenie przed wywolanie skryptu bez parametrow
        var acoc = $('#select-08-00').val(); //pobranie typu ubezpieczenia
        $("#select-08-wait").show();
        $.getJSON('/index.php?c=Calc&a=calculateACOC', {rand: Math.random(), year:rocznik, marka_id:marka, model_id:model, acoc:acoc}, function(respond){
            $("#min-08").html(AC.utils.number_format(respond.data.data.min, 0, ',', ' ')); 
            $("#max-08").html(AC.utils.number_format(respond.data.data.max, 0, ',', ' '));
            $(".save-08").html(AC.utils.number_format(respond.data.data.save, 0, ',', ' '));                
            
            var auto = ' z '+$("#select-08-01").val()+' r.'; //tu bedzie generowan tresc do tooltipa
                            
            $(".auto-08").html(auto);
            $("#select-08-wait").hide();
            return false;
        });                
    }
    $('#vis_ubezpieczenia .loading').hide();
    return false;
};

AC.registerController(new calcUbSamochodu);
