

Handlers = new function() {
	this.addToShoppingCart = function (theForm, productId) {
		// preparing post data
		var data = new Array();
		data[0] = ["command", "shoppingCartAdd"];
		if (productId == null) {
			for (var i = 0; i < theForm.elements.length; i++) {
				var elm = theForm.elements[i];
				//alert(elm.name);
				if (elm.name.indexOf("checkbox_") != 0) {
					continue;
				}
				if (!elm.checked) {
					continue;
				}
				var productId = elm.name.substring(9);
				var amount = parseInt(theForm["amount_" + productId].value);
				if (isNaN(amount) || (amount <= 0)) {
					alert("Введите положительное целое число.");
					theForm["amount_" + productId].focus();
					return;
				}
				data[data.length + 1] = ["productId_" + productId, amount];
				//alert("Added: " + productId);
			}
			// Clear al checkboxes.
			for (var i = 0; i < theForm.elements.length; i++) {
				var elm = theForm.elements[i];
				if (elm.name.indexOf("checkbox_") != 0) {
					continue;
				}
				elm.checked = false;
			}
		} else {
			var amount = parseInt(theForm["amount_" + productId].value);
			if (isNaN(amount) || (amount <= 0)) {
				alert("Введите положительное целое число.");
				theForm["amount_" + productId].focus();
				return;
			}
			data[1] = ["productId_" + productId, amount];
		}
		if (data.length < 2) {
			alert("Отметьте позиции, которые хотите заказать.");
			return;
		}
		var amount = theForm["amount_" + productId].value;
		Util.doXmlRequest("/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/catalogueData.jsp",
			function(oXmlDoc) { // success handler
				//alert(Util.getXmlNodeValue(oXmlDoc.documentElement));
				var wnd = Popup.open(null, "shoppingCartAddNotification", "", 640, 480);
				wnd.document.clear();
				wnd.document.write(Util.getXmlNodeValue(oXmlDoc.documentElement));
				document.body.style.cursor = "default";
			},
			function(url) { // start request handler
				// no-op
				document.body.style.cursor = "wait";
			},
			function(url, error) { // error handler
				alert(error);
				document.body.style.cursor = "default";
			},
			data // POST data
		);
	}
	
	this.searchFreeText = function (query, segment) {
		if (segment == null) {
			segment = 0;
		}
		Util.doXmlRequest("/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/catalogueData.jsp",
			function(oXmlDoc) { // success handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = Util.getXmlNodeValue(oXmlDoc.documentElement);
			},
			function(url) { // start request handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "wait";
				elm.innerHTML = "<b>Ищем \"" + query + "\"...</b>";
			},
			function(url, error) { // error handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = error;
			},
			[["command", "productFreeTextSearch"], ["query", query], ["segment", segment]] // POST data
		);
	}
	
	this.showSpecials = function (specialsType, segment) {
		if (segment == null) {
			segment = 0;
		}
		Util.doXmlRequest("/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/catalogueData.jsp?command=productListSpecials"
			+ "&segment=" + segment
			+ ((specialsType != null) ? "&specialsType=" + specialsType : ""),
			function(oXmlDoc) { // success handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = Util.getXmlNodeValue(oXmlDoc.documentElement);
			},
			function(url) { // start request handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "wait";
				elm.innerHTML = "<b>Загрузка...</b>";
			},
			function(url, error) { // error handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = error;
			}
		);
	}
	
	this.displayNode = function (nodeId, parentNodeId, segment) {
		if (parentNodeId) {
			var node = Util.findNodeInTree(tree.childNodes, parentNodeId);
			if (node != null) {
				node.expand();
				node = Util.findNodeInTree(node.childNodes, nodeId);
				if (node != null) {
					node.focus();
				}
			}
		}
		if (segment == null) {
			segment = 0;
		}
		var sourceUrl = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/catalogueData.jsp?command=productList&nodeId="
			+ nodeId + "&segment=" + segment;
		Util.doXmlRequest(sourceUrl,
			function(oXmlDoc) { // success handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = Util.getXmlNodeValue(oXmlDoc.documentElement);
			},
			function(url) { // start request handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "wait";
				elm.innerHTML = "<b>Загрузка...</b>";
			},
			function(url, error) { // error handler
				var elm = document.getElementById("mainPanel");
				elm.style.cursor = "default";
				elm.innerHTML = error;
			}
		);
	}


	this.showProdCard = function (id, isTemplate) {

		var sourceUrl = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/product_details_temp.jsp?productCardId=" + id;

		Util.doHtmlRequest(sourceUrl, "mainPanel");


	}





}

