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

function encodeStr(str){
	if(isNaN(str) && !isArray(str)) {
		str = str.replace(/&/g, '##AND##');		
		str = str.replace(/=/g, '##EQUAL##');
		str = str.replace('?', '##QUESTION##');
		str = str.replace('%', '##PERCENT##');
	}
	return str;
}
function decodeStr(str){
	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.fnVars = new Array();
	this.dbVars = new Array();
	this.sendMethod = 'POST';
	this.gotoFunction = '';
	this.xmlData = '';	
	this.status = 'loadingDiv';
	this.AjaxPostSQL = AjaxPostSQL;
	this.createData = createData;
	this.errorData = errorData;
	this.sqlTracer = sqlTracer;	
	this.xmlOpener = xmlOpener;
	this.maintainance = maintainance;
	this.externalErrors = externalErrors;	
	this.phpFile = _globalDocRoot + "lib/ajax.data.php";
}

function AjaxPostSQL(){
	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.sendMethod == 'GET') {
			pageUrl += queryStr;
	}
	var Ajax = AjaxInit();
	try{
		var callObj = this;
		Ajax.open(this.sendMethod, pageUrl);
		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.status);
			if (Ajax.readyState == 4 && Ajax.status == 200) {
				if(loadingObj){
					loadingObj.innerHTML = 'Done.';
				}
				handleAjax(Ajax, callObj);
			}else if(Ajax.readyState == 1){
				if(loadingObj){
					loadingObj.innerHTML = 'Connecting to server. Please wait...';
				}
			}else if(Ajax.readyState < 4){
				if(loadingObj){
					loadingObj.innerHTML = '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 response = Ajax.responseXML.documentElement;
	var dataObj = response.getElementsByTagName('row');
	var errorObj = response.getElementsByTagName('sqlerror');
	var textObj = response.getElementsByTagName('textdata');
	
	switch(callObj.vars['action']) {
		case "update":
		case "modify":
			if(Ajax.responseText.indexOf('maintainance()') >= 0){
				callObj.maintainance();
				break;
			}
	}	
	dataArr = callObj.createData(dataObj,textObj);
	callObj.errorData(errorObj, dataObj, textObj);
	callObj.xmlData = Ajax.responseText;
	
	
	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 'db_fetch_array':
						if(!dataArr[fieldName]) dataArr[fieldName] = new Array();
						if(!dataArr[j]) dataArr[j] = new Array();
						dataArr[fieldName][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
						dataArr[j][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
					
					case 'db_fetch_row':
						if(!dataArr[j]) dataArr[j] = new Array();
						dataArr[j][i] = (colObj[j].firstChild) ? colObj[j].firstChild.nodeValue : '';
					break;
					
					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{
		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(sessSql || sessDebug ||sessTrace){

	//this.sqlTracer(); //commented by chetan as it was popping error div
	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 = _globalDocRoot + 'index/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++;
	hideStatus();
}
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.');
	}
	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 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 showStatus(){
	document.getElementsByTagName('BODY')[0].style.cursor = 'wait';
	var onObj = document.getElementById('statusOn');
	var offObj = document.getElementById('statusOff');
	if(onObj) {
		onObj.style.visibility = 'visible';
		onObj.style.display = 'block';
	}
	if(offObj) {
		offObj.style.visibility = 'hidden';
		offObj.style.display = 'none';
	}
}
function hideStatus(){
	document.getElementsByTagName('BODY')[0].style.cursor = 'default';
	var onObj = document.getElementById('statusOn');
	var offObj = document.getElementById('statusOff');
	if(offObj) {
		offObj.style.visibility = 'visible';
		offObj.style.display = 'block';
	}
	if(onObj) {
		onObj.style.visibility = 'hidden';
		onObj.style.display = 'none';
	}
}
