// Asynchronous Javascript and XML (AJAX) tools
//
// (c) e-Buzz bv (SvI), 2006
// OLD VERSION -- One request/response handling at a time!!
var http_request = false;

function loadXMLDoc(url) {
	http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP.6.0");
		} catch (e) {
  		try {
  			http_request = new ActiveXObject("Msxml2.XMLHTTP.3.0");
  		} catch (e) {
    		try {
    			http_request = new ActiveXObject("Microsoft.XMLHTTP");
    		} catch (e) {}
  		}
  	}	
	}
	if (!http_request) {
		alert('Cannot create an XMLHTTP instance. This browser does not (fully) support XMLHttpRequest.');
		return false;
	}
	http_request.onreadystatechange = alertContents;
	http_request.open('GET', url, true);
	http_request.send(null);
}

function alertContents() {
	// only if http_request shows "complete"
	if (http_request.readyState == 4) {
		// only if "OK"
		if (http_request.status == 200) {
			// ...processing statements go here...
			var xmlDoc  = http_request.responseXML;
			// alert(http_request.responseText);
			var responseNode = xmlDoc.getElementsByTagName('response');
			var method = null;
			for (var i=0;i<responseNode.length;i++) {
				var method = responseNode[i].getAttribute('method');
				eval(method + '(\'\', xmlDoc)');
			}
		} else {
			alert("There was a problem retrieving the XML data:\n" + http_request.statusText);
		}
	}
}

function getTranslation (id) {
	return document.getElementById(id).firstChild.data;
}

function removeChildNodes(node) {
// Remove all childs of node
	var nodesLength = node.childNodes.length
	if (node.hasChildNodes) {
		for (var i=0;i<nodesLength;i++) {
			node.removeChild(node.childNodes[0]);
		}
	}
}

function updateChildTextNode(element,text) {
// Replace innerHtml text of element
	var nodes = element.childNodes;
	var textNode = document.createTextNode(text);
	// Remove existing textnodes
	if (nodes.length != 0) {
		for (var i = 0; i <= nodes.length; i++){
			try {
				if (nodes[i].nodeType == 3) {
					element.removeChild(nodes[i]);
				}
			}
			catch(e) {/* <= nodes.length????? */}
		}
	}
	// Add textNode
	element.appendChild(textNode);
}

function appElementNodeText(parentNode, element, elId, styleClass, txt) {
// Append new element with innerHtml text to parentNode
	var newElement = document.createElement(element);
	var txtNode = document.createTextNode(txt);
	newElement.setAttribute("id", elId);
	newElement.className = styleClass;
	newElement.appendChild(txtNode);
	parentNode.appendChild(newElement);
}


// (c) ECi (SB), 2008
// NEW VERSION -- Multiple request/response handlings at a time!!
// See DealerApproval App. for usage!

/*— content loader object for cross-browser requests —*/
var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;

net.ContentLoader=function(url,onload,onerror,method,params,contentType){
	this.req=null;
	this.onload=onload;
	this.onerror=(onerror) ? onerror : this.defaultError;
	this.loadXMLDoc(url,method,params,contentType);
	this.parameter = null;
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
	if (!method) method="GET";
	if (!contentType && method=="POST") contentType='application/x-www-form-urlencoded';
	if (window.ActiveXObject){  
		this.req=new ActiveXObject("Microsoft.XMLHttp");
	} else if (window.XMLHttpRequest){
		this.req=new XMLHttpRequest();
	}
	if (this.req){
		try{
			var loader=this;
			this.req.onreadystatechange=function(){
				net.ContentLoader.onReadyState.call(loader);
			}
			this.req.open(method,url,true);
			if (contentType) {
				this.req.setRequestHeader('Content-Type', contentType);
				this.req.setRequestHeader('Content-length', params.length);
				this.req.setRequestHeader('Connection', 'close');
			}
			this.req.send(params);
		}
		catch (e) {
			this.onerror.call(this);
		}
	}
}

