function showPopup(where) {
	$(".popup").hide();
	$("#" + where).css("visibility", "hidden").fadeIn("fast");
	//alert($("html").height());
	var h = Math.round($("html").height()) / 3 - Math.round($("#" + where).height() / 2);
	var h = 50;
	$("#" + where).css("margin-top", h).css("visibility", "visible");
	$("#shadow").show().animate({
		opacity: 0.4
	}, 150, 'swing');
	if (/MSIE (6).+Win/.test(navigator.userAgent)) {
		$("body").addClass("hideselects");
	}
	$("#" + where).find(":input").eq(0).focus();
}
function show_fast_adr(val){
	if (val == 1){
		$('#fast_riv').css('display','none');
		$('#fast_vol').css('display','none');
		$('#fast_adr').css('display','none');
		$('#city').css('display','none');
		$('#DelAdr').val('Самовывоз из офиса.');
		$('#delivery_date_label').html('Дата самовывоза:');
		$('#del_time_label').html('Время самовывоза:');
	}else{
		$('#fast_riv').css('display','');
		$('#fast_vol').css('display','');
		$('#fast_adr').css('display','');
		$('#city').css('display','');
		$('#DelAdr').val('');
		$('#delivery_date_label').html('Дата доставки:');
		$('#del_time_label').html('Время доставки:');
	}
}
function msg(msg_txt)
{
		$("#sys_msg").html("");
		$("#MsgForm").stop().hide();
		$('#shadow').hide();
		if (/MSIE (6).+Win/.test(navigator.userAgent)) {
			$("body").removeClass("hideselects");
		}
		$("#sys_msg").html(""+msg_txt+"");
		$("#MsgForm").css('opacity',1);
		showPopup("MsgForm");
		//alert(msg_txt);
		//alert($("#sys_msg").html());
		//$('#shadow').hide();
		if (/MSIE (6).+Win/.test(navigator.userAgent)) {
			$("body").removeClass("hideselects");
		}
		//$("#MsgForm").animate({'opacity':0},10000);
}
function carousel_item_btm(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};
function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
};
//Установить куки
function setCookie(name, value) {
      var valueEscaped = escape(value);
      var expiresDate = new Date();
      expiresDate.setTime(expiresDate.getTime() + 365 * 24 * 60 * 60 * 1000); // срок - 1 год, но его можно изменить
      var expires = expiresDate.toGMTString();
      var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
      if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
}

