$(document).ready(function() {
	
    $(".btn-slide").mouseover(function(){
        $("#panel").slideToggle("slow");
      
    }).mouseout(function(){
        $("#panel").slideToggle("slow");
    });
	
    $(".btn-slide").click(function(){       
        return false;
    });
        
    $("#type_site, #cancel_button, #send_button, #ok_button").uniform();
	
	
    /*$(".btn-slide").click(function(){
        $("#panel").slideToggle("slow");
        /*$(this).toggleClass("active"); 
        return false;
    });
	*/
    /*
	$(".close-slide").click(function(){
		$("#panel").slideToggle("slow");
		/*$(".btn-slide").removeClass("active"); 
		return false;
	});
*/
	
	
    $.fn.alignCenter = function() {
        //получаем отступ слева
        var marginLeft = - $(this).width()/2 + 'px';
        //получаем отступ справа
        var marginTop = - $(this).height()/2 + 'px';
        //возвращаем обновленный элемент
        return $(this).css({
            'margin-left':marginLeft, 
            'margin-top':marginTop
        });
    };

    $.fn.togglePopup = function(){
        //detect whether popup is visible or not
        if($('#popup').hasClass('hidden'))
        {
            //hidden - then display
            //when IE - fade immediately
            if($.browser.msie)
            {
                $('#opaco').height($(document).height()).toggleClass('hidden');
            }
            else
            //in all the rest browsers - fade slowly
            {
                $('#opaco').height($(document).height()).toggleClass('hidden').fadeTo('slow', 0.7);
            }

            $('#popup')
            .html($(this).html())
            .alignCenter()
            .toggleClass('hidden');
        }
        else
        {
            //visible - then hide
            $('#opaco').toggleClass('hidden').removeAttr('style');
            $('#popup').toggleClass('hidden');
        }
	     
        //передаем значения из всплывающей формы в основную  
        $("#popup input, #popup textarea").keyup(function() {	 		
            currentId =  $(this).attr("id");
            newId ="#"+ currentId.substring(0, currentId.length - 1);
            var newValue =  $(this).val();	 		
            $(newId).val(newValue);
	 		
            //счетчик символов оставшихся
            if (currentId == 'comment1'){
                var maxLength = parseInt($('#comment1').attr("maxlength"));
                var currentLength = $('#comment1').val().length;
                var deltaLength = maxLength - currentLength;
                var deltaLengthMsg = 'Осталось символов: '+deltaLength;
                $('#comment_count').text(deltaLengthMsg);
            }
	 		
        });
	 	
	 	

	 	
	 	
        //валидация и отправка формы
        $('#uniform-send_button').click(function() {
	 		
            var formIsValid = $("#popup_form").validate().form();
	 		
            if(formIsValid == true){
                $('#calculator_form').submit();
                $('#popup #popup_form, #popup .buttonbox').remove();
                $('#ok_msg').removeClass('hidden');
	 			
            //$('#popup').togglePopup();
            }	 		
	 		
        });
	 	
	 	
        $("#opaco, #uniform-cancel_button, #uniform-ok_button").click(function(){
            $('#popup').togglePopup();	
            return false;
        //$('#opaco').toggleClass('hidden').removeAttr('style').unbind('click');
        });
	 	

	     
    };
	   
	   
	
    SiteChange();
	
    $("#type_site").change(function() {
		
        $(".tooltip").remove();
		
        var typeOfSite = $("#type_site :selected").val(),
        formOftype = $("#config_site");
			
        /* Обнуляем общую и сумм с НДС в поле вывода */
        //$("#summ span").text("0");
        //$("#summ_nds span").text("0");

        /* Выбираем соответствующую форму из файла */
        //formOftype.load("/calculator.php",{option:typeOfSite});
        //PriceUpdate();
        formOftype.load("/calculator.php",{
            option:typeOfSite
        }, 
        function(){
            Decoform();
            PriceUpdate();
            l_tooltip(".ttp_lnk a","tooltip");
        });
					
					
        //Decoform();
			
        /* Выбираем все чекбоксы которые были подгружены, в этом нам поможет функция live */
        formOftype.live("change",function() {
            PriceUpdate();					
        });	
			
    });	
	
	
	
    $("#config_site").keyup(function() {
        PriceUpdate();
    });
	

	
	
	
    $(".tip_link").click(function(){
        return false;
    });
	

	
	
});

function Decoform() {
    $("#config_site input, #config_site textarea, #config_site select, #config_site button, #popup_form input, #popup_form textarea").uniform();
    //$("#config_site textarea, #config_site select, #config_site button").uniform();
    $(".tip_link").click(function(){				
        return false;
    });
}

function PriceUpdate() {
    /* При проведении действий пересчитываем сумму в зависимости от выбраных чекбоксов */
    var totalSum = 0, /* Полную сумму сначала приравниваем к нулю */
    totalSumNDS = 0;
    //choiceCMS = parseInt($("#cms_radio :selected").val());
		
    /* Приплюсовываем сумму стоимости CMS */
    //totalSum += choiceCMS;
	
    /*Обрабатываем выпадающие списки*/
    $(".Sel").each(function() {
        var Sel = parseInt($(".Sel option:selected").val()); 
        totalSum += Sel;
    //parseInt($(".Sel").val()) * parseInt($(".inputCell").attr("price"));
    });
	
    /* Каждое поле ввода проверяем на введеное значение, если больше нуля то считаем его */
    $(".inputCell").each(function(i,elem){
        var price = parseInt($(elem).attr("price"));
        var count = parseInt($(elem).attr("value"));
        if (!count) {
            count = 0;
        }
        totalSum = totalSum + price*count;
    });

	
    /* Пересчитываем все чекбоксы которые отмечены галочкой*/
    $(this + "input[name=''] :checked").each(function() {
        var currentchbvalue = parseInt($(this).val());	
        if (currentchbvalue > 1){
            totalSum += parseInt($(this).val());			
        }
		
    });
	
    /* Подсчет и вывод суммы итоговой */
    var oldSum = parseInt($("#summ1").text());
    var Delta = totalSum - oldSum;
    var Step = Delta/10;
    var tempSum = oldSum;
	
    $("#sendprice").val(totalSum);
	
    var intervalID = setInterval (function() {
        tempSum+=Step;
        $("#summ1, #summ2").text(tempSum);
        if(tempSum == totalSum){
            clearInterval(intervalID)
        }		
    },30);
	
}

function SiteChange() {
    if ( $('#type_site').length ){
		
        var typeOfSite = $("#type_site :selected").val(),
        formOftype = $("#config_site");
		
        /* Обнуляем общую и сумм с НДС в поле вывода */
        //$("#summ span").text("0");
        //$("#summ_nds span").text("0");

        /* Выбираем соответствующую форму из файла */
        //formOftype.load("/calculator.php",{option:typeOfSite});
        //PriceUpdate();
        formOftype.load("/calculator.php",{
            option:typeOfSite
        }, 
        function(){
            PriceUpdate();
            Decoform();
            l_tooltip(".ttp_lnk a","tooltip");
        });
				
				
        //Decoform();
		
        /* Выбираем все чекбоксы которые были подгружены, в этом нам поможет функция live */
        formOftype.live("change",function() {
            PriceUpdate();					
        });	
		
		
        $('#calculator_form').ajaxForm(function() {
            //alert("Ваша заявка успешно отправлена. Наш менеджер свяжется с вами в ближайшее время.");
            });	
		

		
		
		
    }
	
}




