/*

 Cookie-based SoppingCart script v.3.0
 ▐ервый автор  - Matevosyan Artem (zverek@nm.ru)
 ▐оследний автор - Тульский ┬горь (tigor@wm.ru)

 Usage:

	<input type="button" value="addItem"		onclick="cart.addItem('unique_id', 'Text Name', 'price', 'quantity', 'item_rub', 'more_args1', 'more_args2', ...);">
	<input type="button" value="editQuantity"	onclick="cart.editQuantity('unique_id');">
	<input type="button" value="deleteItem"		onclick="cart.deleteItem('unique_id');">
	<input type="button" value="clear"			onclick="cart.clear();">

	<input type="checkbox" id="id[% item.id %]" onclick="return cart.ChangeItemStatus('[% item.id %]', '[% item.title | html %]' , '[% item.price %]', '1', '[% item.rub %]');">

	Dynamic text string:

	<body onload="OnLoadCartActions();">
	<span id="Cart_Counter"></span> //  можно поменЯть , но с заменой значениЯ переменной HtmlElementWithCounter

  ┌ерсиЯ v3.0
  ^3.0
  + ░елиз
  * ┬справлениЯ позже опишу...*

 Version 2.xx history:
	^2.0.1
	+ add "don't ask" feature to clear method; call cart.clear(1); to void confirmation;
	^2.0
	+ Release
	* Moved to object oriented style
	* Fixed using '&' and '|' in args problem

 Version 1.xx history
	^1.05
	* Fixed some bugs in clearCart() finction
	+ Added cookie exiration date
	^1.04
	* Added confirm dialog to deleting an item from cart
	* Commented getCookie function deleted
	* Optimized add2cart function: precisely the statement determining the item existance. If the
	  item already ordered?
	^1.03
	* Fixed getCookie function. There was an error getting the cookie text. Therefore the algorithm
	  was replaced by another one using regexp to locate the cookie. The old getCookie function
	  commented. Anyway it doesn't work :)
	* Multi argumential add2cart function, you can now provide additional arguments
	  to your cart. In addition to id, name, price and quantity you may use i.e. description
	  or picture id. This information also will be saved in cookie. The only condition of using
	  additional args is they can not contain '&' or '|' as this will ruin the cookie structure
	^1.02
	+ CountGoods function showing the number of goods in shopping cart
	+ Usage script respective to russian literal count bendings
	* Fixed getCookie(): added no cookie defined case
	^1.01
	+ Editing goods quantity support
	+ Delting goods support
	^1.00
	+ Release

  Known bugs:

	# The checkCookieSupport() function doesn't work

*/


//  ===============================    CONFIG    ==================================

// Добавление в корзину происходит по нажатии на 'checkbox' ┬▀┬ 'button'. ²то и задаем.
var data_type = 'checkbox'; 

// █а обычной странице каталога:
var confirm_adding_on_COMMON_page	= false; // ▐одтверждать добавление?
var confirm_deleting_on_COMMON_page	= false; // ▐одтверждать удаление?
// █а странице оформлениЯ заказа:
var confirm_deleting_on_ORDER_page	= false; // ▐одтверждать удаление?
																	   // └обавлениЯ нет на странице оформлениЯ заказа 

// id ²лемента, в котором выводим количество товаров
var HtmlElementWithCounter  = 'Cart_Counter';


//  ============================    SOME TECH PRESETS    =============================																	   

// Change this with changing WMcart.pm!!!
var cname = 'WM_Eshop'; // cookie name used to store order data 
//var Items_SplitStr = "|it|"; 		
//var ItemFields_SplitStr = "|fi|";
var Items_SplitStr = "i";
var ItemFields_SplitStr = "f";


var ORDER_PAGE;


//  ===============================    MAIN CODE    ==================================

// Cart object
function Cart () {
	this.Items = new Array;
	this.init();
}

