/*

 Cookie-based SoppingCart script v.2.0.1
 by Matevosyan Artem (zverek@nm.ru)

 Usage:

	<script>
		var cart = new Cart;
	</script>

	<button onclick="cart.addItem('unique_id', 'Text Name', 'price', 'quantity', 'more_args1', 'more_args2', ...)">addItem</button>
	<button onclick="cart.editQuantity('unique_id')">editQuantity</button>	
	<button onclick="cart.deleteItem('unique_id')">deleteItem</button>	
	<button onclick="cart.clear()">clear</button>

	Dynamic text string:

	<body onload="refreshCount()">
	<script>function refreshCount() { 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+=' товаров'; w(x); } function w (t) {
	document.getElementById('countGoodsDiv').innerHTML = t; } </script>
	<span id="countGoodsDiv"></span>


 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
//

// Please set the cookie name used to store order data
cname = 'KengurushaEshop';

//
// MAIN CODE
//

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

Cart.prototype.toString = function() {
    var tx = "";
	tx += "Cart now contains:\n\n";
	for ( i=0; i<this.Items.length; i++ ) {
		tx += (i+1)+"." +
			" " + this.Items[i].name + " " +
			" (" + this.Items[i].quantity + " шт. x " + this.Items[i].price + ") " +
			"\n";
	}
	return tx;
}

// 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, itemName, itemPrice, itemQuantity ) {
	
	var moreArgs = new Array;
	for ( i=4; i<arguments.length; i++ ) {
		moreArgs.push( arguments[i] );
	}

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

	// Are you sure?
	if ( confirm("Добавить "+itemName+", "+itemQuantity+" шт. в корзину?") ){ 
		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, '', itemPrice, itemQuantity, moreArgs) );
		//alert('Товар добавлен');
		this.save();
	}
}

// editQuantity
Cart.prototype.editQuantity = function ( uniqueId ) {
	var t = this.isItemExists(uniqueId)
	if (t > -1) {
		var newqty = prompt('Введите новое количество товара '+this.Items[t].name, this.Items[t].quantity)
		if (!newqty) return
		if (newqty.search(/^\d+$/) != -1 && newqty > 0){
			this.Items[t].quantity = newqty
			this.save();
			//alert('Количество изменено')
			window.location = window.location
		}else
			alert('Неверноый ввод\nКоличество НЕ изменено')
	}else
		alert('Ошибка! Неверный идентификатор!')
}

// deleteItem
Cart.prototype.deleteItem = function ( uniqueId ){
	var t = this.isItemExists(uniqueId)
	if (t > -1){
		if(confirm('Удалить '+ this.Items[t].name +' из корзины?')){
			this.Items.splice(t,1)
			this.save();
			//alert('Товар удален из корзины')
			window.location = window.location
		}
	}else
		alert('Ошибка! Неверный идентификатор!')
}

// 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 ).concat( ci.moreArgs ).join("|fi|"); }
	var es = new Date(); es.setTime(es.getTime() + 365*24*60*60*1000);
	document.cookie = cname + '=' + items.join("|it|") + '; '+
	'expires=' + es.toGMTString() + '; ' + 'path=/'
}

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

// UTILS
// splitCookie
function splitCookie(str){
	var items = str.split("|it|");
	var fields = new Array();
	var ret = new Array();
	for( i=0; i<items.length; i++){
		fields = items[i].split("|fi|");
		ret.push( new CartItem( fields[0], fields[1], fields[2], fields[3], fields.splice(4, fields.length-4) ) )
	}
	return ret;
}

// checkCookieSupport
function checkCookieSupport(){
	return true
}