﻿$(document).ready(function(){

    $(".placeholder").placeholder();

    QA();

    Calc();

Ask();

zayavka_na_credit();

var a = $('#Field1').attr('value','Ваш вопрос').css('color','#cccccc');
var b = $('#Field2').attr('value','Ваш e-mail').css('color','#cccccc');

$('#Field3').attr('value','Фамилия');
$('#Field4').attr('value','Имя*');
$('#Field5').attr('value','Отчество');
$('#Field6').attr('value','Телефон*');
$('#Field7').attr('value','E-mail');
$('#Field8').attr('value','Сумма кредита (руб.)');


//Поле Ваш вопрос
$('#Field1').focus(function() {
if($(this).val() == "Ваш вопрос") {
$(this).val('');
$(this).css('color','#000000');
$(this).css('border','');
}
});

$('#Field1').blur(function() {
if ($(this).val() == ""){
$(this).val("Ваш вопрос");
$(this).css('color','#cccccc');
}
});
//Конец поля ФИО

//Поле Ваш e-mail
$('#Field2').focus(function() {
if($(this).val() == "Ваш e-mail") {
$(this).val('');
$(this).css('color','#000000');
$(this).css('border','');
}
});

$('#Field2').blur(function() {
if ($(this).val() == ""){
$(this).val("Ваш e-mail");
$(this).css('color','#cccccc');
$(this).css('border','');
}
});
//Конец поля Регион


//Поле Фамилия

$('#Field3').focus(function() {

if($(this).val() == "Фамилия") {
$(this).val('');
}

});

$('#Field3').blur(function() {
if ($(this).val() == ""){
$(this).val("Фамилия");
}
});
//Конец поля Фамилия

//Поле Имя

$('#Field4').focus(function() {

if($(this).val() == "Имя*") {
$(this).val('');
}

});

$('#Field4').blur(function() {
if ($(this).val() == ""){
$(this).val("Имя*");
}
});
//Конец поля Имя

//Поле Отчество

$('#Field5').focus(function() {

if($(this).val() == "Отчество") {
$(this).val('');
}

});

$('#Field5').blur(function() {
if ($(this).val() == ""){
$(this).val("Отчество");
}
});
//Конец поля Отчество

//Поле Телефон

$('#Field6').focus(function() {

if($(this).val() == "Телефон*") {
$(this).val('');
}

});

$('#Field6').blur(function() {
if ($(this).val() == ""){
$(this).val("Телефон*");
}
});
//Конец поля Телефон

//Поле E-mail

$('#Field7').focus(function() {

if($(this).val() == "E-mail") {
$(this).val('');
}

});

$('#Field7').blur(function() {
if ($(this).val() == ""){
$(this).val("E-mail");
}
});
//Конец поля E-mail

//Поле Сумма кредита (руб.)

$('#Field8').focus(function() {

if($(this).val() == "Сумма кредита (руб.)") {
$(this).val('');
}

});

$('#Field8').blur(function() {
if ($(this).val() == ""){
$(this).val("Сумма кредита (руб.)");
}
});
//Конец поля Сумма кредита (руб.)

    Bangal();

});


function QA(){
    $("#qa .title").each(function(){
        $(this).click(function(){
            $(this).parent().toggleClass("expanded");
        });
    });
}

function Calc(){
    var calc = $("#calc");
    var date = new Date();
    var month = (date.getMonth() < 10) ? "0" + date.getMonth() : date.getMonth();

    var dateObj = $(".calc-date");
    dateObj.val(date.getDate() + "-" + month + "-" + date.getFullYear());

    var periodObj = calc.find(".calc-period");
    var sumObj = calc.find(".calc-sum");
    var percentObj = calc.find(".calc-percent");

    $(".calc-submit").click(function(){
        var ok = true;

        var period = Number(periodObj.val());
        if (isNaN(period) || period == 0 || period == ""){
            periodObj.addClass("error");
            ok = false;
        }

        var sum = Number(sumObj.val());
        if (isNaN(sum) || sum == 0 || sum == ""){
            sumObj.addClass("error");
            ok = false;
        }

        var percent = Number(percentObj.val()) / 100;
        if (isNaN(percent) || percent == 0 || percent == ""){
            percentObj.addClass("error");
            ok = false;
        }

        if (ok){
            var result = sum*((percent/12)/(1 - Math.pow(1 + percent/12, 2-period)));
            result = Math.round(result);
            $(".calc-result").show().find("span").html(result);
            $(".calc-form").show();
        } else {
            $(".calc-result").hide();
        }
    });

    var dataObj = calc.find("#Field11");
    var emailObj = calc.find("#Field10");
    var nameObj = calc.find("#Field9");

    calc.find('form').ajaxForm(
        {
            beforeSubmit: function(){
                var s = "Срок кредита: " + periodObj.val() +
                "\nДата выдачи кредита: " + dateObj.val() +
                "\nПроцентная ставка: " + percentObj.val() +
                "\nСумма кредита: " + sumObj.val();

                dataObj.text(s);

                var ok = true;
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

                if (!reg.test(emailObj.val())){
                    emailObj.addClass("error");
                    ok = false;
                }

                if(nameObj.val() == ""){
                    nameObj.addClass("error");
                    ok = false;
                }

                if (!ok){
                    return false
                }
            },
            success: function(responseText, statusText){
                calc.find(".ok").html("Ваша заявка успешно отправлена!")
            }

        }
    );

    calc.find("input").focus(function(){
        $(this).removeClass("error");
    });
}









