/**
	* Template handler.
	* Fields to be replaced in the template are contained inside { and }.
	*/
	function templateHandler(template){
		this.template = template;
		this.evaluate = function(data){
			/*
			Data is an associative array, the keys representing the template values and values representing the replaced values
			*/
			var temporaryTemplate = this.template; // make a temporary copy so successive calls with different datasets evaluate properly
			for(var i in data)
				temporaryTemplate = temporaryTemplate.replace(eval("/\{!*"+i.toUpperCase()+"\}/g"), data[i]);
			return temporaryTemplate;
		}
		this.setTemplate = function(template){
			this.template = template;
		}
	}
	templateHandler.cleanup = function(template){
		return template.replace(/\{!*[A-Z0-9_]+\}/g, "");
	}


function WCart(id, options){
		options = options || {};
		options.currency = options.currency || WCart.DEFAULT_CURRENCY;
		options.statusMessage = options.statusMessage || WCart.MESSAGE_STATUS;
		options.backendURL = options.backendURL || WCart.backendURL;
		options.checkoutURL = options.checkoutURL || WCart.checkoutURL;
		options.showFooter = options.showFooter === false ? false : true;
		options.emptyMessage = unescape(options.emptyMessage) || WCart.MESSAGE_EMPTY;
		options.title = unescape(options.title) || WCart.MESSAGE_YOUR_CART;
		options.controls = options.controls || WCart.CONTROLS_ALL;
		options.labelNew = options.labelNew || WCart.LABEL_NEW;
		options.labelCheckout = options.labelCheckout || WCart.LABEL_CHECKOUT;
		options.confirmation = options.confirmation || WCart.MESSAGE_CONFIRMATION;
		options.id = id;
		this.options = options;
		document.write("<div id='WCart_"+id+"'></div>");
		this.container = $("WCart_"+id);
		
		this.options = options;
		this.cartStatus = {count:0, value:0};
		this.inited = false;
		this.setBackingObject();
		WCart.INSTANCES.push(this);
		return this;
	}
	WCart.initAll = function(){
		//alert("initing wtabs")
		for(var i=0; i<WCart.INSTANCES.length; i++)
			WCart.INSTANCES[i].init();
	}
	WCart.prototype.setBackingObject = function(){
		WUtility.traverse(this.element, Delegate.create(this, function(node){
			try{
				node.backingObject = this;
			}catch(e){}
		}));
	}
	WCart.prototype.init = function(){
		this.inited = true;
		
		var t = new templateHandler(this.options.template);
		var id = this.options.id;
		
		//alert(this.options.title);
		
		if(this.options.controls & WCart.CONTROL_TITLE){
			this.title = WUtility.createElement("DIV");
			this.title.innerHTML = this.options.title;
			this.container.appendChild(this.title);
		}
		if(this.options.controls & WCart.CONTROL_CONTENT){
			this.content = WUtility.createElement("DIV");
			this.container.appendChild(this.content);
		}
		if(this.options.controls & WCart.CONTROL_STATUS){
			this.status = WUtility.createElement("DIV", {"align":"center"}, {"marginBottom":"4px"});
			this.container.appendChild(this.status);
		}
		if(this.options.controls & WCart.CONTROL_FOOTER){
			this.footer = WUtility.createElement("DIV", {"align":"center"});
			this.container.appendChild(this.footer);
		}
		
		//alert(t.evaluate({"ID":id}));
		//this.container.innerHTML = t.evaluate({"ID":id});
		//this.container.innerHTML = ""
		/*this.title = $(id+"Title")
		this.footer = $(id+"Footer");
		this.element = $(id);
		this.content = $(id+"Content");
		this.status = $(id+"Status");*/
		
		if(this.footer){
			var newButton = WUtility.createElement("INPUT", {"type":"button", "class":"smallbutton", "value":this.options.labelNew});
			newButton.onclick = Delegate.create(this, function(){this.clearAll()});
			var checkoutButton = WUtility.createElement("INPUT", {"type":"button", "class":"smallbutton", "value":this.options.labelCheckout});
			checkoutButton.onclick = Delegate.create(this, function(){this.checkout()});
			this.footer.appendChild(newButton);
			this.footer.appendChild(document.createTextNode(" "));
			this.footer.appendChild(checkoutButton);
			
		}
		this.refresh();
	}
	WCart.prototype.add = function(description, qty, unitprice, image){
		if(!this.inited) return false;
		var url = Address.dynamic(this.options.backendURL + "?action=add&description="+escape(description)+"&qty="+qty+"&unitprice="+unitprice+"&image="+escape(image));
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//alert(root.firstChild.nodeValue);
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			this.refresh();
			return true;
		}
		//return true;*/
	}
	WCart.prototype.refresh = function(){
		if(!this.inited) return false;
		var url = this.options.backendURL + "?action=queue";
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
		}else{
			var totalValue = parseFloat(root.getElementsByTagName("productPrice")[0].firstChild.nodeValue);
			var totalCount = parseInt(root.getElementsByTagName("productCount")[0].firstChild.nodeValue);
			//alert(root.getElementsByTagName("productPrice")[0]);
			this.cartStatus = {"count":totalCount, "value":totalValue};
			if(totalCount==0){
				if(this.status)
					this.status.innerHTML = this.options.emptyMessage;
				if(this.content)
					this.content.innerHTML = "";
			}else{
				if(this.content){
					var products = root.getElementsByTagName("products")[0].getElementsByTagName("product");
					this.content.innerHTML = "";
					var table = WUtility.createElement("TABLE", {"width":"100%"});
					var tbody = WUtility.createElement("TBODY");
					
					
					table.appendChild(tbody);
					for(var i=0; i<products.length; i++){
						var product = products[i];
						var description = product.getAttribute("description");
						var count = parseFloat(product.getAttribute("count"));
						var price = parseFloat(product.getAttribute("price"));
						var tr = WUtility.createElement("TR");
						
						var td = WUtility.createElement("TD", {"width":"1", "align":"center", "valign":"top"});
						td.innerHTML = count;
						tr.appendChild(td);
						
						var td = WUtility.createElement("TD", {"width":"1", "align":"center", "valign":"top"});
						td.innerHTML = "x";
						tr.appendChild(td);
						
						var td = WUtility.createElement("TD");
						td.innerHTML = description;
						tr.appendChild(td);
						
						var td = WUtility.createElement("TD", {"width":"1", "valign":"top"});
						td.innerHTML = sprintf("%.2f", price * count);
						tr.appendChild(td);
						
						tbody.appendChild(tr);
						
						//alert(product.description)
					}
					this.content.appendChild(table);
					
				}
				if(this.status){
					this.status.innerHTML = sprintf(WCart.MESSAGE_STATUS, totalCount, totalValue, this.options.currency)
				}
			}
			
		}
		
		
		//this.status.innerHTML = sprintf(this.options.statusMessage, this.cartStatus.count, this.cartStatus.value, this.options.currency);
		this.setBackingObject();
		try{ window.callable_rounded_corner_onresize() }catch(e){}
	}
	WCart.prototype.remove = function(id, variant, removeAll){
		if(!this.inited) return false;
		removeAll = (removeAll == true) ? "&all" : "";
		var url = this.options.backendURL + "?action=remove&id="+id+"&va="+variant+removeAll;
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			this.refresh();
			return true;
		}
	}
	WCart.prototype.clearAll = function(){
		if(!this.inited) return false;
		if(this.cartStatus.count>0){
			if(confirm(this.options.confirmation)){
				var url = Address.dynamic(this.options.backendURL + "?action=flush");
				var response = HTTPRequest.get(url);
				var root = response.xml.getElementsByTagName("response")[0]; // process the XML
				//alert(root.firstChild.nodeValue);
				if(root.getAttribute("result").toUpperCase()=="FAILURE"){
					alert(root.firstChild.nodeValue);
					return false;
				}else{
					this.refresh();
					return true;
				}
			}
		}else{
			alert(this.options.emptyMessage);
		}
	}
	
	WCart.prototype.checkout = function(){
		if(!this.inited) return false;
		if(this.cartStatus.count>0){
			//if(confirm(sprintf("Total %d preparate, %.2f %s. Confirma?", this.cartStatus.count, this.cartStatus.value, this.options.currency)))
			Address.redirect(this.options.checkoutURL);
		}else{
			alert(this.options.emptyMessage);
		}
	}
	WCart.INSTANCES = [];
	WCart.messagePageInit = "Va rugam asteptati pana se initializeaza pagina!";
	WCart.backendURL = "/modules/wcart/wcart/";
	WCart.checkoutURL = "/orders/";
	WCart.MESSAGE_STATUS = "Total <strong>%d</strong> produse<br/><strong>%8.2f %s</strong>.";
	WCart.MESSAGE_EMPTY = "Cosul Dvs. este gol."	
	WCart.MESSAGE_YOUR_CART = "Cosul tau"	
	WCart.MESSAGE_CONFIRMATION = "Sunteti sigur?";
	WCart.DEFAULT_CURRENCY = "EUR";
	WCart.LABEL_NEW	= "Cos nou";
	WCart.LABEL_CHECKOUT = "Finalizare";

	WCart.CONTROL_TITLE = 1;
	WCart.CONTROL_CONTENT= 2;
	WCart.CONTROL_STATUS = 4;
	WCart.CONTROL_FOOTER = 8;

	WCart.CONTROLS_ALL = WCart.CONTROL_TITLE | WCart.CONTROL_CONTENT | WCart.CONTROL_STATUS | WCart.CONTROL_FOOTER;
	WCart.CONTROLS_MINIMALISTIC = WCart.CONTROL_TITLE | WCart.CONTROL_STATUS | WCart.CONTROL_FOOTER;
	
	// 
	
	window.addOnLoadListener(window, WCart.initAll); // initialize shopping carts
