var ajaxCallOn = 0;
var ajaxCallOff = 0;
var ajaxCallCnt = 0;
	
var maintainanceArr = new Array();

function encodeStr(str){
	if(isNaN(str) && !isArray(str)) {
		str = str.replace(/&/g, '##AND##');		
		str = str.replace(/\+/g, '##ADD##');		
		str = str.replace('=', '##EQUAL##');
		str = str.replace('?', '##QUESTION##');
		str = str.replace('%', '##PERCENT##');
	}
	return str;
}
function decodeStr(str){
	str = str.replace('##ADD##', '+');
	str = str.replace('##AND##', '&');
	str = str.replace('##EQUAL##', '=');
	str = str.replace('##QUESTION##', '?');
	str = str.replace('##PERCENT##', '%');
	return str;
}

function AjaxInit(){
	var AjaxObj = false;
	if(window.XMLHttpRequest){
		AjaxObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		AjaxObj=new ActiveXObject("Msxml2.XMLHTTP");
		if (!AjaxObj){
			AjaxObj=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return(AjaxObj);
}
function ajaxVars(){
	this.vars = new Array();
	this.vars['sqlDB'] = '0';
	this.fnVars = new Array();
	this.dbVars = new Array();
	this.sendMethod = 'POST';
	this.gotoFunction = '';
	this.xmlData = '';	
	this.statusDiv = 'loadingDiv';
	this.AjaxPostSQL = AjaxPostSQL;
	this.createData = createData;
	this.errorData = errorData;
	this.sqlTracer = sqlTracer;	
	this.xmlOpener = xmlOpener;
	this.maintainance = maintainance;
	this.externalErrors = externalErrors;
	this.session = 1;
	this.sessionVar = 'sessCPAuth';
	this.phpFile = _gDOC_ROOT + "playscheme_lib/ajax.data.php";
	this.incModule = '';
	this.noLayer = 1;
}

function AjaxPostSQL(){
	
	if (ajaxCallCnt)
		ajaxCallCnt++;
	var pageUrl = this.phpFile;
	if(pageUrl.indexOf('?') < 0) {
		pageUrl += '?';
	}else{
		pageUrl += '&';
	}

	pageUrl += 'random=' + Math.random();
	
	var queryStr = '&dbVars=' + this.dbVars;
	for(key in this.vars){
		queryStr += '&' + key + '='  + encodeStr(this.vars[key]);
	}
	if(this.session) {
		queryStr += '&sessionVar='  + this.sessionVar;
	}
	if(this.incModule){
		queryStr += '&incModule='  + this.incModule;
	}
	if(this.sendMethod == 'GET') {
			pageUrl += queryStr;
	}
	
	var Ajax = AjaxInit();
	
	try{
		var callObj = this;
		Ajax.open(this.sendMethod, pageUrl, true);
		Ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
		str = '';
		for(key in Ajax) {
			str += key + "\n";
		}
		Ajax.onreadystatechange = function(){
			var loadingObj = document.getElementById(callObj.statusDiv);
			if (Ajax.readyState == 4 && Ajax.status == 200) {
				
				var dtStatus = handleAjax(Ajax, callObj);
				if(dtStatus === false){
					return false;
				}
				
				if(ajaxCallCnt)
					ajaxCallCnt--;
				
				if(loadingObj){
						if(ajaxCallCnt == 0) {
							if(callObj.noLayer == 1){
								hideStatus(loadingObj.id, 'Done.');
							}
						}
				}
			}else if(Ajax.readyState == 1){
				if(loadingObj){
					var bodyObj = document.getElementsByTagName('BODY')[0];
					if(callObj.noLayer == 1){
						showStatus(loadingObj.id, 'Communicating with the server. Please wait...');
					}
				}
			}else if(Ajax.readyState < 4){
				if(loadingObj){
					if(callObj.noLayer == 1){
						showStatus(loadingObj.id, 'Loading data. Please wait...');
					}
				}
			}else{
				var statusLostObj = document.getElementById('statusLost');
				if(statusLostObj){
					statusLostObj.style.visibility = 'visible';
					statusLostObj.style.display = 'block';
				}
			}
		}
		Ajax.send(queryStr);
	}
	catch(e){
		alert('Error: Unable to contact the server.');
	}
}
function handleAjax(Ajax, callObj){
	var ajaxRes = Ajax.responseText;
//	alert(Ajax.responseText);
 	if(ajaxRes.indexOf('META HTTP-EQUIV=') > 0) {
	 	if(location.href.indexOf('index.php')<0){
		 	parent.parent.location.href = 'index.php';
		}
		return false;
 	}
 	if( (ajaxRes.indexOf('Fatal error')) >= 0 && (ajaxRes.indexOf('on line')) || 
 		 (ajaxRes.indexOf('Warning')) >= 0 && (ajaxRes.indexOf('on line')) || 
		 (ajaxRes.indexOf('Parse error')) >= 0 && (ajaxRes.indexOf('on line')) ){
	 	
	 	var re = /<[^>]*>/g;
	 	var matches = ajaxRes.replace(re,'');
 		alert(matches);
 		
		ajaxCallCnt = 0;
		hideStatus(callObj.statusDiv, 'Done.');
		return false;
 	}
 	
	var response = Ajax.responseXML.documentElement;
	var sessionObj = response.getElementsByTagName('session');
	
	var dataObj = response.getElementsByTagName('row');
	var errorObj = response.getElementsByTagName('sqlerror');
	var textObj = response.getElementsByTagName('textdata');
	
	switch(callObj.vars['action']) {
		case "update":
		case "modify":
			if(ajaxRes.indexOf('maintainance()') >= 0){
				callObj.maintainance();
				break;
			}
	}
	if(callObj.session) {
		var sessionId = sessionObj[0].firstChild.nodeValue;
		if(!sessionId) {
			parent.parent.pageOpener('login','devArea','err=9');
			hideStatus(callObj.statusDiv, 'Done.');
			ajaxCallOn = 0;
			ajaxCallOff = 0;
			ajaxCallCnt = 0;
			return false;
		}
	}
	
	dataArr = callObj.createData(dataObj,textObj);
	callObj.errorData(errorObj, dataObj, textObj);
	callObj.xmlData = ajaxRes;
	var xmlLinkObj = document.getElementById('xmlLink');
	if(xmlLinkObj) {
		xmlLinkObj.href = "javascript:void(0);";
		xmlLinkObj.mainObj = callObj;
		xmlLinkObj.onclick = function(e) {
			var hiddenObj = document.getElementById('xmlajaxdata');
			hiddenObj.value = this.mainObj.xmlData;
			this.mainObj.xmlOpener();
		}
	}
	eval(callObj.gotoFunction + '(dataArr, callObj.fnVars)');
	
}
function createData(rowObj, textObj){
	if(rowObj.length > 0) {
		var str = '';
		var dataArr = new Array();
		var str = '';
		for(var i=0; i<rowObj.length; i++){
			var colObj = rowObj[i].getElementsByTagName('column');
			for(var j=0; j<colObj.length; j++){
				var fieldName = colObj[j].getAttribute('name');
				switch(this.vars['action']) {
					case "update":
					case "modify":
					case 'phpArray':
					case 'db_fetch_array':
					case 'db_fetch_row':
					case 'db_fetch_assoc':
						if(!dataArr[fieldName]) dataArr[fieldName] = new Array();
						dataArr[fieldName][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
				}
			}
		}
		return dataArr;
	}else{
		if(textObj[0]) {
			return textObj[0].firstChild.nodeValue;
		}
	}
}
function externalErrors(){
	var debugDivObj = document.getElementById('debugSql');
	var errorTags = document.getElementsByTagName('p');
	if(errorTags.length > 0) {
		var errLen = errorTags.length;
		for(var i=0; i<errLen; i++){
			var attName = errorTags[0].getAttribute('name');
			if(attName == 'sqlerror'){
				errorTags[0].name = 'ajaxsqlerror';
				errorTags[0].setAttribute('name', 'ajaxsqlerror');
				
				var errorDiv = document.createElement('DIV');
				errorDiv.innerHTML = errorTags[0].innerHTML;
				errorDiv.style.fontFamily = errorTags[0].style.fontFamily;
				errorDiv.style.fontSize = errorTags[0].style.fontSize;				
				errorDiv.style.backgroundColor = errorTags[0].style.backgroundColor;								
				errorDiv.style.color = errorTags[0].style.color;
				errorDiv.style.padding = '5px';				
				errorDiv.setAttribute('name', 'ajaxsqlerror');				

				debugDivObj.insertBefore(errorDiv, debugDivObj.firstChild);
				
				errorTags[0].parentNode.removeChild(errorTags[0]);				
			}
		}
	}
}
function errorData(dataObj, rowObj, textObj){
return false;
	// if($_SESSION["sess_sql"] || $_SESSION["sess_debug"] || $_SESSION["sess_trace"]) {

	// this.sqlTracer();
	// showHideDiv('debugDiv', true);
	
	// var debugWinObj = document.getElementById('debugDiv');
	// var debugDivObj = document.getElementById('debugSql');
	// var debugObj = document.getElementById('debugData');
	
	// if(dataObj.length > 0) {
		
		// this.externalErrors();
				
		// for(key=0; key<dataObj.length; key++){
			// var errorData = dataObj[key].getElementsByTagName('p');
			// if(errorData[0].firstChild.nodeValue) {
				// var errorText = "<DIV NAME=\"ajaxsqlerror\" STYLE=\"padding:5px;"+errorData[0].getAttribute('style')+"\">";
				// errorText += errorData[0].firstChild.nodeValue;
				// errorText += "</DIV>";
				// debugDivObj.innerHTML = errorText + debugDivObj.innerHTML;
			// }
		// }
		// var newOut = '';
		// if(rowObj.length) {
			// for(var i=0; i<rowObj.length; i++){
				// var colObj = rowObj[i].getElementsByTagName('column');
				// newOut += '<hr />';
				// for(var j=0; j<colObj.length; j++){
					// var fieldName = colObj[j].getAttribute('name');
					// newOut += '<span style="color: #F00; font-family: arial; font-size:11px;">' + fieldName + '</span>';
					// newOut += '<span style="color: #000; font-family: arial;font-size:11px;">=</span>';
					// newOut += '<span style="color: #00F; font-family: arial;font-size:11px;">' + colObj[j].firstChild.nodeValue + '</span>';
					// newOut += '<br />';
				// }
			// }
		// }else{
			// newOut += '<hr />';			
			// newOut += '<span style="color: #FF0; font-family: arial;font-size:11px;">' + textObj[0].firstChild.nodeValue + '</span>';
		// }
		// var debugObj = document.getElementById('debugData');
		// if(debugObj) {
			// debugObj.innerHTML = newOut + debugObj.innerHTML;
		// }
	// }
// } else { 	
	// showHideDiv('debugDiv', false);
 // } 	
}

function sqlTracer(){
	
	var debugWinObj = document.getElementById('debugDiv');
	var debugDivObj = document.getElementById('debugSql');
	var debugObj = document.getElementById('debugData');
	var bodyObj = document.getElementsByTagName('BODY')[0];
	
	var formObj = document.createElement('FORM');
	formObj.target = '_blank';
	formObj.method = 'POST';
	formObj.name = 'xmldata';
	formObj.id = 'xmldata';
	formObj.action = _gDOC_ROOT + 'echodata.php';
	
	var hiddenObj = document.createElement('INPUT');
	hiddenObj.type = 'hidden';
	hiddenObj.name = 'data';
	hiddenObj.id = 'xmlajaxdata';
	formObj.appendChild(hiddenObj);
	
	var hiddenObj = document.createElement('INPUT');
	hiddenObj.type = 'hidden';
	hiddenObj.name = 'filename';
	hiddenObj.value = 'xmldata.xml';
	hiddenObj.id = 'xmlfilename';	
	formObj.appendChild(hiddenObj);
	
	bodyObj.appendChild(formObj);
		
	if(!debugWinObj) {
		var debugWinObj = document.createElement('DIV');
		debugWinObj.id = 'debugDiv';
		debugWinObj.style.position = 'absolute';
		debugWinObj.style.top = '0px';
		debugWinObj.style.width = '40%';
		debugWinObj.style.height = '80%';
		debugWinObj.style.backgroundColor = '#CCCCCC';
		debugWinObj.style.cursor = 'default';
		bodyObj.appendChild(debugWinObj);
			
		var dragDivObj = document.createElement('DIV');
		dragDivObj.id = 'debugDrag';
		dragDivObj.style.backgroundColor = 'buttonFace';
		dragDivObj.style.padding = '2px 10px 2px 10px';
		dragDivObj.style.border = "1px outset buttonShadow";
		dragDivObj.style.cursor = 'move';
		dragDivObj.style.fontSize = '12px';
		dragDivObj.style.fontFamily = 'arial';
		dragDivObj.innerHTML = '<B>SQL Tracer</B>';
		dragDivObj.onmousedown = function(e) {
			var divDrag = new drag;
			moveDiv(e, divDrag, this.parentNode.id);
		}
		dragDivObj.open = true;
		dragDivObj.ondblclick = function(e) {
			if(dragDivObj.open) {
				dragDivObj.open = false;
				showHideDiv('debugSql', false);
				showHideDiv('tracerSpacer', false);
				showHideDiv('debugData', false);
				this.parentNode.style.height = this.parentNode.firstChild.offsetHeight + 'px';
			}else{
				dragDivObj.open = true;
				showHideDiv('debugSql', true);
				showHideDiv('tracerSpacer', true);
				showHideDiv('debugData', true);
				this.parentNode.style.height = '80%';
			}
		}
		debugWinObj.appendChild(dragDivObj);
			
		var debugDivObj = document.createElement('DIV');
		debugDivObj.id = 'debugSql';
		debugDivObj.style.height = '40%';
		debugDivObj.style.padding = '10px';
		debugDivObj.style.overflow = 'auto';
		debugDivObj.style.backgroundColor = '#CCCCCC';
		debugWinObj.appendChild(debugDivObj);
		
		var spacerDivObj = document.createElement('DIV');
		spacerDivObj.id = 'tracerSpacer';
		
		var xmlLinkObj = document.createElement('A');
		xmlLinkObj.href = "javascript:void(0);";
		xmlLinkObj.innerHTML = 'XML output';
		xmlLinkObj.style.fontSize = '11px';
		xmlLinkObj.style.fontFamily = 'arial';
		
		xmlLinkObj.mainObj = this;
		xmlLinkObj.id = 'xmlLink';
		xmlLinkObj.onclick = function(e) {
			this.mainObj.xmlOpener();
		}
		
		spacerDivObj.appendChild(xmlLinkObj);
		
		spacerDivObj.style.textAlign = 'right';		
		spacerDivObj.style.padding = '5px 10px 5px 0px';				
		debugWinObj.appendChild(spacerDivObj);
		
		var newHeight = debugWinObj.offsetHeight - dragDivObj.offsetHeight - dragDivObj.offsetHeight - debugDivObj.offsetHeight - spacerDivObj.offsetHeight;
		
		var debugObj = document.createElement('DIV');
		debugObj.id = 'debugData';
		debugObj.style.backgroundColor = '#CCCCCC';
		debugObj.style.height = newHeight + 'px';
		debugObj.style.padding = '10px';
		debugObj.style.overflow = 'auto';
		debugWinObj.appendChild(debugObj);
	}
	showHideDiv('debugDiv', true);
}

function xmlOpener(){
	var formObj = document.getElementById('xmldata');
}
function empty(){
	ajaxCallOff++;
}
function maintainance(){
	if(maintainanceArr[location.href] != 1) {
		maintainanceArr[location.href] = 1;
		alert('Sorry! Data cannot be saved at this moment. Maintainance program is running in one of the branches.');
	}
	if(callObj.noLayer == 1){
		hideStatus();
	}
}
function resetMaintainance(){
	maintainanceArr[location.href] = 0;
}
function isArray(obj) {
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false; 
	else 
		return true; 
}
function showHideDiv(id, status){
	var divObj = document.getElementById(id);
	if(divObj) {
		if(status) {
			divObj.style.visibility = "visible"; 
			divObj.style.display = "block"; 
		}else{
			divObj.style.visibility = "hidden"; 
			divObj.style.display = "none"; 
		}
	}
}
function showHideDivBlock(id, status){
	var divObj = document.getElementById(id);
	if(divObj) {
		if(status) {
			divObj.style.visibility = "visible"; 
			divObj.style.display = "block"; 
		}else{
			divObj.style.visibility = "hidden"; 
			divObj.style.display = "block"; 
		}
	}
}
function showHideDivClass(id, status){
	var divObj = document.getElementById(id);
	if (status == 1){
		divObj.style.visibility = "visible"; 
		divObj.style.display = "block"; 
	}else{
		divObj.style.visibility = "hidden"; 
		divObj.style.display = "none"; 
	}	
}
function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}else if (obj.x){
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}else if (obj.x){
		curtop += obj.x;
	}
	return curtop;
}
function hideStatus(divId, err){
	var loadingObj = document.getElementById(divId);
	if(loadingObj) {
		loadingObj.style.visibility = 'hidden';
		loadingObj.style.cursor = 'default';
// 		loadingObj.innerHTML = err;
		loadingObj.childNodes[1].innerHTML = err;
	}
}
function showStatus(divId, err){
	var loadingObj = document.getElementById(divId);
	if(loadingObj) {
		loadingObj.style.visibility = 'visible';
		loadingObj.style.cursor = 'wait';
// 		loadingObj.innerHTML = err;
		loadingObj.childNodes[1].innerHTML = err;
	}
}