function Bangal(){
    // I'm using .each() because sometimes there can be some carousels on one page
    $("#bangal").each(function(){
        var obj = $(this);
        var animationSpeed = 1000;
        var changeSpeed = 5000;

        var ul = obj.find("ul");
        var banCounter = 0;
        var lipages = obj.find(".paginator span");

        var lis = [];
        ul.find("li").each(function(){
            lis.push($(this));
        });

        var banAmount = lis.length - 1;

        lis[0].css({display:"block", opacity: "1"});

        /**
         * change da picture
         * @param to integer null-based
         */
        var Change = function(to){
            if (to == undefined){
                to = banCounter + 1;
            }

//            с последнего на первый
            if (banCounter == banAmount){
                to = 0;
            }

            lis[banCounter].animate({opacity:0}, animationSpeed, function(){$(this).css({display:"none"})});
            lis[to].css({display:"block"}).animate({opacity:1}, animationSpeed);
            lipages.filter(".active").removeClass("active");
            $(lipages[to]).addClass("active");

            banCounter = to;
        };

        lipages.each(function(){
            $(this).click(function(){
                var id = $(this).index();
                if (obj.find(":animated").length == 0 && id != banCounter){
                    Change(id);
                    clearInterval(interval);
                    interval = setInterval(function(){
                        Change();
                    }, changeSpeed)
                }
            });
        });

//        var next = function(){
//            banCounter++;
//            banCounter %= banAmount;
//            if(!banCounter){
//                ul.css({left: "0%"});
//                banCounter++;
//            }
//            ul.animate({
//                left: -100 * banCounter + "%"
//            }, speed );
//        };
//
//        var prev = function(){
//            banCounter--;
//            if ( banCounter < 0 ) {
//                banCounter = banAmount -1;
//                ul.css({left: -100 * banCounter + "%"});
//                banCounter --;
//            }
//            ul.animate({
//                left: -100 * banCounter + "%"
//            }, speed );
//        };



//        if (banAmount>2) {
//            $(this).find(".prev").click(function(){
//                prev();
//                clearInterval(interval);
//                return false;
//            });
//            $(this).find(".next").click(function() {
//                next();
//                clearInterval(interval);
//                return false;
//            });
//        }

        var interval = setInterval(function(){
            Change();
        }, changeSpeed)
    })
}


function Ask(){
    var form = $('#ask form');

    $("#ask .toggler").click(function(){
        form.toggle();
    });

    form.ajaxForm({
    beforeSubmit: function(formData, jqForm, options) {
	var poleleft1 = $('#Field1');
	var poleleft2 = $('#Field2');
	var uspeh = $('.uspeh');
	var jForm = jqForm[0];
	if( !jForm.Field1.value || jForm.Field1.value == 'Ваш вопрос' ||
	    !jForm.Field2.value || jForm.Field2.value == 'Ваш e-mail'){


          if (!jForm.Field1.value || jForm.Field1.value == 'Ваш вопрос') {
             poleleft1.css('border','1px solid red');
            }

	  if (!jForm.Field2.value || jForm.Field2.value == 'Ваш e-mail') {
             poleleft2.css('border','1px solid red');
            }


	     uspeh.html("<p>Заполните все поля!</p>").css('color','red').css('margin-left','20px').css('font-size','14px').css('margin-top','4px');
    	    return false;
    	} else {
	    return true;
	}
    },
    success: function() {
       form.find(".ok").show();
        setTimeout(function(){
            form.hide();
            form.find(".ok").hide();
        }, 2000);
    }});


}



/*Вопросы и ответы*/

function zayavka_na_credit(){

var form3 = $('#form_zayavka form');
var form_zayavka = $('#form_zayavka');
var uspeh = $('.uspeh');
    form3.ajaxForm({
    beforeSubmit: function validate(formData, jqForm, options) { 
		var polecredit4 = $('#Field4');
		var polecredit6 = $('#Field6');
		
    var creditform = jqForm[0]; 
    if (!creditform.Field4.value || creditform.Field4.value == 'Имя*' || 
		!creditform.Field6.value || creditform.Field6.value == 'Телефон*') 
    { 
          if (!creditform.Field4.value || creditform.Field4.value == 'Имя*') {
             polecredit4.css('border','1px solid red');
            }

	   else {
		polecredit4.css('border','1px solid #828181');
	   }

if (!creditform.Field6.value || creditform.Field6.value == 'Телефон*') {
             polecredit6.css('border','1px solid red');
            }

	   else {
		polecredit6.css('border','1px solid #828181');
	   }

          uspeh.html("<p>Заполните обязательные поля!</p>").css('color','red').css('margin-left','20px').css('font-size','14px');
			form_zayavka.css('height','454px');
        return false; 
    } 
    else {
	return true;
    }
},

    success: function() {
        setTimeout(function(){
            form3.html("<p>Ваш запрос успешно отправлен!</p>").css('color','green').css('font-size','12px');
        }, 2000);

}});

};
/*Вопросы и ответы*/



/**
 * эмуляция атрибута placeholder
 * использование: $(".placeholder").placeholder();
 */
(function($) {
    $.fn.placeholder = function() {
        return this.each(function() {
            var me = $(this);
            var defaultText = me.val();
            $(this).addClass("blur");

            $(this).focus(function(){
                if (me.val() == defaultText ){
                    me.val("").removeClass("blur");
                }
            }).blur(function(){
                if (me.val() == ""){
                    me.val(defaultText).addClass("blur");
                }
            });
        });
    };
})(jQuery);

