var num = parseFloat('10.1')*5;
point = ',';
if(num>50) {
	point = '.';
}

// if point=='.'
// number(5.3) => 5.3
// number(5,3) => 5.3
function number(num)
{
	var myString = 0;
	if (num) {
		myString = new String(num); //String переменная
		if (point=='.') {
			myString = myString.replace(",",".");
		} else {
			myString = myString.replace(".",",");
		}
	}
	num = parseFloat(myString);
	if(isNaN(num)) {
		num = 0;
	}
	return num;
}

function TabSW( aTab )
{
    var i=1;
    while(document.getElementById("tab"+i)){
        if ( aTab == i) {
            document.getElementById("tab"+i).style.display = 'block';
        }else{
            document.getElementById("tab"+i).style.display = 'none';
        }
        i++;
    }
}
function Cart( sw )
{
    if (sw ==1){
        document.getElementById("incart").style.display = 'block';
        document.getElementById("cart_open").style.display = 'none';
    }	else{
        document.getElementById("incart").style.display = 'none';
        document.getElementById("cart_open").style.display = 'block';
    }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function toggleUlMenu (el) {
    var ul = null;
    var childs = el.childNodes;
    for (var i = 0; i<childs.length; i++) {
        if (childs[i].tagName == 'UL') {
            ul = childs[i];
        }
    }
    if (ul) {
        if (ul.style.display == '')	{
            childs = ul.getElementsByTagName('UL');
            for (var i = 0; i<childs.length; i++) {
                childs[i].style.display = 'none';
            }
            ul.style.display = 'none';
        } else {
            ul.style.display = '';
        }
    }
    if (el.parentNode.id && el.parentNode.parentNode.tagName != 'UL' && el.parentNode.parentNode.tagName != 'LI') {
        childs = el.parentNode.childNodes;
        for (var i = 0; i<childs.length; i++) {
            if (childs[i].tagName == 'LI' && childs[i] != el) {
                var uls = childs[i].getElementsByTagName('UL');
                for (var j=0; j<uls.length; j++) {
                    uls[j].style.display = 'none';
                }
            }
        }

    }
}

function rollMenu(except, subcat, suba)
{
	var node = null;
	var i = 1;
	while(node=document.getElementById(subcat+i)) {
		if(except!=i) {
			node.style.display = 'none';
			if(node=document.getElementById(suba+i)) {
				node.className='';
			}
		}
		i++;
	}
}

function toggleMenu (el)
{
	var ul = null;
	//var id = null;
	//id = document.getElementById(el);
	var childs = document.getElementById(el).childNodes;

	for (var i = 0; i<childs.length; i++) {
		if (childs[i].tagName == 'UL') {
			ul = childs[i];
		}

		if (childs[i].tagName == 'A') {
			childs[i].className = (childs[i].className=='active' ? '' : 'active');
		}
	}

	if (ul) {
		if (ul.style.display == '')	{
			childs = ul.getElementsByTagName('UL');
			for (var i = 0; i<childs.length; i++) {
				childs[i].style.display = 'none';
			}
			ul.style.display = 'none';
		} else {
			ul.style.display = '';
		}
	}
	return false
}


function toggleCart()
{
	if ($("#incart").css("display") == 'none') {
		$("#cart_open").hide();
		$("#cart_close").show();
	}

	$("#incart").slideToggle("normal", function() {

			if (this.style.display == 'none') {
				$("#cart_open").show();
			}

			createCookie('cart_state', (this.style.display == 'none' ? 'close' : 'open'), 0);
			}
		);

}

function toggleFilters()
{
    if ($("#side_filters").css("display") == 'none') {
        $("#side_filters_open").hide();
    }
    $("#side_filters").slideToggle("normal", function() {
                                                if (this.style.display == 'none') {
                                                    $("#side_filters_close").hide();
                                                    $("#side_filters_open").show();
                                                } else {
                                                    $("#side_filters_open").hide();
                                                    $("#side_filters_close").show();
                                                }
                                                createCookie('filters_state', (this.style.display == 'none' ? 'close' : 'open'), 0);
                                             });
}

function move_analogs (dir)
{
    var start_ind = -1;
    var stop_ind = -1;
    var items = $("#analogs > .item");
    var count = items.length;
    if (count>3) {
        var ind = 0;
        var first = -1;
        var last = -1;
        items.each(function() {
            if (first<0 && $(this).css("display") != 'none') {
                first = ind;
            }
            if ($(this).css("display") != 'none') {
                last = ind;
            }
            ind++;
        });
        if (last - first == 2) {
            if (dir == 'left' && first > 0) {
                $(items.get(last)).hide();
                $(items.get(first-1)).show();
            }
            if (dir == 'right' && last < count-1) {
                $(items.get(first)).hide();
                $(items.get(last+1)).show();
            }
        }
    }
}

var analogs_animate = 0;
function move_analogs_anim (dir, item_size, item_count)
{
    if (!analogs_animate) {
        if (dir == 'left') {
            if (parseInt($("#analogs_inner").css("left"))<0) {
                analogs_animate = 1;
                $("#analogs_inner").animate({left: parseInt($("#analogs_inner").css("left")) + item_size + 'px'}, 500, function() {analogs_animate = 0});
            }
        } else if (dir == 'right') {
            if (parseInt($("#analogs_inner").css("left")) > item_size * item_count - parseInt($("#analogs_inner").css("width"))) {
                analogs_animate = 1;
                $("#analogs_inner").animate({left: parseInt($("#analogs_inner").css("left")) - item_size + 'px'}, 500, function() {analogs_animate = 0});
            }
        }
    }
}


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
function win_popup(url,width,heigh,win)
{
	var win_handle = window.open(url,win,'height='+heigh+',width='+width+',resizable=yes,scrollbars=yes,toolbar=no,status=no,location=no,menubar=no');
	win_handle.window.focus();
}

function win_popup_menu(url,width,heigh,win)
{
	var win_handle = window.open(url,win,'height='+heigh+',width='+width+',resizable=yes,scrollbars=yes,toolbar=no,status=no,location=no,menubar=yes');
	win_handle.window.focus();
}

function open_window(url,width,heigh)
{
	win_popup(url,width,heigh,'compare');
}

function open_window_order(url,width,heigh)
{
	win_popup(url,width,heigh,'order');
}

//тСМЙЖХЪ ДКЪ БШАНПЙХ ГЮДЮММНЦН cookie МЮ JavaScript
//var cook_uname = GetCookie('uname');
function GetCookie (name)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var endstr = 0;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			endstr = document.cookie.indexOf (";", j);
			if (endstr == -1){
				endstr = document.cookie.length;
			}
			return unescape(document.cookie.substring(j, endstr));
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) { break; }
	}
	return null;
}