Util = new function() {
	this.getXmlNode = function (node, tagName) {
		var children = node.childNodes;
		var len = children.length;
		for (var i = 0; i < len; i++) {
			if (children[i].tagName == tagName)
				return children[i];
		}
		return null;
	}
	
	this.getXmlNodeValue = function (node, tagName) {
		if (tagName) {
			node = this.getXmlNode(node, tagName);
		}
		if (!node) {
			return null;
		}
		var result = "";
		var children = node.childNodes;
		var len = children.length;
		for (var i = 0; i < len; i++) {
			if ((children[i].nodeType == 3) // TEXT
					|| (children[i].nodeType == 4)) { // CDATA
				result += children[i].nodeValue;
			}
		}
		return result;
	}
	
	this.doXmlRequest = function (url, onSuccessHandler, onStartHandler, onErrorHandler, data) {
		var xmlHttp = XmlHttp.create();
		var encodedData = null;
		// add random param to URL to prevent caching
		if (url.indexOf("?") == -1) {
			url += "?";
		} else {
			url += "&";
		}
		url += "rnd=" + new Date().getTime();
		if (data == null) {
			xmlHttp.open("GET", url, true); // async
		} else {
			xmlHttp.open("POST", url, true); // async
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			// preparing POST data
			// data is expected as 2-dimensional array (n x 2)
			encodedData = "";
			for (var i = 0; i < data.length; i++) {
				if (data[i] == null) {
					continue;
				}
				if (encodedData != "") {
					encodedData += "&";
				}
				encodedData += data[i][0] + "=" + encodeURIComponent("" + data[i][1]);
			}
		}
		xmlHttp.onreadystatechange = function () {

			if (xmlHttp.readyState == 4) {
				var oXmlDoc = xmlHttp.responseXML;
				if(!oXmlDoc
						|| (oXmlDoc.parserError && oXmlDoc.parseError.errorCode != 0)
						|| !oXmlDoc.documentElement) {
					var error;
					if (!oXmlDoc || oXmlDoc.parseError.errorCode == 0) {
						error = "<b>An error has occurred while loading data.</b><br>Resource URL: " + url
							+ "<br>Status: " + xmlHttp.status + ", " + xmlHttp.statusText
							+ "<br>Data:<br>" + xmlHttp.responseText;
					}else{
						error = "<b>An error has occurred while parsing data.</b><br>Resource URL: " + url
							+ "<br>Reason: " + oXmlDoc.parseError.reason
							+ "<br>Source: " + oXmlDoc.parseError.srcText
							+ "<br>Error code: " + oXmlDoc.parseError.errorCode
							+ "<br>Data:<br>" + xmlHttp.responseText;
					}
					if (onErrorHandler) {
						onErrorHandler(url, error);
					}
					return;
				}
				onSuccessHandler(oXmlDoc);
			}
		};
		if (onStartHandler) {
			onStartHandler(url);
		}
		// call in new thread to allow UI to update
		window.setTimeout(function () {
			xmlHttp.send(encodedData);
		}, 10);
	}
	
	this.doHtmlRequest = function (url, elementId, anchor) {
		var xmlHttp = XmlHttp.create();
		xmlHttp.open("GET", url, true); // async
		xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		var elm = document.getElementById(elementId);







		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState != 4) {
				return;
			}
			elm.style.cursor = "default";
			var oXmlDoc = xmlHttp.responseXML;
			if(!oXmlDoc
					|| (oXmlDoc.parserError && oXmlDoc.parseError.errorCode != 0)
					|| !oXmlDoc.documentElement) {
				elm.innerHTML = xmlHttp.responseText;
			} else {
				elm.innerHTML = Util.getXmlNodeValue(oXmlDoc.documentElement);
			}
			if (anchor) {
				var obj = document.anchors(anchor);
				if (obj) {
					obj.scrollIntoView();
				}
			}

		};
		elm.style.cursor = "wait";
		elm.innerHTML = "<b>Загрузка...</b>";
		// call in new thread to allow UI to update
		window.setTimeout(function () {
			xmlHttp.send(null);
		}, 10);
	}
	
	this.findNodeInTree = function (nodes, nodeId) {
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			if (node.customId == nodeId) {
				return node;
			}
			node = this.findNodeInTree(node.childNodes, nodeId);
			if (node != null) {
				return node;
			}
		}
		return null;
	}
}

Popup = new function() {
	this.showProductCard = function (id, isTemplate) {
		if (isTemplate) {
			var url = "http://desten.ru:8080/configurator/?article=" + id;
		} else {
			var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/popup_product_details.jsp?productCardId=" + id;
		}
		this.open(url, "productCardWnd", "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes", 670, 620);
		
	}






//	this.showProdCard = function (id, isTemplate) {
//		var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/product_details_temp.jsp?productCardId=" + id;
//		var elm = document.getElementById("mainPanel");
//		elm.style.cursor = "default";
//		elm.innerHTML = Util.doHtmlRequest(url, 'mainPanel');
//	}





	this.showShoppingCart = function() {
		var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/popup_shopping_cart.jsp?noResizeWindow=true";
		this.open(url, "shoppingCartWnd", "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes", 600, 430);
	}
	
	this.showOrders = function() {
		var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/popup_order_list.jsp?noResizeWindow=true";
		this.open(url, "shoppingCartWnd", "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes", 655, 640);
	}
	
	this.showOrder = function() {
		var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/popup_order.jsp";
		this.open(url, "shoppingCartWnd", "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes", 580, 600);
	}

	this.loginForm = function() {
		var url = "/dn/opencms/system/modules/com.gridnine.opencms.modules.desten.estore/standalone/popup_user.jsp?noResizeWindow=true";
		this.open(url, "shoppingLoginForm", "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=no,resizable=yes", 380, 435);
	}
	
	this.open = function(url, windowName, windowFeatures, w, h) {
		windowFeatures = windowFeatures
			+ ",top=" + ((screen.availHeight - h) / 2 + (Math.random() - 0.5) * 20)
			+ ",left=" + ((screen.availWidth - w) / 2 + (Math.random() - 0.5) * 20)
			+ ",width=" + w + ",height=" + h;
		var popupWnd = window.open("", windowName, windowFeatures);
		popupWnd.focus();
		if ((url != null) && (url != "")) {
			popupWnd = window.open(url, windowName, windowFeatures);
		}
		return popupWnd;
	}
}
