imgs = new Array();
imgs[0] = new Image();
imgs[0].src = '/images/wait.gif';
imgs[1] = new Image();
imgs[1].src = '/images/checkbox.gif';
imgs[2] = new Image();
imgs[2].src = '/images/free_delivery.gif';
imgs[3] = new Image();
imgs[3].src = '/images/fon02.gif';
imgs[4] = new Image();
imgs[4].src = '/images/fon10.gif';
imgs[5] = new Image();
imgs[5].src = '/images/fon11.gif';
$(document).ready(function () 
{
	var options = {};

	$(".tree .stylized_select :input").live('change', function () 
	{
		$(this.children).each(function () {
			if(this.selected) item_val = $(this).text();
		});
		itval = item_val.substr(1);
		$(this).parent().find('em').text(itval);
	});
	//очистка в корзине
	$("#basket .allreset").click(function () 
	{
		$('#wheelbas').html("<img src='/images/nowheel.gif' width='66' height='66' border='0' alt='' align='left'><strong>Не забудьте купить диски</strong>");
		$('#tyrebas').html("<img src='/images/notyre.gif' width='66' height='66' border='0' alt='' align='left'><strong>Не забудьте купить шины</strong>");
//		$.cookie("isbasket", null); // Удаляем куки шин
		delCookie("isbasket");
		return false;
	});
	//плюс-минус в корзине
	$(".minus").live('click', function () 
	{
		countblock = $(this).parent().find('input');
		cnt = (countblock.val()) * 1 - 1;
		if(cnt >= 0)
		{
			price = $(this).parent().parent().find('b b').text();
			sum = cnt * price;
			$(this).parent().parent().find('.itog').find('u').text(sum);
			countblock.val(cnt);
			is_wheels = ($(this).attr("stp")) ? 1 : 0;
			//меняем куку
			getpmcook(cnt,is_wheels);
		}
	});
	$(".plus").live('click', function () 
	{
		countblock = $(this).parent().find('input');
		cnt = (countblock.val()) * 1 + 1;
		price = $(this).parent().parent().find('b b').text();
		sum = cnt * price;
		$(this).parent().parent().find('.itog').find('u').text(sum);
		countblock.val(cnt);
		is_wheels = ($(this).attr("stp")) ? 1 : 0;
		//меняем куку
		getpmcook(cnt,is_wheels);
	});

	$(".tree i").click(function () 
	{
		if (!$(this).parent().find('#free_delivery').is('div')) 
		{
			var item_wid = $(this).parent().width() - 310;
			$(this).parent().append('<div id=free_delivery><p>БЕСПЛАТНО по Нижнему Новгороду и любых партий товара до точки выдачи по адресу ул.Рыбинская, 65.</p><p>ПЛАТНО  за  300  рублей  менее  4-х единиц товара или товар стоимостью менее 6000 рублей.</p></div>').show();
			var free_delivery = $('#free_delivery');
			free_delivery.css({'top' : 356 , 'left' : item_wid}).show();
		}
		else
		{
			$('#free_delivery').show();
		}

	}).parent().bind("mouseleave", function() 
	{
		var free_delivery = $('#free_delivery');
		free_delivery.hide();
	});

	$(".parent li").click(function () 
	{
		//var offset = $(this).offset();
		var $item = $(this).find('ul');
		var $items = $('#autolist .menu ul li ul');
		$items.hide();
		//$item.css({'top' : offset.top}).show();
		$item.show();
		delCookie("isbasket"); // Удаляем куки шин и дисков
	}).parent().parent().parent().bind("mouseleave", function() 
	{
		var $items = $('#autolist .menu ul li ul');
		$items.hide();
	});

	$('#choice').click(function() 
	{
		$(this).parent().parent().parent().find('.spec').addClass("auto_hide");
		$(this).parent().parent().parent().find('#autolist').removeClass("auto_hide");
	});

	$('#basdelivery','#sel_block').change(function() 
	{
		var formsam = $('#samovyvoz');
		if(formsam.is(':selected'))
		{
			$('#address').val('Рыбинская, 65').attr('readonly', true);
		}
		else
		{
			$('#address').val('').attr('readonly', false);
		}
	});

	$('#autolist span').click(function() 
	{
		spec_id = $(this).attr("id");
		$('.wrap').find('#autolist').addClass("auto_hide");
		act_id = '#act'+spec_id;
		$(act_id).removeClass("auto_hide");
		$(act_id).addClass("spshow");
	});
//	$('#wrap').bind("mouseleave", function() { var $items = $('#autolist .menu ul li ul'); $items.hide();	});

	// переключатель шин и дисков
	$("#selwheels").live('click', function () 
	{
		if($(this).hasClass('buttons2'))
		{
			var temp = $('#selector').html();
			$('#selector').html($('#wheels_block').html());
			$('#wheels_block').html(temp);
			$(this).removeClass('buttons2');
			$("#seltyres").addClass('buttons2');
			$(this).parent().parent().find('span').text('Подбор дисков для знающих размер');
		}
	});
	$("#seltyres").live('click', function () 
	{
		if($(this).hasClass('buttons2'))
		{
			var temp = $('#wheels_block').html();
			$('#wheels_block').html($('#selector').html());
			$('#selector').html(temp);
			$(this).removeClass('buttons2');
			$("#selwheels").addClass('buttons2');
			$(this).parent().parent().find('span').text('Подбор шин для знающих размер');
		}
	});

	// покупка из хитов продаж
	$('.toBasket').one('click', function() 
	{
		if (!$(this).attr("basket"))
		{
			is_wheels = ($(this).attr("stp")) ? 1 : 0;
			$(this).addClass("inbasket");
			cur_id = $(this).attr("id");

			var getcook = getCookie("isbasket");
			var pos_cookie = (getcook) ? getcook.split(":") : "";
			if(is_wheels)
			{
				cur_idt = (pos_cookie[0]) ? pos_cookie[0] : 0;
				countt = (pos_cookie[1]) ? pos_cookie[1] : 0;
				cur_idw = cur_id;
				countw = 4;
			}
			else
			{
				cur_idw = (pos_cookie[2]) ? pos_cookie[2] : 0;
				countw = (pos_cookie[3]) ? pos_cookie[3] : 0;
				cur_idt = cur_id;
				countt = 4;
			}
			cookitem = cur_idt + ":" + countt + ":" + cur_idw + ":" + countw;
			setCookie('isbasket', cookitem, 24);// Устанавливаем куки
			window.location = $(this).parent().attr("href");
		}
	});

	//узнать скидку
	$("#discount").bind('click', function () 
	{
		var card = "", parent_block = "";
		parent_block = $(this).parent();
		card = parent_block.find('.disc_input').val();
		if(card)
		{
			$.ajax(
			{
				url: '/service/cards.php',
				dataType: 'json',
				cache: false,
				data: ({'card' : card }),
				success: function (data) 
				{
					var jsonData = eval(data);

					var emp = jsonData.emp;

					if (emp > 0)
					{
						parent_block.find('b').remove();
						parent_block.append('<b>' + jsonData.discount + '</b>');
						parent_block.find('span').text('Узнай свою скидку');
					} 
					else
					{
						parent_block.html('<span>Ваша скидка по карте</span><em>' + jsonData.discount + '</em>');
//						parent_block.find('span').text('Скидка по карте - ' + jsonData.discount + ' ');
						parent_block.find('b').remove();
					}
				}
			});
		}
	});

	// очистка подбора шин
	$("#selector :reset").live('click', function () 
	{
		var str = "", input_names = "";
		stype = conti = first = 0;
		stype = ($("#seltyres").hasClass("buttons2")) ? 1 : 0;

		str = (stype) ? "0:0,1:0,2:0,3:0,4:0,5:0" : "0:0,1:1,2:0,3:0,4:0";
		str_key = (stype) ? "0:counthole,1:pcd,2:diameter,3:typec_1,4:typec_2,5:typec_3" : "0:seasonc_2,1:seasonc_1,2:width,3:height,4:diameter";
		input_names = (stype) ? '0:Кол. отв.,1:PCD,2:Диаметр,3:Ков.,4:Литые,5:Штамп' : '0:Лето,1:Зима,2:Ширина,3:Высота,4:Диаметр';

		surl = (stype) ? '/service/wheels.php' : '/service/tyres.php';
		$('#vitrina_loader').show();
		$.ajax(
		{
			url: surl,
			dataType: 'json',
			cache: false,
			data: ({'str' : str, 'str_key' : str_key, 'conti' : conti, 'first' : first, 'input_names' : input_names, 'onmain' : 1 }),
			success: function (data) 
			{
				var jsonData = eval(data);

				$('#selector').html(jsonData.sels);
				$('#vitrina_loader').hide();
			}
		});
	});

	// подбор шин
	$("#selector :input").live('change', function () 
	{
		var item = this;
		var str = "", str_key = "", first = "", input_names = "";
		var	wait_div = $('#vitrina_loader').html();
		i = 0, stype = 0;
		$("#selector :input").each(function () 
		{
			if($(this).attr('id'))
			{
				temp_str = sel_key = tmp_first = x = "";
				temp_str = ($(this).is(':radio') || $(this).is(':checkbox')) ? is_checked(this) : check_option(this);
				if (i)
				{
					str = str + ",";
					str_key = str_key + ",";
					first = first + ",";
					input_names = input_names + ",";
				}
				str = str + i + ":" + temp_str;
				sel_key = $(this).attr('id');
				str_key = str_key + i + ":" + sel_key;

				tmp_first = ($(this).is(':radio') || $(this).is(':checkbox')) ? ((i==1) ? 'Зима' : 'Лето') : $(this.children).filter('option:first').text();
				first = first + i + ":" + tmp_first;
				x = ($(this).is(':radio') || $(this).is(':checkbox')) ? $(this).parent().find('i').text() : $(this).parent().parent().find('i').text();
				input_names = input_names + i + ":" + x;
				
				i++;
			}
		});

		conti = $(item).attr('id'); // выбранный input
//		alert (str + ' - ' + str_key + ' - ' + first + ' - ' + conti + ' - ' + input_names);

		if(str)
		{
			stype = ($("#seltyres").hasClass("buttons2")) ? 1 : 0;
			surl = (stype) ? '/service/wheels.php' : '/service/tyres.php';
//			$('#selector').html(wait_div);
			$('#vitrina_loader').show();
			$.ajax(
			{
				url: surl,
				dataType: 'json',
				cache: false,
				data: ({'str' : str, 'str_key' : str_key, 'conti' : conti, 'first' : first, 'input_names' : input_names, 'onmain' : 1 }),
				success: function (data) 
				{
					var jsonData = eval(data);

					$('#selector').html(jsonData.sels);
					$('#vitrina_loader').hide();
				}
			});
		}
	});

	function check_option(item) 
	{
		$(item.children).each(function () {
			if(this.selected) item_val = $(this).val();
		});
		return item_val;
	}

	function is_checked(item) 
	{
		item_val = 0;
		if(item.checked) 
		{
			item_val = $(item).val();
		}
	//		alert (item_val);
		return item_val;
	}
	// подбор шин

	function getpmcook(cnt,is_wheels) 
	{
		var getcooki = getCookie("isbasket");
//		alert (getcooki);
		pos_cookie = (getcooki) ? getcooki.split(":") : "";
		if(is_wheels)
		{
			cur_idt = (pos_cookie[0]) ? pos_cookie[0] : 0;
			countt = (pos_cookie[1]) ? pos_cookie[1] : 0;
			cur_idw = (pos_cookie[2]) ? pos_cookie[2] : 0;
			countw = cnt;
		}
		else
		{
			cur_idt = (pos_cookie[0]) ? pos_cookie[0] : 0;
			cur_idw = (pos_cookie[2]) ? pos_cookie[2] : 0;
			countw = (pos_cookie[3]) ? pos_cookie[3] : 0;
			countt = cnt;
		}
		cookitem = cur_idt + ":" + countt + ":" + cur_idw + ":" + countw;
//		alert (cookitem);
		setCookie('isbasket', cookitem, 24); // Меняем куки шин или дисков
		sumw = ($('#wheelbas .itog').find('u')) ? $('#wheelbas .itog').find('u').text() : 0;
		sumt = ($('#tyrebas .itog').find('u')) ? $('#tyrebas .itog').find('u').text() : 0;
		sum = sumw*1 + sumt*1;
		discout_tyres = discout_wheels = 0;

		discout_tyres = $('#discout_tyres').val();
		discout_wheels = $('#discout_wheels').val();
		dissumma = (sumt * (100 - discout_tyres))/100 + (sumw * (100 - discout_wheels))/100;
		dissumma = Math.round(dissumma);

		if (dissumma == sum)
		{
			$('#order').html('Сумма заказа: ' + sum + ' руб.');
		}
		else
		{
			$('#order').html('Сумма заказа: ' + sum + ' руб.<u>Сумма со скидкой: ' + dissumma + ' руб.</u>');
		}
		
		deliv = 'Платная доставка &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;с 12 до 18 – 300р';
		if(((countw*1 + countt*1) >= 4) && (sum >= 6000))
		{
			deliv = "Бесплатная доставка с 12 до 18";
		}
		var formdel = $('#formdelivery');
		formdel.html(deliv);
		if(formdel.is(':selected'))
		{
			formdel.parent().parent().find('#pay_show').html(deliv);
		}
	}

});

function getCookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + "=");
		if (start != -1) {
			start = start + name.length + 1;
			var end = document.cookie.indexOf(";", start);
			if (end == -1) end = document.cookie.length;
			return document.cookie.substring(start, end);
		}
	}
	return "";
}

function setCookie(name, value, days, path) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=" + (path ? path : "/");
}
function delCookie(name) {
	setCookie(name, "", -1, "/");
}


