var DataDia = {};

DataDia.Config = {
	lang : null,
	path : 'xml/cart.xml.php',

	getPath : function () {
		return this.path + (this.lang ? "?lang=" + escape(this.lang) : "");
	}
}

DataDia.Util = {
	hasElementAttribute : function(element, attributeName) {
		if (element.hasAttribute) {
			return element.hasAttribute(attributeName);
		} else {
			return (element.getAttributeNode(attributeName) ? true : false);
		}
	},

	getXMLRequest : function() {
		var request;

		if (navigator.appName == "Microsoft Internet Explorer") {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			request = new XMLHttpRequest();
		}

		return request;
	}
}

DataDia.Cart = {
	id : null,
	name : null,
	webcode : null,
	currency : null,
	customer : null,
	recipient : null,
	recipientCount : 0,
	items : new Array(),
	comment : null,
	colors : new Array(),
	finishings: new Array(),
	total : 0,
	transport : 0,
	loadHandlers : new Array(),
	errorHandlers : new Array(),

	activate : function(customer, func) {
		DataDia.Cart.submitXMLRequest('contact', {
			'customer'          : customer.id,
			'customer_zipcode'  : customer.zipcode,
			'customer_username' : customer.username,
			'customer_password' : customer.password,
			'customer_optin'    : (customer.optin ? 1 : 0)
		}, func);
	},

	/* Deprecated: please use addProduct instead */
	add : function(product, quantity, func) {
		DataDia.Cart.submitXMLRequest('add', {
			'product'  : product,
			'quantity' : quantity
		}, func);
	},
	
	addProduct : function(product, quantity, func) {
		DataDia.Cart.submitXMLRequest('product', {
			'product'  : product,
			'quantity' : quantity
		}, func);
	},

	addItem : function(item, quantity, func) {
		DataDia.Cart.submitXMLRequest('item', {
			'item'     : item,
			'quantity' : quantity
		}, func);
	},

	clear : function(func) {
		DataDia.Cart.submitXMLRequest('clear', {}, func);
	},

	load : function(func) {
		var request = DataDia.Util.getXMLRequest();

		request.onreadystatechange = function () {
			if (request.readyState == 1) {
				document.body.style.cursor = 'progress';
			}
			if (request.readyState == 4) {
				if (request.responseXML) {
					DataDia.Cart.loadXML(request.responseXML, func);
				}
				document.body.style.cursor = 'default';
				request = null;
			}
		};
		request.open("get", DataDia.Config.getPath());
		request.send(null);
	},

	loadXML : function(xmldoc, func) {
		if (xmldoc.documentElement.tagName == 'error') {
			var errorType = xmldoc.documentElement.getAttribute("type");
			var errorMessage = xmldoc.documentElement.textContent;

			for (var i=0; i<this.errorHandlers.length; i++) {
				this.errorHandlers[i](errorType, errorMessage);
			}
		} else {
			this.id = xmldoc.documentElement.getAttribute("id");
			this.name = xmldoc.documentElement.getAttribute("n");
			this.webcode = xmldoc.documentElement.getAttribute("w");
			this.currency = xmldoc.documentElement.getAttribute("cy");
			this.total = parseFloat(xmldoc.documentElement.getAttribute("tt"));

			this.recipientCount = (DataDia.Util.hasElementAttribute(xmldoc.documentElement, "rc") ? parseInt(xmldoc.documentElement.getAttribute("rc")) : 0);
			
			this.colors = new Array();
			var colors = xmldoc.documentElement.getElementsByTagName("c");
			for (var i=0; i<colors.length; i++) {
				this.colors[i] = new DataDia.CartItemProperty();
				this.colors[i].id = colors[i].getAttribute("id");
				this.colors[i].name = colors[i].getAttribute("n");
				this.colors[i].desc =  colors[i].getAttribute("d");
			}

			this.finishings = new Array();
			var finishings = xmldoc.documentElement.getElementsByTagName("f");
			for (var i=0; i<finishings.length; i++) {
				this.finishings[i] = new DataDia.CartItemProperty();
				this.finishings[i].id = finishings[i].getAttribute("id");
				this.finishings[i].name = finishings[i].getAttribute("n");
				this.finishings[i].desc = finishings[i].getAttribute("d");
			}

			var comment = xmldoc.documentElement.getElementsByTagName("comment");
			this.comment = (comment[0] ? comment[0].textContent : "");
			
			this.customer = null;
			this.recipient = null;
			
			var customer = xmldoc.documentElement.getElementsByTagName("customer");
			if (customer[0]) {
				this.customer = new DataDia.CartContact();
				this.customer.id = customer[0].getAttribute("id");
				this.customer.name = customer[0].getAttribute("n");
				this.customer.address = customer[0].getAttribute("ad");
				this.customer.zipcode = customer[0].getAttribute("zc");
				this.customer.city = customer[0].getAttribute("ci");
				this.customer.state = customer[0].getAttribute("st");
				this.customer.country = customer[0].getAttribute("co");
				this.customer.phone = customer[0].getAttribute("ph");
				this.customer.fax = customer[0].getAttribute("fax");
				this.customer.mobile = customer[0].getAttribute("mobile");
				this.customer.email = customer[0].getAttribute("em");
				this.customer.im = customer[0].getAttribute("im");

				var recipient = xmldoc.documentElement.getElementsByTagName("recipient");
				if (recipient[0]) {
					this.recipient = new DataDia.CartContact();
					this.recipient.id = recipient[0].getAttribute("id");
					this.recipient.name = recipient[0].getAttribute("n");
					this.recipient.address = recipient[0].getAttribute("ad");
					this.recipient.zipcode = recipient[0].getAttribute("zc");
					this.recipient.city = recipient[0].getAttribute("ci");
					this.recipient.state = recipient[0].getAttribute("st");
					this.recipient.country = recipient[0].getAttribute("co");
					this.recipient.phone = recipient[0].getAttribute("ph");
					this.recipient.fax = recipient[0].getAttribute("fax");
					this.recipient.mobile = recipient[0].getAttribute("mobile");
					this.recipient.email = recipient[0].getAttribute("em");
					this.recipient.im = recipient[0].getAttribute("im");
				}
			}

			this.items = new Array();
			var items = xmldoc.documentElement.getElementsByTagName("i");
			for (var i=0; i<items.length; i++) {
				this.items[i] = new DataDia.CartItem();
				this.items[i].product = items[i].getAttribute("p");
				this.items[i].name = items[i].getAttribute("n");
				this.items[i].description = items[i].getAttribute("d");
				this.items[i].dimensions = items[i].getAttribute("di");
				this.items[i].finishing = items[i].getAttribute("fi");
				this.items[i].color = items[i].getAttribute("co");
				this.items[i].image = items[i].getAttribute("i");
				this.items[i].quantity = parseFloat(items[i].getAttribute("q"));
				this.items[i].price = parseFloat(items[i].getAttribute("pr"));
				this.items[i].currency = items[i].getAttribute("cy");
				this.items[i].total = parseFloat(items[i].getAttribute("tt"));
				this.items[i].vat = parseFloat(items[i].getAttribute("v"));
				this.items[i].ondemand = (parseInt(items[i].getAttribute("od")) == 1);
			}

			var transport = xmldoc.documentElement.getElementsByTagName("transport");
			if (transport[0]) {
				this.transport = parseFloat(transport[0].getAttribute("pr"));
			} else {
				this.transport = 0;
			}

			for (var i=0; i<this.loadHandlers.length; i++) {
				this.loadHandlers[i]();
			}

			if (func) {
				func();
			}
		}
	},

	newCustomer : function (customer, func) {
		DataDia.Cart.submitXMLRequest('contact', {
			'customer'          : '',
			'customer_name'     : customer.name,
			'customer_address'  : customer.address,
			'customer_zipcode'  : customer.zipcode,
			'customer_city'     : customer.city,
			'customer_state'    : customer.state,
			'customer_country'  : customer.country,
			'customer_phone'    : customer.phone,
			'customer_fax'      : customer.fax,
			'customer_mobile'   : customer.mobile,
			'customer_email'    : customer.email,
			'customer_im'       : customer.im,
			'customer_optin'    : (customer.optin ? 1 : 0),
			'customer_username' : customer.username,
			'customer_password' : customer.password
		}, func);
	},

	onLoad : function (handler) {
		this.loadHandlers[this.loadHandlers.length] = handler;
	},

	onError : function (handler) {
		this.errorHandlers[this.errorHandlers.length] = handler;
	},

	remove : function(index, func) {
		DataDia.Cart.submitXMLRequest('remove', {'item' : index}, func);
	},

	reset : function (func) {
		DataDia.Cart.submitXMLRequest('reset', {}, func);
	},

	roundNumber : function(number, precision) {
		var result;

		if (number.toFixed) {
			//if browser supports toFixed() method
			result = number.toFixed(precision);
		} else {
			//if browser doesn't support toFixed() method
			//simply round float
			var factor = 10 ^ precision;
			result = round(number * factor) / factor;
		}

		return result;
	},

	setRecipient : function(recipient, func) {
		if ((typeof recipient == "object") && (recipient != null)) {
			//assume CartContact
			DataDia.Cart.submitXMLRequest('recipient', {
				'recipient'         : recipient.id,
				'recipient_address' : recipient.address,
				'recipient_zipcode' : recipient.zipcode,
				'recipient_city'    : recipient.city,
				'recipient_state'   : recipient.state,
				'recipient_country' : recipient.country,
				'recipient_phone'   : recipient.phone
			}, func);
		} else {
			//assume recipient id
			DataDia.Cart.submitXMLRequest('recipient', {'recipient' : recipient}, func);
		}
	},
	
	setWebcode : function(webcode, func) {
		DataDia.Cart.submitXMLRequest('webcode', {'webcode' : webcode}, func);
	},

	signin : function(username, password, func) {
		DataDia.Cart.submitXMLRequest('contact', {
			'username' : username,
			'password' : password
		}, func);
	},
	
	signinWebcode : function(username, password, webcode, func) {
		DataDia.Cart.setWebcode(webcode, DataDia.Cart.signin(username, password, func));
	},

	submit : function(confirm, func) {
		DataDia.Cart.submitXMLRequest('submit', {'confirm' : (confirm ? 1 : 0)}, func);
	},
	
	submitXMLRequest : function(type, data, func) {
		var request = DataDia.Util.getXMLRequest();
		var requestString = 'submit=' + escape(type);

		for (d in data) {
			requestString += '&' + escape(d) + '=' + escape(data[d]);
		}		
		
		request.onreadystatechange = function () {
			if (request.readyState == 1) {
				document.body.style.cursor = 'progress';
			}
			if (request.readyState == 4) {
				if (request.responseXML) {
					DataDia.Cart.loadXML(request.responseXML, func);
				}
				document.body.style.cursor = 'default';
				request = null;
			}
		};

		request.open("post", DataDia.Config.getPath());
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				
		return request.send(requestString); 
	},

	update : function(func) {
		DataDia.Cart.submitXMLRequest('update', {'comment' : DataDia.Cart.comment}, func);
	},
	
	updateQuantities : function(quantities, func) {
		var temp = {};
		
		if (quantities.length > 0) {
			for (var i=0; i<quantities.length; i++) {
				temp['quantity[' + i + ']'] = quantities[i];
			}
			
			DataDia.Cart.submitXMLRequest('update', temp, func);
		}
	}
}





DataDia.CartItem = function() {
	this.product;
	this.name;
	this.description;
	this.dimensions;
	this.finishing;
	this.color;
	this.image;
	this.quantity;
	this.price;
	this.currency;
	this.total;
	this.vat;
	this.ondemand;
}





DataDia.CartItemProperty = function() {
	this.id;
	this.name;
	this.desc;
}





DataDia.CartContact = function() {
	this.id;
	this.username;
	this.password;
	this.name;
	this.address;
	this.zipcode;
	this.city;
	this.state;
	this.country;
	this.phone;
	this.fax;
	this.mobile;
	this.email;
	this.optin;
	this.im;
};
