//------------------------------------------------------------------
//	Title				Shopping Cart Script
//  Date 				21 November 2007
//  Author	 			Alexey Generalov [webradical]
//  Copyright	 		Ulter West
//------------------------------------------------------------------
//  Script constants
//------------------------------------------------------------------
	// Cookie settings
	Cart.prototype.COOKIE_DAYS = 4;
	Cart.prototype.COOKIE_NAME = "cartdata";
	Cart.prototype.COOKIE_NAME_HREF = "cartdatahref";
	
	//	Qunatity range
	Cart.prototype.QUANTITY_MIN_VALUE = 1;
	Cart.prototype.QUANTITY_MAX_VALUE = 10000;
	
	// Data settings
	Cart.prototype.ARTICUL_POSITION = 0;
	Cart.prototype.PRICE_POSITION_CATALOG = 5;
	Cart.prototype.PRICE_POSITION = 2;
	Cart.prototype.QUANTITY_POSITION = 3;
	Cart.prototype.SUMPRICE_POSITION = 4;
	Cart.prototype.DELBTN_POSITION = 5;
	Cart.prototype.VIEWBTN_POSITION = 6;	
	Cart.prototype.DATA_SEPARATOR = "|";   
	Cart.prototype.ORDER_COLUMN_SEPARATOR = "\t\t";
	Cart.prototype.ORDER_LINE_SEPARATOR = "\n";
	
	 
	// Cart settings
	Cart.prototype.SHOWCART_ID = "cart";
	Cart.prototype.SHOWCART_ORDERPRICE_ID = "orderprice";
	Cart.prototype.SHOWCART_DATAONLY_ID = "cartdataonly";
	Cart.prototype.SHOWCART_DATA_CONTAINER = "td";
	Cart.prototype.SHOWCART_GOODS_CONTAINER = "tr";
	Cart.prototype.SHOWCART_WRAPPER = "table";
	Cart.prototype.SHOWCART_CONTAINER = "tbody";
	
	Cart.prototype.GOODS_DEFINITION_RANGE = 2; 
	Cart.prototype.SHOWCART_EMPTY_MSG = "Корзина пуста";
	Cart.prototype.SHOWCART_GOODS_ATT = "Артикул|Название|Цена|Кол-во|Сумма||";
	
	// Cart informer settings
	Cart.prototype.INFORMER_QUANTITY_ID = "infquantity";
	Cart.prototype.INFORMER_SUMPRICE_ID = "infsumprice";

	//	Order form settings
	Cart.prototype.ORDER_SUBMIT_ID = 'ordersubmit'; 
	Cart.prototype.ORDER_FORM_ID = 'orderform';
	Cart.prototype.ORDER_HIDDEN_ID = 'hiddenfield';
	
	//Images
	Cart.prototype.IMAGE_VIEWBTN = '/images/view.gif';
	Cart.prototype.IMAGE_REMOVEBTN = '/images/delete.gif';
	