function setTitle(my, title)
{
	if(my.value=='') {
		my.value=title;
	}
}

function clearField(my, title)
{
	if(my.value==title) {
		my.value='';
	}
}

function removeFocusOnAllLinks()
{
	for(var i=0; i<document.links.length; i++) {
		document.links[i].onfocus=blurLink;
	}
}

function blurLink()
{
	if (this.blur) {
		this.blur();
	}
}

//window.onload=removeFocusOnAllLinks;

function showLoader()
{
	var txt = '<div id="jquery-overlay" style="background-color:rgb(0, 0, 0); opacity:0.6; width:1263px; height:2049px; left:0pt; line-height:0pt; position:absolute; text-align:center; top:0pt; width:100%; z-index:100;"></div>';
	$("body").append(txt);

	txt = "<div id='TB_load'><img src='/img/js/loadingAnimation.gif' onload=''/></div>";
	$("body").append(txt);
	$('#TB_load').show();
}
function removeLoader()
{
	$("#jquery-overlay").remove();
	$("#TB_load").remove();
}

function convert(my,id,ix,price,count)
{
	var p = 'sum_' + id+'_'+ix
	var count = parseInt(my.value)*count
	var money = 0;
	if(!isNaN(count)){
		money = parseInt(count*price*100+0.05)/100
		//money = count * price
	}
	if(money==0){money='0'}
	$('#'+p).html(money)

	money = 0;
	var a = eval('sum_'+id+';')
	for(var i=0; i<a.length; i++){
		var p = $('#sum_'+id+'_'+a[i]).html()*1
		money += p
	}
	money = parseInt(money*100+0.05)/100
	if(money==0){money='0'}
	$('#sum_'+id).html(money)
}


/***********************POPUPS****************************/
function buyAccessory(id,zakaz)
{
	if(id){
		createOverlay();
		var dialog = $('#popup');
		dialog.load("/cart/popup/id/"+id+"/zakaz/"+zakaz+"/accessory/1",function(resp){
			if (resp) {
				var y = 0;
				y = document.documentElement.scrollTop || 0;
				if (!y) y=document.body.scrollTop || 0;
				var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
				var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);
				if (top < 0) top = 25;
				$(this).css('left',left);
				$(this).css('top', top);
				$(this).css('z-index',1001);
				$(this).show();
			} else {
				document.location = "/";
			}
		});
	}
}

function buyItem(id,zakaz)
{
	if(id){
		createOverlay();
		var dialog = $('#popup');
		dialog.load("/cart/popup/id/"+id+"/zakaz/"+zakaz,function(resp){
			if (resp) {
				var y = 0;
				y = document.documentElement.scrollTop || 0;
				if (!y) y=document.body.scrollTop || 0;
				var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
				var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);
				if (top < 0) top = 25;
				$(this).css('left',left);
				$(this).css('top', top);
				$(this).css('z-index',1001);
				$(this).show();
			} else {
				document.location = "/";
			}
		});
	}
}


