﻿
//GET
//Non-Asynchronous getXML
function getXML(sURL) {
	var xmlHTTP = getXmlHTTP();

	if (sURL.indexOf("?") == -1) sURL += "?";
	xmlHTTP.open("GET", sURL + "&t=" + new Date().toLocaleString(), false);

	xmlHTTP.send(null);

	var sResponse = xmlHTTP.responseText;
	if (xmlHTTP.status != 200) {
		sResponse = "ERROR";
		addAlert(sResponse + " " + xmlHTTP.status);
	}
	if (sResponse.match("!ERROR!") == "!ERROR!") {
		addAlert(sResponse);
	}
	//alert(sResponse);
	return sResponse;
}
function fillXML(sURL) {
	var sXML = getXML(sURL);
	if (sXML == "") { return null; }
	return getXMLDocFromString(sXML);
}

//Asynchronous getXML
var asyncCallBack = null;
function getXML_async(sURL, callBack) {
	var xmlHTTP = getXmlHTTP();
	if (!sURL.contains("?")) sURL += "?";
	xmlHTTP.open("GET", sURL + "&t=" + new Date().toLocaleString(), true);
	xmlHTTP.onreadystatechange = function() {
		if (xmlHTTP.readyState == 4) {
			var sResponse = xmlHTTP.responseText;
			if (xmlHTTP.status != 200) {
				sResponse = "ERROR";
				addAlert(sResponse + " " + xmlHTTP.status);
			}
			if (sResponse.match("!ERROR!") == "!ERROR!") {
				addAlert(sResponse.replace("!ERROR!", ""), window.location.href);
			}
			if (gDebugMode) alert(sResponse);
			if (callBack) callBack(sResponse);
		}
	}
	xmlHTTP.send(null);
}
function fillXML_async(sURL, callBack) {
	asyncCallBack = callBack;
	getXML_async(sURL, fillXML_async2);
}
function fillXML_async2(response) {
	var sXML = response;
	if (sXML == "") { return null; }
	asyncCallBack(getXMLDocFromString(sXML));
}



//POST
//Non-Asynchronous postXML
function postXML(sURL, sXML) {
	if (gDebugMode) alert(sXML);
	var xmlHTTP = getXmlHTTP();
	xmlHTTP.open("POST", sURL, false);
	xmlHTTP.send(sXML);
	var sResponse = xmlHTTP.responseText;
	if (gDebugMode) { alert(sResponse) };
	if (sResponse.contains("SUCCESS")) {
		if (sResponse.length > 7) return sResponse.substring(7);
	}
	else {
		addAlert(sResponse, window.location.href, 0, true);
		return null;
	}
	if (xmlHTTP.status != 200) {
		sResponse = "error";
		addAlert(sResponse);
	}
	return sResponse;
}

// == POST Asynchronously ==
function postForm_async(url, contents, callBack) {
	if (gDebugMode) alert(contents);
	var xmlHTTP = getXmlHTTP();
	xmlHTTP.open("POST", url, true);
	xmlHTTP.onreadystatechange = function() {
		if (xmlHTTP.readyState == 4) {
			var sResponse = xmlHTTP.responseText;
			if (sResponse.contains("SUCCESS")) {
				if (sResponse.length > 7) {
					if (callBack) callBack(sResponse.substring(7));
					return;
				}
			}
			else {
				addAlert(sResponse);
			}
			if (xmlHTTP.status != 200) addAlert(xmlHTTP.responseText);
			if (callBack) callBack(sResponse);
		}
	}
	xmlHTTP.send(contents);
}