//------------------------------------------------------------------
	function Goods(data, quantity, price, href){
		this.data = (data == undefined) ? "" : data;
		this.quantity = (quantity == undefined) ? 1 : quantity;
		this.price = (price == undefined) ? null : price;
		this.href = (href == undefined) ? null : href;
	}

	function Cart(){this.goodsArr = new Array(); }

	Cart.prototype.getSumPrice = function(){
		var sum = 0;
		var killspaces = /^\s+|\s+$/g
		for (var i = 0; i < this.goodsArr.length; i++)
			sum += parseFloat(this.goodsArr[i].price) * parseInt(this.goodsArr[i].quantity);
		return sum.toFixed(2);
	}

	Cart.prototype.showInformer = function(){
		var q = document.getElementById(this.INFORMER_QUANTITY_ID);
		var s = document.getElementById(this.INFORMER_SUMPRICE_ID);
		
		
		if (q != undefined) q.firstChild.nodeValue = this.goodsArr.length;
		if (s != undefined) s.firstChild.nodeValue = this.getSumPrice();
	}
	
	Cart.prototype.getCookieID = function(data){
		var c = unescape(document.cookie).split(';');
		data = unescape(data);
		var rxp = /\d+/; 
		for (var i = 0; i < c.length; i++){

			if (c[i].indexOf(data) != -1) return parseInt(c[i].match(rxp));
		}
		return null;
	}
	
	
	Cart.prototype.getHREFCID = function(matchcid)
	{
	
		var data = document.cookie.split(';');		
		var reg = /(\s*cartdatahref\d{1,2}=\s*)/;
		var cid_reg = /\d{1,2}/;
		
		for (var i = 0; i < data.length; i++){
			if (data[i].match(reg) != null) { 
				var cid = parseInt(unescape(data[i]).match(cid_reg));
				
				if (cid == matchcid)
				{
												
				var href = unescape(data[i]).replace(reg, '');
				
				return href;
				}
				
				
				
			}
		}
		
		return '';
		
	}

	Cart.prototype.restoreCart = function(){
		this.goodsArr = new Array();
		if (document.cookie == '') {this.showCart(); this.showInformer(); return;}
	
		
		var data = document.cookie.split(';');
		var reg = /(\s*cartdata\d{1,2}=\s*)/;
		var cid_reg = /\d{1,2}/;
		
		for (var i = 0; i < data.length; i++){
			if (data[i].match(reg) != null) {
			
				var cid = parseInt(unescape(data[i]).match(cid_reg));
				var href= this.getHREFCID(cid);
				
				var str = unescape(data[i]).replace(reg, '');
				var str = str.split(this.DATA_SEPARATOR);
				var price = unescape(str[this.PRICE_POSITION]).replace(/\s/g, '');	  
				price = parseFloat(price);
				var q = str.pop(); 
				var tmp = new Goods(str.join(this.DATA_SEPARATOR), q, price, href);
				//alert("data: " + tmp.data + ", quantity: " +tmp.quantity + ", price: " + tmp.price + ", href: " + tmp.href);
				this.goodsArr.push(tmp);
			}
		}

		
		this.showInformer();
		if (document.getElementById(this.SHOWCART_ID))
			this.showCart();		
		
		if (document.getElementById(this.SHOWCART_DATAONLY_ID))
			this.showCart(true);
		
	}
	
	Cart.prototype.removeGoodsCID = function(cid){
		this.createCookie(this.COOKIE_NAME + cid, '', -1);
		this.createCookie(this.COOKIE_NAME_HREF + cid, '', -1);
	}
	
	Cart.prototype.removeGoods = function(obj){
		var data = this.getDataDOM(obj, 0);	 
		var cid = this.getCookieID(data);
		
		this.removeGoodsCID(cid);
		this.restoreCart();
	}
	
	Cart.prototype.clearCart = function(){
		for (var i= 0; i < this.goodsArr.length; i++){
			var cid = this.getCookieID(this.goodsArr[i].data);
			this.removeGoodsCID(cid);
		}
		
		var order = document.getElementById(this.SHOWCART_ORDERPRICE_ID);
		if (order != undefined){
			var text = document.createTextNode('0');
			order.replaceChild(text, order.firstChild);
		}
				
		this.restoreCart();
	}
	
	
	//	Set quantity of goods with @data and 
	Cart.prototype.setGoodsQuantity = function(data, quantity){
		if ((quantity < this.QUANTITY_MIN_VALUE) || (quantity > this.QUANTITY_MAX_VALUE)) {alert("The quantity is out of range [" + this.QUANTITY_MIN_VALUE + "-" + this.QUANTITY_MAX_VALUE + "]"); return null;}
		var data = unescape(data);
		var cid = this.getCookieID(data);
		
		this.createCookie(this.COOKIE_NAME + cid, data + this.DATA_SEPARATOR + quantity, this.COOKIE_DAYS);				
		
	}
	
	Cart.prototype.setUserQuantity = function(goods){
		var goods = goods.childNodes;
		var data = this.getDataDOM(goods, 0);
		
		var input = goods[this.QUANTITY_POSITION].firstChild;
		var test = input.value.match(/\D+/);
		
		if (test != null || input.value==''){
			alert("The quantity does not contain any non-digit characters. " + test);
			this.restoreCart();
			return;
		}
		
		this.setGoodsQuantity(data, parseInt(input.value));
		this.restoreCart();
	}
	
	//	Cart interfeice with 
	//	goods table, remove button, quantity field 
	Cart.prototype.showCart = function(){			
		var obj = arguments[0] ? document.getElementById(this.SHOWCART_DATAONLY_ID) : document.getElementById(this.SHOWCART_ID);
		if (obj == undefined) return;
		if (this.goodsArr.length == 0){
			var text = document.createTextNode(this.SHOWCART_EMPTY_MSG);
			obj.replaceChild(text, obj.firstChild);
			this.updateSumPrice();
			return; 
		}
		
		var att = this.SHOWCART_GOODS_ATT.split(this.DATA_SEPARATOR);
		var wrapper = document.createElement(this.SHOWCART_WRAPPER);
		//wrapper.setAttribute('class', 'tablelist');
		wrapper.className='tablelist';
		var container = document.createElement(this.SHOWCART_CONTAINER);
	
		for (var i = 0; i < (this.goodsArr.length + 1); i++){
			
			var goods = document.createElement(this.SHOWCART_GOODS_CONTAINER);
			
			if (i != 0) {
				var att_value = unescape(this.goodsArr[i-1].data).split(this.DATA_SEPARATOR);
			}
			
			for (var j = 0; j < att.length; j++){
				var data = document.createElement(this.SHOWCART_DATA_CONTAINER);

				
				var content = "";
		
				if (i != 0){
					switch (j){
						case this.QUANTITY_POSITION:
							if (arguments[0]) {var node = document.createTextNode(this.goodsArr[i-1].quantity); break;}
							var node = document.createElement('input');
							node.setAttribute('type', 'text');
							//node.setAttribute('class', 'catalog-input');
							node.className='catalog-input';
							node.value = this.goodsArr[i-1].quantity;

							function constr2(p){
								return function(){
									cart.setUserQuantity(p);
								}
							}
							
							node.onkeyup = constr2(goods);
							break; 
						case this.SUMPRICE_POSITION: 
							var node = document.createTextNode((this.goodsArr[i-1].quantity * this.goodsArr[i-1].price).toFixed(2));
							data.className = 'summary';
							break;
						case this.DELBTN_POSITION: 
							if (arguments[0]) {var node = null; break;}
							var node = document.createElement('img');
							
							node.setAttribute('src', this.IMAGE_REMOVEBTN);
							node.setAttribute('alt', 'Удалить товар из корзины');
							node.setAttribute('title', 'Удалить товар из корзины');
							node.className='cart-btn-remove';
							function constr(p){	 
								return function(){
									cart.removeGoods(p);
								}
							}
							
							node.onclick = constr(goods.childNodes);
							
							break;
						case this.VIEWBTN_POSITION:
							if (arguments[0]) {var node = null; break;}
							var node = document.createElement('img');
							node.setAttribute('src', this.IMAGE_VIEWBTN);
							node.setAttribute('alt', 'Вернуться на страницу с товаром');
							node.setAttribute('title', 'Вернуться на страницу с товаром');
							node.className='cart-btn-view';
							function constr23(p){
								return function(){location.href=p;}
							}
							
							node.onclick = constr23(this.goodsArr[i-1].href);
							
							break;
						case this.PRICE_POSITION:
							var node = document.createTextNode(att_value[j]);
							data.className = 'price';
							break;
						
						default: 
							var node = document.createTextNode(att_value[j]);
					}	
					
				}else{
					if (arguments[0] && ((j == this.VIEWBTN_POSITION) || (j == this.DELBTN_POSITION))){
						var node = null;
					}else{
						var node = document.createTextNode(att[j]);
					}
				}
				
				if (node != null){
					data.appendChild(node);
					goods.appendChild(data);
				}
			}
			container.appendChild(goods);
			var footer = document.getElementById('footer');
			footer.style.bottom = 0;
		}
		wrapper.appendChild(container);
		obj.replaceChild(wrapper, obj.firstChild)
		this.updateSumPrice();
	}
	Cart.prototype.updateSumPrice = function()
	{
		var order = document.getElementById(this.SHOWCART_ORDERPRICE_ID);
		var text = document.createTextNode(this.getSumPrice());
		order.replaceChild(text, order.firstChild);
	}
	
	//	Generate cookie id
	Cart.prototype.genCookieID = function(){
		var c = unescape(document.cookie).split(';');
		if (c.length == 0) return 0;
		for (var i = c.length - 1; i > -1; i--){
			if (c[i].indexOf(this.COOKIE_NAME) != -1) return parseInt(c[i].match(/\d+/)) + 1;
		}
		return 0;
	}
	
	//	Returns quantity of goods with cookie id = @cid
	Cart.prototype.getGoodsQuantityCID = function(cid){
		var c = unescape(document.cookie).split(';');
		for (var i = 0; i < c.length; i++){
			if (c[i].indexOf(this.COOKIE_NAME + cid) != -1){
				return parseInt(c[i].match(/\d+$/));
			}
		}
		return null;
	}
	
	Cart.prototype.addGoods = function(obj){
		var obj = obj.parentNode.parentNode.childNodes;
		var data = this.getDataDOM(obj);
		//	get cookie id
		var cid = this.getCookieID(data);
		
		if (cid == null){
			cid = this.genCookieID();
			var q = 1;
			this.createCookie(this.COOKIE_NAME + cid, data + this.DATA_SEPARATOR + 1, this.COOKIE_DAYS); 
		}else{
			var q = this.getGoodsQuantityCID(cid) + 1;
			this.createCookie(this.COOKIE_NAME + cid, data + this.DATA_SEPARATOR + q, this.COOKIE_DAYS);
		}

		this.restoreCart();
	}
	
	Cart.prototype.getDataDOM = function(obj){
		if (arguments[1] != undefined){
			var start = arguments[1];
		}else{
			var start = 1;		
		}
		var reg = /^\s+|\s+$/g	
		var data = obj[start].firstChild.nodeValue.replace(reg, '');
		for (var i = start + 1; i < (this.GOODS_DEFINITION_RANGE + 1); i++){
			data += this.DATA_SEPARATOR + obj[i].firstChild.nodeValue;
		}
		
		if (arguments[1] == undefined){
			/*
			var price = obj[this.PRICE_POSITION_CATALOG].firstChild.nodeValue;
			data += this.DATA_SEPARATOR + price.replace(reg,'').replace(/\D*$/g,'').replace(/,/,'.');
			*/
			var price = obj[obj.length-1].firstChild.nodeValue;		
			data += this.DATA_SEPARATOR + price.replace(reg,'').replace(/\D*$/g,'').replace(/,/,'.');
				
		}



		


		return data;
	};
		  
	
	Cart.prototype.catalogSubmit = function(obj)
	{
		var obj = obj.parentNode.parentNode.parentNode.childNodes;
		for (var i = 1; i < (obj.length - 1) ; i++){
			if (obj[i].firstChild.firstChild.checked || (obj[i].firstChild.firstChild.type == 'hidden'))
			{
				
				var data = this.getDataDOM(obj[i].childNodes);
				var cid = this.getCookieID(data);
				var input_qvalue = parseInt(obj[i].childNodes[obj[i].childNodes.length - 2].firstChild.value);
				
				
				
				if (cid == null)
				{
					cid = this.genCookieID();
					var q = input_qvalue;
					this.createCookie(this.COOKIE_NAME + cid, data + this.DATA_SEPARATOR + q, this.COOKIE_DAYS);
					// Create cookie with goods URL
					this.createCookie(this.COOKIE_NAME_HREF + cid, location.href, this.COOKIE_DAYS); 		 
				}
				else
				{
					var q = this.getGoodsQuantityCID(cid) + input_qvalue;
					this.createCookie(this.COOKIE_NAME + cid, data + this.DATA_SEPARATOR + q, this.COOKIE_DAYS);
					// Create cookie with goods URL
					this.createCookie(this.COOKIE_NAME_HREF + cid, location.href, this.COOKIE_DAYS); 		
				}
				this.restoreCart();					
				
			}			
		}
	
	};
	
	//	Create cookie @name with @value (cookie expire days = @days).
	//	You can also give the @days of -1 and it will be erased immediately. 
	Cart.prototype.createCookie = function(name, value, days){
		//alert("createCookie(" + name + ", " + value + ", " + days + ")");
		
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name + "=" + escape(value) + expires + "; path=/";
	}
	
	Cart.prototype.orderForm = function(){
		this.restoreCart();
		var hidden = document.getElementById(this.ORDER_HIDDEN_ID);
		if (hidden == undefined) return;

			var field = document.createElement("input");
			field.setAttribute('type', 'hidden'); 
			field.setAttribute('name', 'orderdetails');
			
			var str = "Артикул\t\tНазвание\t\tЦена\t\tКол-во\t\tСумма\n";

		for (var i = 0; i < this.goodsArr.length; i++){
			var data = this.goodsArr[i].data.split(this.DATA_SEPARATOR);
			str += data[0] + this.ORDER_COLUMN_SEPARATOR + data[1] + this.ORDER_COLUMN_SEPARATOR + data[2];
			str += this.ORDER_COLUMN_SEPARATOR + this.goodsArr[i].quantity.toString();
			str += this.ORDER_COLUMN_SEPARATOR + (this.goodsArr[i].quantity * this.goodsArr[i].price).toString();
			str += this.ORDER_LINE_SEPARATOR;
		}
		str += this.ORDER_LINE_SEPARATOR + "Итого: " + this.getSumPrice();
		field.setAttribute('value', str);
		hidden.appendChild(field);
		
	}
	
	Cart.prototype.validateInput = function(obj){
		var test = obj.value.match(/\D+/);
		if (test != null){
			alert("The quantity does not contain any non-digit characters. " + test);
			obj.value=1;
			return;
		}
	}

	
	function addLoadEvent(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		}else{
			window.onload = function() {
				if (oldonload){
				oldonload();
				}
      			func();
    		}
  		}
	}



	addLoadEvent(function() {
  		cart.restoreCart();
 		cart.orderForm();
	});

	
	

	
	var cart = new Cart();

	
	