function closeOverlay()
{
	$("#jquery-overlay-spec").remove();
	$('embed, object, select').css({ 'visibility' : 'visible' });
}

function closePopup()
{
	$("#jquery-overlay-spec").remove();
	$('embed, object, select').css({ 'visibility' : 'visible' });
	$("#popup").remove();
}

var idTimeoutAmount = 0
function amount(obj, price, gprice)
{
	clearTimeout(idTimeoutAmount);
	idTimeoutAmount = setTimeout(function(){
			var count = number($(obj).val());
			count = count > 9999 ? 9999 : (count < 1 ? 1 : parseInt(count)*1);
			var txt = $(obj).val()

			if((txt+'')!=(count+'')){$(obj).val(count);}
			$("#total_sum").html(parseInt(count*number(price)*100+0.05)/100);
			$("#gtotal_sum").html(parseInt(count*number(gprice)*100+0.05)/100);
			idTimeoutAmount = 0
		}, 1000)
}

function addToCart(count, id, garanty, to_order)
{
	$('#cart_tires').css('opacity','0.6')
	$('#order1').css('opacity','0.6')

	$.ajax({
		  url: "/cart/add/",
		  cache: false,
		  data: "count="+count+"&id="+id+"&garanty="+garanty,
		  success: function(html){
	  		if (to_order) {
					//showCart(true);
					if (html) {
						var dialog = $('#popup');
						dialog.attr('innerHTML',html);
						var left = Math.round(($(window).width() - dialog.width())/2);
						var y = $(window).attr('scrollY') | 0;
						var top  = y + Math.round(($(window).height() - dialog.height())/2);
						if (top < 0) top = 25;
						dialog.css('left',left);
						dialog.css('top', top);
						dialog.css('z-index',1000);
						dialog.show();

						conversionCart('#popup');
					}

					$('#cart_tires').css('opacity','1')
					$('#order1').css('opacity','1')
					correctionWindow()
	  		} else {
	  			conversionCart(html);
	  			closePopup();
		  	}
		  }
	});
}


function ExpressPodbor() 
{
	createOverlay();
	var dialog = $('#popup');
	dialog.load("/express/",function(html){
		if (html) {
			var y = 0;
			y = document.documentElement.scrollTop || 0;
			if (!y) y=document.body.scrollTop || 0;
			var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
			var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);
			if (top < 0) top = 25;
			$(this).css('left',left);
			$(this).css('top', top);
			$(this).css('z-index',1001);
			$(this).show();
		} else {
			document.location = "/";
		}
	});	
}

function createOverlay()
{
	if(!document.getElementById('jquery-overlay-spec')){
		$('embed, object, select').css({ 'visibility' : 'hidden' });

		var height = $(document.body).height();
		var width = $(document.body).width();
		var txt = '<div id="jquery-overlay-spec" style="background-color:rgb(0,0,0); opacity:0.7; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70); height:'+height+'px; line-height:0pt; position:absolute; text-align:center; top:0px; width:'+width+'px; z-index:700; left:0px;"></div>';
		$(document.body).append(txt);

		$(document.body).append('<div id="popup" style="position:absolute; display:none"></div>');
	}
}

function showCart()
{
	createOverlay();
	var dialog = $('#popup');
	dialog.hide();
	var y = $(window).attr('scrollY') | 0;
		dialog.load("/cart/",function(html){			
			if (html) {
				$(this).attr('innerHTML',html);
				var left = Math.round(($(window).width() - $(this).width())/2);
				var top  = y + Math.round(($(window).height() - $(this).height())/2);
				if (top < 0) top = 25;
				$(this).css('left',left);
				$(this).css('top', top);
				$(this).css('z-index',1000);
				$(this).show();

				conversionCart('#popup');
				correctionWindow();
				//$("#navigation_all_sum div.button_navigation > a.button_back_products").click();
				loadRegion(null);
			} else {
				document.location = "/";
			}
			$('#order1').css('opacity','1')
		});
}

function conversionCart(mix)
{
	var itemsCount=0;
	$(mix).find('table#itemsGrid tr').each(function(){
	//$('table#itemsGrid tbody tr',mix).each(function(){
    if(parseInt($(this).find("input.input_text1").val())>0) {
    	itemsCount += parseInt($(this).find("input.input_text1").val())
    }
	});
	$('#in_basket #count').text(itemsCount);
	$('#in_basket b').text($(mix).find('span#ajax_total').text());
  if(itemsCount==0){closePopup()}
}

