/*
 * 
 * Pub-Me Content Management System (CMS)
 * http://www.pub-me.com/
 * 
 * (c) 2005-2010 Malenek webdesign - http://www.malenek.cz
 * 
 * This program or any of its parts may not be used, redistributed, and/or 
 * modified without an explicit permission of the author and/or 
 * the copyrights owner.
 * 
 * 
 *  JS comment management improvements
 *  - this plugin makes it possible to directly reply to comments
 *  - reply form is displayed just under the comment you reply to
 *  - if not supported or implemented, the functionality of the form is not affected (just less comfort provided)
 *  - tested in IE6, FF2, Opera 9    
 *  
 */

var PM_eshopajax = {
	XmlHttp : false,
	handleServerResponseFunction : false,
	ajaxDivId : false,
	ajaxWaitText : "...",
	sendValues : null,

	createXmlHttpRequestObject : function () {
		var xmlHttp;
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e) {
			var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
																			"MSXML2.XMLHTTP.5.0",
																			"MSXML2.XMLHTTP.4.0",
																			"MSXML2.XMLHTTP.3.0",
																			"MSXML2.XMLHTTP",
																			"Microsoft.XMLHTTP");
			for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
				try { 
					xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
				} catch (e) {
				}
			}
		}
		if (!xmlHttp)
			alert("Error creating the XMLHttpRequest object.");
		else 
			return xmlHttp;
	} ,

	openHttpRequest : function ( aMethod, aScript, aStatus, handleServerResponse ) {
		if (this.XmlHttp) {
			// try to connect to the server
			// open the script to handle
			try {
				this.handleServerResponseFunction = handleServerResponse;
				this.XmlHttp.open( aMethod, aScript + "&" + "AjaxProcess", aStatus);
				if (aMethod == "POST") {
					this.XmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					this.XmlHttp.setRequestHeader("Content-length", this.sendValues);
					this.XmlHttp.setRequestHeader("Connection", "close");
				}
				this.XmlHttp.onreadystatechange = this.handleRequestStateChange ;
				this.XmlHttp.send( this.sendValues );
			} catch (e) {
				alert ( "Can't connect to server: " + aScript + "\n" + e.toString() );
			}
			return true;
		}
	} ,

	handleRequestStateChange : function () {
		// 'this' reference does not work here... 
		oEshopThis = PM_eshopajax;
		if (oEshopThis.XmlHttp.readyState == 1 ) {
			document.getElementById ( oEshopThis.ajaxDivId ).innerHTML = '<div class="AjaxWait">' + oEshopThis.ajaxWaitText + '</div>';
		}
		if (oEshopThis.XmlHttp.readyState == 4) {
			if (oEshopThis.XmlHttp.status == 200) {
				try {
					// open the function that handles successful server response
					eval ( oEshopThis.handleServerResponseFunction );
				} catch(e) {
					alert("Error reading the response: " + e.toString());
				}
			} else {
				alert("There was a problem retrieving the data:\n" + XmlHttp.statusText);
			}
		} 
	} ,

	GETSubmit : function ( Script, DivId ) {
		this.ajaxDivId = DivId;
		this.sendValues = null; 
		return this.openHttpRequest ( "GET", Script, true, "oEshopThis.HandleServerResponse()" );
	} ,
	
	POSTSubmit : function ( Script, DivId, FormId ) {
		this.ajaxDivId = DivId;
		this.sendValues = this.getFormValuesAsString ( FormId );
		return this.openHttpRequest ( "POST", Script, true, "oEshopThis.HandleServerResponse()" );
	} ,

	
	HandleServerResponse : function () {
		var Div = document.getElementById ( this.ajaxDivId );
		var response = this.XmlHttp.responseText;
		Div.innerHTML = response;
		eshopHandler.updateCartPreview ();
	} ,
	
	getFormValuesAsString : function ( FormId ) {
		var f = getE ( FormId );
		var values = new Array;
		for( var i = 0; i < f.elements.length; i++ ) {
			if ( f.elements[i].name.length > 0 )
				values[i] = encodeURIComponent (f.elements[i].name) + '=' + encodeURIComponent(f.elements[i].value) ;
		}
		values = values.join ('&');
		return (values);
	} ,
	
	activateAjax : function () {
		this.XmlHttp = this.createXmlHttpRequestObject();
	}

}