// init
Cart.prototype.init = function () {
	if(!checkCookieSupport()) return alert('Чтобы сделать заказ онлайн, включите поддержку Cookies в вашем браузере')
	string = document.cookie; re= new RegExp(cname+'(=([^;]+))?;?'); rear = re.exec(string); if (rear) ctxt = rear[2];
	else ctxt = false; if (ctxt) this.Items = splitCookie(ctxt); //alert(document.cookie); //alert(ctxt);
}

// isItemExists
Cart.prototype.isItemExists = function ( uniqueId ) {
	var found_id = -1; for( i=0; i<this.Items.length; i++ ){ if ( uniqueId
	== this.Items[i].uniqueId ) { found_id = i; break; }} return found_id;
}

// addItem
Cart.prototype.addItem = function ( itemUniqueId, itemQuantity ) {
	var OperationCompleted = false;
	var add_it = true;

	var moreArgs = new Array;
	for ( i=5; i<arguments.length; i++ ) {
		moreArgs.push( arguments[i] );
	}

	// Checking input
	if ( itemQuantity.search(/^\d+$/) == -1 || itemQuantity < 1 || itemQuantity > 9999 ) return alert('┌ведите количество')

	// ┤апрашиваем подтверждение, если оно нужно.
	if( !ORDER_PAGE && confirm_adding_on_COMMON_page )
		add_it = confirm("Добавить "+itemName+", "+itemQuantity+" шт. в корзину?");
	if ( add_it ){ 
		var t = this.isItemExists(itemUniqueId);
		if (t > -1) this.Items[t].quantity = parseInt(itemQuantity)	+ parseInt(this.Items[t].quantity);
		else this.Items.push( new CartItem(itemUniqueId, itemQuantity) );
		//alert('▓овар добавлен');
		OperationCompleted = true;
		this.save();
	}
	cart.refreshCount();
	return OperationCompleted;
}

// editQuantity
Cart.prototype.editQuantity = function ( uniqueId, newqty ) {
	var t = this.isItemExists(uniqueId)
	if (t > -1) {
		this.Items[t].quantity = newqty
		this.save();
	}
	cart.refreshCount();
}

// deleteItem
Cart.prototype.deleteItem = function ( uniqueId ){
	var OperationCompleted = false;
	var delete_it = true;
	var t = this.isItemExists(uniqueId)
	if (t > -1){
		if( (!ORDER_PAGE && confirm_deleting_on_COMMON_page) || (ORDER_PAGE && confirm_deleting_on_ORDER_page) )
			delete_it = confirm('Удалить '+ this.Items[t].name +' из корзины?');
		if(delete_it){
			this.Items.splice(t,1)
			this.save();
			//alert('▓овар удален из корзины');
			OperationCompleted = true;
			// commented 10dec2006
			//if(ORDER_PAGE) window.location = window.location;			
		}
	} else { 
		alert('Ошибка! Неверный идентификатор!');
	}
	cart.refreshCount();
	return OperationCompleted;
}

// countTItems
Cart.prototype.countTItems = function () {
	return this.Items.length;
}

// countTQuantity
Cart.prototype.countTQuantity = function () {
	var totalqty = 0; for( i=0; i<this.Items.length; i++ ){
	totalqty += Number( this.Items[i].quantity ); }
	return totalqty;
}

// clear
Cart.prototype.clear = function ( dontask ) {
	if ( !dontask ){
		if( !confirm('Вы уверены, что хотите очистить корзину?') ) return;
	}
	this.Items = new Array();
	this.save();
	//alert('Корзина очищена')
	window.location = window.location
}