function deleteFromCart(url)
{
	var dialog = $('#popup');
	$('#order1').css('opacity','0.6')

	var y = $(window).attr('scrollY') || 0;
	dialog.load(url,function(resp){
		if (resp) {
			$(this).attr('innerHTML',resp);
			/*var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
			var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);*/
			var left = Math.round(($(window).width() - $(this).width())/2);
			var top  = y + Math.round(($(window).height() - $(this).height())/2);
			if (top < 0) top = 25;
			$(this).css('left',left);
			$(this).css('top', top);
			$(this).css('z-index',1001);
			conversionCart('#popup');
		} else {
			document.location = "/";
		}
		$('#order1').css('opacity','1')
	});
}

function sendOrderMail(frm, id)
{
	var mail =  frm.email.value;
	var phone = frm.phone.value;
	var name =  frm.name.value;
	var count =  frm.amount.value;
	var note =  frm.note.value;

	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

	if (mail != "" && phone != "" && mail!="" && pattern.test(mail)) {
		$(frm).find("input, textarea").attr("disabled","disabled").css("background","#eee");

		$.ajax({
			  type : "POST",
			  url: "/cart/popup/?oper=send",
			  cache : false,
			  data: "count="+count+"&id="+id+"&name="+name+"&phone="+phone+"&mail="+mail+"&note="+note,
			  success: function(resp){
			  		if (resp == "success") {
			  			alert('Ваш заказ принят. В ближайшее время с Вами свяжутся наши менеджеры.');
			  			closePopup();
			  		} else {
			  			alert('Ошибка! Попробуйте сделать заказ позже или по телефону.');
			  			closePopup();
			  		}
			  }
		});
	} else {
		alert('Ошибка! Все поля должны быть заполены. Е-mail введен корректно.')
	}
}

$(function() {
	$("a.que, a.help, div.help").hint();
});


/*дополнения*/
function validateForm(frm)
{
    var form = $(frm);
        
    form.find("input:enabled, select:enabled, textarea").each(function(){
        if ($(this).hasClass("required")) {
            var name = $(this).attr("name");
            var name = name.replace(/[\]\[]/gi,"");                 
            $("#"+name+"_error").hide();    
        }
    })
    var success = true;         
    form.find("input:enabled, select:enabled, textarea").each(function(){       
        if ($(this).hasClass("required") || $(this).hasClass("validate")) {                         
            var value = $(this).val();          
            var error = false;
            
            if ((!value || value==0 || value=='other') && $(this).hasClass("required")) {
                error = true;
            }
            
            if ($(this).hasClass("email") && value) {
                var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
                if(!pattern.test(value)){         
                    error = true;
                }
            } else if ($(this).hasClass("password") && value) {
                var repass = $("#re" + $(this).attr("name")).val();
                if (value.lenght < 5 || repass != value) {
                    error = true;
                }
            } else if ($(this).hasClass("time") && value) {             
                var pattern = /^[0-2]?[0-9]\:[0-5][0-9]$/;              
                if(!pattern.test(value)){               
                    error = true;
                } 
            } else if ($(this).hasClass("numeric") && value) {             
                var pattern = /^[1-9][0-9]*$/;              
                if(!pattern.test(value)){               
                    error = true;
                } 
            } else if ($(this).hasClass("phonecode") && value) {                
                var pattern = /^(\([\d]+\))?[\s]?[\d\-]+$/;             
                if(!pattern.test(value)){               
                    error = true;
                } 
            } else if ($(this).hasClass("phone") && value) {                
                var pattern = /^(\([\d]+\))?[\s]?[\d\-]+$/;             
                if(!pattern.test(value)){               
                    error = true;
                } 
            }                 
            if (error) {
                var name = $(this).attr("name");
                var name = name.replace(/[\]\[]/gi,"");
                $("#"+name+"_error").show();                        
                success = false;
            } 
        }
    })

    return success; 
}

function orderService()
{
    createOverlay();
    var dialog = $('#popup');
    dialog.load("/ajax/order-service/",function(resp) {
        if (resp) {
            var y = 0;
            y = document.documentElement.scrollTop || 0;
            if (!y) y=document.body.scrollTop || 0;
            var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
            var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);
            if (top < 0) top = 25;
            $(this).css('left',left);
            $(this).css('top', top);
            $(this).css('z-index',1001);
            $(this).show();
        } else {
            document.location = "/";
        }
    });
}
function orderExpress()
{
    createOverlay();
    var dialog = $('#popup');
    dialog.load("/ajax/order-express/",function(resp) {
        if (resp) {
            var y = 0;
            y = document.documentElement.scrollTop || 0;
            if (!y) y=document.body.scrollTop || 0;
            var left = Math.round($(window).width() / 2) - Math.round($(this).width() / 2);
            var top = y + parseInt($(window).height() / 2) - parseInt($(this).height() / 2);
            if (top < 0) top = 25;
            $(this).css('left',left);
            $(this).css('top', top);
            $(this).css('z-index',1001);
            $(this).show();
        } else {
            document.location = "/";
        }
    });
}