//Functions
function getXmlHTTP() {
	var xmlHTTP = null;
	if (window.XMLHttpRequest) {
		xmlHTTP = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xmlHTTP;
}


function getXMLData() {
	// Error Handling & Validation
	// Loop through all columns to see if the column exists
	// Make sure that objXML has xml in it
	// Make sure the row exists and tell the user that there are only x amount of row

	var objXML = arguments[0];
	var rowNumber = 0;
	var columnName = "";
	if (isNaN(arguments[1])) {
		columnName = arguments[1];
	}
	else {
		rowNumber = arguments[1];
		columnName = arguments[2];
	}
	
	var s = "";
	var tableName = "";
	try {
		tableName = objXML.getElementsByTagName("*")[1].nodeName;
		var value = "";
		if (window.ActiveXObject) {
			var path = "//XMLData/" + tableName + "/" + columnName;
			value = objXML.selectNodes(path).item(rowNumber).text;
		}
		else {
			value = objXML.getElementsByTagName(columnName)[rowNumber].childNodes[0].nodeValue;
		}
		value = value.replace("*es*", "");
		if (value.toLowerCase() == "false") value = false;
		return value;
	}
	catch (err) {
		if (!objXML && !columnName) {
			addAlert("XML object is undefined.'");
		}
		else if(!objXML && columnName) {
			addAlert("XML object is empty while trying to access Row " + rowNumber + " of column '" + columnName + "'");
		}
		else if (objXML && columnName && tableName) {
			addAlert("Column '" + columnName +  "' not found in table '" + tableName + "'");
		}
		else {
			addAlert(err.description, err.url, err.line);
		}
	}
}

function getXMLDocFromString(sXML) {
	var xmlDoc = null;
	if (!window.ActiveXObject) {
		//var xmlDoc = document.implementation.createDocument("", "", null);
		//alert(sXML);
		var parser = new DOMParser();
		xmlDoc = parser.parseFromString(sXML, "text/xml");
	}
	else {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(sXML);
	}
	return xmlDoc;

}

function createObjectFromXMLDocument(xmlDoc) {
  var tableName = $("XMLData", xmlDoc).children(0)[0].tagName;
  var cols = $("XMLData " + tableName, xmlDoc).children(0);
  obj = new Object();
  for (var L = 0; L <= cols.length - 1; L++) {
    var colName = cols[L].tagName;
    var value = $(cols[L]).text();
    eval("obj." + colName + "='" + value + "'");
    value = value.replace("*es*", "");
  }
  return obj;
}


function runCommand(command, values) {
	if (command.toLowerCase().contains("runxml")) {
		var url = gAppPath + "/elexiajax/aspx/command.aspx?command=" + command;
		return postXML(url, values);
	}
	else {
		var url = gAppPath + "/elexiajax/aspx/command.aspx?command=" + command + "&" + values;
		return getXML(url);
	}
}

function runCommand_async(command, paramsOrXml, callback) {
	if (typeof paramsOrXml == "function") {
		callback = paramsOrXml;
		paramsOrXml = "";
	}
	if (command.toLowerCase().contains("runxml")) {
		//TO BE DEVELOPED
		var url = gAppPath + "/elexiajax/aspx/command.aspx?command=" + command + "&dt=" + new Date();
		return postForm_async(url, paramsOrXml, callback);
	}
	else {
		var url = gAppPath + "/elexiajax/aspx/command.aspx?command=" + command + "&" + paramsOrXml;
		return getXML_async(url, callback);
	}
}

function getRecords_async(table, callback, recordID, fields, where, orderBy, tableName, topOne) {
//	var url = gAppPath + "/elexiajax/aspx/getxml.aspx?";
//	url += "&table=" + table;
//	if (fields) url += "&fields=" + fields;
//	if (recordID == 0) url += "&blankrecord=1";
//	else if (recordID) url += "&id=" + recordID;
//	if (orderBy) url += "&orderby=" + orderBy;
//	if (where) url += "&where=" + where;
//	if (tableName) url += "&tablename=" + tableName;
//	if (topOne) url += "&topone=1";
//  fillXML_async(url, callback);
	getData({
		table: table,
		recordID: recordID,
		fields: fields,
		where: where,
		orderBy: orderBy,
		tableName: tableName,
		topOne: topOne
	}, callback);
	
}


// == LATEST & GREATEST JQUERY IMPLEMENTATION == //
function getData(props, callback) {
	var url = gAppPath + "/elexiajax/aspx/";
	var page = "getxml.aspx";
	var params = "";

	if (props.blankRecord || props.recordID == 0) page = "blankrecord.aspx";
	if (props.command) {
		page = "command.aspx";
		params += addParam("command", props.command);
	}
	params += addParam("releaseid", gAppReleaseID);
	if (props.params) params += props.params;
	if (props.table) params += addParam("table", props.table);
	if (props.fields) params += addParam("fields", props.fields);
	if (props.recordID && props.recordID != 0) params += addParam("id", props.recordID);
	if (props.orderBy) params += addParam("orderBy", props.orderBy);
	if (props.where) params += addParam("where", props.where);
	if (props.tableName) params += addParam("tableName", props.tableName);
	if (props.topOne) params += addParam("topOne", 1);

	if (props.success) callback = props.success;

	if (props.debug) {
		var s = "";
		for (var i in props) {
			if (i != "success") s += i + ": " + props[i] + "<br>";
		}
		addAlert(s);
	}
	
	url += page + "?" + params;

	var allowCache = false;
	if (props.cache == true) allowCache = true;
	var doAsync = false;
	if (props.async == null) doAsync = true;
	else if (props.async) doAsync = props.async;

	if (!window.ajaxCount) ajaxCount = 0;
	window.ajaxCount += 1;
	appStatus("Loading");
	
	if (props.debug) addAlert(url);
	return $.ajax({
		type: "GET",
		url: url,
		dataType: "xml",
		success: callback,
		error: handleError,
		cache: allowCache,
		async: doAsync,
		complete: function() {
			window.ajaxCount -= 1;
			if (window.ajaxCount == 0) appStatus("Loaded", true, { delay: 600 });
		}
	});
}


function handleError(XMLHttpRequest, textStatus, errorThrown) {
	addAlert(XMLHttpRequest.responseText);
	//alert(XMLHttpRequest.responseText);
}


function getRecord_async(table, recordID, callback, fields, tableName) {
	getRecords_async(table, callback, recordID, fields, null, null, tableName, true)
}
function getRecord(table, recordID, fields, where, tableName) {
	return getRecords(table, recordID, fields, where, null, tableName, true);
}


function getRecords(table, recordID, fields, where, orderBy, tableName, topOne) {
	var url = gAppPath + "/elexiajax/aspx/getxml.aspx?";
	url += "&table=" + table;
	if (fields) url += "&fields=" + fields;
	if (recordID == 0) url += "&blankrecord=1";
	else if (recordID) url += "&id=" + recordID;
	if (orderBy) url += "&orderby=" + orderBy;
	if (where) url += "&where=" + where;
	if (tableName) url += "&tablename=" + tableName;
	if (topOne) url += "&topone=1";
	return fillXML(url);
}


function getRecordCount(objXML) {
	if (!objXML.getElementsByTagName("XMLData")[0].childNodes[0]) return 0;
	var tableName = objXML.getElementsByTagName("*")[1].nodeName;
	var firstColumnName = objXML.getElementsByTagName("*")[2].nodeName;
	return $("XMLData " + tableName + " " + firstColumnName, objXML).length;
}

//Convenience
function runXMLUpdate(xml) { return runCommand("runxmlupdate", xml); }
function runXMLUpdate_async(xml, callback) { runCommand_async("runxmlupdate", xml, callback); }
function runXMLDelete(xml) { runCommand("runxmldelete", xml); }
function runXMLInsert(xml) { return runCommand("runxmlinsert", xml); }
function runXMLInsert_async(xml, callback) { runCommand_async("runxmlinsert", xml, callback); }

function manageSession(action, variable, value) { return runCommand("managesession", "action=" + action + "&variable=" + variable + "&value=" + value); }


//Backwards Compatibility
function GetXML(sURL) { return getXML(sURL); }
function FillXML(sURL) { return fillXML(sURL); }
function PostXML(sURL, sXML) { return postXML(sURL, sXML); }
function getRowCount(objXML) { return getRecordCount(objXML); }
function postXML_async(url, xml, callBack) { postForm_async(url, xml, callBack); }