net.ContentLoader.onReadyState=function(){
	var req=this.req;
	var ready=req.readyState;
	if (ready==net.READY_STATE_COMPLETE){
		var httpStatus=req.status;
		if (httpStatus==200 || httpStatus==0){
			this.onload.call(this);
		} else {
			this.onerror.call(this);
		}
	}
}

net.ContentLoader.prototype.defaultError=function(){
	alert("error fetching data!"
		+"\n\nreadyState:"+this.req.readyState
		+"\nstatus: "+this.req.status
		+"\nheaders: "+this.req.getAllResponseHeaders());
}

var aUrl='';
//Actual AJAX call NEW VERSION 
function doAjax(url, callback) {
	aUrl = url;
	loader = new net.ContentLoader(url,callback, ajaxError);
}
function doAjaxPost(url, callback, parms) {
	aUrl = url;
	loader = new net.ContentLoader(url,callback, ajaxError, "POST", parms);
}


function getStock(prdcod) {// SB/122189 Get Stock  
	doAjax('ajStockInq?product='+prdcod, updateStock);
}    
function updateStock() {
	if (this.req.responseXML.getElementsByTagName('stock')[0].firstChild) {
		var stock = this.req.responseXML.getElementsByTagName('stock')[0].firstChild.nodeValue;
	} else {
		var stock = '';
	}  
	var prod = this.req.responseXML.getElementsByTagName('product')[0].firstChild.nodeValue;      
	var oldChild = document.getElementById('stockEnquiry' +prod).firstChild;
	var newChild = document.createTextNode(stock);
	if (document.getElementById('stockEnquiry' +prod).innerHTML != '') {
		removeChildNodes(document.getElementById('stockEnquiry' +prod));
	}
	document.getElementById('stockEnquiry' +prod).appendChild(newChild);
}  
function saveView(prog, mode) {// SB/167 Save Settings 
	if (prog=='INFOPR3'){
		var setArr = new Array();
		try {setArr[0] = document.getElementsByName('sort')[0].value;}
		catch (e) {setArr[0]  = '';}
	}
	if (prog=='INQORD3'){
		var setArr = new Array(4);
		try {setArr[0] = document.getElementsByName('accountNbr')[0].value;}
		catch (e) {setArr[0] = '';}
		try {setArr[1] = document.getElementsByName('orderStatus')[0].value;}
		catch (e) {setArr[1] = '';}
		try {setArr[2] = document.getElementsByName('showOrdzzz')[0].value;}
		catch (e) {setArr[2] = '';}
		setArr[3] = document.getElementsByName('sort')[0].value;
	}
	saveSettings( setArr, setArr.length, prog, mode);
}


// SB/167 Save Settings 
function saveSettings( sArr, idx, prog, mode ) {
	var url = 'ajSaveSet?progr=' +prog+ '&mode=' +mode+ '&nbrIdx=' +idx;
	for (i=0; i< sArr.length; i++) {
		url = url + '&varPar[' +i+ ']=' +sArr[i]; 
	}
	doAjax(url, showMessage);
	function showMessage() {
		document.getElementById('savSetting_Message').innerHTML = this.req.responseText;
		document.getElementById('savSetting_'+prog).style.display = "block";
	}
}

function ajaxError(){
	var errorState = this.req.status;
	var errorLevel = String(errorState).substr(0, 1);
	switch (errorState) {
	case 404 :
		var errorMessage = "Document "+aUrl+" not found.";
		break;
	case 408 :
		var errorMessage = "The server did not respond in the allocated time.";
		break;
	case 500 :
		var errorMessage = "Server too busy.";
		break;
	case 504 :
		var errorMessage = "The server did not respond in the allocated time.";
		break;
	default :
		switch (errorLevel) {
		case 4 :
			var errorMessage = "File error.";
			break;
		case 5 :
			var errorMessage = "Server error.";
			break;
		default :    
			var errorMessage = "Sorry, unknown error.";
		}  
	}
	errorHeader = 'Something went wrong! The following problem occured:\n';
	if (location.port!='') errorHeader = 'When executing\n'+ aUrl+',\n the following problem occured:\n';
	alert(errorHeader+errorMessage + ' (' +errorState+ ').');
}