function Get_Cookie(name) { 
	   var start = document.cookie.indexOf(name+"="); 
	   var len = start+name.length+1; 
	   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	   if (start == -1) return null; 
	   var end = document.cookie.indexOf(";",len); 
	   if (end == -1) end = document.cookie.length; 
	   return unescape(document.cookie.substring(len,end)); 
}
function update_cart(id,qty,action){
	var Splitter 	= id.attr('id').split("_");
	var tovID 	= Splitter[1];
	if (!qty){
		var qty = $("input[id=qty_"+tovID+"]").val();	
	}
	if (!isNaN(qty)){
		//qty = 1;
	}	
	$.ajax({
		type: "POST",
		url: "/inc/ajax/cart.php",
		data: { tovarID: parseInt(tovID), tovarQty: parseInt(qty), action: action},
		success: function(resp) {
				 var cart = Get_Cookie("CART");
				 var cnt_items = 0;
				 var cnt_sum = 0;
				 if (cart){
					 cart = cart.split("=");
					 var cnt_items = 0;
					 var cnt_sum = 0;
					 $.each(cart, function(index, value) { 
						 var item_in = value.split("|");
						 cnt_items = parseInt(cnt_items) + parseInt(item_in[1]); 
						 cnt_sum = parseInt(cnt_sum) + parseInt(item_in[1])*parseInt(item_in[2]);
					 });
				 }
				 var kurs = $("input[name=currency_usd]").val();
				 var dostavka = parseFloat($("input[name=dostavka]").val());
				 var cnt_sum_wd = parseFloat(cnt_sum)+parseFloat(dostavka);
				 var dostavka_usd = parseFloat($("input[name=dostavka_usd]").val());
				 
				 $("#global_cost_uah").html(number_format(cnt_sum_wd, 2, ',', ' ')+" <span>грн.</span>");
				 $("#global_cost_usd").html(number_format(parseFloat(cnt_sum/kurs+dostavka_usd), 2, ',', ' ')+" $");
				 
				 $("#global_cart_cnt").html(cnt_items);
				 $("#global_cart_sum").html(number_format(parseFloat(cnt_sum), 2, ',', ' '));				 
				 
				 if (action == 'del'){
					 $("div[id=item_"+tovID+"]").remove();
				 }else if (action == 'chng'){
					 $("input[id=qty_"+tovID+"]").val(qty);					 
					 $("#cost_uah_"+tovID).html(qty*parseFloat($("#price_"+tovID).html().substring(0,$("#price_"+tovID).html().length-18).replace(" ",""))+" <span>грн.</span>");
					 $("#cost_usd_"+tovID).html((parseFloat($("#cost_uah_"+tovID).html().substring(0,$("#cost_uah_"+tovID).html().length-18).replace(" ",""))/kurs)+" $");
					  $("#qty_"+tovID).html(cnt_items+" шт.");
				 }else if ($("div[id=item_"+tovID+"]").html() != ''){
					 $("div[id=item_"+tovID+"]").remove();
					 $(".cart-items .rows").after(resp);
				 }else if(resp && $("div[id*=item_]").html()){
					 $(".cart-items .rows").after(resp);
				 }				 
				 //showPopup("CartBackForm");
				 //$("input[id=qty_"+tovID+"]").focus();				
		}
	});
	return false;
};
function error_msg()
{
		if ($("input[name=error]").length > 0 && $("input[name=error]").val()!=''){
			var msg_txt = $("input[name=error]").val();
			msg(msg_txt);
		}
}
function edit_compare_box(action,tovar_id){
	$.ajax({
		type: "POST",
		url: "/inc/ajax/compare_cart.php",
		data: { action: action, tovar_id: tovar_id},
		success: function(data) {
			if (data != 0){
				$('#compare_box').html(data);
				$('#compare_box').css('display', '');
			} else {
				$('#compare_box').css('display', 'none');
			}
		}
	})
}

function activate_campare_button(tovar_id){
		var str = '<a style="cursor:pointer;" onClick="deactivate_campare_button('+tovar_id+'); edit_compare_box(\'add\','+tovar_id+')">Сравнить</a>';
		if ($('#cmp_' + tovar_id) != undefined) {$('#cmp_' + tovar_id).html('<span class="compare" name="comparison_details"> <span class="sprite"><i></i></span>'+str+'</span>');}
}
function deactivate_campare_button(tovar_id){
		var cmpr = Get_Cookie("COMPARE");
		var ptrn = /[0-9]\-[0-9]/;
		var str = 'к&nbsp;сравнению';
		if (cmpr){
			str = '<a href="/compare_products/" onClick="deactivate_campare_button('+tovar_id+'); edit_compare_box(\'add\','+tovar_id+')">к&nbsp;сравнению</a>';
		}
		$('#cmp_' + tovar_id).html('<span class="compare" name="comparison_details"> <span class="sprite"><i></i>Добавлено </span>'+str+'</span>');
}
function delete_from_compare(tovar_id_do){
	var new_location = window.location.toString().split('?');
	$.ajax({
		type: "POST",
		url: "/inc/ajax/compare_cart.php",
		data: { action: 'delete', tovar_id: tovar_id_do},
		success: function(data) {
			window.location = new_location[0];
		}
	})
}

