var images =  new Array();
var tempX = 0;
var tempY = 0;
var path = "";
var init_menu = 1;


$(document).ready(function(){

	if($.cookie('header') == null){
		$.cookie('header', 1, {domain: "100-tovarov.ru",path: "/"});
	};

	$("#myhead").load("/inc/head_menu.utf8?rev="+rev,function(data){
		setcity('moscow');
		hide_header();
	});

	if(init_menu == 1){
		$("#leftmenu").html($("#leftmenuh").html());
		bindenu();
	}else{
		$("#leftmenu").load("/inc/left_menu.utf8?rev="+rev,function(data){
			if(path_id){
				var arr = path_id.split("_");
				var node;
				while (node = arr.shift()){
					node_open(node);
				}
			}
			bindenu();
		});
	};	
	$("#seotext").html($("#seotexth").html());

	//$("#myhead").html($("#myheadh").html());
	
	// Биндим меню


	//## Инициализация шапки
	

	//## Инициализация сортировки
	/*sorter_init();*/

	//## Очистка корзины если нужно
	if(delcookie){
		$.cookie('cart', null,{ domain: "100-tovarov.ru",path: "/"});
	}
	
	//## Апдейт корзины товаров
	cart_update();

	//## Апдейт счетчика товаров
	count_total();

	//## Раскраска
	clz();

	//## Чтение истории посецения товаров
	history();
	
	//tb_remove();
	
	tabs();

});


function bindenu(){
	var hideid = window.setTimeout(hide, 100);
	$(".mit").bind('mouseover',function(){
		$(".mit").css("background-color","");
		$(this).css("background-color","#EEE");
		var offset = $(this).offset();
		$(this).find("div:first").bind('mouseout',function(){
			$("#pmenu").hide();
		});
		var html = $(this).find("div:first").html();
		if(html){
			$("#pmenu").html(html);
			$("#pmenu").find("table:first").bind("mouseout",function(){
				hideid = window.setTimeout(hide, 200);
			});
			$("#pmenu").find("table:first").bind("mousemove",function(){
				if(hideid){
					clearTimeout(hideid);
				}
			});
			var top = offset.top;
			var mh = $("#pmenu").height();
			var wh = $(window).height();
			var ws = $(window).scrollTop();
			if((top+mh) > (wh+ws)){
				top = (wh+ws)-mh-15;
			}
			$("#pmenu").css("top",top).css("left",(offset.left+$(this).width()));
			$("#pmenu").show();	
		}else{
			$("#pmenu").hide();
		}
	});
}

function hide(){
	$("#pmenu").hide();
}