// save
Cart.prototype.save = function () {
	var items = new Array;
	for( i=0; i<this.Items.length; i++ ){
		//var ci = this.Items[i];	items[i] = new Array( ci.uniqueId,
		//	ci.name, ci.price, ci.quantity, ci.rub ).concat( ci.moreArgs ).join(ItemFields_SplitStr); }
		var ci = this.Items[i];
		items[i] = new Array( ci.uniqueId, ci.quantity ).join(ItemFields_SplitStr);
	}
	var es = new Date(); es.setTime(es.getTime() + 365*24*60*60*1000);
	document.cookie = cname + '=' + items.join(Items_SplitStr) + '; '+
	'expires=' + es.toGMTString() + '; ' + 'path=/'
}

// CartItem object
function CartItem ( uniqueId, quantity ) {
	this.uniqueId = uniqueId;
	this.quantity = quantity;
}

// Change Item's status in Cart - add or delete
Cart.prototype.ChangeItemStatus = function (itemUniqueId, itemQuantity){
	var OperationCompleted = false;

	if(document.getElementById('id' + itemUniqueId).checked) {
		OperationCompleted = cart.addItem(itemUniqueId, itemQuantity);
	} else {
		OperationCompleted = cart.deleteItem(itemUniqueId);
	}
	return OperationCompleted;
}

// ▐ри загрузке странице устанавливаем данные
Cart.prototype.initData = function(){
    for( i=0; i<this.Items.length; i++ ) {
		var item = this.Items[i];

		c_e = document.getElementById('id' + item.uniqueId); // Checking Element
		if( c_e ) { // если есть такой элемент на странице
			if(data_type == 'checkbox'){
				c_e.checked = true;
			}
		}
		
		item_qty = document.getElementById('qty' + item.uniqueId); // Checking Element
		if( item_qty ) { // если есть такой элемент на странице
			if(data_type == 'checkbox'){				
				item_qty.value = item.quantity;
			}
		}
    }
}

// ▌бновлЯем счетчик с количеством товаров
Cart.prototype.refreshCount = function(){
	c = cart.countTQuantity();
	cs = new String(c);
	x = c;
	cs = new Number(cs.substring(cs.length-1,1));
	if (cs == 1) x+=' товар';
		else if (cs >= 2 && cs <= 4) x+=' товара'; 
			else x+=' товаров';
	document.getElementById(HtmlElementWithCounter).innerHTML  = x;
}



Cart.prototype.OrderListCheck_and_Recalculating = function(){
	var recalculate_error = false;

	// проверка заполненности полей
	for(var i in this.Items) {
		good_qty = check_good_qty(this.Items[i].uniqueId);
		if( !good_qty ){
			recalculate_error = true;
			break;
		} else
			cart.editQuantity(this.Items[i].uniqueId, good_qty);
	}

	if(	!recalculate_error ){		
		for(var i in this.Items) {
			del_id = document.getElementById('del' + this.Items[i].uniqueId);
			if( del_id && del_id.checked )
				cart.deleteItem(this.Items[i].uniqueId);
		}
	}
	return !recalculate_error;
}


function check_good_qty( id ){
	input_qty_id = document.getElementById('qty' + id);
	if( input_qty_id ){
		if( !(input_qty_id.value.search(/^\d+$/) != -1 && input_qty_id.value > 0) ) {
			alert('Неверно указано количество товара!');
			input_qty_id.focus();
			return false;
		} else
			return input_qty_id.value;
	} else {
		alert('Неверный идентификатор поля! Проверка невозможна');
		return false;
	}
}












// UTILS
// splitCookie
function splitCookie(str){
	var items = str.split(Items_SplitStr);
	var fields = new Array();
	var ret = new Array();
	for( i=0; i<items.length; i++){
		fields = items[i].split(ItemFields_SplitStr);
		ret.push( new CartItem( fields[0], fields[1] ) )
	}
	return ret;
}

// checkCookieSupport
function checkCookieSupport(){
	return true 
}


// ==============================================================================  //

function OnLoadCartActions(){
	if(data_type == 'checkbox') cart.initData(); // установка данных
	cart.refreshCount();								   // обновление счетчика
}


var cart = new Cart;