// Work with XML and XSLT thru Ajax
// Especially build for compare products page
// At this point (09-10-09) not yet active
function listOfComparedProducts(url, elem) {
	// Get the XML file from the server.
	loader = new net.ContentLoader(url,  null, ajaxError);    
	var xml_doc = loader.req.responseXML;

	// Get the XSLT from the server.
	url = url + '&xsl=1';
	loader = new net.ContentLoader(url, null, ajaxError);    
	var xsl_doc = loader.req.responseXML;

	var div = document.getElementById (div_name);
	// Use object detection to find out if we have
	// Firefox/Mozilla/Opera or IE XSLT support.
	if (typeof XSLTProcessor != "undefined") {
		var xsl_proc = new XSLTProcessor ();
		xsl_proc.importStylesheet (xsl_doc);
		var node = xsl_proc.transformToFragment (xml_doc, document);
		div.innerHTML = "";
		div.appendChild (node);
	}
	else if (typeof xml_doc.transformNode != "undefined") {
		div.innerHTML = xml_doc.transformNode (xsl_doc);
	}
	else {
		div.innerHTML = "XSLT not supported in browser.";
	}
}

function rtvPrice(cod, acc, qty) {
	url = '/easyorder/ajwsprice?accountNbr='+acc+'&article='+cod+'&quantity='+qty;
	document.getElementById('price_'+cod).innerHTML = '...';
	doAjax(url, showPrice);
}
function showPrice() {
	var price=null,prd=null,seq=null,pct=null,disc=null;
	if (this.req.responseXML.getElementsByTagName('price')[0]) {
		if (this.req.responseXML.getElementsByTagName('price')[0].firstChild) {
			price = this.req.responseXML.getElementsByTagName('price')[0].firstChild.nodeValue;
		}
	}
	if (this.req.responseXML.getElementsByTagName('prod')[0]) {
		if (this.req.responseXML.getElementsByTagName('prod')[0].firstChild) {
			prd = this.req.responseXML.getElementsByTagName('prod')[0].firstChild.nodeValue;
		}
	}
	if (this.req.responseXML.getElementsByTagName('errorMsg')[0]) {
		if (this.req.responseXML.getElementsByTagName('errorMsg')[0].firstChild) {
			err = this.req.responseXML.getElementsByTagName('errorMsg')[0].firstChild.nodeValue;
			inps=document.getElementsByTagName('input');
			for (i=0; i<inps.length; i++) {
				if (inps[i].value && inps[i].name.substr(0,6) == 'prdCod'){
					if (inps[i].value == prd) seq=inps[i].name.substr(6);
					if (seq!=null) break;
				}
			}
			document.getElementById('infoErr'+seq).innerHTML = err;
		}
	}
	if (price!=null && prd!=null) document.getElementById('price_'+prd).innerHTML = price;
	if (pageId=='INFOPR4') {
		if (this.req.responseXML.getElementsByTagName('discPct')[0] && document.getElementById('prod_disc_pct_'+prd)) {
			if (this.req.responseXML.getElementsByTagName('discPct')[0].firstChild) {
				pct = this.req.responseXML.getElementsByTagName('discPct')[0].firstChild.nodeValue;
				document.getElementById('prod_disc_pct_'+prd).innerHTML = pct+'%';
			}
		}
		if (this.req.responseXML.getElementsByTagName('discPrice')[0] && document.getElementById('prod_disc_price_'+prd)) {
			if (this.req.responseXML.getElementsByTagName('discPrice')[0].firstChild) {
				disc = this.req.responseXML.getElementsByTagName('discPrice')[0].firstChild.nodeValue;
				document.getElementById('prod_disc_price_'+prd).innerHTML = disc;
			}
		}
		if (pct>0) document.getElementById('prod_discount').style.display=''; else document.getElementById('prod_discount').style.display='none';
		if (pct==null || disc==null) document.getElementById('prod_discount').style.display='none';
	}
}

