//Корзина
//@author wiz <wiz@kerpc.ru>
//@version 2.5
//
//В куке 'cart' хранится строка с текущим заказом в виде "id=quantity=price|id=quantity=price"
//tr с элементами относящимися к одному товару должна иметь name равный id товара, либо другому уникальному полю товара.
//В той же tr находится span с классом price, содержащий цену товара,
//а так же input с классом quantity для ввода количества товара для заказа.
//нажатие на .order - добавление в корзину (альтернативно - при изменении значения в поле количества, строка 36). Если есть класс rettrue - вернёт true.
//.cart_calc - принудительно пересчитывает корзину (пробегается по всем количествам в таблице) и удаляет строки с input.chdel:checked
//div.cart - строка с информацией о корзине
//. cart_clear - элемент управления, очищающий корзину
// span.carttotal - общая цена корзины

var cart = '';

$(document).ready(function() {
	//загружаем кук с корзиной
	cart = getCookie('cart');
	if (!cart) {
		cart = '';
	}
	
	//пересчитываем всё
	recalc();
	
	//фильтр нажатий кнопок в полях ввода количества
	$("input.quantity").bind("keypress", function(e) {
		var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);
		if (e.ctrlKey || e.altKey || key < 32)
			return true;
		key = String.fromCharCode(key);
		return /\d/.test(key);
	});
	
	//в корзину добавляем 
	//$("input.quantity").bind("keyup", function(e) { //поменялось значение в форме
	$(".order").click(function() { //нажали "добавить в корзину"
		tr = $(this).parents("tr");

		id = $(tr).attr("name");
		//quantity = this.value;
		quantity = $("input.quantity", tr).attr("value");
		price = $("span.price", tr).html();
		
		cartadd(id, quantity, price); //добавляем в корзину
		
		recalc(); //пересчитываем всё
		
		if ($(this).hasClass("rettrue")) return true;
		else return false;
	});
	
	$(".cart_calc").click(function() {
		$("input.quantity").each(function() { //пробегаем по всем строкам
			tr = $(this).parents("tr");
			id = $(tr).attr("name");
			quantity = $("input.quantity", tr).attr("value");
			price = $("span.price", tr).html();
			cartadd(id, quantity, price); //добавляем в корзину
		});
		recalc(); //пересчитываем всё
		return false;
	});
	
	//по данным из корзины заполним поля с количеством на текущей странице
	$.each( cart.split('|'), function(i, n){
		if (n) {
			it = n.split('=');
			if (it[1] > 0) {
				//alert(it[0]);
				$('tr[name="'+it[0]+'"] input.quantity').val(it[1]);
			}
		}
	});

	//кнопка очистка карзины
	$(".cart_clear").click( function() {
		deleteCookie('cart');
		$("input.quantity").val(''); //очищаем поля на форме
		cart = '';
		recalc();
		return false;
	});
	
	//удаление из корзины
	$(".cart_calc").click( function() {
		$("input.chdel:checked").each( function(i, n) {
			tr = $(this).parents("tr");
			id = $(tr).attr("name");
			//удаляем строку таблицы (если бы не ie6, было бы tr.css)
			tr.children("td").css("background", "#dd6666").fadeOut("slow", function(){
				$(this).remove();
				/*$("table.catalog").each( function(){
					//alert($("tr", this).length);
					if ($("tr", this).length == 1) {
						this.remove();
					}
				});*/
			});
			//удаляем из куков
			cartdel(id);
		});
		recalc();
		return false;
	});

	//подсветка поиска
	var string = location.search;
	var id = string.substring (1, string.length);
	id = id.match(/h=([^&]+)/);
	if (id) {
		id = id[1];
		$("tr[name="+id+"] td").css('background', '#fff8bf');
	}


})

function cartdel(id) {
	//ищем, есть ли такой в куке корзины и удаляем его
	$.each( cart.split('|'), function(i, n) {
		if (n) {
			it = n.split('=');
			if (it[0] == id) {
				cart = cart.replace(n+'|', '');
			}
		}
	});
	setCookie('cart', cart);
}

function cartadd(id, quantity, price) {
	
	//ищем, есть ли такой уже в корзине
	flag = false; //флаг - такого нет в корзине
	price = price.replace(',', '.');//запятые на точки
	price = price.replace(/[^0-9.]/g, ''); //убираем всяку хрень
	price = price.replace(/\.$/, ''); //убираем точку с конца
	
	$.each( cart.split('|'), function(i, n) {
		if (n) {
			it = n.split('=');
			if (it[0] == id) {
				if (quantity == 0) { //надо удалить из корзины
					cart = cart.replace(n+'|', '');
				} else {
					cart = cart.replace(n, id + "=" + quantity + "=" + price); //заменяем количество
				}
				flag = true;
			}
		}
	});
	if (!flag) {
		cart += id + '=' + quantity + "=" + price + '|';
	}

	setCookie('cart', cart);
}

function recalc() {
	if (!cart || cart=='') {
		setCookie('totalnum', 0);
		setCookie('total', 0);
		$("div.cart").html('В вашей корзине: 0 товаров <span>/</span> <span class="fn">Итого: <span>0</span></span>');
		$("span.carttotal").html('0');
		return;
	}
	total = 0;
	totalnum = 0;
	$.each( cart.split('|'), function(i, n){
		if (n) {
			it = n.split('=');
			total += it[1] * it[2].replace(',', '.');
			if (parseInt(it[1])>0) totalnum += parseInt(it[1]);
			t = it[1] * it[2].replace(',', '.');
			//alert(Math.round(t*100)/100);
		}
	});
	total = Math.round(total*100)/100;
	if (total <= 0) {
		setCookie('totalnum', 0);
		setCookie('total', 0);
		$("div.cart").html('В вашей корзине: 0 товаров <span>/</span> <span class="fn">Итого: <span>0</span></span>');
		$("span.carttotal").html('0');
	} else {
		setCookie('totalnum', totalnum);
		setCookie('total', total);
		
		$("div.cart").html("<a href='cart'>Редактировать корзину (оформить заказ)</a> <span>/</span> В вашей корзине:  "+totalnum+" товаров <span>/</span> <span class='fn'>Итого: <span>"+total+"</span></span>");
		$("span.carttotal").html(total);
	}
}

function emptycart() {
	deleteCookie('cart');
	$("input.quantity").val(''); //очищаем поля на форме
	cart = '';
	recalc();
}

function getCookie( 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 setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
	( ( expires ) ? ';expires='
	+expires_date.toGMTString() : '' ) +
	( ( path ) ? ';path=' + path : ';path=/' ) +
	( ( domain ) ? ';domain=' + domain : '' ) +
	( ( secure ) ? ';secure' : '' );
	//alert(name+'='+escape( value ) +( ( expires ) ? ';expires='	+expires_date.toGMTString() : '' ) +( ( path ) ? ';path=' + path : ';path=/' ) +( ( domain ) ? ';domain=' + domain : '' ) +( ( secure ) ? ';secure' : '' ));
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) setCookie (name, '', 'Thu, 01-Jan-1970 00:00:01 GMT');
	/*
	if ( getCookie( name ) ) document.cookie = name + '=' +
	( ( path ) ? ';path=' + path : '') +
	( ( domain ) ? ';domain=' + domain : '' ) +
	';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	*/
 }