var eshopHandler = {
	active : false ,                              // status of the entire plugin (set true after everything is loaded)
	tab    : 0,
	tabIds : new Array(),                         // ids of the tabs
	tabIdsBool : new Array(),                     // status of the tabs
	activate : function () {
		for (i=0;i<this.tab;i++) {
			if(!this.tabIdsBool[this.tabIds[i]]) {
				getE(this.tabIds[i]).style.display="none";
			}
		}
		// switch to comments if proper hash is set
		if ( window.location.hash.substring(0,2) == "#c") {
			h = window.location.hash.substring(1)
			if (getE(h)) {
				this.toggleTabs ("ProductComments");
			}
		}
	} ,
	toggleTabs : function ( id ) {
		for (i=0;i<this.tab;i++) {
			if( this.tabIds[i] == id ) {
				getE(this.tabIds[i]).style.display="";
				getE("ProductSwitcher"+this.tabIds[i]).className="Active";
			} else {
				getE(this.tabIds[i]).style.display="none";
				getE("ProductSwitcher"+this.tabIds[i]).className="";
			}
		} 
		return true;
	} ,
	brandSwitcher : function ( obj ) {
		var selectAll = false;
		if (obj.id == "EshopBrand__all") {
			if ( getE("EshopBrand__all").checked ) {
				selectAll = true;
			}
			getE("EshopBrand__all").checked = selectAll; // toggle All brands
			var n = document.getElementsByName("eshop_brands[]");
			for (i=0;i<n.length;i++) {
				n[i].checked = false;
			}
		} else {
			var selectBrands = false;
			var n = document.getElementsByName("eshop_brands[]");
			for (i=0;i<n.length;i++) {
				if (n[i].checked) {
					selectBrands = true;
				}
			}
			getE("EshopBrand__all").checked = !selectBrands; // toggle All brands
		}
		return true;
	} ,
	submitBrandSwitcher : function ( arg, path ) {
		l = getE("EshopBrandsLink").value ;
		var selectBrands = false;
		var n = document.getElementsByName("eshop_brands[]");
		var brandNames = "";
		for (i=0;i<n.length;i++) {
			if (n[i].checked) {
				selectBrands = true;
				if ( brandNames!="") { brandNames += "," }
				brandNames += n[i].value;
			}
		}
		if (selectBrands) {
			l +=  "/" + arg + "/" + brandNames;
		}
		window.location.href = (path+l);
		return true;
	} ,
	submitBrandSorting : function ( arg, path ) {
		l = getE("EshopSortingLink").value ;
		if (getE("EshopSortingSelect").value!="") {
			l +=  "/" + arg + "/" ;
			l += getE("EshopSortingSelect").value ;
		}
		window.location.href = l;
		return true;
	} ,

	changeCartItem : function ( id, add ) {
		if ( add=='del' ) {
			getE(id).value = 0;
		} else {
			getE(id).value = parseFloat(getE(id).value) + parseFloat(add);
		}
	} ,

	updateCartPreview : function () {
		if ( getE("EshopCartPreviewTotalPrice") && getE("EshopTableTotalPrice") ) {
			getE("EshopCartPreviewTotalPrice").innerHTML =  getE("EshopTableTotalPrice").innerHTML;
		} else {
			if ( getE("EshopCartPreviewTotalPrice") ) {
				getE("EshopCartPreviewTotalPrice").innerHTML = 0;
			}
		}
		if ( getE("EshopCartPreviewTotalCount") && getE("EshopTableTotalCount") ) {
			getE("EshopCartPreviewTotalCount").innerHTML =  getE("EshopTableTotalCount").innerHTML;
		} else {
			if ( getE("EshopCartPreviewTotalCount") ) {
				getE("EshopCartPreviewTotalCount").innerHTML = 0;
			}
		}
	} ,
	
	deliveryButton  : false,
	paymentButton   : false,
	paymentMethodsArray : new Array (),
	
	deliveryButtonEnable : function ( idpay ) {
		if ( idpay ) {
			var v = " " + getE(idpay).value;
			// alert (getE(idpay).value);
			var a = this.paymentMethodsArray;
			for (i=0;i<a.length;i++) {
				if (v.lastIndexOf("["+a[i]+"]")>0) {
					this.paymentMethodEnable ( a[i] );
				} else {
					this.paymentMethodDisable ( a[i] );
				}
			}
		}

		this.deliveryButton = true;
		this.deliveryButtonChangeState();
	} ,
	paymentButtonEnable : function () {
		this.paymentButton = true;
		this.deliveryButtonChangeState();
	} ,
	deliveryButtonChangeState : function () {
		if ( this.deliveryButton && this.paymentButton ) {
			getE("DeliverySubmitButton").disabled  = false;
			getE("DeliverySubmitButton").className = 'SubmitButton';
		} else {
			getE("DeliverySubmitButton").disabled  = true;
			getE("DeliverySubmitButton").className = 'SubmitButton Disabled';
		}
	} ,
	paymentMethodEnable : function ( id ) {
		var obj = getE("Eshop_PaymentSelect"+id); 
		obj.disabled = false;

		var cls = getE("Eshop_PaymentTr"+id).className;
		if (cls.indexOf(" ")>0) { cls = cls.substring (0,cls.indexOf(" ")); }
		getE("Eshop_PaymentTr"+id).className = cls;
	} ,
	paymentMethodDisable : function ( id ) {
		var obj = getE("Eshop_PaymentSelect"+id); 
		if ( obj.checked ) {
			obj.checked = false;
			this.paymentButton = false;
			this.deliveryButtonChangeState();
		}
		obj.disabled = true;

		var cls = getE("Eshop_PaymentTr"+id).className;
		if (cls.indexOf(" ")>0) { cls = cls.substring (0,cls.indexOf(" ")); }
		cls = cls+" EshopPaymentOff";
		getE("Eshop_PaymentTr"+id).className = cls;
	} ,
	
	cartContactSwitcher : function ( id ) {
		if ( getE(id+"Switcher") && getE(id+"Content") ) {
			if (getE(id+"Switcher").checked) {
				getE(id+"Content").style.display = ""
			} else {
				getE(id+"Content").style.display = "none"
			}
		}
	} ,
	
	cartContactAnonymousSwitcher : function () {
		if ( getE("Eshop_AnonymousSwitcher") && getE("Eshop_ContactLoginForm")  && getE("Eshop_ContactContainer") ) {
			if (getE("Eshop_AnonymousSwitcher").checked) {
				getE("Eshop_ContactLoginForm").style.display = "none"
				getE("Eshop_ContactContainer").style.display = ""
			} else {
				getE("Eshop_ContactLoginForm").style.display = ""
				getE("Eshop_ContactContainer").style.display = "none"
			}
		}
	}

}


PM_eshopajax.activateAjax ();