function fs_category_change(){
	var category_id_do = $('select[id=fs_category_id]').val();
	$.ajax({
		type: "POST",
		url: "/inc/ajax/fs_category.php",
		data: { category_id: category_id_do},
		success: function(data) {
			if (data != 0){
				$('#fs_brand_id').html(data);
				$('#fs_tovars').html('<option value="0" disabled>Выберите бренд...</option>');
			}
		}
	})
}
function show_fs_compare(category_id_do,category_name){
	if (category_name != ''){
		$('#category_name').html('Категория: ' + category_name);
	}
	$('#fs_category_id').val(category_id_do);
	$.ajax({
		type: "POST",
		url: "/inc/ajax/fs_category.php",
		data: { category_id: category_id_do},
		success: function(data) {
			if (data != 0){
				$('#fs_brand_id').html(data);
				$('#fs_tovars').html('<option value="0" disabled>Выберите бренд...</option>');
			}
		}
	})
}
function fs_brand_change_compare(){
	if ($("#category_name").html().length > 500){
		var category_id_do = $('select[id=fs_category_id]').val();
	}else{
		var category_id_do = $('#fs_category_id').val();
	}
	var brand_id_do = $('#fs_brand_id').val();
	$.ajax({
		type: "POST",
		url: "/inc/ajax/fs_brand.php",
		data: { category_id: category_id_do, brand_id: brand_id_do},
		success: function(data) {
			if (data != 0){
				$('#fs_tovars').html(data);
			}
		}
	})
}
function fs_tovar_select_compare(){
	var tovar_id_do = $('#fs_tovars').val();
	$.ajax({
		type: "POST",
		url: "/inc/ajax/compare_cart.php",
		data: { action: 'add', tovar_id: tovar_id_do},
		success: function(data) {
			if (data != 0) {
				var new_location = window.location.toString().split('?');
				window.location = new_location[0];
			}
		}
	})
}
function fs_tovar_select(){
	var tovar_id_do = $('#fs_tovars').val();
	if ($("#category_name").html().length > 500){
		$.ajax({
			type: "POST",
			url: "/inc/ajax/fs_tovar.php",
			data: { tovar_id: tovar_id_do},
			success: function(data) {
				if (data != 0){
					document.location = data;
				}
			}
		});
	}else{
		fs_tovar_select_compare();
	}
}

