var cookie = function() {
	return {
		set: function(name, value, expires, path, domain, secure) {
			path = "/";
			value = escape(value);
			domain = document.domain;
			domain = domain.replace(/www./, "");
			
			var curCookie = name + "=" + value +
				((expires) ? "; expires=" + expires.toGMTString() : "") +
				((path) ? "; path=" + path : "") +
				((domain) ? "; domain=" + domain : "") +
				((secure) ? "; secure" : "");
		
			document.cookie = curCookie;
		},
		get: function(name) {
		 var prefix = name + "=";
		 var cookieStartIndex = document.cookie.indexOf(prefix);
		 if (cookieStartIndex == -1) return null;
		 var cookieEndIndex = document.cookie.indexOf(";",cookieStartIndex + prefix.length);
		 if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
		 return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
		},
		del: function(name) {
			var exp = new Date();
			exp.setTime (exp.getTime() - 1000000000);  // This cookie is history (changed -1 to make it previous time)
//    	var cval = cookie.get(name);
//    	document.cookie =name + "=" + cval + "; expires=" + exp.toGMTString();
			cookie.set(name, '', exp);
		}	
	};
}();
		
var shop = function() {
	return {
		//params -> {id:1, add:1, frame:false, hardware:true, prehung:true; set:true} все кроме id - необязятельные параметры
		//set:true означает не прибавлять значение add к количеству, а установить количество в значение add
		addProduct: function(params) { 
			var products = new Array(); 
			var product = '';
			var index = -1;
			var order = cookie.get('order');
			if (order) {
				var products = order.split(';'); //формат order -> id,quantity,frame,hardware,prehung;id,quantity,frame,hardware,prehung;...
				for (var i = 0; i < products.length; i++) {
					if (products[i].indexOf(params.id) == 0) {
						product = products[i];
						index = i;
						break;
					}
				}
			}
			var items;
			if (product != '')
				items = product.split(',');
			else
				items = new Array(params.id, 0, 0, 0, 0); 
			if (params.add != null) {
				items[1] = params.set ? params.add : parseInt(items[1]) + params.add;
				if (items[1] < 0)
					items[1] = 0;
			}
			if (params.frame != null)
				items[2] = params.frame ? 1 : 0;  
			if (params.hardware != null)
				items[3] = params.hardware ? 1 : 0;  
			if (params.prehung != null)
				items[4] = params.prehung ? 1 : 0;
			product = items.join(',');
			switch(true) {
				case index != -1:
					products[index] = product;
					break;
				case index = -1 && items[1] > 0:
					products.push(product);
					break;
			}
			
			this.setCosts(products);
			
			if (index != -1 && items[1] == 0)
				products.splice(index,1);
			
			order = products.join(';');
			
			var exp = new Date();
			exp.setTime(exp.getTime() + 31*24*60*60*1000);  // добавляем 31 день
			cookie.set("order", order, exp);
			
			this.setCosts(products);
		},
		setQuantity: function(el, id) {
			this.validateQuantity(el);
			this.addProduct({id:id, add:el.value, set:true});
		},
		setQuantityChecked: function(el, id) {
				this.validateQuantity(el);
				this.addProduct({id:id, add:el.value, set:true, frame:true, hardware:true, prehung:true});
			},
		validateQuantity: function(el) {
			el.value = el.value.replace(/^0+/,'').replace(/[^0-9]+/,'');
			el.value += (el.value == '' ? '0' : '');
		},
		setCosts: function(products) {
			var total = $('#total');
			if (total != null) { //будет выполняться на странице корзины, но не будет выполняться на странице товара
				var total_value = 0;
				for (var i = 0; i < products.length; i++) {
					items = products[i].split(',');
					var value = (parseFloat($('#price' + items[0]).val()) +
						(items[2] == "1" ? parseFloat($('#frame_price' + items[0]).val()) : 0) +
						(items[3] == "1" ? parseFloat($('#hardware_price' + items[0]).val()) : 0) +
						(items[4] == "1" ? parseFloat($('#prehung_price' + items[0]).val()) : 0)) * items[1];
					total_value += value;
					$('#cost' + items[0]).html((Math.round(value * 100) / 100 + '').replace(/(\d)(?=(\d\d\d)+([^\d]|$))/, '$1&nbsp;'));
				}
				//total.html(parseInt(value/1000) + '&nbsp;' + Math.round(value % 1000 * 100) / 100);
				total.html((Math.round(total_value * 100) / 100 + '').replace(/(\d)(?=(\d\d\d)+([^\d]|$))/, '$1&nbsp;'));
			}
		}
	};
}();
