$(function(){
var reg_email =/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/;
var reg_tel =/^(\+79|89)(\d{9})$/;
var reg_tel2 = /^[0-9]/;
var reg_password = /^[a-zA-Z0-9]+$/;
var tel_count1 = 0;
var tel_count2 = 0;
var tel_count3 = 0;
var tel_count4 = 0;



	$('.tel_2').click(function() {
		if ($('.tel_2').val() == "")
			$('.tel_1').focus();
	});
	$('.tel_3').click(function() {
		if ($('.tel_3').val() == "")
			$('.tel_1').focus();
	});
	$('.tel_4').click(function() {
		if ($('.tel_4').val() == "")
			$('.tel_1').focus();
	});



$('input[name="tel_1"]').bind("keyup", function () {
$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");
	if ($('input[name="tel_1"]').val().length == 3 && reg_tel2.exec($('input[name="tel_1"]').val()) != null) {
		$('.tel_2').focus();
		tel_count1 = 1;
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
	}
	else if ($('input[name="tel_1"]').val().length < 3 && reg_tel2.exec($('input[name="tel_1"]').val()) != null) {
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count1 = 0;
	}
	else{
		$(".err_PERSONAL_MOBILE").addClass("marker_fields");
		$(".regok_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count1 = 0;
	}
});

$('input[name="tel_2"]').bind("keyup", function () {
$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");
	if ($('input[name="tel_2"]').val().length == 3 && reg_tel2.exec($('input[name="tel_2"]').val()) != null) {
		$('.tel_3').focus();
		tel_count2 = 1;
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
	}
	else if ($('input[name="tel_2"]').val().length < 3 && reg_tel2.exec($('input[name="tel_2"]').val()) != null) {
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count2 = 0;
	}
	else{
		$(".err_PERSONAL_MOBILE").addClass("marker_fields");
		$(".regok_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count2 = 0;
	}
});

$('input[name="tel_3"]').bind("keyup", function () {
	$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");	
	if ($('input[name="tel_3"]').val().length == 2 && reg_tel2.exec($('input[name="tel_3"]').val()) != null) {
		$('.tel_4').focus();
		tel_count3 = 1;
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
	}
	else if ($('input[name="tel_3"]').val().length < 2 && reg_tel2.exec($('input[name="tel_3"]').val()) != null) {
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count3 = 0;
	}
	else{
		$(".err_PERSONAL_MOBILE").addClass("marker_fields");
		$(".regok_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count3 = 0;
	}
});

$('input[name="tel_4"]').bind("keyup", function () {
$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");
	if ($('input[name="tel_4"]').val().length == 2 && reg_tel2.exec($('input[name="tel_4"]').val()) != null) {
		tel_count4 = 1;
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields")
		if (tel_count1 == 1 && tel_count2 == 1 && tel_count3 == 1  && tel_count4 == 1  ) {
			$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
			$(".regok_PERSONAL_MOBILE").addClass("marker_fields");
			$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");	
			$('input[name="REGISTER[PERSONAL_MOBILE]"]').val (("+7")+($('input[name="tel_1"]').val())+($('input[name="tel_2"]').val())+($('input[name="tel_3"]').val())+($('input[name="tel_4"]').val()));	
		}
	}
	else if ($('input[name="tel_4"]').val().length < 2 && reg_tel2.exec($('input[name="tel_4"]').val()) != null) {
		$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
		$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count4 = 0;
	}
	else{
		$(".err_PERSONAL_MOBILE").addClass("marker_fields");
		$(".regok_PERSONAL_MOBILE").removeClass("marker_fields");
		tel_count4 = 0;
	}
});




	$('input[name="REGISTER[PASSWORD]"]').bind("keyup", function () {
		if ($('input[name="REGISTER[PASSWORD]"]').val() == "" || $('input[name="REGISTER[PASSWORD]"]').val().length <6 || $('input[name="REGISTER[PASSWORD]"]').val().length >50) {
				$(".err_PASSWORD").addClass("marker_fields");
				$(".regok_PASSWORD").removeClass("marker_fields");
				$(".regerr1_PASSWORD").removeClass("marker_fields");
			} 
			else {
				$(".regok_PASSWORD").addClass("marker_fields");
				$(".err_PASSWORD").removeClass("marker_fields");
				$(".regerr1_PASSWORD").removeClass("marker_fields");
			}
		if (reg_password.exec($('input[name="REGISTER[PASSWORD]"]').val()) == null ) {
			$(".err_PASSWORD").removeClass("marker_fields");
				$(".regok_PASSWORD").removeClass("marker_fields");
				$(".regerr1_PASSWORD").addClass("marker_fields");
		}
		if ($('input[name="REGISTER[PASSWORD]"]').val() != $('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() )
				{	$(".err_CONFIRM_PASSWORD").addClass("marker_fields");
					$(".regok_CONFIRM_PASSWORD").removeClass("marker_fields");
					
				}
	
	});
	
	$('input[name="REGISTER[CONFIRM_PASSWORD]"]').bind("keyup", function () {
		if  ($('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() == "") {
				$(".err_CONFIRM_PASSWORD").removeClass("marker_fields");
				$(".regok_CONFIRM_PASSWORD").removeClass("marker_fields");
				$(".regerr_CONFIRM_PASSWORD").addClass("marker_fields");
			}
			else {
				$(".regerr_CONFIRM_PASSWORD").removeClass("marker_fields");
				if ($('input[name="REGISTER[PASSWORD]"]').val() != $('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() )
				{	$(".err_CONFIRM_PASSWORD").addClass("marker_fields");
					$(".regok_CONFIRM_PASSWORD").removeClass("marker_fields");
				} else {
					$(".regok_CONFIRM_PASSWORD").addClass("marker_fields");
					$(".err_CONFIRM_PASSWORD").removeClass("marker_fields");
				}
			}
	
	});
	$('input[name="REGISTER[EMAIL]"]').bind("keyup", function () {
		if (reg_email.exec($('input[name="REGISTER[EMAIL]"]').val()) == null || $('input[name="REGISTER[EMAIL]"]').val() =="") {
				$(".err_EMAIL").addClass("marker_fields");
				$(".regok_EMAIL").removeClass("marker_fields");
			} else {
				$(".regok_EMAIL").addClass("marker_fields");
				$(".err_EMAIL").removeClass("marker_fields");
			}
	
	});
	
		$('input[name="REGISTER[LOGIN]"]').bind("keyup", function () {
		
		var login_err;
		var request_timeout;
		clearTimeout(request_timeout);
		   request_timeout = setTimeout(function(){
			 $.getJSON(
			'/ajax_reg.php',
			{
				action: 'register_form_login',
				login: $('input[name="REGISTER[LOGIN]"]').val(),
			},
			function(data){
				switch(data.status){
					case 'ok':	
						login_err = 1;
						break;
					case 'wrong_login':
						login_err = 0;
						break;
					case 'wrong_login_en':
						login_err = 2;
						break;
						
				}
				if($('input[name="REGISTER[LOGIN]"]').val() == "" || $('input[name="REGISTER[LOGIN]"]').val().length <3 || $('input[name="REGISTER[LOGIN]"]').val().length >50) {
					$(".err_LOGIN").removeClass("marker_fields");
					$(".regok_LOGIN").removeClass("marker_fields");
					$(".regerr_LOGIN").removeClass("marker_fields");
					$(".regerr1_LOGIN").addClass("marker_fields");
				}
				else {
				$(".regerr1_LOGIN").removeClass("marker_fields");
					if (login_err == 0) {
						$(".err_LOGIN").addClass("marker_fields");
						$(".regok_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").removeClass("marker_fields");
					} 
					else if  (login_err == 2) {
						$(".regok_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").addClass("marker_fields");
							$(".err_LOGIN").removeClass("marker_fields");
					}
					else {
						$(".regok_LOGIN").addClass("marker_fields");
						$(".err_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").removeClass("marker_fields");
						
					}
				}
			}
		);
	  }, 200);
    });
	
	

		
	 $('#reloadcaptcha').click(function(){
         $('#whiteBlock').show();
         $.getJSON('/personal/register/reload_captcha.php', function(data) {
            $('#captchaImg').attr('src','/bitrix/tools/captcha.php?captcha_sid='+data);
            $('#captchaSid').val(data);
            $('#whiteBlock').hide();
         });
         return false;
      });
	  var tel_rep;
	 $(".tel_repeat").live("click", function () {
		$(this).addClass("active");
		tel_rep = 1;
		$('.noactive_inp').css("display","inline-block");
		$('.rep_tel_field').hide();
		$(".err_PERSONAL_PHONE").removeClass("marker_fields");
		$(".regerr_PERSONAL_PHONE").removeClass("marker_fields");
	 });
	  

	$("#register_but").live("click", function () {
	var capcha_err;    
    $.getJSON(
        '/ajax_reg.php',
        {
            action: 'register_form_capcha',
            captcha_code: $('#code_captcha').val(),
            captcha_sid: $('#captchaSid').val(),
        },
        function(data){
            switch(data.status){
                case 'ok':
					$(".err_CAPCHA").removeClass("marker_fields");
					$(".regok_CAPCHA").addClass("marker_fields");
					capcha_err = 1;				
                    break;
                case 'wrong_code':
                    $(".err_CAPCHA").addClass("marker_fields");
					$(".regok_CAPCHA").removeClass("marker_fields");
					capcha_err = 0;	
                    break;
            }
			if ((capcha_err == 1	) && (tel_count1 == 1 && tel_count2 == 1 && tel_count3 == 1  && tel_count4 == 1  )  && ((reg_tel2.exec($('input[name="REGISTER[PERSONAL_PHONE]"]').val()) != null && $('input[name="REGISTER[PERSONAL_PHONE]"]').val() !="" )|| (tel_rep == 1)) && $('input[name="REGISTER[NAME]"]').val() != "" && $('input[name="REGISTER[SECOND_NAME]"]').val() != ""  && $('input[name="REGISTER[LAST_NAME]"]').val() != ""  && $('input[name="REGISTER[WORK_COMPANY]"]').val() != "" && $('input[name="REGISTER[WORK_STREET]"]').val() != "" && $('input[name="REGISTER[WORK_STATE]"]').val() != "")
			{
				$('#regform_req').submit();
			}
			else {
				if ($('input[name="REGISTER[NAME]"]').val() == "") {
					$(".err_NAME").addClass("marker_fields");
					$(".regok_NAME").removeClass("marker_fields");
				} else {
					$(".regok_NAME").addClass("marker_fields");
					$(".err_NAME").removeClass("marker_fields");
				}
				
		
				
				if ($('input[name="REGISTER[PERSONAL_PHONE]"]').val() == "") {
					$(".err_PERSONAL_PHONE").removeClass("marker_fields");
					$(".regok_PERSONAL_PHONE").removeClass("marker_fields");
					$(".regerr_PERSONAL_PHONE").addClass("marker_fields");			
				} 
				else {
					$(".regerr_PERSONAL_PHONE").removeClass("marker_fields");
						if (reg_tel2.exec($('input[name="REGISTER[PERSONAL_PHONE]"]').val()) == null ) {
						$(".regok_PERSONAL_PHONE").removeClass("marker_fields");
						$(".err_PERSONAL_PHONE").addClass("marker_fields");
						}
						else {
						$(".regok_PERSONAL_PHONE").addClass("marker_fields");
						$(".err_PERSONAL_PHONE").removeClass("marker_fields");
						
						}
				}
				if (tel_rep == 1)
				{
					$(".err_PERSONAL_PHONE").removeClass("marker_fields");
					$(".regok_PERSONAL_PHONE").removeClass("marker_fields");
					$(".regerr_PERSONAL_PHONE").removeClass("marker_fields");
				}
				
				
				if ($('input[name="REGISTER[SECOND_NAME]"]').val() == "") {
					$(".err_SECOND_NAME").addClass("marker_fields");
					$(".regok_SECOND_NAME").removeClass("marker_fields");
				} else {
					$(".regok_SECOND_NAME").addClass("marker_fields");
					$(".err_SECOND_NAME").removeClass("marker_fields");
				}
				if ($('input[name="REGISTER[LAST_NAME]"]').val() == "") {
					$(".err_LAST_NAME").addClass("marker_fields");
					$(".regok_LAST_NAME").removeClass("marker_fields");
				} else {
					$(".regok_LAST_NAME").addClass("marker_fields");
					$(".err_LAST_NAME").removeClass("marker_fields");
				}
				if (tel_count1 == 1 && tel_count2 == 1 && tel_count3 == 1  && tel_count4 == 1  ) {
					$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
					$(".regok_PERSONAL_MOBILE").addClass("marker_fields");
					$(".regerr_PERSONAL_MOBILE").removeClass("marker_fields");			} 
				else {
					$(".err_PERSONAL_MOBILE").removeClass("marker_fields");
					$(".regok_PERSONAL_MOBILE").removeClass("marker_fields");
					$(".regerr_PERSONAL_MOBILE").addClass("marker_fields");	
				}
				

				if ($('input[name="REGISTER[WORK_COMPANY]"]').val() == "") {
					$(".err_WORK_COMPANY").addClass("marker_fields");
					$(".regok_WORK_COMPANY").removeClass("marker_fields");
				} else {
					$(".regok_WORK_COMPANY").addClass("marker_fields");
					$(".err_WORK_COMPANY").removeClass("marker_fields");
				}
				if ($('input[name="REGISTER[WORK_STREET]"]').val() == "") {
					$(".err_WORK_STREET").addClass("marker_fields");
					$(".regok_WORK_STREET").removeClass("marker_fields");
				} else {
					$(".regok_WORK_STREET").addClass("marker_fields");
					$(".err_WORK_STREET").removeClass("marker_fields");
				}
				if ($('input[name="REGISTER[WORK_STATE]"]').val() == "") {
					$(".err_WORK_STATE").addClass("marker_fields");
					$(".regok_WORK_STATE").removeClass("marker_fields");
				} else {
					$(".regok_WORK_STATE").addClass("marker_fields");
					$(".err_WORK_STATE").removeClass("marker_fields");
				}
			}
		}
    );
});  
	  
	  
	$("#next_reg").live("click", function () {	
		var login_err;
		 $.getJSON(
        '/ajax_reg.php',
        {
            action: 'register_form_login',
            login: $('input[name="REGISTER[LOGIN]"]').val(),
        },
        function(data){
            switch(data.status){
                case 'ok':	
					login_err = 1;
                    break;
                case 'wrong_login':
					login_err = 0;
                    break;
				case 'wrong_login_en':
					login_err = 2;
					break;
            }
			if($('input[name="REGISTER[LOGIN]"]').val() == "") {
				$(".err_LOGIN").removeClass("marker_fields");
				$(".regok_LOGIN").removeClass("marker_fields");
				$(".regerr1_LOGIN").addClass("marker_fields");
				$(".regerr_LOGIN").removeClass("marker_fields");
			}
			else {
			$(".regerr1_LOGIN").removeClass("marker_fields");
				if (login_err == 0) {
						$(".err_LOGIN").addClass("marker_fields");
						$(".regok_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").removeClass("marker_fields");
						
					} 
					else if  (login_err == 2) {
						$(".regok_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").addClass("marker_fields");
							$(".err_LOGIN").removeClass("marker_fields");
					}
					else {
						$(".regok_LOGIN").addClass("marker_fields");
						$(".err_LOGIN").removeClass("marker_fields");
						$(".regerr_LOGIN").removeClass("marker_fields");
						
					}
				
			}
			
			var reg_usr_name = /[a-z]+/i;
		

		if ((login_err == 1)&& (reg_email.exec($('input[name="REGISTER[EMAIL]"]').val()) != null && $('input[name="REGISTER[EMAIL]"]').val() !="") && $('input[name="REGISTER[PASSWORD]"]').val() != "" && $('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() != "" && ($('input[name="REGISTER[PASSWORD]"]').val() == $('input[name="REGISTER[CONFIRM_PASSWORD]"]').val())) {
			$(".active_field").addClass("noactive_newfield");
			$(".noactive_newfield").removeClass("active_field");
			$(".noactive_field").addClass("active_newfield");
			$(".active_newfield").removeClass("noactive_field");
			$(".regok_LOGIN").addClass("marker_fields");
			$(".regok_PASSWORD").addClass("marker_fields");
			$(".regok_CONFIRM_PASSWORD").addClass("marker_fields");
			$(".regerr_CONFIRM_PASSWORD").removeClass("marker_fields");
			$(".regok_EMAIL").addClass("marker_fields");
			$(".err_LOGIN").removeClass("marker_fields");
			$(".err_PASSWORD").removeClass("marker_fields");
			$(".err_CONFIRM_PASSWORD").removeClass("marker_fields");
			$(".err_EMAIL").removeClass("marker_fields");
		}
		else 
		{
			if ($('input[name="REGISTER[PASSWORD]"]').val() == "" || $('input[name="REGISTER[PASSWORD]"]').val().length <6 || $('input[name="REGISTER[PASSWORD]"]').val().length >50) {
				$(".err_PASSWORD").addClass("marker_fields");
				$(".regok_PASSWORD").removeClass("marker_fields");
			} else {
				$(".regok_PASSWORD").addClass("marker_fields");
				$(".err_PASSWORD").removeClass("marker_fields");
			}
			if  ($('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() == "") {
				$(".err_CONFIRM_PASSWORD").removeClass("marker_fields");
				$(".regok_CONFIRM_PASSWORD").removeClass("marker_fields");
				$(".regerr_CONFIRM_PASSWORD").addClass("marker_fields");
			}
			else {
				$(".regerr_CONFIRM_PASSWORD").removeClass("marker_fields");
				if ($('input[name="REGISTER[PASSWORD]"]').val() != $('input[name="REGISTER[CONFIRM_PASSWORD]"]').val() )
				{	$(".err_CONFIRM_PASSWORD").addClass("marker_fields");
					$(".regok_CONFIRM_PASSWORD").removeClass("marker_fields");
				} else {
					$(".regok_CONFIRM_PASSWORD").addClass("marker_fields");
					$(".err_CONFIRM_PASSWORD").removeClass("marker_fields");
				}
			}
			if (reg_email.exec($('input[name="REGISTER[EMAIL]"]').val()) == null || $('input[name="REGISTER[EMAIL]"]').val() =="") {
				$(".err_EMAIL").addClass("marker_fields");
				$(".regok_EMAIL").removeClass("marker_fields");
			} else {
				$(".regok_EMAIL").addClass("marker_fields");
				$(".err_EMAIL").removeClass("marker_fields");
			}
			
		}
			
        }
    );
		
	});

	  
	
	
	
	$("#prev_reg").live("click", function () {		
		$(".active_newfield").addClass("noactive_field");
		$(".noactive_field").removeClass("active_newfield");
		$(".noactive_newfield").addClass("active_field");
		$(".active_field").removeClass("noactive_newfield");
	});
	
	
    if ($(".fright .consult_order_cont").length) {
        $(".consult_order_cont form").attr("action", "/consult-order/")
    }
    if ($(".compare_table").length) {
        initScrollbars()
    }
    if ($(".print").length) {
        $(".print").prev().css("width", "70%")
    }
    if ($(".cities").length) {
        $(".cities ul a").live("click", function () {
            if (!$(this).parent().hasClass("active")) {
                var a = $(this).parent().attr("id").replace("city-menu-", "");
                var b = $(this);
                $(this).parent().parent().find(".active").removeClass("active");
                $(this).parent().addClass("active");
                $(this).parent().parent().next().find(".active").fadeOut(300, function () {
                    $(this).removeClass("active");
                    $(b).parent().parent().next().find(".cities_contact:nth-child(" + a + ")").fadeIn(300, function () {
                        $(this).addClass("active")
                    })
                })
            }
            $(this).blur();
            return false
        })
    }
    if ($(".city_contact_selector").length) {
        $(".current_city a").live("click", function () {
            $(".contacts_city_list").fadeIn(300);
            $(this).blur();
            return false
        });
        $(".contacts_city_list ul a").live("click", function () {
            var a = $(this);
            $(this).parent().parent().find(".active").removeClass("active");
            $(this).parent().addClass("active");
            $(".current_city a").text($(this).text());
           /* $(".contact_cities > .active").fadeOut(300, function () {
                $(".contact_cities .contact_cities_item:nth-child(" + $(a).parent().attr("id").replace("city-menu-contact-", "") + ")").fadeIn(300, function () {
                    $(".contact_cities > .active").removeClass("active");
                    $(this).addClass("active")
                })
            });*/
			
			
            $(".contacts_city_list").fadeOut(300);
            $(this).blur();
            return false
        });
        $(".close_contacts_city_list").live("click", function () {
            $(".contacts_city_list").fadeOut(200);
            $(this).blur();
            return false
        })
    }
    if ($(".consult_order").length) {
        $(".consult_order_bottom a").live("mousedown", function () {
            if (!$(".consult_order_form").hasClass("opened")) {
                $(".consult_order_bottom").css("background-position", "0 -149px")
            } else {
                $(".consult_order_bottom").css("background-position", "0 -169px")
            }
            $(this).blur()
        });
        $(".consult_order_bottom a").live("mouseup", function () {
            if (!$(".consult_order_form").hasClass("opened")) {
                $(".consult_order_bottom").css("background-position", "0 -149px")
            } else {
                $(".consult_order_bottom").css("background-position", "0 -129px")
            }
            $(this).blur()
        });
        $(".consult_order_bottom a").live("click", function () {
            if (!$(".consult_order_form").hasClass("opened")) {
                $(".consult_order_bottom").css("background-position", "0 -129px");
                $(".consult_order_form").slideDown(300).addClass("opened")
            } else {
                $(".consult_order_bottom").css("background-position", "0 -109px");
                $(".consult_order_form").slideUp(300).removeClass("opened")
            }
            $(this).blur();
            return false
        })
    }
	
	if ($(".consult_order_new").length) {
        $(".consult_order_bottom_new a").live("mousedown", function () {
            if (!$(".consult_order_form_new").hasClass("opened2")) {
                $(".consult_order_bottom_new").css("background-position", "0 0px")
            } else {
                $(".consult_order_bottom_new").css("background-position", "0 0px")
            }
            $(this).blur()
        });
        $(".consult_order_bottom_new a").live("mouseup", function () {
            if (!$(".consult_order_form_new").hasClass("opened2")) {
                $(".consult_order_bottom_new").css("background-position", "0 0px")
            } else {
                $(".consult_order_bottom_new").css("background-position", "0 0px")
            }
            $(this).blur()
        });
        $(".consult_order_bottom_new a").live("click", function () {
            if (!$(".consult_order_form_new").hasClass("opened2")) {
                $(".consult_order_form_new").slideDown(300).addClass("opened2").animate({opacity:1}, 0, function(){$('.consult_order_bottom_new').addClass("bottom_error_form")});
				$('.consult_order_cont_new').removeAttr('style');
            } else {
                $(".consult_order_bottom_new").css("background-position", "0 0px");
                $(".consult_order_form_new").slideUp(300).animate({opacity:1}, 0, function(){$('.consult_order_cont_new').attr('style', 'height:45px;');$('.consult_order_form_new_inner').removeAttr('style');$('.consult_order_bottom_new').removeClass("bottom_error_form"); $(".consult_order_form_new").removeClass("opened2");})
            }
            $(this).blur();
            return false
        })
    }
	
	
    if ($(".tabs").length) {
        $(".tab_menu a").live("click", function () {
            if (!$(this).hasClass("active")) {
                $(".tab_menu a.active").removeClass("active");
                $(this).addClass("active");
                $(".tabs .tab:visible").fadeOut(300, function () {
                    $($(".tab_menu a.active").attr("href")).fadeIn(300);
                    if ($(".tabs_contact").length && !$(".tab_menu a.active .mousetrap").length) {
                        $(".cloud-zoom, .cloud-zoom-gallery").CloudZoom()
                    }
                })
            }
            $(this).blur();
            return false
        })
    }
   /* if ($(".big_button").length) {
        $(".big_button a").live("mouseover", function () {
			$('#top_slider').hide();
            $(".big_img img:visible").removeClass("active").hide();
            $(".big_button .active").removeClass("active");
            $(this).addClass("active");
            $(".big_img img:nth-child(" + $(this).parent().attr("id").replace("big-button-", "") + ")").show()
			$("#all_show1").hide();
			$("#all_show2").hide();
        })
        
        $(".big_button a").live("mouseout", function () {
			$('#top_slider').show();
            $(".big_img img:visible").removeClass("active").hide();
            $(".big_button .active").removeClass("active");
            $("#all_show1").show();
			$("#all_show2").show();
        })
    }*/
    if ($("#machine_name_hidden").length) {
        $("#machine_name input").val($("#machine_name_hidden").val())
    }
    if ($("ol").length) {
        $("ol").each(function (b) {
            var a = '<table class="ol">';
            $(this).find("li").each(function (c) {
                a += '<tr><td class="num"><span>' + parseInt(c + 1) + "</span></td><td>" + $(this).text() + "</td></tr>"
            });
            a += "</table>";
            $(this).replaceWith(a)
        })
    }
    if ($(".weekly_mailing").length) {
        $(".weekly_mailing a").live("click", function () {
            $(".weekly_mailing .field").slideToggle(300);
            $(this).blur();
            return false
        })
    }
    if ($(".features_menu").length) {
        $(".features_menu a").live("click", function () {
            if (!$(this).parent().hasClass("active")) {
                $(this).parent().parent().find(".active").removeClass("active");
                $(this).parent().addClass("active");
                if($('.tab').length){
                    if ($(this).parent().attr("id") == "features-menu-2") {
                        $(".tab:visible table .nodiff").fadeOut(300);
                        $(".tab:visible table .nodiff").next().fadeOut(300)
                    } else {
                        $(".tab:visible table .nodiff").fadeIn(300);
                        $(".tab:visible table .nodiff").next().fadeIn(300)
                    }
                }else{
                    if ($(this).parent().attr("id") == "features-menu-2") {
                        $(".nodiff").fadeOut(300);
                        $(".nodiff").next().fadeOut(300)
                    } else {
                        $(".nodiff").fadeIn(300);
                        $(".nodiff").next().fadeIn(300)
                    }
                }
            }
            $(this).blur();
            return false
        })
    }
    if ($("#cons-city-sel").length) {
        $(".cons_city_list ul a").live("click", function () {
            var a = $(this).attr("id").replace("cons-city-", "");
            $("#cons-city-sel").text($(this).text());
            $(".cons_city_list").fadeOut(200);
            $(".phone_list li:visible").fadeOut(100, function () {
                $(".phone_list li:nth-child(" + a + ")").fadeIn(200)
            });
            $(this).blur();
            return false
        });
        $("#cons-city-sel").live("click", function () {
            $(".cons_city_list").fadeIn(200);
            $(this).blur();
            return false
        });
        $(".close_city_list").live("click", function () {
            $(".cons_city_list").fadeOut(200);
            $(this).blur();
            return false
        })
    }
    if ($(".search").length) {
        $(".search .submit input").live("mouseover", function () {
            $(this).css("color", "#4a78be");
            $(this).blur();
            return false
        });
        $(".search .submit input").live("mouseout", function () {
            $(this).css("color", "#999");
            $(this).blur();
            return false
        });
        $(".search .submit input").live("mousedown", function () {
            $(this).css("color", "#fff");
            $(this).blur();
            return false
        })
    }
    if ($('a[rel="fancybox"]').length) {
        $('a[rel="fancybox"]').fancybox({
            titleShow: false,
            transitionIn: "elastic",
            transitionOut: "elastic"
        })
    }
    if ($(".tabs_contact .tab_cont").length) {
        $(".tabs_contact .tab_cont a").fancybox({
            titleShow: false,
            transitionIn: "elastic",
            transitionOut: "elastic"
        })
    }
    if ($(".cur_rate").length) {
        $(".calc_data input#yes_active, .calc_data input#new_calk, .calc_data input#new_calk2, .calc_data input#s_new_calk, .calc_data input#s_new_calk2").live("change", reCalculatePrices);
        $(".calc_data input#yes_active, .calc_data input#new_calk, .calc_data input#new_calk2, .calc_data input#s_new_calk, .calc_data input#s_new_calk2").live("click", function () {
            if ($(this).val() == 0) {
                $(this).val("")
            }
        });
        $(".calc_data input#yes_active, .calc_data input#new_calk, .calc_data input#new_calk2, .calc_data input#s_new_calk, .calc_data input#s_new_calk2").live("blur", function () {
            if ($(this).val() == "") {
                $(this).val("0")
            }
        })
    }
    if ($(".quantity_inc").length) {
        $(".quantity_dec").live("click", function () {
            var a = $(this).next().val();
            if (a > 1) {
                $(this).next().val(--a)
            }
            $(this).blur();
            return false
        });
        $(".quantity_inc").live("click", function () {
            var a = $(this).prev().val();
            $(this).prev().val(++a);
            $(this).blur();
            return false
        });
        $(".submit input").live("mouseover", function () {
            $(this).addClass("jshover")
        });
        $(".submit input").live("mouseout", function () {
            $(this).removeClass("jshover")
        })
    }
    if ($(".certificates a").length) {
        $(".certificates a").fancybox({
            titleShow: false,
            transitionIn: "elastic",
            transitionOut: "elastic"
        })
    }
	
    if ($(".reportlink").length) {
        $(".reportlink").fancybox({
            titleShow: false,
            transitionIn: "elastic",
            transitionOut: "elastic"
        })
    }
	
    if ($(".order_history").length) {
        $(".order_history .level-1>a").live("click", function () {
            if ($(this).parent().hasClass("active")) {
                $(this).parent().removeClass("active")
            } else {
                $(this).parent().addClass("active")
            }
            $(this).blur();
            return false
        })
    }
    if ($(".personal_right").length) {
        $(".personal_right .editable").live("click", function () {
            var c = $(this).attr("id");
            var b = $(this).text().replace(/^\s*/, "").replace(/\s*$/, "").replace("&nbsp;", "");
            var a = $(this);
			$('a.editable').removeAttr('style');
			$('input.editable_field, input.editable_button').hide();
            $(a).hide().after('<input class="editable_field" type="text" name="' + c + '" value="' + b + '" /><input class="editable_button" type="button" name="editable_button" value="" /><div id = "lk_load"></div>');
			

			$('.header, .fleft, .fmain, .footer').bind('click', function () {
				$('input.editable_field, input.editable_button').hide();
				$('a.editable').removeAttr('style');
            });
			
			

			
			$('.editable_button').bind('click', function () {
				$('.editable_button').css({"display":"none"});
				$('#lk_load').css({"display":"block"});
                $.get("/ajax.php", {
                    name: c,
                    value: $(this).prev().val(),
                }, function (d) {
                    $(a).html(d).fadeIn(300);
                    $(a).next().remove();
                    $(a).next().remove();
					$('#lk_load').remove();
                })
            });
            $(a).next().keydown(function (d) {
                if (d.keyCode == "13") {
                    $.get("/ajax.php", {
                        name: c,
                        value: $(this).val()
                    }, function (e) {
                        $(a).html(e).fadeIn(300);
                        $(a).next().remove();
                        $(a).next().remove()
                    })
                }
            });
            $(this).blur();
            return false
        })
    }
    
    $('.add_to_compare a').live('click', function(){
        if(!$(this).hasClass('active')){
            $(this).addClass('active');
        }else{
            $(this).removeClass('active');
        }
        if($(this).parentsUntil('.machines_list_cont').parent().find('.add_to_compare a.active').length == 1){
            $(this).parentsUntil('.machines_list_cont').parent().find('.add_to_compare a').not('.active').each(function(){
                $(this).find('span').css('opacity', 0).show().stop().animate({
                    opacity: 1,
                    top: '-29'
                }, 300);
            });
        }else{
            $(this).parentsUntil('.machines_list_cont').parent().find('.add_to_compare a').each(function(){
                $(this).find('span').stop().animate({
                    opacity: 0,
                    top: '-49'
                }, 300);
            });
            $(this).parentsUntil('.machines_list_cont').parent().find('.tooltip_more_0').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            $(this).parentsUntil('.machines_list_cont').parent().find('.tooltip_more_1').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            $(this).parentsUntil('.machines_list_cont').parent().find('.tooltip_more_2').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
        }
        var link = $(this).parentsUntil('.machines_list_cont').parent().find('.compare a');
        $(link).attr('href', '/production/compare/compare-machines.php?type=' + $(link).attr('id').replace('type_', ''));
        $(this).parentsUntil('.machines_list_cont').parent().find('.add_to_compare a.active').each(function(){
            $(link).attr('href', $(link).attr('href') + $(this).attr('href').replace('#compare_', '&id[]='));
        });
        return false;
    });
    
    $('.compare a').live('click', function(){
        if($(this).parent().parent().find('.add_to_compare a.active').length == 1){
            $(this).parent().find('.tooltip_more_1').css('opacity', 0).show().stop().animate({
                opacity: 1,
                top: '32'
            }, 300);
            $(this).parent().find('.tooltip_more_0').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            $(this).parent().find('.tooltip_more_2').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            return false;
        }else if($(this).parent().parent().find('.add_to_compare a.active').length == 0){
            $(this).parent().find('.tooltip_more_0').css('opacity', 0).show().stop().animate({
                opacity: 1,
                top: '32'
            }, 300);
            $(this).parent().find('.tooltip_more_1').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            $(this).parent().find('.tooltip_more_2').stop().animate({
                opacity: 0,
                top: '32'
            }, 300);
            return false;
        }else{
        }
    });
	
	if($('.dipl').length)
	{
	 $('#close_dipl').click(function(){
			jQuery.get("/bage.php",{'mode':'close'},function(result){
			 $('#d_container').hide(); 
			});
		});
	}
	
	if($('#lenta').length)
	{
	 initCarousel();
	 $('.minilavazza a').click(function(){
			var j = $(this).attr('jcarouselindex');
			carouselScrollTo(j);
		});
	}
	
	if($('.t').length)
	{
	 $('.t').hover(
	 
			function(){
						if(!$(this).hasClass("z"))
						{
						 $(this).addClass("z");
						}
					  },

			function(){
						 $(this).removeClass("z");
					  }
					  
		);
	}
	
    
    $('.delorder').live('click', function(){
        if(confirm('Заказ будет отменен. Продолжить?')){
            return true;
        }else{
            return false;
        }
    });
	
	
});

var marginArray = new Array(381,-53,-475);
var current_device = 2, prev_device = 2;

function scrollPrev()
{
prev_device = current_device;
var delta = 1;
 if(current_device==1) current_device=4;
      /*return false;*/
  
  if(scrollPrev.arguments.length==1)
	delta = scrollPrev.arguments[0];

 current_device-=delta;  
 $('#lenta').animate({marginLeft:marginArray[current_device-1] + "px"});
  /*if(current_device==1) 
      $('#arrow_prev').fadeOut(100);*/
  if(current_device>=1) 
    $('#arrow_prev').fadeIn(100);
      if(current_device<=3) 
    $('#arrow_next').fadeIn(100);
	
  loadDeviceContent('prev');
 
}

function scrollNext()
{
prev_device = current_device;
var delta = 1;

 if(current_device==3) current_device=0;
    /*return false;*/

    if(scrollNext.arguments.length==1)
	delta = scrollNext.arguments[0];

current_device+=delta;
 $('#lenta').animate({marginLeft:marginArray[current_device-1] + "px"});
  /*if(current_device==3) 
    $('#arrow_next').fadeOut(100);*/
    if(current_device<=3) 
    $('#arrow_next').fadeIn(100);
      if(current_device>=1) 
    $('#arrow_prev').fadeIn(100);
	
	
 loadDeviceContent('next');
}

function carouselScrollTo(pos)
{
 if(pos > current_device)
	scrollNext(pos - current_device);

  if(pos < current_device)
		scrollPrev(current_device - pos);
}


function loadDeviceContent(state)
{
 $('#white_content').hide();
  $('#lavazzabody').show();

	  
	 if(state!='show')
	 {
	  var o = $('#lenta div[jcarouselindex="' + current_device + '"]'),
	  o2 = $('#lenta div[jcarouselindex="' + prev_device + '"]'),

	  p = $('.minilavazza a[jcarouselindex="' + current_device + '"]'),
	  p2 = $('.minilavazza a[jcarouselindex="' + prev_device + '"]');
	
	  var device_id = $(o).attr('did');
	
		  $(o).find('img.iniimg').hide();
		  $(o).find('div.hiddendevice').show();
		  $(o).find('div.devicetitle').css('visibility','visible');
	
		  $(o2).find('img.iniimg').show();
		  $(o2).find('div.hiddendevice').hide();	 
		  $(o2).find('div.devicetitle').css('visibility','hidden');

	
		  $(p).attr("class","vis_link");
	
		  $(p2).attr("class","hid_link");

		  
		  $('#machine_name').find('input').val($(o).find('div.devicetitle').text());
		  
	  $.get("/device.php",{'device_id':device_id},function(result){
	      $('.lavazzamenu a').attr("class","lmlink");
		$('#lavazzabody').html(result);
	  });
	}  
}

function initCarousel()
{
	$('#lenta div[jcarouselindex="2"]').find('img.iniimg').hide();
	$('#lenta div[jcarouselindex="2"]').find('div.hiddendevice').show();
	$('#lenta div[jcarouselindex="2"]').find('div.devicetitle').css('visibility','visible');

	$('#machine_name').find('input').val($('#lenta div[jcarouselindex="2"]').find('div.devicetitle').text());
		  
		  $.get("/device.php",{'device_id':97},function(result){
				$('#lavazzabody').html(result);
			  });	
}


function showLavazzaInfo(n,obj)
{
  $('#lavazzabody').hide();
  $('.lavazzamenu a').attr("class","lmlink");
  $(obj).attr("class","lmlink_s");
  
 if($('#white_content').is(":hidden"))
   $('#white_content').show();

	$(".innerwhite").hide();
	$("#white" + n + "_content").show();  
}

function showServiceInfo(n)
{
var ot = Math.abs(n-3);
 if($("#folder" + n + "_content").is(":hidden"))
 {
   $(".folder" + n).removeClass("t").addClass("b");   
   $(".folder" + ot).css({zIndex:"-1"}); 
   $("#folder" + n + "_content").slideDown('slow',function(){
		$(".folder" + n).toggleClass("z");
		
   });


 }
 else {
		
		$("#folder" + n + "_content").slideUp('slow',function(){
				$(".folder" + n).toggleClass("z");
				$(".folder" + n).removeClass("b").addClass("t");     
				$(".folder" + ot).css({zIndex:""}); 				
			});
	  }  

}

/*function reCalculatePrices() {
    var b = 30;
    var a = 84;
    if ($(".tab:visible").attr("id") == "tab-1") {
        cur_rate = $("#tab-1 .cur_rate").val();
        auto_price = $("#tab-1 .auto_price").val();
        auto_num = $("#tab-1 .auto_num").val();
        $(".avg_glass_earn").val($(".avg_sell_price").val() - $(".avg_cost").val());
        avg_glass_sell = $("#tab-1 .avg_glass_sell").val();
        avg_glass_earn = $("#tab-1 .avg_glass_earn").val();
        total_price = auto_price * auto_num;
        total_price_rub = total_price * cur_rate;
        $("#tab-1 .total_price").val(number_format(total_price, 2, ".", ""));
        $("#tab-1 .total_price_rub").val(number_format(total_price_rub, 2, ".", ""));
        place_rent = parseInt($("#tab-1 .place_rent").val());
        oil = parseInt($("#tab-1 .oil").val());
        tax = parseInt($("#tab-1 .tax").val());
        payment = parseInt($("#tab-1 .payment").val());
        office_rent = parseInt($("#tab-1 .office_rent").val());
        other = parseInt($("#tab-1 .other").val());
        month_income = b * auto_num * avg_glass_sell * avg_glass_earn;
        month_cost = place_rent + oil + tax + payment + office_rent + other;
        month_income_wo_amort = month_income - month_cost;
        amort = number_format(total_price_rub / a, 2, ".", "");
        total_month_income = month_income_wo_amort - amort;
        total_month_income_euro = number_format(total_month_income / cur_rate, 2, ".", "");
        total_year_income_euro = number_format(total_month_income / cur_rate * 12, 2, ".", "");
        payback_time = Math.ceil(auto_price / total_month_income_euro);
        $("#tab-1 .month_income").val(month_income);
        $("#tab-1 .month_cost").val(month_cost);
        $("#tab-1 .month_income_wo_amort").val(month_income_wo_amort);
        $("#tab-1 .amort").val(amort);
        $("#tab-1 .total_month_income").val(total_month_income);
        $("#tab-1 .total_month_income_euro").val(total_month_income_euro);
        $("#tab-1 .total_year_income_euro").val(total_year_income_euro);
        $("#tab-1 .payback_time").val(payback_time)
    } else {
        cur_rate = $("#tab-2 .cur_rate").val();
        auto_price = $("#tab-2 .auto_price").val();
        auto_num = $("#tab-2 .auto_num").val();
        sell_volume = $("#tab-2 .sell_volume").val();
        addit_price = $("#tab-2 .addit_price").val();
        total_price = auto_price * auto_num;
        total_price_rub = total_price * cur_rate;
        $("#tab-2 .total_price").val(number_format(total_price, 2, ".", ""));
        $("#tab-2 .total_price_rub").val(number_format(total_price_rub, 2, ".", ""));
        place_rent = parseInt($("#tab-2 .place_rent").val());
        oil = parseInt($("#tab-2 .oil").val());
        tax = parseInt($("#tab-2 .tax").val());
        payment = parseInt($("#tab-2 .payment").val());
        office_rent = parseInt($("#tab-2 .office_rent").val());
        other = parseInt($("#tab-2 .other").val());
        month_income = number_format((sell_volume * b * auto_num) - sell_volume / (1 + addit_price / 100) * b * auto_num, 2, ".", "");
        month_cost = place_rent + oil + tax + payment + office_rent + other;
        month_income_wo_amort = month_income - month_cost;
        amort = number_format(total_price_rub / a, 2, ".", "");
        total_month_income = month_income_wo_amort - amort;
        total_month_income_euro = number_format(total_month_income / cur_rate, 2, ".", "");
        total_year_income_euro = number_format(total_month_income / cur_rate * 12, 2, ".", "");
        payback_time = Math.ceil(auto_price / total_month_income_euro);
        $("#tab-2 .month_income").val(month_income);
        $("#tab-2 .month_cost").val(month_cost);
        $("#tab-2 .month_income_wo_amort").val(month_income_wo_amort);
        $("#tab-2 .amort").val(amort);
        $("#tab-2 .total_month_income").val(total_month_income);
        $("#tab-2 .total_month_income_euro").val(total_month_income_euro);
        $("#tab-2 .total_year_income_euro").val(total_year_income_euro);
        $("#tab-2 .payback_time").val(payback_time)
    }
    return false
}*/
function initScrollbars() {
    return false
}
function SelectSection(b, a) {
    if (!a || a == "" || a == 0) {
        a = 1
    }
    if (b == 0) {
        if (a == 1) {
            $("#slave_section").fadeOut()
        }
        $("#slave_items").fadeOut(100);
        return false
    } else {
        if (a == 1) {
            $("#slave_section").fadeOut()
        }
        $("#slave_items").fadeOut(100)
    }
    if (a == 1) {
        $("#slave_section").html('<img src="/i/loading.gif" width="16" height="16" alt="" />');
        $("#slave_section").fadeIn(100)
    } else {
        if (a == 2) {
            $("#slave_items").html('<img src="/i/loading.gif" width="16" height="16" alt="" />');
            $("#slave_items").fadeIn(100)
        }
    }
    $.get("/addons/ajax.php", {
        mode: "section",
        id: b,
        dataType: "json"
    }, function (c) {
        if (a == 1) {
            $("#slave_section").html(c);
            $("#slave_section").fadeIn(100)
        }
        if (a == 2) {
            $("#slave_items").html(c);
            $("#slave_items").fadeIn(100)
        }
        return false
    })
}
function openOrderSpare(c, b, a) {
    $("#num" + a).blur().addClass("loading");
    $.get("/personal/spare/spare.php", {
        id: c,
        product_id: b
    }, function (d) {
        $("#num" + a).removeClass("loading").parent().append(d);
        $("#spare_order_form").fadeIn(200);
        return false
    });
    return false
}
function closeOrderSpare() {
    $("#spare_order_form").fadeOut(50, function () {
        $(this).remove()
    })
}
function number_format(f, c, h, e) {
    f = (f + "").replace(",", "").replace(" ", "");
    var b = !isFinite(+f) ? 0 : +f,
        a = !isFinite(+c) ? 0 : Math.abs(c),
        j = (typeof e === "undefined") ? "," : e,
        d = (typeof h === "undefined") ? "." : h,
        i = "",
        g = function (o, m) {
            var l = Math.pow(10, m);
            return "" + Math.round(o * l) / l
        };
    i = (a ? g(b, a) : "" + Math.round(b)).split(".");
    if (i[0].length > 3) {
        i[0] = i[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, j)
    }
    if ((i[1] || "").length < a) {
        i[1] = i[1] || "";
        i[1] += new Array(a - i[1].length + 1).join("0")
    }
    return i.join(d)
}
function changeInputType(a, c) {
    var b = document.createElement("input");
    b.type = c;
    if (a.size) {
        b.size = a.size
    }
    if (a.value) {
        b.value = a.value
    }
    if (a.name) {
        b.name = a.name
    }
    a.parentNode.replaceChild(b, a);
    b.focus()
};



    $('#master_video').change(function() {
    var a = $(this);
      $.get("/personal/video/ajax.php", {
            value: $(a).val()
        }, function (d) {
            $('#video').html(d);
        })
    });
    
$(document).ready(function(){    
    $(".capsule_block_element").mouseover(function (){
       $(this).find('.capsule_fon').show();
    });
    $(".capsule_block_element").mouseout(function (){
        $(this).parent().find('.capsule_fon').hide();
    });
    $(".dostavka_new").mouseover(function (){
       $(this).find('.dostavka_fon').show();
    });
    $(".dostavka_new").mouseout(function (){
        $(this).find('.dostavka_fon').hide();
    });
});

/*=== kikko close ===*/
function close_kikko(){
$('#kikko_but').hide();
}     

/*==== калькулятор ====*/
	var i_p = 0;
	var par;
	var kofConst;
	var kof_lavConst;
	var bankConst;
	var monConst;
function show_formk(){
	i_p++;
	var block = "<div id = 'main_auto' class = 'main_auto"+ i_p +"'><div id = 'form1' class = 'form"+ i_p +"'><div id = 'hint_kof' class = 'hint_kof"+ i_p +"'><div id = 'top_kof'></div><div id = 'middle_kof'><div id = 'left_v'><ul><li class = 'active_v' id = 'one_k"+ i_p +"' onClick = 'list_k(par = "+ i_p +")'>Кофейный</li><li id = 'two_k"+ i_p +"' onClick = 'list_l(par = "+ i_p +")'>Кофейный LAVAZZA</li></ul></div><div id = 'mid_v'></div><div id = 'right_v' class = 'kof_right"+ i_p +"'><ul>"+ kofConst +"</ul></div><div id = 'right_v' class = 'lav_right"+ i_p +"' style = 'display:none;'><ul>"+ kof_lavConst +"</ul></div></div><div id = 'bottom_kof'></div><div id = 'close_kof' onClick = 'hide_f(par = "+ i_p +");'></div></div><div id = 'hint_bank' class = 'hint_bank" + i_p +"'><div id = 'top_bank'></div><div id = 'middle_bank'><ul>"+ bankConst +"</ul></div><div id = 'bottom_bank'></div><div id = 'close_bank' onClick = 'hide_b(par = " + i_p +")'></div></div><div id = 'hint_mon' class = 'hint_mon" + i_p +"'><div id = 'top_mon'></div><div id = 'middle_mon'><ul>"+ monConst +"</ul></div><div id = 'bottom_mon'></div><div id = 'close_mon' onClick = 'hide_m(par = " + i_p +")'></div></div><div id = 'hint_kup' class = 'hint_kup"+ i_p +"'><div id = 'top_kup'></div><div id = 'middle_kup'><ul><li><a href = 'javascript:void(0)'>Евро</a></li><li><a href = 'javascript:void(0)'>Рубли</a></li></ul></div><div id = 'bottom_kup'></div><div id = 'close_kup' onClick = 'hide_kup(par = "+ i_p +")'></div></div><div id = 'line_one'><div id = 'form_text1'>Выберите модель автомата</div><div id = 'form_select1'><div id = 'but_select1' onClick = 'hint_k(par = "+ i_p +");'></div><div id = 'text_avt' class = 'text_avt"+ i_p +"'></div></div></div><div id = 'clear_form'></div><div id = 'line_two'><div id = 'quest_one'></div><div id = 'form_text2'>Платёжные системы</div><div id = 'form_v'></div><div id = 'block_text'><div id = 'text_in_one'>Банктнотоприёмник</div><div id = 'form_select2'><div id = 'but_select1' onClick = 'hint_b(par = "+ i_p +")'></div><div id = 'text_bank' class = 'text_bank"+ i_p +"'></div></div><div id = 'text_in_two'>Монетоприёмник</div><div id = 'form_select3'><div id = 'but_select1' onClick = 'hint_m(par = " + i_p +")'></div><div id = 'text_mon' class = 'text_mon"+ i_p +"'></div></div></div></div><div id = 'clear_form2'></div><div id = 'line_three'><div id = 'form_text3'>Количество</div><div class= 'calc_data'><span class = 'field_av'><input class='auto_num"+ i_p +"' type='text' value='0' id = 'new_calk'/></span></div></div><div id = 'clear_form3'></div><div id = 'line_four'><div id = 'form_text4'>Итоговая цена данного автомата</div><div id = 'form_select4'><div id = 'but_select1' onClick = 'hint_kup(par = "+ i_p +")'></div><div id = 'text_kup' class = 'text_kup"+ i_p +"'>Евро</div></div><div class= 'calc_data'><span class = 'field_av'><input class='auto_price"+ i_p +"' type='text' value='0' id = 'new_calk2'/></span></div></div><span id = 'avt_selector'></span><span id = 'ban_selector'></span><span id = 'mon_selector'></span><span id = 'total_pr' class = 'total_pr"+ i_p +"'></span></div><div id = 'minus1' class = 'minus"+ i_p +"' onClick = 'hide_formk(par = "+ i_p +")'></div></div>";
	$('#calc_data').after(block);
}
	var i_s = 0;
	var par_s;
	var snekConst;
function s_show_formk(){
	i_s++;
	var block = "<div id = 's_main_auto' class = 's_main_auto"+ i_s +"'><div id = 's_form1' class = 's_form"+ i_s +"'><div id = 'hint_snek' class = 'hint_snek"+ i_s +"'><div id = 'top_snek'></div><div id = 'middle_snek'><ul>"+ snekConst +"</ul></div><div id = 'bottom_snek'></div><div id = 'close_snek' onClick = 'hide_s(par_s = "+ i_s +")'></div></div><div id = 's_hint_bank' class = 's_hint_bank" + i_s +"'><div id = 's_top_bank'></div><div id = 's_middle_bank'><ul>"+ bankConst +"</ul></div><div id = 's_bottom_bank'></div><div id = 's_close_bank' onClick = 's_hide_b(par_s = " + i_s +")'></div></div><div id = 's_hint_mon' class = 's_hint_mon" + i_s +"'><div id = 's_top_mon'></div><div id = 's_middle_mon'><ul>"+ monConst +"</ul></div><div id = 's_bottom_mon'></div><div id = 's_close_mon' onClick = 's_hide_m(par_s = " + i_s +")'></div></div><div id = 's_hint_kup' class = 's_hint_kup"+ i_s +"'><div id = 's_top_kup'></div><div id = 's_middle_kup'><ul><li><a href = 'javascript:void(0)'>Евро</a></li><li><a href = 'javascript:void(0)'>Рубли</a></li></ul></div><div id = 's_bottom_kup'></div><div id = 's_close_kup' onClick = 's_hide_kup(par_s = "+ i_s +")'></div></div><div id = 's_line_one'><div id = 's_form_text1'>Выберите модель автомата</div><div id = 's_form_select1'><div id = 's_but_select1' onClick = 'hint_s(par_s = "+ i_s +");'></div><div id = 's_text_avt' class = 's_text_avt"+ i_s +"'></div></div></div><div id = 's_clear_form'></div><div id = 's_line_two'><div id = 's_quest_one'></div><div id = 's_form_text2'>Платёжные системы</div><div id = 's_form_v'></div><div id = 's_block_text'><div id = 's_text_in_one'>Банктнотоприёмник</div><div id = 's_form_select2'><div id = 's_but_select1' onClick = 's_hint_b(par_s = "+ i_s +")'></div><div id = 's_text_bank' class = 'text_bank"+ i_s +"'></div></div><div id = 's_text_in_two'>Монетоприёмник</div><div id = 's_form_select3'><div id = 's_but_select1' onClick = 's_hint_m(par_s = " + i_s +")'></div><div id = 's_text_mon' class = 's_text_mon"+ i_s +"'></div></div></div></div><div id = 's_clear_form2'></div><div id = 's_line_three'><div id = 's_form_text3'>Количество</div><div class= 'calc_data'><span class = 'field_av'><input class='s_auto_num"+ i_s +"' type='text' value='0' id = 's_new_calk'/></span></div></div><div id = 's_clear_form3'></div><div id = 's_line_four'><div id = 's_form_text4'>Итоговая цена данного автомата</div><div id = 's_form_select4'><div id = 's_but_select1' onClick = 's_hint_kup(par_s = "+ i_s +")'></div><div id = 's_text_kup' class = 's_text_kup"+ i_s +"'>Евро</div></div><div class= 'calc_data'><span class = 'field_av'><input class='s_auto_price"+ i_s +"' type='text' value='0' id = 's_new_calk2'/></span></div></div><span id = 'snek_selector'></span><span id = 's_ban_selector'></span><span id = 's_mon_selector'></span><span id = 's_total_pr' class = 's_total_pr"+ i_s +"'></span></div><div id = 's_minus1' class = 's_minus"+ i_s +"' onClick = 's_hide_formk(par_s = "+ i_s +")'></div></div>";
	$('#s_calc_data').after(block);
}
function hide_formk(par){
	$('.main_auto'+ par).slideUp();
	$('span.total_pr'+ par).remove();
	return reCalculatePrices();
}
function s_hide_formk(par_s){
	$('.s_main_auto'+ par_s).slideUp();
	$('span.s_total_pr'+ par_s).remove();
	return reCalculatePrices();
}

function hint_k(par){
	$('#hint_bank, #hint_mon, #hint_kup, #hint_kof').hide();
	$('.hint_kof'+ par).slideDown();
}
function hint_s(par_s){
	$('#s_hint_bank, #s_hint_mon, #s_hint_kup, #hint_snek').hide();
	$('.hint_snek'+ par_s).slideDown();
}

function hint_b(par){
	$('#hint_kof, #hint_mon, #hint_kup, #hint_bank').hide();
	$('.hint_bank'+ par).slideDown();
}
function s_hint_b(par_s){
	$('#hint_snek, #s_hint_mon, #s_hint_kup, #s_hint_bank').hide();
	$('.s_hint_bank'+ par_s).slideDown();
}

function hint_m(par){	
	$('#hint_kof, #hint_bank, #hint_kup, #hint_mon').hide();
	$('.hint_mon'+ par).slideDown();
}
function s_hint_m(par_s){	
	$('#hint_snek, #s_hint_bank, #s_hint_kup, #s_hint_mon').hide();
	$('.s_hint_mon'+ par_s).slideDown();
}

function hint_kup(par){
	$('#hint_kof, #hint_bank, #hint_mon, #hint_kup').hide();
	$('.hint_kup'+ par).slideDown();
}
function s_hint_kup(par_s){
	$('#hint_snek, #s_hint_bank, #s_hint_mon, #s_hint_kup').hide();
	$('.s_hint_kup'+ par_s).slideDown();
}

function hide_f(par){
	$('.hint_kof'+ par).slideUp().animate({opacity:"100"},
		1000, function(){
			$('#two_k' + par).removeAttr('class');
			$('#one_k' + par).attr('class', 'active_v');
			$('.lav_right'+ par).animate(
				{opacity:"0"}, 0,
				function(){
					$(this).hide();
					$('.kof_right'+ par).removeAttr('style');
					$('.kof_right'+ par).fadeIn(0, 0); }
				);
		}
	);	 
}

function hide_b(par){
	$('.hint_bank'+ par).slideUp();
}
function s_hide_b(par_s){
	$('.s_hint_bank'+ par_s).slideUp();
}

function hide_l(par){
	$('.hint_lav'+ par).slideUp();
}
function hide_s(par_s){
	$('.hint_snek'+ par_s).slideUp();
}

function hide_m(par){
	$('.hint_mon'+ par).slideUp();
}
function s_hide_m(par_s){
	$('.s_hint_mon'+ par_s).slideUp();
}

function hide_kup(par){
	$('.hint_kup'+ par).slideUp();
}
function s_hide_kup(par_s){
	$('.s_hint_kup'+ par_s).slideUp();
}

function list_l(par){
	$('#one_k'+ par).removeAttr('class');
	$('#two_k'+ par).attr('class', 'active_v');
	$('.kof_right'+ par).animate(
	{opacity:"0"}, 300,
	function(){
		$(this).hide();
		$('.lav_right'+ par).removeAttr('style');
		$('.lav_right'+ par).fadeIn(300, 0);}
		); 	
}

function list_k(par){
	$('#two_k'+ par).removeAttr('class');
	$('#one_k'+ par).attr('class', 'active_v');
	$('.lav_right'+ par).animate(
	{opacity:"0"}, 300,
	function(){
		$(this).hide();
		$('.kof_right'+ par).removeAttr('style');
		$('.kof_right'+ par).fadeIn(300, 0); }
	); 
}

$(document).ready(function(){
	//Обработка блока с автоматами
	$('#hint_kof li a').live('click', function(){
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var avt_field = form + ' #text_avt';
		//Переменная для сохранения названия товара
		var tovar = form + ' #avt_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле; 
		if($(price_input).val() != 0){
			if($(avt_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtextwe = text.slice(0, 25) + '...';
			$(avt_field).html(newtext);
		}
		if(count <= 28){
			$(avt_field).html(text);
		}
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		//Определяем селектор для списка автоматов LAVAZZA
		var lavaz = form + ' li[id *= two_k]';
		//Определяем селектор для списка автоматов
		var avt = form + ' li[id *= one_k]';
		//Определяем селектор для блока автоматов LAVAZZA
		var block_lavaz = form + ' div[class *= lav_right]';
		//Определяем селектор для блока автоматов
		var block_avt = form + ' div[class *= kof_right]';
		$(close).slideUp().animate({opacity:"100"},
			1000, function(){
				$(lavaz).removeAttr('class');
				$(avt).attr('class', 'active_v');
				$(block_lavaz).animate(
					{opacity:"0"}, 0,
					function(){
						$(this).hide();
						$(block_avt).removeAttr('style');
						$(block_avt).fadeIn(0, 0); }
					);
			}
		);
		return reCalculatePrices();
	});
	//Обработка блока банкнотоприёмниками
	$('#hint_bank li a').live('click', function () {
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var bank_field = form + ' #text_bank';
		//Переменная для сохранения названия товара
		var tovar = form + ' #ban_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле
		if($(price_input).val() != 0){
			if($(bank_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtext = text.slice(0, 25) + '...';
		}
		$(bank_field).html(newtext);
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		$(close).slideUp();
		return reCalculatePrices();
	});
	//Обработка блока с монетоприёмниками
	$('#hint_mon li a').live('click', function(){
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var mon_field = form + ' #text_mon';
		//Переменная для сохранения названия товара
		var tovar = form + ' #mon_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле
		if($(price_input).val() != 0){
			if($(mon_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtext = text.slice(0, 25) + '...';
		}
		$(mon_field).html(newtext);
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		$(close).slideUp();
		return reCalculatePrices();
	});
	//Обработка блока с купюрами
	$('#hint_kup li a').live('click', function () {
		var text = $(this).html();
		//Определяем переменную, в которой хранится селектор блока с купюрой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var close = form + ' #hint_kup';
		//Вычисляем селектор текущего поля с купюрой
		var kup_field = form + ' #text_kup';
		var kup = $(kup_field).html();
		$(kup_field).html(text);
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#new_calk2';
		var price = $(price_input).val();
		if(text == 'Рубли'){
			if(kup == 'Евро'){
				price *= $('input.cur_rate').val();
				$(price_input).val(price.toFixed());
			}
		}
		if(text == 'Евро'){
			if(kup == 'Рубли'){
				price /= $('input.cur_rate').val();
				$(price_input).val(price.toFixed());
			}
		}
		$(close).slideUp();
	});
	/*
	Для того, чтобы формы для автоматов кофейных с снековых работали независимо, мы вышенаписанные функции повторим с модифицированными селекторами
	*/
	
	//Обработка блока с автоматами (снековые)
	$('#hint_snek li a').live('click', function(){
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#s_new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var avt_field = form + ' #s_text_avt';
		//Переменная для сохранения названия товара
		var tovar = form + ' #snek_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #s_text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле; 
		if($(price_input).val() != 0){
			if($(avt_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtextwe = text.slice(0, 25) + '...';
			$(avt_field).html(newtext);
		}
		if(count <= 28){
			$(avt_field).html(text);
		}
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #s_total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		$(close).slideUp();
		return reCalculatePrices();
	});
	//Обработка блока банкнотоприёмниками (снековые)
	$('#s_hint_bank li a').live('click', function () {
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#s_new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var bank_field = form + ' #s_text_bank';
		//Переменная для сохранения названия товара
		var tovar = form + ' #s_ban_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #s_text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле
		if($(price_input).val() != 0){
			if($(bank_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtext = text.slice(0, 25) + '...';
		}
		$(bank_field).html(newtext);
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #s_total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		$(close).slideUp();
		return reCalculatePrices();
	});
	//Обработка блока с монетоприёмниками
	$('#s_hint_mon li a').live('click', function(){
		//Определяем переменную, в которой хранится класс текущей подсказки для закрытия окошка
		var close = $(this).parent().parent().parent().parent().attr('class');
		close = '.' + close;
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#s_new_calk2';
		//Вычисляем селектор текущего поля с ценой банкнотоприёмника
		var mon_field = form + ' #s_text_mon';
		//Переменная для сохранения названия товара
		var tovar = form + ' #s_mon_selector';
		//Вычисляем значение текущей цены
		var price = $(this).parent().next().html();
		price = price.slice(0,-2);
		price = parseInt(price); 
		//Создаём переменную с селектором на предыдущий товар
		var put = $(this).parent().parent().parent().parent().parent().attr('class');
		put = '.' + put;
		var selector = put + ' a:contains('+ $(tovar).html() +')';
		//Вычисляем значение текущего поля с купюрой
		var kup_field = form + ' #s_text_kup';
		var kup = $(kup_field).html();
		//Если в дальнейшем кол-во купюр возрастёт, то удобней будет использовать конструкцию switch(){}. Поэтому используем её в данном случае.
		switch(kup){
		case 'Рубли': 
			price *= $('input.cur_rate').val(); 
			price = price.toFixed();
			price = parseInt(price);
		break;
		}
		//Вставляем цену в поле
		if($(price_input).val() != 0){
			if($(mon_field).html() == ''){
				price = price + parseInt($(price_input).val());
				$(price_input).val(price);
			}
			else{
				var price_past = $(selector).parent().next().html();
				price_past = price_past.slice(0,-2);
				price_past = parseInt(price_past);
				if(kup == 'Рубли'){
					price_past *= $('input.cur_rate').val();
					price_past = price_past.toFixed();
					price_past = parseInt(price_past);
				}
				price = price + parseInt($(price_input).val()) - price_past;
				$(price_input).val(price);
			}
		}
		if($(price_input).val() == 0 || $(price_input).val() == ''){
			$(price_input).val(price);
		}
		var text = $(this).html();
		var count = $(this).html().length;
		if(count > 28){
			var newtext = text.slice(0, 25) + '...';
		}
		$(mon_field).html(newtext);
		$(tovar).html(text);
		//Здесь вносим в блок суммы товара. Блок является своего рода ящиком памяти
		var total = $(price_input).val();
		var span = form + ' #s_total_pr';
		if(kup == 'Рубли'){
			total /= $('input.cur_rate').val();
			total = total.toFixed();
		}
		$(span).html(total);
		$(close).slideUp();
		return reCalculatePrices();
	});
	//Обработка блока с купюрами
	$('#s_hint_kup li a').live('click', function () {
		var text = $(this).html();
		//Определяем переменную, в которой хранится селектор блока с купюрой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var close = form + ' #s_hint_kup';
		//Вычисляем селектор текущего поля с купюрой
		var kup_field = form + ' #s_text_kup';
		var kup = $(kup_field).html();
		$(kup_field).html(text);
		//Определяем переменную, в которой хранится селектор текущего поля с ценой
		var form = $(this).parent().parent().parent().parent().parent().attr('class');
		form = '.' + form;
		var price_input = form + ' input#s_new_calk2';
		var price = $(price_input).val();
		if(text == 'Рубли'){
			if(kup == 'Евро'){
				price *= $('input.cur_rate').val();
				$(price_input).val(price.toFixed());
			}
		}
		if(text == 'Евро'){
			if(kup == 'Рубли'){
				price /= $('input.cur_rate').val();
				$(price_input).val(price.toFixed());
			}
		}
		$(close).slideUp();
	});
});

function reCalculatePrices() {
    var b = 22;
    var a = 84;
	var sum = 0;
	var num;
	var kol = 0;
	var price = 0;
	var w;
	var x;
	var y;
	var year;
	var word_m;
	var word_y;
    if ($(".tab:visible").attr("id") == "tab-1"){
		$('span#total_pr').each(function(){
			num = $(this).parent().attr('class');
			num = '.' + num;
			num = num + ' input#new_calk';
			kol += parseInt($(num).val());
			price += parseInt($(this).html());
			sum += parseInt($(this).html()) * parseInt($(num).val());
		});
        cur_rate = $("#tab-1 .cur_rate").val();
        $(".avg_glass_earn").val($(".avg_sell_price").val() - $(".avg_cost").val());
        avg_glass_sell = $("#tab-1 .avg_glass_sell").val();
        avg_glass_earn = $("#tab-1 .avg_sell_price").val() - $("#tab-1 .avg_cost").val();
		total_price = sum;
        total_price_rub = total_price * cur_rate;
        $("#tab-1 .total_price").val(number_format(total_price, 0, "", ""));
        $("#tab-1 .total_price_rub").val(number_format(total_price_rub, 0, "", ""));
        place_rent = parseInt($("#tab-1 .place_rent").val());
        oil = parseInt($("#tab-1 .oil").val());
        tax = parseInt($("#tab-1 .tax").val());
        payment = parseInt($("#tab-1 .payment").val());
        office_rent = parseInt($("#tab-1 .office_rent").val());
        other = parseInt($("#tab-1 .other").val());
        month_income = b * kol * avg_glass_sell * avg_glass_earn;
        month_cost = place_rent + oil + tax + payment + office_rent + other;
        month_income_wo_amort = month_income - month_cost;
		srok_amort = $("#tab-1 input.srok_amort").val();
		amort = (50/59)*(cur_rate * total_price)/srok_amort;
        total_month_income = month_income_wo_amort - amort;
		w = (total_price_rub / total_month_income).toFixed(5);
		x = w/12;
		year = x - (x%1);
		y = (x - year) * 12;
		month = y - (y%1);
		month += 1;
		if(month == 12){
			month = 0;
			year += 1;
		}
		if(month == 1){
			word_m = ' месяц';
		}
		if(month == 2 || month == 3 || month == 4){
			word_m = ' месяца';
		}
		if(month > 4){
			word_m = ' месяцев';
		}
		if(year == 1){
			word_y = ' год';
		}
		if(year == 2 || year == 3 || year == 4){
			word_y = ' года';
		}
		if(year > 4){
			word_y = ' лет';
		}
		if(year != 0 && month != 0){
			payback_time = year + word_y + ' ' + month + word_m;
		}
		if(year != 0 && (month = 0 || month == '')){
			payback_time = year + word_y;
		}
		if((year == 0 || year == '') && month != 0){
			payback_time = month + word_m;
		}
		if((year == 0 || year == '') && (month = 0 || month == '')){
			payback_time = 0;
		}
		if($('.avg_glass_sell').val() == 0){
			payback_time = 0;
		}
        $("#tab-1 .month_income").val(month_income.toFixed(2));
        $("#tab-1 .month_cost").val(month_cost);
        $("#tab-1 .month_income_wo_amort").val(month_income_wo_amort.toFixed(2));
        $("#tab-1 .amort").val(amort.toFixed(2));
        $("#tab-1 .total_month_income").val(total_month_income.toFixed(2));
        $("#tab-1 .payback_time").val(payback_time)
    } else {
		$('span#s_total_pr').each(function(){
			num = $(this).parent().attr('class');
			num = '.' + num;
			num = num + ' input#s_new_calk';
			kol += parseInt($(num).val());
			price += parseInt($(this).html());
			sum += parseInt($(this).html()) * parseInt($(num).val());
		});
        cur_rate = $("#tab-2 .cur_rate").val();
        sell_volume = $("#tab-2 .sell_volume").val();
        addit_price = $("#tab-2 .addit_price").val();
        total_price = sum;
        total_price_rub = sum * cur_rate;
        $("#tab-2 .total_price").val(number_format(total_price, 0, "", ""));
        $("#tab-2 .total_price_rub").val(number_format(total_price_rub, 0, "", ""));
        place_rent = parseInt($("#tab-2 .place_rent").val());
        oil = parseInt($("#tab-2 .oil").val());
        tax = parseInt($("#tab-2 .tax").val());
        payment = parseInt($("#tab-2 .payment").val());
        office_rent = parseInt($("#tab-2 .office_rent").val());
        other = parseInt($("#tab-2 .other").val());
		month_income = b * kol * (sell_volume - sell_volume/(1 + 0.01 * addit_price));
        month_cost = place_rent + oil + tax + payment + office_rent + other;
        month_income_wo_amort = month_income - month_cost;
		srok_amort = $("#tab-2 input.srok_amort").val();
		amort = (50/59)*(cur_rate * total_price)/srok_amort;
        total_month_income = month_income_wo_amort - amort;
		w = (total_price_rub / total_month_income).toFixed(5);
		x = w/12;
		year = x - (x%1);
		y = (x - year) * 12;
		month = y - (y%1);
		month += 1;
		if(month == 12){
			month = 0;
			year += 1;
		}
		if(month == 1){
			word_m = ' месяц';
		}
		if(month == 2 || month == 3 || month == 4){
			word_m = ' месяца';
		}
		if(month > 4){
			word_m = ' месяцев';
		}
		if(year == 1){
			word_y = ' год';
		}
		if(year == 2 || year == 3 || year == 4){
			word_y = ' года';
		}
		if(year > 4){
			word_y = ' лет';
		}
		if(year != 0 && month != 0){
			payback_time = year + word_y + ' ' + month + word_m;
		}
		if(year != 0 && (month = 0 || month == '')){
			payback_time = year + word_y;
		}
		if((year == 0 || year == '') && month != 0){
			payback_time = month + word_m;
		}
		if((year == 0 || year == '') && (month = 0 || month == '')){
			payback_time = 0;
		}
		if($('.sell_volume').val() == 0 || $('.addit_price').val() == 0){
			payback_time = 0;
		}
        $("#tab-2 .month_income").val(month_income.toFixed(2));
        $("#tab-2 .month_cost").val(month_cost);
        $("#tab-2 .month_income_wo_amort").val(month_income_wo_amort.toFixed(2));
        $("#tab-2 .amort").val(amort.toFixed(2));
        $("#tab-2 .total_month_income").val(total_month_income.toFixed(2));
        $("#tab-2 .payback_time").val(payback_time)
    }
    return false
}

function q_show_k(){
	$('#main_q_kal').fadeIn();
}
function q_hide_k(){
	$('#main_q_kal').fadeOut();
}
function q_show_k2(){
	$('#main_q_kal2').fadeIn();
}
function q_hide_k2(){
	$('#main_q_kal2').fadeOut();
}
function q_show_k3(){
	$('#main_q_kal3').fadeIn();
}
function q_hide_k3(){
	$('#main_q_kal3').fadeOut();
}
function q_show_k4(){
	$('#main_q_kal4').fadeIn();
}
function q_hide_k4(){
	$('#main_q_kal4').fadeOut();
}
function q_show_k5(){
	$('#main_q_kal5').fadeIn();
}
function q_hide_k5(){
	$('#main_q_kal5').fadeOut();
}
function q_show_k6(){
	$('#main_q_kal6').fadeIn();
}
function q_hide_k6(){
	$('#main_q_kal6').fadeOut();
}
function q_show_k7(){
	$('#main_q_kal7').fadeIn();
}
function q_hide_k7(){
	$('#main_q_kal7').fadeOut();
}
function q_show_k8(){
	$('#main_q_kal8').fadeIn();
}
function q_hide_k8(){
	$('#main_q_kal8').fadeOut();
}
function q_show_k9(){
	$('#main_q_kal9').fadeIn();
}
function q_hide_k9(){
	$('#main_q_kal9').fadeOut();
}

function snek_q_show_k(){
	$('#s_main_q_kal').fadeIn();
}
function snek_q_hide_k(){
	$('#s_main_q_kal').fadeOut();
}
function snek_q_show_k2(){
	$('#s_main_q_kal2').fadeIn();
}
function snek_q_hide_k2(){
	$('#s_main_q_kal2').fadeOut();
}
function snek_q_show_k3(){
	$('#s_main_q_kal3').fadeIn();
}
function snek_q_hide_k3(){
	$('#s_main_q_kal3').fadeOut();
}
function snek_q_show_k4(){
	$('#s_main_q_kal4').fadeIn();
}
function snek_q_hide_k4(){
	$('#s_main_q_kal4').fadeOut();
}
function snek_q_show_k5(){
	$('#s_main_q_kal5').fadeIn();
}
function snek_q_hide_k5(){
	$('#s_main_q_kal5').fadeOut();
}
function snek_q_show_k6(){
	$('#s_main_q_kal6').fadeIn();
}
function snek_q_hide_k6(){
	$('#s_main_q_kal6').fadeOut();
}
function snek_q_show_k7(){
	$('#s_main_q_kal7').fadeIn();
}
function snek_q_hide_k7(){
	$('#s_main_q_kal7').fadeOut();
}
function snek_q_show_k8(){
	$('#s_main_q_kal8').fadeIn();
}
function snek_q_hide_k8(){
	$('#s_main_q_kal8').fadeOut();
}
function snek_q_show_k9(){
	$('#s_main_q_kal9').fadeIn();
}
function snek_q_hide_k9(){
	$('#s_main_q_kal9').fadeOut();
}
/*========= конец калькулятор ===========*/

function piter_contact(){
	$('p #moskowk, p #minskk, p #kievk, p #doneckk').hide().animate({ opacity: 1}, 0, function(){$('p #piterk').fadeIn(300);});	
}
function moskow_contact(){
	$('p #piterk, p #minskk, p #kievk, p #doneckk').hide().animate({ opacity: 1}, 0, function(){$('p #moskowk').fadeIn(300);});	
}
function minsk_contact(){
	$('p #piterk, p #moskowk, p #kievk, p #doneckk').hide().animate({ opacity: 1}, 0, function(){$('p #minskk').fadeIn(300);});	
}
function kiev_contact(){
	$('p #piterk, p #moskowk, p #minskk, p #doneckk').hide().animate({ opacity: 1}, 0, function(){$('p #kievk').fadeIn(300);});	
}
function doneck_contact(){
	$('p #piterk, p #moskowk, p #minskk, p #kievk').hide().animate({ opacity: 1}, 0, function(){$('p #doneckk').fadeIn(300);});	
}
/*=========== форма об ошибках браузера ==============*/
function browser(){
	$('#browser').slideToggle();
}
$(document).ready(function(){
	$('#middle li a').live('click', function () {
		$('#browser').slideUp();
		//$('#browser').slideToggle();
		$('#bad_form #text').html('');
		var a = $(this).html();
		$('#bad_form #text').html(a);
		$('input[name=form_hidden_23]').val(a);
		//$('input[name=form_text_23]').val(a)
	});
	$('.consult_order_form_new .submit input').val('');
	$('.consult_order_form_new .field input').attr('maxlength', '5');
	$('#browser a').hover(function(){$(this).attr('style', 'text-decoration:none;')}, function(){$(this).removeAttr('style');});
	$('input[name=form_hidden_23]').val('Opera');
	//$('input[name=form_text_23]').val('Opera')
	$(".consult_order_form_new_inner input[name='web_form_submit']").live('click', function () {
		$("input[name='error_hidden']").val('yes_yes');
	});
	$("input[name='error_hidden']").val('');
});

/*================ Слайдер на главной ======================*/
$(document).ready(function(){
	$('#top_slider #slider_2').click(function (){
		$(this).attr('id', 'active2').attr('style', 'display:block');
		$('#top_slider #active').attr('id', 'slider_1').attr('style', 'display:block;');
		$('#top_slider #slider_2').attr('style', 'display:none');
		$('a#img_show_1').animate({opacity:0}, 600, function(){
			$(this).css('display', 'none');
			$('a#img_show_2').css({'opacity':'100'}).fadeIn(0);
		});
	});
	$('#top_slider #active').click(function (){
		$(this).attr('id', 'active').attr('style', 'display:block');
		$('#top_slider #active2').attr('id', 'slider_2').attr('style', 'display:block');
		$('#top_slider #slider_1').attr('style', 'display:none');
		$('a#img_show_2').animate({opacity:0}, 600, function(){
			$(this).css('display', 'none');
			$('a#img_show_1').css({'opacity':'100'}).fadeIn(400);
		});
	});
	var cnt = false;
	var slider = function(){
		console.info('slider');
		if(cnt){
			$('#top_slider #slider_1').trigger('click');		
		}
		else{
			$('#top_slider #slider_2').trigger('click');
		}
		cnt=!cnt;
		console.info('cnt',cnt);
	}
	setInterval(slider, 8000);
});
/*==================Таймер для слайдера ======================*/
$(document).ready(function(){
	$('#close_canto').click(function (){
		$(this).fadeOut();
		$('#canto').fadeOut();
	});
});