$(document).ready(function() {	
						   
	$("select[name=old_phone]").live("change",function(){
		$("#old_phone_msg").html("");
		$("#PhToName").val("+380(__)___-__-__");
		if ($(this).val() > 0){																  
			$("#old_phone_msg").html("<a href='javascript:void(0)' id='del_phone_"+$(this).val()+"'><img src='/i/del.gif' border=0></a>");																	
			$("#PhToName").val($('select[name=old_phone] :selected').text()).focus();		
			return false;
		}
		
	});
	
	$("select[name=old_del_adr]").live("change",function(){
		//alert($(this).val());												 
		$("#old_adr_msg").html("");
		$("textarea[name=delivery_adress]").val("");
		if ($(this).val() > 0){																  
			$("#old_adr_msg").html("<a href='javascript:void(0)' id='del_adr_"+$(this).val()+"'><img src='/i/del.gif' border=0></a>");												
			$("textarea[name=delivery_adress]").val($('select[name=old_del_adr] :selected').text());
			return false;
		}
		
	});
	
	$("a[id*=del_phone]").unbind("click").live("click",function(){
		var val_id = $(this).attr('id').split('_')[2];
		$("select[name=old_phone] option[value="+val_id+"]").remove();	
		var str = "id="+val_id;										   	
    	$.post("/inc/ajax/remove_phone.php", str, function(res){
			   msg(res);			
			   $("#old_phone_msg").html("");
			   $("#PhToName").val("+380(__)___-__-__");
		});
		return false;
	});				
	
	$("a[id*=del_adr_]").unbind("click").live("click",function(){
		var val_id = $(this).attr('id').split('_')[2];																
		$("select[name=old_del_adr] option[value="+val_id+"]").remove();	
		var str = "id="+val_id;										   	
    	$.post("/inc/ajax/remove_adr.php", str, function(res){	
			   $("#old_adr_msg").html("");
			   $("textarea[name=delivery_adress]").val("");
		});
		return false;
	});	
	
	$("input[name=del_ava]").unbind("click").live("click",function(){		
		if ($(this).val() == 'on'){														   
			if (confirm("Вы точно хотите удалить свой аватар?")){
				var user_id = $(this).attr('id').split('_')[2];
				var str = "uid="+user_id;	
				$.post("/inc/ajax/remove_avatar.php", str, function(res){
					   msg(res);
					   $("img#avatar").attr('src','/i/avatar.png');
					   setTimeout(function () { location.href=window.location; }, 3000);
					   $("input[name=del_ava]").attr('checked',false);
				});
			}else{
				$("input[name=del_ava]").attr('checked',false);
			}
		}
		return false;
	});
						   
	$("a[id=checkout]").unbind("click").live("click",function(){
	   var url = $(this).attr('rel');														  
	   location.href=url;														  	
	   return false;
	});						  
						   
	$().piroBox({
			my_speed: 400, //animation speed
			bg_alpha: 0.3, //background opacity
			slideShow : false, // true == slideshow on, false == slideshow off
			slideSpeed : 4, //slideshow duration in seconds(3 to 6 Recommended)
			close_all : '.piro_close,.piro_overlay'// add class .piro_overlay(with comma)if you want overlay click close piroBox

	});					   
	
	$('#PhToName').mask('+999(99)999-99-99');
	$("#delivery_date").datepicker({startDate:'01.01.2002'});
	show_fast_adr($("select[id=iz_ofica]").val());
	$("select[id=iz_ofica]").live('change',function(){					 
    	show_fast_adr($(this).val());
		if ($(this).val() == 1){
			$("#map").css('display','');	
		}else{
			$("#map").css('display','none');	
		}
    });	
	
	$("input[name=confirm]").unbind("click").live("click",function(){
		var str="";
		var error = false;
    	$.each($("form[name=order] input, textarea"), function(n, element) { 
    		if($(element).attr("type")!="button")
    		{ 
    			if ($(element).attr("value")=="" && $(element).attr('name')!='email' && $(element).attr('name')!='comment')
    			{
    				$(element).css({border: "1px solid #FF0000"},400);
					msg("Заполните необходимые поля. Они выделенны красным цветом.");
					var error = true;
    			}else if ($(element).val()=="+___(__)___-__-__" || $(element).val()=="+380(__)___-__-__"){
					$(element).css({border: "1px solid #FF0000"},400);
					msg("Заполните необходимые поля. Они выделенны красным цветом.");
					var error = true;
				}else{
    				$(element).css({border: "1px solid #a7b9c3"},400);
    				str=str + $(element).attr("name") +"="+$(element).val()+"&";					
    			}
    		}
		});	
		if (error == false){
			msg("Подождите несколько секунд ...");
			$.post($("form[name=order]").attr('action'), str, function(res){
				   msg(res);
				   $("#error").html(res);
				   $("#error").css({border: "1px solid #FF0000"},400);
			});
		}
		return false;
	});
	
	$("#forgot_passw").live('click',function(){
    	$("#login_form").html('<div>Эл. почта:</div><div><input type="text" class="text" name="login" id="login"></div><br/><div style="float:left;"><div><div><input name="forget" id="sbm_login" value="Прислать пароль" style="font-size:160%;" type="button"></div></div><div style="margin-top:10px;">&nbsp;<a href="javascript:void(0)" id="remembered">Вспомнил</a></div>');
    });
	
    $("#remembered").live('click',function(){
    	$("#login_form").html('<div>Эл. почта:</div><div><input type="text" class="text" name="login" id="login"></div><div>Пароль:</div><div><input class="text" name="passw" id="passw" type="password"></div><br/><div style="float:left;"><div><div><input name="sbm" id="sbm_login" value="Войти" style="font-size:160%;" type="button"></div></div><div style="margin-top:10px;">&nbsp;<a href="javascript:void(0)" id="forgot_passw">Забыли пароль</a></div>');
    });
	
	$("input[name=forget]").live('click',function(){
		var str = "login="+$("form[name=login_form] input[name=login]").val();												  
    	$.post("/inc/ajax/remember_password.php", str, function(res){
    		if (!res && $("form[name=login_form] input[name=login]")!=""){
				msg("Такой email не найден в базе.");
    			setTimeout(function () { location.href=window.location; }, 3000);
    		}else{
				msg(res);    			
				setTimeout(function () { location.href=window.location; }, 3000);
    		}
    	});
    	return false;
    });
	
	$("form[name=login_form] input[name=sbm]").live('click',function(){
		var str = "login="+$("form[name=login_form] input[name=login]").val()+"&passw="+$("form[name=login_form] input[name=passw]").val();										   	
    	$.post("/inc/ajax/login.php", str, function(res){
    		if (!res && $("form[name=login_form] input[name=login]")!="" && $("form[name=login_form] input[name=passw]")!=""){
				//dump("AAA");
				msg("Такой email не найден в базе.");
    			setTimeout($("form[name=login_form]").html('<div>Эл. почта:</div><div><input type="text" class="text" name="login" id="login"></div><br/><div style="float:left;"><div><div><input name="forget" id="sbm_login" value="Прислать пароль" style="font-size:160%;" type="button"></div></div><div style="margin-top:3px;">&nbsp;<a href="javascript:void(0)" id="remembered"><small>Вспомнил</small></a></div>'),3000);
    		}else{
				msg(res);
    			//$("form[name=login_form]").html("<p>"+res+"</p>");
				$("#login_form").html('<div>Эл. почта:</div><div><input type="text" class="text" name="login" id="login"></div><div>Пароль:</div><div><input class="text" name="passw" id="passw" type="password"></div><br/><div style="float:left;"><div><div><input name="sbm" id="sbm_login" value="Войти" style="font-size:160%;" type="button"></div></div><div style="margin-top:3px;">&nbsp;<a href="javascript:void(0)" id="forgot_passw"><small>Забыли пароль</small></a></div>');
    			//setTimeout(location.href=window.location,6000);		
				setTimeout(function () { location.href=window.location; }, 3000);
    		}
    	});
    	return false;
    });
						   
	jQuery('#btm_carousel').jcarousel({
        auto: 3,
        wrap: 'last',
        initCallback: carousel_item_btm
    });
	/* === Инициализация попапов === */
	if (/MSIE (6).+Win/.test(navigator.userAgent)) {
		$('.popup').find('.tl,.tr,.bl,.br').html('<i class="p24"></i>');
	}
	var h = $('.container').height();
	if (h <= $('body').height()) {
		h = $('body').height();
	}
	$('#shadow').animate({
		opacity: 0
	}, 1);
	$('#shadow').height(h);
	
	/* === Клик по линке на попап === */	
	$("a[rel='popup']").unbind('click').click(function() {
		var attr = $(this).attr("href").replace(/^.*#(.*)/, "$1");
		showPopup(attr)
		if (attr == 'fastNavigation'){
			var category_id = $(this).attr("id");
			var category_name = $(this).attr("alt");
			if (category_name != ''){
				show_fs_compare(category_id,category_name)
			}else{
					
			}
		}
		return false;
	});
	$("[id*=remove_]").live('click', function(){
		update_cart($(this),"","del");
		return false;
    });    
	$("[id*=qty_]").live('keypress', function(event){
    	var val = String.fromCharCode(event.which);
    	update_cart($(this),parseInt(val),"chng");
    	return false;
    });		
	$("[id*=addtocart_]").live('click', function(){									 
    	update_cart($(this),1,"add");		
    	return false;
    });
	
	/* === Клик линке на закрыть === */
	$("[rel='popup-close']").unbind('click').click(function() {
		$(this).parents(".popup").hide();
		$('#shadow').hide();
		if (/MSIE (6).+Win/.test(navigator.userAgent)) {
			$("body").removeClass("hideselects");
		}
		var order_id = $("#order_id").html();
		if (order_id){
			location.href='/congratulation/?order_id='+order_id;
		}
		return false;
	});
	
	/* === Клик линке на продолжить === */
	$("[rel='popup-proceed']").unbind('click').click(function() {
		$(this).parents(".step").hide().next('.step').show();
		reloadPage();
		return false;
	});
	
	$("#shadow").unbind("click").live("click",function(){
		$(".popup").hide();
		$('#shadow').hide();
		if (/MSIE (6).+Win/.test(navigator.userAgent)) {
			$("body").removeClass("hideselects");
		}
		return false;											   
	});

	$('.menu li').eq(0).hover(function() {
		$(this).parents('.menu').find('li.bl').hide();
	}, function() {
		$(this).parents('.menu').find('li.bl').show();
	});

	var nav = $('.menu ul > li').each(function() {
		$(this).hover(function() {
			var tmp = 0;
			$(this).prevAll('li').each(function(){
				tmp += $(this).width();
			});
			//console.debug($(this).parents('.menu').width() - tmp);
			if (($(this).parents('.menu').width() - tmp) < 560) {
				$(this).addClass('inverse');
			}
			if ($.browser.msie && $.browser.version < 7) {
				$(this).addClass('hover');
			}
		}, function() {
			if ($.browser.msie && $.browser.version < 7) {
				$(this).removeClass('hover');
			}
			$(this).removeClass('inverse');
		});
	});
	
	$('.tabs .nav a').click(function(){
		$(this).parent('li').siblings('li').removeClass('active').end().addClass('active');
		var hr = $(this).attr('href');
		$('.tabs .tab').addClass("tab-hidden");
		$(hr).removeClass("tab-hidden");
		var url = window.location;
		//alert(url);
		var tab_id = $(this).attr('href').split('#')[1];
		if($(this).attr('id') == 'checkout'){
			var url = $(this).attr('rel');
			location.href=url;
		}		
		$(tab_id).removeClass("tab-hidden");
		//alert(window.location);
		//window.location.replace(url);
		return false;
	});
	
	$("input[id=callback]").unbind('click').live('click',function(){
		var str = "";
		$.each($("form[name=callback] input, textarea"), function(n, element) {
			if ($(element).attr("type") != "button") {
				if ($(element).attr("value") == "") {
					$(element).css({
						border: "1px solid #FF0000"
					}, 400);
				} else if ($(element).attr("value")=="+___(__)___-__-__" || $(element).attr("value")=="+380(__)___-__-__"){
					$(element).css({border: "1px solid #FF0000"},400);
				} else {
					$(element).css({
						border: "1px solid #a7b9c3"
					}, 400);
					str = str + $(element).attr("name") + "=" + $(element).val() + "&";
				}
			}
		});
		$.post($("form[name=callback]").attr('action'), str, function(res) {
			if (res == 1) {
				msg("Спасибо что воспользовались услугой!<br>Вам перезвонят в ближайшее время.");
				setTimeout(function() {
					$("form[name=callback] input[class=text], textarea[class=text]").val("");
				}, 5000);
			}
			//alert(res);
		});
    	return false;
    });
	$("#edit_cart").live('click', function(){
	   showPopup("CartBackForm");										
	});
	$("#productPrice input").click(function() {
//		alert(this.id);
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 			= productIDValSplitter[1];
		if (typeof(productIDValSplitter[2]) != 'undefined') {var productIDVal2 = productIDValSplitter[2];} else {var productIDVal2 = '';}
		if (typeof(productIDValSplitter[3]) != 'undefined') {var skidkaVal = productIDValSplitter[3];} else {var skidkaVal = '';}
		var productX 		= $("#productImageWrapID_" + productIDVal).offset().left;
		var productY 		= $("#productImageWrapID_" + productIDVal).offset().top;

		$("#contentWrapRight")
		.css({'display' : 'block'});

		if( $("#productID_" + productIDVal).length > 0){
			var basketX 		= $("#productID_" + productIDVal).offset().left;
			var basketY 		= $("#productID_" + productIDVal).offset().top;
		} else {
			var basketX 		= $("#basketItemsWrap").offset().left;
			var basketY 		= $("#basketItemsWrap").offset().top;
		}

//		alert(basketX);
//		alert(basketY);

		var gotoX 			= basketX - productX;
		var gotoY 			= basketY - productY;

		var newImageWidth 	= $("#productImageWrapID_" + productIDVal).width() / 3;
		var newImageHeight	= $("#productImageWrapID_" + productIDVal).height() / 3;

		
		$("#contentWrapRight")
		.css({'opacity' : '.6'});

		$("#notificationsLoader")
		.css({'position' : 'relative'})
		.css({'top' : $("#contentWrapRight").height()/2.05})
		.html('<img src="/i/loader.gif">');
		
		if ($("#contentWrapRight").width() > 300){
			$("#notificationsLoader").css({'left' : $("#contentWrapRight").width()/2.05-22})
		}

		$("#productImageWrapID_" + productIDVal + " img")
		.clone()
		.prependTo("#productImageWrapID_" + productIDVal)
		.css({'position' : 'absolute'})
		.animate({opacity: 0.4}, 100 )
		.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {

			$(this).remove();
			
//			alert($(".lising_info").css('display'));
			if ($(".lising_info").css('display') == 'block'){
				var bnVal = 'bn';
			}

			$.ajax({
				type: "POST",
				url: "/inc/addProduct.php",
				data: { productId: productIDVal, bn: bnVal, action: "addToBasket"},
				success: function(theResponse) {
				if (productIDVal2 != '') {
					$.ajax({
						type: "POST",
						url: "/inc/addProduct.php",
						data: { productId: productIDVal2, skidka: skidkaVal, action: "addToBasket"},
						success: function(theResponse) {
							alert(theResponse);
                            prid2split = productIDVal2.split("/");
                			if (prid2split[1] != 'NULL') {productIDVal2 = prid2split[0];}

							if( $("#productID_" + productIDVal2).length > 0){
								$("#productID_" + productIDVal2).animate({ opacity: 0 }, 500);
								$("#productID_" + productIDVal2).after(theResponse).remove();
								$("#productID_" + productIDVal2).animate({ opacity: 0 }, 500);
								$("#productID_" + productIDVal2).animate({ opacity: 1 }, 500);
								$("#notificationsLoader").empty();

							} else {
								$("#basketItemsWrap").after(theResponse);
								$("#notificationsLoader").empty();
							}

							$("#contentWrapRight")
							.css({'opacity' : '1'});

							}
					});
				}
//					alert(theResponse);

					if( $("#productID_" + productIDVal).length > 0){
						$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
						$("#productID_" + productIDVal).after(theResponse).remove();
						$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
						$("#productID_" + productIDVal).animate({ opacity: 1 }, 500);
						$("#notificationsLoader").empty();

					} else {
						$("#basketItemsWrap").after(theResponse);
						$("#notificationsLoader").empty();
					}

					$("#contentWrapRight")
					.css({'opacity' : '1'});

					}
				});
		});
	});

	$("#tableItemsWrap .del").live("click", function(event) {
//		alert(this.id);
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 			= productIDValSplitter[1];
		$("#notificationsLoader").html('<img src="/i/loader.gif">');

		$.ajax({
			type: "POST",
			url: "/inc/addProduct.php",
			data: { productId: productIDVal, action: "deleteFromBasket"},
			success: function(theResponse) {

				$("#productID_" + productIDVal).hide("slow",  function() {$(this).remove();});

				var cart = Get_Cookie("CART");
				if (!cart){
					$("#contentWrapRight").css({'display' : 'none'});
				}
				$("#notificationsLoader").empty();

			}
		});
	});
	
	$("#forget_password").unbind("click").live("click",function(){
		//alert($(this).html());	
		if ($(this).html() == 'Забыли пароль?'){
			$("#login_header").html("Восстановление пароля");
			$("#login_text").html("Введите свой e-mail и нажмите на кнопку \"Отправить\"");
			$("input[id*=sbm_login]").val("Отправить");		
			$("input[id*=sbm_login]").attr('name','forget');
			$("#login_passw").css('display','none');
			$(this).html("Вспомнил пароль");
		}else{
			$("#login_header").html("Вход для пользователей");
			$("#login_text").html("Войдите, используя свой логин и пароль и воспользуйтесь скидкой для постоянных клиентов.");
			$("input[id*=sbm_login]").val("Войти");
			$("input[id*=sbm_login]").attr('name','sbm');
			$("#login_passw").css('display','');
			$(this).html("Забыли пароль?");	
		}
	});
	$("select[id=fs_category_id]").live("change",function(){
		fs_category_change();														   
	});
	$("select[id=fs_brand_id]").live("change",function(){
		fs_brand_change_compare();														   
	});
	$("select[id=fs_tovars]").live("change",function(){
		fs_tovar_select();														   
	});
	
	var cache = {};
	$("#country_name").autocomplete({
		source: function(request, response) {
			if (cache.term == request.term && cache.content) {
				response(cache.content);
			}
			if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
				var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
				response($.grep(cache.content, function(value) {
					return matcher.test(value.value)
				}));
			}
			$.ajax({
				url: "/inc/ajax/autocomplete.php",
				dataType: "json",
				data: request,
				success: function(data) {
					cache.term = request.term;
					cache.content = data;
					response(data);
				}
			});
		},
		minLength: 2,
		select: function(event, ui) {
			$("#country_id").val(ui.item.id);
		}
	});	
	error_msg();	
});