
function dbgVar(v) {
	var msg = '' +
	'Type: '+typeof(v)+'\n'+
	'Length/Size: '+v.length+'\n'+
	alert(msg);
}

var basket = function(title, currency){
	this.title = title;
	this.currency = "EUR";
	this.template = '<html><head><title>{cartTittle}</title><script type="text/javascript" src="cart.lib.js"></script> <script type="text/javascript"> 	var cart = new basket("test-cart"); </script></head><body>Items: {itemCount}<br>{itemList}<p onclick="window.close()">schlie?en</p></body></html>';
	
	!navigator.cookieEnabled ?
		alert("Beachten Sie:\n\nDer Warenkorb speichert Ihre Artikel in Cookies.\nAktivieren Sie bitte die Cookie-Unterstützung Ihres Browsers.\n\nDanke!") : null ;
	
	//alert(document.cookie.indexOf("cart_item_count"));
	if(document.cookie.indexOf("cart_item_count") == -1) {
		document.cookie = "cart_item_count=0; path=/";		
	}
	
	/**
	 *	we urgently need a trim'er, so let's extend JavaScript's String Object
	 *	
	 *	@return string		the trim'ed string
	 */	 	 	 
	String.prototype.trim = function() {
		var regexp_end = /\s+$/; // detect white spaces at the end
		var regexp_start = /^\s+/; // detect white spaces at the beginning
		
		return (this.replace(regexp_start, "").replace(regexp_end, ""));
	}
	
	/**
	 *	adds an item to the cart (cookie) and increases the item counter
	 *	
	 *	@param string 		the unique id of the item to add
	 *	@param string 		the literal name of the item
	 *	@param string 		the price for the single item
	 *	@param int 			the amount the client wants to order
	 */
	this.addItem = function(artno, name, price, amount) {
		if(artno == '') {
			alert("Cart: No unique item ID specified!\nItem not added.");
			return false;
		}
		var old_count, new_count;
		var item_key = "cart_items_" + artno;
		// increase the item count only if the item_key does not exist
		if(this.getCookieVal(item_key) == false) {
			//alert("new itemnew_count);
			old_count = this.getCookieVal("cart_item_count"); 
			old_count = isNaN(old_count) ? 0 : old_count;
			new_count = parseInt(old_count) + 1;
			
			document.cookie = "cart_item_count=" + new_count + "; path=/";
		}
		
		// save a new item only if it does not already exist
		if(!this.getCookieVal(item_key) && Math.round(amount) > 0) {
			clean_price = price.match(/\d+[,|.]\d+/);
			//alert(clean_price);
			document.cookie = item_key + "=" + escape(name + "::" + clean_price + "::" + Math.round(amount)) + "; path=/";
		}
		
		/**/
		//alert(this.getCookie());
	}
	
	/**
	 *	removes an item from the cart
	 *	
	 *	@param string 		the unique item identifier
	 */
	this.removeItem = function(artno) {
		var cookieTime = new Date();
		cookieTime.setTime((cookieTime.getTime() - (1 * 24 * 60 * 60 * 1000)));
		//alert(cookieTime.toGMTString());
		document.cookie = "cart_items_"+artno+"=empty; expires="+cookieTime.toGMTString();
		var item_count = this.getCookieVal("cart_item_count");
		document.cookie = "cart_item_count="+(parseInt(item_count) - 1);
	}
	
	/**
	 *	sets the amount of an item in the cart to a spedific value
	 *	
	 *	@param string 		the unique item identifier
	 *	@param string 		the amount to set
	 *	@return boolean 	false on error, else true
	 */	 	 
	this.setItemAmount = function(artno, amount) {
		var item = this.getItem("cart_items_"+artno);

		if(item == false) {
			return false;
		}
		amount = parseFloat(amount);
		amount = isNaN(amount) ? 1 : amount;
		amount = Math.round(amount) < 1 ? 1 : Math.round(amount);
		document.cookie = "cart_items_" + artno + "=" + escape(item[0] + "::" + item[1] + "::" + amount);
		return true;
	}
	
	/**
	 *	gets an item and returns its properties in an array
	 *	
	 *	@param string 		the item_key
	 *	@return array 		the item's properties
	 *	@return boolean 	false on failure
	 */	 	 	 	 	 	
	this.getItem = function(name) {
		var item = this.getCookieVal(name);
		
		if(item == false) {
			return false;
		}
		item = item.split("::");
		
		return item;
	}
	
	/**
	 *	gets the value of a cookie
	 *	
	 *	@param string 		the name of the cookie
	 *	@return string 		the value of the cookie
	 */	 	 	 	 	
	this.getCookieVal = function(name) {
		var cookies = document.cookie;
		if((cookies.length < 1)  ) {
			return false;
		}
		
		cookies = cookies.split(";");
		for(var x=0; x < cookies.length; x++) {
			var data = cookies[x].split("=");
			data[0] = data[0].trim();
			data[1] = data[1].trim();
			if(data[0] == name) {
				return unescape(data[1]);
			}
		}
		return false;
	}
	
	/**
	 *	returns the title of the cart instance
	 *	
	 *	@return string 		the title of the cart
	 */	 	 	 	
	this.getTitle = function() {
		return this.title;
	}
	
	/**
	 *	gets the whole cookie string of the site
	 *	
	 *	@return string 		the entire rfc-like cookie string
	 */	 	 	 	
	this.getCookie = function() {
		return unescape(document.cookie);
	}
	
	/**
	 *	returns the amount of different items in the cart
	 *	
	 *	@return string 		the amount of items
	 */	  	 	
	this.getItemCount = function() {
		var i = this.getCookieVal("cart_item_count");
		if(isNaN(i)) {
			return 0;
		} else {
			return i;
		}
	}
	
	/**
	 *	returns a multidimensional associative array of items in the cart with properties
	 *	
	 *	@return array 		all items in the cart
	 */	 	 	 	
	this.itemsToArray = function() {
		var cookie_string = unescape(document.cookie);
		
		var tmp = cookie_string.split(";");
		var cookies = new Array(); // the final cart cookie strings will be stored
		// filter for cart cookies
		for(var i = 0; i < tmp.length; i++) {
			if(tmp[i].indexOf("cart_items") != -1) {
				//alert("found -.- "+i);
				//tmp.splice(i, 1);
				cookies.push(tmp[i]);
			}
		}
		
		var items = new Array();
		for(var i = 0; i < cookies.length; i++) {
			var var_val_pair = cookies[i].split("=");
			var itemProperties = var_val_pair[1].split("::");
			
			var temp = var_val_pair[0]; // the cookie name
			/cart_items_(\d+)/.exec(temp);
			var artno = RegExp.$1; // the position of the last underscore
			
			items[i] = new Array();
			items[i]['artno'] = artno;
			items[i]['name'] = itemProperties[0];
			items[i]['price'] = itemProperties[1];
			items[i]['amount'] = itemProperties[2];
		}
		
		return items.reverse();
	}
	
	/**
	 *	takes the user-defined template and renders it
	 *	
	 *	@param object 		the reference to the window.document object of the window to output the template
	 */	  	 	
	this.drawTemplate = function(win) {
		
		var output = this.template;
		var items, itemHTML;
		var priceSum = 0;
		
		output = output.replace(/{cartTitle}/, this.title);
		output = output.replace(/{itemCount}/, this.getItemCount());
		output = output.replace(/{test}/, "TESTING...");
		
		// get items
		items = this.itemsToArray();
		
		itemHTML = "";
		itemHTML += '<table class="items">\n';
		itemHTML += '<thead><tr>\n\t<td>Bez.</td>\n\t<td>Preis</td>\n\t<td>Anzahl</td>\n</tr></thead>\n<tbody>\n';
		for(var i = 0; i < items.length; i++) {
			itemHTML += '<tr>\n';
			//itemHTML += '\t<td>' + items[i]['artno'] + '</td>\n';
			itemHTML += '\t<td class="descr">' + items[i]['name'] + '</td>\n';
			itemHTML += '\t<td class="price">' + (parseFloat(items[i]['price']) * items[i]['amount']).toFixed(2) + ' {currency}</td>\n';
			itemHTML += '\t<td class="action"><input type="text" class="amount" id="item_' + items[i]['artno'] + '" value="' + items[i]['amount'] + '" size="' + items[i]['amount'].length + '" /> <input type="button" class="button default" value="Übernehmen" onclick="cart.setItemAmount(\'' + items[i]['artno'] + '\',document.getElementById(\'item_' + items[i]['artno'] + '\').value);cart.drawTemplate(window);" /> <input type="button" class="button default bold" onclick="cart.removeItem(\'' + items[i]['artno'] + '\');cart.drawTemplate(window);" value="Löschen" /></td>\n';
			itemHTML += '</tr>\n';
			
			itemHTML = itemHTML.replace(/{currency}/, this.currency);
			priceSum += (parseFloat(items[i]['price']) * items[i]['amount']);
		}
		
		if(!items[0]) {
			itemHTML += '<tr>\n';
			itemHTML += '\t<td colspan="3">Keine Artikel im Warenkorb.</td>\n';
			itemHTML += '</tr>\n';
		}
		/**/
		itemHTML += '</tbody>\n</table><br>';
		output = output.replace(/{itemList}/, itemHTML);
		output = output.replace(/{priceSum}/, priceSum.toFixed(2) + " " + this.currency);
				
		win.document.open();
		win.document.write(output);
		win.document.close();
		
		// the fucking IE does not interpret javascript put on site with document.write()
		// so we have to reload the location.
		if(navigator.appName == "Microsoft Internet Explorer") {
			win.location.reload();
		}
	}
}