function tabs(){
	$(".tab.active").show();
	$(".tabs").find("li").bind('click',function(){
		var cl = $(this).attr("class").split(' ');
		$(".tabs").find("li").removeClass("active");
		$(this).addClass("active");
		$(".tab").hide();
		$("."+cl[0]).show();
	});
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/*
function sorter_init(){


	if(is_search == 1){
		$("#table_filter").hide();
		$("#table_search").show();
		$("#sfield").val(to_serach);
	}
	else{
		load_filter_brands();
		
		// Slider
		slider_init();
	
		$("#simplesearch").find("img:first").bind("click",function(){
			$("#table_filter").show();
			$("#table_search").hide();
		});
	}
}
*/
	function ipop(source){
		var newImg = new Image();
		newImg.src = source;
		var x = newImg.width;
		var y = newImg.height;
		if(x >= 400){
			var dw = parseInt(($(document).width()/2)-(x/2));
			$("#window").css("width",x+"px");
			$("#window").css("height",y+"px");
		}
		else{
			var dw = parseInt(($(document).width()/2)-200);
		}
		$("#w_title").remove();

		$("#w_text").html("<center><img src='"+source+"' valign='middla'/></center>");
		$("#window").css("left",dw+"px");
		$("#window").show();
		$("#window").click(function () { 
     		 $(this).hide(); 
    	})
	}
	function fsubmit(){
		var ok = 1;
		if(!$("#fio").val()){
			$("#fio").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#email").val()){
			$("#email").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#phone").val()){
			$("#phone").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#country").val()){
			$("#country").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#city").val()){
			$("#city").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#province").val()){
			$("#province").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#indexx").val()){
			$("#indexx").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(!$("#adress").val()){
			$("#adress").css({backgroundColor:"#aa2222"});
			ok = 0;
		}
		if(opt == 1){
			var total = 0;
			$(".productListing-even").each(function(){
				var id = $(this).attr("rel");
				var count = $(this).find("#count_"+id).val();
				var price = $(this).find("#price_"+id).text();
				total = total + (count*price);
			});
			if(total < 2500){
				ok = 0;
				alert("Минимальная сумма заказа 2.500 рублей.");
			}
		}
		if(ok == 1){
			$('#form').submit();
		}
	}

	function count_total() {
		var total = 0;
		$("img.ids").each(function(){
			var price = parseInt($("#price_"+this.id).text());
			var count = parseInt($("#count_"+this.id).val());
			var cost = price*count;
			total = total + cost;
		});
		$("#total").text(total);
	}

	function count_cart() {
		var total = 0;
		$(".productListing-even").each(function(){
			var id = $(this).attr("rel");
			var count = $(this).find("#count_"+id).val();
			var price = $(this).find("#price_"+id).text();
			total = total + (count*price);
		});
		$("#cart_total").text(total);
	}

	var current;
	function item_show(id){
		if(current != id){
		$.getJSON("/wshop/ajax/"+id+".html",{ajax_get:1},
			function(data){
				for( var ArrVal in data['item'] ) {
					$("#title").text(data['item'] [ArrVal]['name']);
					$("#price").text(data['item'] [ArrVal]['price']);
					$("#text").html(data['item'] [ArrVal]['text']);
					$("#image").attr("src","http://img.100-tovarov.ru/images/u/"+data['item'] [ArrVal]['image']);
					$(".price").show();
					$("#order_btn").unbind('click');
					$("#order_btn").click(function(){
						add_to_cart(data['item'] [ArrVal]['id']);
				
					});
					clz();
					current = id;
				
				}
			});
		
		}
		
	};

	function add_to_cart(id) {
		var add = $.cookie('cart');
		var ids = '';

		if(add){
			ids = add + ':' + id;
		}
		else{
			ids = id;
		}
		
		$.cookie('cart', ids, {domain: "100-tovarov.ru",path: "/"});
		window.parent.location="/shopping_cart.php?id="+id;
		cart_update();


	};

	function del_from_cart(id) {
		var add = $.cookie('cart').split(/:/);
		var narr = new Array();
		for (var i = 0; i < add.length; i++){
			if(id != add[i]){	
		 		narr.push(add[i]);	
			}
		}
		add = narr.join(":");
		$.cookie('cart', add, { domain: "100-tovarov.ru",path: "/"});	
		window.location.reload();
	}


	function cart_update() {
		var id = $.cookie('cart');
		if(id){
			$.getJSON("carp.php?Cart="+id+"&a=1",{},
				function(data){
					$("#cart_summ").text(data['summ']);
					$("#cart_items").text(data['items']);
				});
		}
		else{
			$("#cart_summ").text(0);
			$("#cart_items").text(0);
		}
	}
	function delete_cookie() {
		$.cookie('cart', null,{ domain: "100-tovarov.ru",path: "/"});
		$("#cart_summ").text(0);
		$("#cart_items").text(0);
		window.location.reload(true);
	}

var i = parseInt(0);
var color = "#d3d3d3";


 function clz() {

    $(".param_table tr").each(function(){
        if(i > 0){
            $(this).css("background-color",color);
            i=0;
        }
        else{ 
            i++;
        }
    });
	i=0;
}


var pos = parseInt(-1);

function anext(id){
	if(id <= -1){
		if(pos <= 0){
			pos = 5;
		}
	}
	else{
		if(pos >= arr.length-1){
			pos = -1;
		}
	}
	pos=pos+id;
	alert(id+"|"+pos+"|"+arr[pos]);
}

function tooltip(text,left){
	$("#tooltip").css('position','absolute');
	$("#tooltip").css('top','-26px');
	$("#tooltip").css('left',left+'px');
	$("#tooltip").show();
	$("#tooltip_text").text(text);
}



function setcity(city){
	
	var city_id;
	if(city){city_id=city}
	else{city_id = $("#city_id").val();}
	
	$("#city_text").html(items[city_id]['text']);
	var html;
	if(items[city_id]['images_end']){
		var cur = 1;
		while(cur <= items[city_id]['images_end']) {
			dir = city_id;
			pref = items[city_id]['images_pref'];
			suff = items[city_id]['images_suff'];
			if(html){
				html=html+"<li><a rel='shadowbox' href='/images/hut/"+dir+"/"+pref+cur+".jpg'><img src='/images/hut/"+dir+"/"+pref+cur+suff+".jpg' alt='' /></a></li>";
			}
			else{
				html="<li><a rel='shadowbox'  href='/images/hut/"+dir+"/"+pref+cur+".jpg'><img src='/images/hut/"+dir+"/"+pref+cur+suff+".jpg' alt='' /></a></li>";
			}
			cur++;
		}
		$("#fs").html(html);
		
		images = new Array();
		$("#fs li").each(function(i){
			images.push(this.innerHTML);
		});
		//tb_remove();
		//tb_init('a.thickbox, area.thickbox, input.thickbox');
		Shadowbox.clearCache(); 
		Shadowbox.setup();
	}
	else{
		var cur = 1;
		while(cur <= 7) {
			if(html){
				html=html+"<li><img src='/images/hut/no-foto.jpg' alt='' /></li>";
			}
			else{
				html="<li><img src='/images/hut/no-foto.jpg' alt='' /></li>";
			}
			cur++;
		}
		$("#fs").html(html);

		images = new Array();
		$("#fs li").each(function(i){
			images.push(this.innerHTML);
		});
	}
}

function hpop(){
	$("#window").hide();
}


var fspos = 0;
function move(direct){
	if(direct == -1){
		images.unshift(images.pop());
	}
	else{
		images.push(images.shift());
	}

	var html;
	for( var ArrVal in images ) {
		if(html){
			html=html+"<li>"+images[ArrVal]+"</li>";
		}
		else{
			html="<li>"+images[ArrVal]+"</li>";
		}
	}
	$("#fs").html(html);
	Shadowbox.clearCache(); 
	Shadowbox.setup();

}

var items = {
	moscow:{
		text:"Часы работы магазина: ПН-ПТ с 9.00 до 21.00, СБ-ВС с 10.00 до 16.00 | Доставка малогабаритных товаров на сумму от 2.500 бесплатно (в пределах МКАД) | Доставка по России (EMS Почта России) от 3 до 14 дней.",
		images_pref:"moskva",
		images_end:40,
		images_suff:"m"
	},
	piter:{
		text:"Доставка в город Санкт-Петербург 2-3 дня. Стоимость доставки 300-400 рублей.<br>Уникальные дилерские цены для магазинов из Санкт-Петербурга.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"spb",
		images_end:13,
		images_suff:"m"
	},
	novosib:{
		text:"Доставка в город Новосибирск 3-7 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Новосибирска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"novosib",
		images_end:27,
		images_suff:"m"
	},
	ekat:{
		text:"Доставка в город Екатеринбург 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Екатеринбурга.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"ekat",
		images_end:28,
		images_suff:"m"
	},
	nn:{
		text:"Доставка в город Нижний Новгород 3-5 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Нижнего Новгорода.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"niz",
		images_end:8,
		images_suff:"m"
	},
	samara:{
		text:"Доставка в город Самара 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Самары.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"samara",
		images_end:22,
		images_suff:"m"
	},
	omsk:{
		text:"Доставка в город Омск 4-6 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Самары.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"omsk",
		images_end:15,
		images_suff:"m"
	},
	kazan:{
		text:"Доставка в город Казань 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Казани.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"kazan",
		images_end:30,
		images_suff:"m"
	},
	chelyab:{
		text:"Доставка в город Челябинск 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Челябинска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"chel",
		images_end:11,
		images_suff:"m"
	},
	rostov:{
		text:"Доставка в город Ростов-на-Дону 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Ростова-на-Дону.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"rostov",
		images_end:30,
		images_suff:"m"
	},
	ufa:{
		text:"Доставка в город Уфа 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Уфы.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"ufa",
		images_end:30,
		images_suff:"m"
	},
	perm:{
		text:"Доставка в город Пермь 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Перми.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"perm",
		images_end:40,
		images_suff:"m"
	},
	volgograd:{
		text:"Доставка в город Волгоград 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Волгограда.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"volgo",
		images_end:40,
		images_suff:"m"
	},
	krasnoyarsk:{
		text:"Доставка в город Красноярск 4-7 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Красноярска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"krasnoyar",
		images_end:40,
		images_suff:"m"
	},
	voronez:{
		text:"Доставка в город Воронеж 3-5 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Воронежа.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"voronez",
		images_end:36,
		images_suff:"m"
	},
	saratov:{
		text:"Доставка в город Саратов 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Саратова.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"saratov",
		images_end:20,
		images_suff:"m"
	},
	krasnodar:{
		text:"Доставка в город Краснодар 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Краснодара.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"krasnodar",
		images_end:20,
		images_suff:"m"
	},
	tolatti:{
		text:"Доставка в город Тольятти 3-4 дня. Стоимость доставки 610-810 рублей.<br>Уникальные дилерские цены для магазинов из Тольятти.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"toliatti",
		images_end:20,
		images_suff:"m"
	},
	izhevsk:{
		text:"Доставка в город Ижевск 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Ижевска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"izevsk",
		images_end:20,
		images_suff:"m"
	},
	ulyanovsk:{
		text:"Доставка в город Ульяновск 4-7 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Ульяновска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"ulyanovsk",
		images_end:30,
		images_suff:"m"
	},
	yaroslavl:{
		text:"Доставка в город Ярославль 3-6 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Ярославля.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"yaroslavl",
		images_end:40,
		images_suff:"m"
	},
	barnaul:{
		text:"Доставка в город Барнаул 4-7 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Барнаула.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"barnaul",
		images_end:40,
		images_suff:"m"
	},
	vladik:{
		text:"Доставка в город Владивосток 4-7 дней. Стоимость доставки 650-920 рублей.<br>Уникальные дилерские цены для магазинов из Владивостока.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"vladivostok",
		images_end:30,
		images_suff:"m"
	},
	habarovsk:{
		text:"Доставка в город Хабаровск 4-13 дней. Стоимость доставки 650-920 рублей.<br>Уникальные дилерские цены для магазинов из Хабаровска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"habarovsk",
		images_end:40,
		images_suff:"m"
	},
	irkutsk:{
		text:"Доставка в город Иркутск 3-7 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Иркутска.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"irkutsk",
		images_end:40,
		images_suff:"m"
	},
	novokuz:{
		text:"Доставка в город Новокузнецк 2-4 дня. Стоимость доставки 680-930 рублей.<br>Уникальные дилерские цены для магазинов из Новокузнецка.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"novokuzneck",
		images_end:37,
		images_suff:"m"
	},
	tyumen:{
		text:"Доставка в город Тюмень 3-6 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Тюмени.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"tum",
		images_end:41,
		images_suff:"m"
	},
	orenburg:{
		text:"Доставка в город Оренбург 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Оренбурга.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"orenburg",
		images_end:38,
		images_suff:"m"
	},
	kemerovo:{
		text:"Доставка в город Кемерово 3-6 дней. Стоимость доставки 580-800 рублей.<br>Уникальные дилерские цены для магазинов из Кемерово.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"kemerovo",
		images_end:40,
		images_suff:"m"
	},
	razyan:{
		text:"Доставка в город Рязань 3-5 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Рязани.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"ryazan",
		images_end:40,
		images_suff:"m"
	},
	penza:{
		text:"Доставка в город Пенза 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Пензы.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"penza",
		images_end:40,
		images_suff:"m"
	},
	nabchel:{
		text:"Доставка в г. Набережные Челны 3-6 дней. Стоимость доставки 610-810 рублей.<br>Уникальные дилерские цены для магазинов из Набережных Челнов.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"chelny",
		images_end:38,
		images_suff:"m"
	},
	astrah:{
		text:"Доставка в город Астрахань 3-5 дней. Стоимость доставки 530-700 рублей.<br>Уникальные дилерские цены для магазинов из Астрахани.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"astrahan",
		images_end:39,
		images_suff:"m"
	},
	lipezk:{
		text:"Доставка в город Липецк 3-5 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Липецка.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"lipeck",
		images_end:39,
		images_suff:"m"
	},
	tula:{
		text:"Доставка в город Тула 3-5 дней. Стоимость доставки 480-600 рублей.<br>Уникальные дилерские цены для магазинов из Тулы.<br>На всю продукцию распространяется гарантия через наш сервисный центр.",
		images_pref:"tula",
		images_end:40,
		images_suff:"m"
	},
	other:{
		text:"Доставка в другой город России и в города стран СНГ от 3 до 14 дней.<br>Стоимость доставки в другие города от 300 до 3000 рублей.<br>Подробности узнавайте у наших менеджеров.",
		images_pref:"drugie",
		images_end:34,
		images_suff:"m"
	}
};

function sshow(id){

    var ourDiv = document.getElementById("sts_"+id);
    var y = parseInt(absPosition(ourDiv).y);

	var title = $("#sts_"+id).html();
	var text = $("#stt_"+id).html();

	var dw = parseInt(($(document).width()/2)-200);

	$("#w_title").html(title);
	var inhtml = text;
	$('#w_title').parent().find("p").remove();
	$('#w_title').parent().find("br").remove();
	$("#w_title").parent().append("<br/>"+inhtml);

	$("#window").css("left",dw+"px");
	$("#window").css("top",(y-150)+"px");
	$("#window").show();

}

function wshow(id){

	if(current != id){
		$.getJSON("/cgi-bin/index.cgi",{ajax_get:1,page:id},
			function(data){
					if(data['content'].length >= 5){

						var dw = parseInt(($(document).width()/2)-200);
						$("#w_title").html(data['content_title']);
						var inhtml = data['content'];
						$('#w_title').parent().find("p").remove();
						$('#w_title').parent().find("br").remove();
						$("#w_title").parent().append("<br/>"+inhtml);
						$("#window").css("left",dw+"px");
						$("#window").css("top","200px");
						$("#window").show();	
					}
					else{
						$("#window").hide();
					}
			});
		
	}

}

function wmailus(){
	var dw = parseInt(($(document).width()/2)-200);
	//$("#ansp").attr('src','/cgi-bin/antispam.cgi');
	$("#antispam_image").html('<img  alt="" id="ansp" src="/cgi-bin/antispam.cgi" width="89" height="34"/>');
	$("#w_title").html('Обратная связь');
	$("#w_text").html($("#fmailus").html());
	$("#window").css("left",dw+"px");
	$("#window").show();	
}

function buynow(id){
		var add = $.cookie('cart');
		var ids = '';

		if(add){
			ids = add + ':' + id;
		}
		else{
			ids = id;
		}
		
		$.cookie('cart', ids, {domain: "100-tovarov.ru",path: "/"});

	var dw = parseInt(($(document).width()/2)-200);
	//alert($("#ansp2").attr('src'));
	$("#ansp2").attr('src','/cgi-bin/antispam.cgi?key='+Math.random());
	$("#w_title").html($("#cartname").html());

	var inhtml = $("#cartid").html();
	$('#w_title').parent().find("#form").remove();
	$('#w_title').parent().find("p").remove();
	$('#w_title').parent().find("br").remove();
	$("#w_title").parent().append("<br/>"+inhtml);

//	$("#w_text").html($("#cartid").html());
	$("#window").css("left",dw+"px");
	$("#window").show();	
}

function node_open(id){
	if($("#nav_"+id).attr("src") == '/images/ico_plus.gif'){
		$("#nav_"+id).attr("src","/images/ico_minus.gif");
	}
	else{
		$("#nav_"+id).attr("src","/images/ico_plus.gif");
	}
	$("#node_"+id).toggle();
	$("#a_"+id).css("font-weight","bold");
}

function history() {
	var add = $.cookie('history');
	if(add){
		var arr = add.split(/\$/);	
		for (var i = 0; i < 10; i++){
			if(arr[i]){
				var item = arr[i].split(/\|/);
				//alert(item[1]);
				$("#history").append('<li><a href="/product_info.php?products_id='+item[0]+'">'+item[1]+'</a></li>');
			}
		}
	}

}

function addhis(id,name){
		
		var add = $.cookie('history');
		var curri = id+"|"+name;
		var newitem = "true";
		var narr = new Array();
		if(add){
			var arr = add.split(/\$/)
			for (var i = 0; i < arr.length; i++){
				if(arr[i]){	
					if(curri == arr[i]){
						newitem = "false";
					}
					else{
						narr.push(arr[i]);
					}
				}
			}
			if(newitem){
				narr.push(curri);
			}
		}
		else{
			narr.push(curri);
		}
		narr.reverse();
		var cookie = narr.join('\$');
		$.cookie('history', cookie , {domain: "100-tovarov.ru",path: "/"});
}


//###### IMAGE_POPUP

function absPosition(obj) {
      var x = y = 0;
      while(obj) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
      }
      return {x:x, y:y};
}

function hide_im_pop(){
	$("#popimdiv").hide();
}

function show_im_pop(id,img){
    var ourDiv = document.getElementById("im_"+id);
    var x = parseInt(absPosition(ourDiv).x);
    var y = parseInt(absPosition(ourDiv).y);
	x=x-270;
	y=y-300;
	$("#popimdiv").css("top",y+"px").css("left",x+"px").show();
	$("#popim").attr("src","/images/tn_"+img);
}


//###### IMAGE_POPUP

//#### SAVE_INTO_COOKIE

function set_cookie(name,value){
		$.cookie(name, value, {domain: "100-tovarov.ru",path: "/"});
}

//#### SAVE_INTO_COOKIE

////##### EMS

function emsopen(){
	emsload();
	$("#emsform").show();
}

function emsload() {
	$.getJSON("/api/rest",{method:"ems.get.locations",type: "russia",plain: "true"},
        function(data){
	        $.each(data['rsp']['locations'], function(i,item){
				if(item.value != 'city--moskva'){
	            	$("#ems_city").append("<option value='"+item.value+"'>"+item.name+"</option>");
				}
	        });
		}
	);
}

function emscalc() {
	$.getJSON("/api/rest",{method:"ems.calculate",from:"city--moskva",to:$("#ems_city").val(),weight:$("#weight").val()},
		function(data){
			$("#ems_price").text((parseInt(data["rsp"]["price"])+200));
			$("#ems_min").text((parseInt(data["rsp"]["term"]["min"])+1));
			$("#ems_max").text((parseInt(data["rsp"]["term"]["max"])+3));
			/*
			$("#ems_price").text(data["rsp"]["price"]);
			$("#ems_min").text(data["rsp"]["term"]["min"]);
			$("#ems_max").text(data["rsp"]["term"]["max"]);
			*/
		}
	);
}

////##### EMS

////### MOUSE_POSITION
window.onload=initXY;


function initXY() {

var IE = document.all?true:false


if (!IE) document.captureEvents(Event.MOUSEMOVE)


document.onmousemove = getMouseXY;



function getMouseXY(e) {
  if (IE) {
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {  
    tempX = e.pageX;
    tempY = e.pageY;
  }  

  if (tempX < 0){tempX = 0};
  if (tempY < 0){tempY = 0}  ;
  if (!IE) {
    tempX=tempX-145;
    tempY=tempY+15;
  }  
  else{
  	tempX=tempX-145;
    tempY=tempY+15;
  }
  $("#loader").css("left",tempX+"px");
  $("#loader").css("top",tempY+"px");
  $("#loaderx").text(tempX+"px");
  $("#loadery").text(tempY+"px");
  return true;
}


}

function getXY(e) {
  x = (window.Event) ? e.pageX : event.clientX;
  y = (window.Event) ? e.pageY : event.clientY;

}
/////#### MOUSE_POSITION

////##### IMAGE_POPUP

function ishow(img){
	$("#loader").html('<img src="http://img.100-tovarov.ru/images/tn_'+img+'" />');
	$("#loader").show();
}

function ihide(){
	$("#loader").hide();
}

////##### IMAGE_POPUP


////##### FILTER
/*
var special = "";
function apply_filter_(sp){
	special = sp;
	apply_filter();
}

function apply_filter(){
	
	$.getJSON("/ajax/ifilter",{
			from:$(".in-left").val(),
			to:$(".in-right").val(),
			onpage:$("#onpage_id").text(),
			cat_id:p_cat_id,
			brand:$("#brand_id").text(),
			tag:$("#tags_id").text(),
			page:$("#page_id").text(),
			type: "apply",
			special: special
		},
        function(data){
			$(".cat-list").html("");
			$("#cat_table").remove();
			$("#seotext").remove();
			$("#pages").remove();

			var html = "<ul>";
			var items = "";
	        $.each(data['items'], function(i,item){
            	var add; 
				if(item.empty == 1){
					add = "<li>&nbsp;</li>";
				}else{
					var price = item.price;
					if(item.new_price != 0){
						price = "<s>"+item.price+"</s><br/>"+item.new_price;
					}
					if(item.gift == 1){
						add = $("#item_tmpl").clone().html().replace(/##ID##/gi,item.id).replace(/##NAME##/gi,item.name).replace(/##PRICE##/gi,price).replace(/##IMAGE##/gi,item.image).replace(/##GIFT##/,$("#gift_tmpl").clone().html());
					}
					else{
						add = $("#item_tmpl").clone().html().replace(/##ID##/gi,item.id).replace(/##NAME##/gi,item.name).replace(/##PRICE##/gi,price).replace(/##IMAGE##/gi,item.image).replace(/##GIFT##/,'');
					}	
				}
				items=items+add;
			});
			if(items){
				html = html+items+"</ul>";
			}
			else{
				html = "<h3 style='margin-left:15px;'>Ничего не найдено</h3>";
			}
			$(".cat-list").html(html);

			var pages = "";
			for (i = 1; i <= data['pages']; i++){
  				pages = pages+"<a class='"+i+"' href='#"+i+"' onclick=\"set_param('page',this)\">"+i+"</a>";
			}

			$("#page_selector").html(pages);
		
		}
	);
	load_filter_brands();
	
}


function load_filter_tags(){

	$.getJSON("/ajax/ifilter",{
			brand:$("#brand_id").text(),
			type:"get_tags",
			cat_id:p_cat_id
		},
        function(data){
			var html = '<a href="#0" class="0" onclick="set_param(\'tags\',this)">Не учитывать</a>';
	        $.each(data['items'], function(i,item){
				html = html+'<a href="#'+item.tag_id+'" class="'+item.tag_id+'" onclick="set_param(\'tags\',this)">'+item.tag_name+'</a>';
			});
			$("#tags_selector").html(html);
		}
	);
}

function load_filter_brands(){
	$.getJSON("/ajax/ifilter",{
			cat_id:p_cat_id,
			type:"get_brands"
		},
        function(data){
			var html = '<a href="#0" class="0" onclick="set_param(\'brand\',this)">Не учитывать</a>';
			$.each(data['items'], function(i,item){
				html = html+'<a href="#'+item.id+'" class="'+item.id+'" onclick="set_param(\'brand\',this)">'+item.name+'</a>';
			});
			$("#brand_selector").html(html);

		
		}
	);
}

function set_param(type,self){
	$("#"+type+"_selector_block").hide();
	$("#"+type+"_name").text($(self).text());
	$("#"+type+"_id").text($(self).attr("class"));
	load_filter_tags();
	apply_filter();
}


function slider_init(){

	$('#slider').slider({
		range: true,
		min: minp,
		max: maxp,
		values: [minp, maxp],
		slide: function(event, ui) {
			$(".in-left").val(ui.values[0]);
			$(".in-right").val(ui.values[1]);
		},
		stop: function(event, ui) {
			$(".in-left").val(ui.values[0]);
			$(".in-right").val(ui.values[1]);
			apply_filter();
		}
	});
	
	$(".in-right").val(maxp);
	$(".in-left").val(minp);

	$(".in-right").bind("change",function(){
		apply_filter();
	});

	$(".in-left").bind("change",function(){
		apply_filter();
	});

	$("#slider a:first").addClass('sli-left-take').css("margin-top","-4px");
	$("#slider a:last").addClass('sli-right-take').css("margin-top","-4px");
	$("#slider div").addClass('sli-active').css("margin-top","-4px");
	$("#slider").addClass('sli').css("margin-top","4px");

}
*/

////##### FILTER

////##### LOGGER
jQuery.fn.log = function (msg) {
  console.log("%s: %o", msg, this);
  return this;
};
////##### LOGGER

/////### HEADER

function shead(){
		var state = $.cookie('header');
		if(state == 1){
			$('.header').slideUp();
			$('.closetop a').css("background","url(http://img.100-tovarov.ru/images/topline.png)  no-repeat 0 -109px").text('Развернуть основное меню')
			$.cookie('header', 0, {domain: "100-tovarov.ru",path: "/"});
		}else{
			$('.header').slideDown();
			$('.closetop a').css("background","url(http://img.100-tovarov.ru/images/topline.png) no-repeat 0 -90px").text('Свернуть основное меню')
			$.cookie('header', 1, {domain: "100-tovarov.ru",path: "/"});
		}
}

function hide_header(){
	var state = $.cookie('header');
	if(state == 0){
		$('.closetop a').css("background","url(http://img.100-tovarov.ru/images/topline.png)  no-repeat 0 -109px").text('Развернуть основное меню');
		$('.header').hide();
	}else{
		$('.closetop a').css("background","url(http://img.100-tovarov.ru/images/topline.png)  no-repeat 0 -90px").text('Свернуть основное меню');
		$('.header').show();
	}
}
///##HEADER


///##ADV

function show_ad(ad){
	$.getJSON("/ajax/",{
			s:ad,
			c:p_cat_id,
			type: "adv"
		},
        function(data){
			if(data){
		        $.each(data['items'], function(i,item){
					if(item.image){
						$("#"+ad).html("<a href='"+item.url+"'><img src='http://img.100-tovarov.ru/images/p/"+item.image+"' width='59' height='39' alt='"+item.title+"' title='"+item.title+"' /></a>");
					};
				});
			};
		}
	);
}

///##ADV
