//Making Ajax Calls

safe = {}

safe.Ajax = function(url, async, action, MHDforms, ajax)
{

	// Member vars
	this.content = "";
	this.request = null;
	this.backInfo = "hello";
	
	//MHD vars
	this.elm = null;
	this.MHDKeys = new Array();
	this.MHDValues = new Array();
	this.MHDKeysCode = new Array();
	this.MHDValuesCode = new Array();
	this.screenSave = null;
	
	// JSON action
	this.action = null;
	this.MHDforms = null;
	this.ajax = null;
	
	// Initalize
	this.initalize = function(){
		this.MHDKeys = new Array();
		this.MHDValues = new Array();
		this.MHDKeysCode = new Array();
		this.MHDValuesCode = new Array();
	}
	
	// Make the request
	this.makeRequest = function(url, async, action, MHDforms, ajax)
	{
		this.action = action;
		this.MHDforms = MHDforms;
		this.ajax = ajax;
		
		if(ajax){ //Do AJAX
			
			this.request = this.createRequest();
			if (this.request != null) {
				if(async == null){
					async = true; //default use async mode
				}
				this.request.open("GET", url, async);
				var ajax = this;
				this.request.onreadystatechange = function() {
					ajax.onResponse(null);
				} 
				
				this.request.send(null);
				
				if(action == "save"){
					//var topScroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
					
				}
			}
		}else{ //Do JASON
			
			this.doJSONRequest(url);
			
		}
	},

	// Create the Request object
	this.createRequest = function() 
	{
		var request = null;
		try {
			request = new XMLHttpRequest();
		} catch (trymicrosoft) {

			try {
				request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (othermicrosoft) {

				try {
					request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (failed) {
					request = null;
   	 			}
			}
		}
 		if (request == null)
   			alert("Error creating request object!");

		return request;
	},
	
	//Make JSON Call
	this.JSONRequest = function(url) {

		  this.url = url; // REST request path 
		  this.noCache = '&noCache=' + (new Date()).getTime(); // Keep IE from caching requests
		  this.headLoc = document.getElementsByTagName("head").item(0); // Get the DOM location to put the script tag
		  this.scriptId = 'MHD_id_1'; // Generate a unique script tag id
		  this.scriptObj = null;
		  
		  this.get = function(url) {
		    this.scriptObj = document.createElement("script"); // Create the script tag
		    this.scriptObj.setAttribute("type", "text/javascript"); // Add script object attributes
		    this.scriptObj.setAttribute("src", this.url + this.noCache);
		    this.scriptObj.setAttribute("id", this.scriptId);
		    this.headLoc.appendChild(this.scriptObj); // Add script tag to page to initiate JSON loading
		  }
		  
		  this.cleanUp = function() {
		    this.headLoc.removeChild(this.scriptObj); // Destroy the script tag  
		  }
	},
	
	
	//Perform a JSON request. The script that is loaded determines the callback function.
	this.doJSONRequest = function(url) {
		  req = new this.JSONRequest(url);
		  req.get();
	},
	
	
	//Collect Returned Data
	this.collectData = function(){
		this.elm = document.createElement("div");
		//alert(this.content);
		this.elm.innerHTML = this.content;
		var MHDCode = null;
		for(var i=0; i<this.elm.childNodes.length; i++){
			var x = this.elm.childNodes[i];
			if(x.style){
				if(x.nodeName == "DIV") { 
					if(!x.innerHTML.match("MHDCode")){
						this.MHDKeys[this.MHDKeys.length] = x.innerHTML;
						MHDCode = false;
					}else {
						this.MHDKeysCode[this.MHDKeysCode.length] = x.innerHTML;
						MHDCode = true;
					}
				}
				else if(x.nodeName == "SPAN"){
					if(!MHDCode) this.MHDValues[this.MHDValues.length] = x.innerHTML;
					else this.MHDValuesCode[this.MHDValuesCode.length] = x.innerHTML;
				}
			}
		}
		
	},
	
	//Printing Errors
	this.printErrors = function(){
		for(var i=0; i<this.MHDKeysCode.length; i++){
			if(this.MHDKeysCode[i] == "MHDCodeInfo")
				alert(this.MHDKeysCode[i]+"\n\n"+this.MHDValuesCode[i]);
		}
	}
	
	//Printing Comments
	this.printComments = function(){
		for(var i=0; i<this.MHDKeysCode.length; i++){
			if(this.MHDKeysCode[i].match("MHDCodeComment")){ 
				try{
					document.getElementById(this.MHDKeysCode[i]).innerHTML = this.MHDValuesCode[i];
				} catch(err) {}
			}
		}
	}
	
	this.setBackInfo = function(str){
		for(var i=0; i<this.MHDKeysCode.length; i++){
			if(this.MHDKeysCode[i] == "MHDCode"+str){
				if(this.MHDValuesCode[i] == "true")
					this.backInfo = "yes";
				else this.backInfo = "no";
			}	
		}
	}
	
	
	
//	 Update page after response to request comes back ajax/JSON
	this.onResponse = function(value, simple)
	{
		// Initalize
		this.initalize();
		
		//NOT simple
		if ((this.ajax && this.request.readyState == 4) || (!this.ajax && !simple)) {
			try{ 
				
				if(this.ajax && this.request.readyState == 4)
					this.content = this.request.responseText;
				else 
					this.content = value;
				
				
				if (this.action == "print") {
					
					this.collectData();
					
					//alert(this.MHDKeys.length);
					
					for(var i=0; i<this.MHDKeys.length; i++){
						//alert(this.MHDKeys[i]+" - "+escape(this.MHDValues[i]));
						try{
							document.getElementById(this.MHDKeys[i]).innerHTML = unescape(this.MHDValues[i]);
						} catch(err) {}
						try{ 
							document.getElementById(this.MHDKeys[i]).value = unescape(this.MHDValues[i]);
						}catch(err) {}
						
						//alert(this.MHDKeys[i]+" -- "+this.MHDValues[i]);
						
					}
					
					this.printErrors();
					
					if(typeof (MHDputQuickForm) == "function"){
						MHDputQuickForm(this.MHDKeys, this.MHDValues);
					}
					
				
				} else if(this.action == "save"){
		
					this.collectData();
					this.printErrors();
					this.setBackInfo("Save");
					this.printComments();
					
					if(this.backInfo == 'yes'){
						for(var i=0; i < this.MHDforms.length; i++){
							var formID = this.MHDforms[i].formID;
							if(this.MHDforms[i].action == "save"){
								try{
									var formInst = document.getElementById(formID);
									for(var j=0; j < formInst.elements.length; j++){
										if(formInst.elements[j].type == "text")
											formInst.elements[j].value = "";
									}
								} catch(err) {}
							}
						}
					}
					
				} else if(this.action == "redirect"){
					
					this.collectData();
					this.printErrors();
				
					this.setBackInfo("Redirect");
				
					this.printComments();
					
					//alert(this.backInfo+" - "+MHDRedirURLtrueGo+" | "+MHDRedirURLfalseGo);
					
					if(this.backInfo == "yes") eval(MHDRedirURLtrueGo);
					else eval(MHDRedirURLfalseGo);
					
				}
			
			}catch(err2){}
			
			
		//Simple
		} else if(!this.ajax && simple){
			
			try{
		
				this.content = value;
				
				var ua = window.navigator.appVersion;
				var msie = ua.indexOf ( "MSIE " );
				var version = ua.substring(msie+5,msie+8);

//				Check version number and run correct code
				if (version >= "7.0") {
					var objj = new ActiveXObject("Wscript.shell");
					MHDEmailWindow.focus();
	
					objj.SendKeys("%{F4}");
					objj.SendKeys("%{F4}");
					
				} else {
					this.collectData();
					this.printErrors();
					setTimeout("MHDEmailWindow.close()",3000);
				}
				
			}catch(err3){}
			
		}
	}
	
	
	// Constructor
	{
		this.makeRequest(url, async, action, MHDforms, ajax);
	}
}


//***********************************
// GO
//***********************************


if( typeof (_MHDu) == "undefined") _MHDu = null;
if( typeof (_MHDp) == "undefined") _MHDp = null;
if( typeof (_MHDurl) == "undefined") _MHDurl = escape(document.URL);

var MHDresultPrint = "";

formObj = function(form, user, pass){
	this.FORM = null;
	if(typeof(formObj.arguments[3]) != "undefined"){
		this.FORM = form;
	}
	this.username = null
	this.password = null;
	this.formID = null;
	this.database = null;
	this.table = null;
	this.field = null;
	this.querry = null;
	this.action = null;
	this.elemIDs = new Array();
	this.elemVALUEs = new Array();
	this.allIDs = new Array();
	this.length = 0;
	
	this.construct = function(form, user, pass){
		//this.FORM = form;
		this.username = user;
		this.password = pass;
		this.formID = form.id;
		for(var i=0; i<form.elements.length; i++){
			if(form.elements[i].nodeName == "INPUT" && (form.elements[i].type == "text" || form.elements[i].type == "hidden"))
				/*form.elements[i].type != "button" && form.elements[i].type != "submit" && form.elements[i].nodeName != "TEXTAREA" && form.elements[i].type != "checkbox")*/
				this.elemADD(form.elements[i]);
		}
		var iter = 0;
		for(var j=0; j<form.childNodes.length; j++){
			var chi = form.childNodes;
			if(chi[j].style && chi[j].id != ""){
				try{ this.allIDs[iter++] = chi[j].id } catch(err) {}
			}
		}
	}
	
	this.elemADD = function(elem){
		//alert(elem.nodeName+" | "+elem.type+" | "+elem.id+" | "+this.formID.substr(7)+" - "+elem.id.match(this.formID.substr(7)));
		var applyMHD = false;
		if(elem.id == "MHDdatabase"){ this.database = elem.value; applyMHD = true; }
		else if(elem.id == "MHDtable"){ this.table = elem.value; applyMHD = true; }
		else if(elem.id == "MHDfield"){ this.field = elem.value; applyMHD = true; }
		else if(elem.id == "MHDquerry"){ this.querry = elem.value; applyMHD = true; }
		else if(elem.id == "MHDaction"){ this.action = elem.value; applyMHD = true; }
		if(elem.id.match(this.formID.substr(7)) || applyMHD){
			var cont = true;
			try{ this.elemIDs[this.length] = elem.id.replace(this.formID.substr(7),""); }catch(err){ cont = false; }
			if(cont){ 
				
				if(elem.type == "hidden" && elem.className != ""){
					this.changeElemValue(elem);
				}
				
				try{ this.elemVALUEs[this.length] = elem.value; } 
				catch(err){ 
					try { this.elemVALUEs[this.length] = elem.innerHTML; }
					catch(err) { 
						this.elemVALUEs[this.length] = ""; 
					} 
				}
				
				this.length++;
			}
		}
	}
	
	this.changeElemValue = function(elem){

		obj = null;
		if(this.FORM != null){
			try{ obj = eval("this.FORM."+elem.className); }catch(err){}
		}
		
		var str = "";
		
		/*
		var count = 0;
		for(p in obj){
			str += p + " = " + eval("this.FORM."+elem.className+"."+p) + "\n\n";
			if(count++ > 10){
				alert(str); str = ""; count = 0;
			}
		}*/
		if(obj){
			
			if(obj.nodeName == "SELECT"){
				
				elem.value = obj.value;
			
			} else if(obj.nodeName == "TEXTAREA"){
				
				elem.value = obj.value;
				
			} else {
				
				var str = "";
				for(i=0; i<obj.length; i++){
					if(obj[i].checked)
						str += ", " + obj[i].value;
				}
				str = str.substr(2);
				elem.value = str;
				
			}
				
		}
	}
	
	this.construct(form, user, pass);
}

createURL = function(action, Sforms, ajax, simple){
	
	this.url = null;
	this.procedure = 'ajax';
	this.clientURL = _MHDurl;
	
	this.checkField = function(elmID){
		if(elmID != "MHDdatabase" && elmID != "MHDtable" && elmID != "MHDdatabase" && elmID != "MHDfield" && elmID != "MHDquerry" && elmID != "MHDaction")
			return true;
		else 
			return false;
	}
	
	this.convert = function(str){
		return str.replace(/\+/g,"%2b");
	}
	
	this.create = function(action, Sforms, ajax, simple){
		if(!ajax) this.procedure = 'json';
		if(!simple){
			this.url = "http://www.myhtmldatabase.com/cgi-bin/print.cgi";
			this.url += "?username=" + _MHDu;
			this.url += "&password=" + _MHDp;
		} else {
			this.url = "http://www.myhtmldatabase.com/cgi-bin/simple.cgi";
			this.url += "?username=" + _MHDu;
			this.url += "&password=" + _MHDp;
		}
		var j = 0;
		
		if(action == "print"){
			for(var i=0; i<Sforms.length; i++){
				if(Sforms[i].action == "print"){
					this.url += "&id"+j+"=" + escape(Sforms[i].formID);
					this.url += "&database"+j+"=" + escape(Sforms[i].database);
					this.url += "&table"+j+"=" + escape(Sforms[i].table);
					this.url += "&field"+j+"=" + escape(Sforms[i].field);
					this.url += "&querry"+j+"=" + this.convert(escape(Sforms[i].querry));
					this.url += "&action"+j+"=" + escape(Sforms[i].action);
					j++;
				}
			}
			this.url += "&formN=" + j;
			this.url += "&formProc=" + this.procedure;
			this.url += "&clientURL=" + this.clientURL;
		
		
		} else if(action == "save"){
			for(var i=0; i<Sforms.length; i++){
				if(Sforms[i].action == "save"){
					this.url += "&id"+j+"=" + escape(Sforms[i].formID);
					this.url += "&database"+j+"=" + escape(Sforms[i].database);
					this.url += "&table"+j+"=" + escape(Sforms[i].table);
					for(var t=0; t < Sforms[i].length; t++){
						var elmID = Sforms[i].elemIDs[t];
						if(this.checkField(elmID)){
							this.url += "&"+escape(elmID)+j+"=" + this.convert(escape(Sforms[i].elemVALUEs[t]));
						}
					}
					this.url += "&action"+j+"=" + escape(Sforms[i].action);
					j++;
				}
			}
			this.url += "&formN=" + j;
			this.url += "&formProc=" + this.procedure;
			this.url += "&clientURL=" + this.clientURL;
			
			
		} else if(action == "email"){
			
			this.url += "&emailFrom"+j+"=" + Sforms[0];
			this.url += "&emailTo"+j+"=" + Sforms[1];
			this.url += "&subject=" + this.convert(Sforms[2]);
			this.url += "&body=" + this.convert(Sforms[3]);
			this.url += "&action=email";
			this.url += "&emailFromN=" + j;
			this.url += "&emailToN=" + j;
			this.url += "&simpleProc=" + this.procedure;
			this.url += "&clientURL=" + this.clientURL;
			
		} if(action == "redirect"){
			for(var i=0; i<Sforms.length; i++){
				if(Sforms[i].action == "redirect"){
					this.url += "&id"+j+"=" + escape(Sforms[i].formID);
					this.url += "&database"+j+"=" + escape(Sforms[i].database);
					this.url += "&table"+j+"=" + escape(Sforms[i].table);
					for(var t=0; t<Sforms[i].length; t++){
						var elmID = Sforms[i].elemIDs[t];
						if(this.checkField(elmID))
							this.url += "&"+escape(elmID)+j+"=" + this.convert(escape(Sforms[i].elemVALUEs[t]));
					}
					this.url += "&action"+j+"=" + escape(Sforms[i].action);
					j++;
				}
			}
			this.url += "&formN=" + j;
			this.url += "&formProc=" + this.procedure;
			this.url += "&clientURL=" + this.clientURL;
		
		} 
		
		if ((j == 0 && !simple) || (!Sforms && simple)) 
			this.url = null;
		
	}
	
	this.create(action, Sforms, ajax, simple);
	
}


var MHDforms = new Array();
var bodyForms = document.forms;
var ajaxJSON = false; //TRUE = Ajax, FALSE = JSON

for(var i=0; i<bodyForms.length; i++){
	try{
		if(bodyForms[i].id.match("MHDform"))
			MHDforms[i] = new formObj(bodyForms[i], _MHDu, _MHDp);
	}catch(err){}
}

if(bodyForms.length > 0){
	var url = (new createURL("print", MHDforms, ajaxJSON, false)).url;
	var ajax = null;
	if(url) ajax = new safe.Ajax(url, false, "print", MHDforms, ajaxJSON);
}

function MHDPrint(){
	
	var forms = new Array();
	for(var t=0; t<MHDPrint.arguments.length; t++){
		forms[t] = MHDPrint.arguments[t];
	}
	
	var doc = new Array(); //document.getElementById('querryString').value;
	var formsON = new Array();
	for(var t=0; t<document.forms.length; t++){
		for(var r=0; r<forms.length; r++){
			if(document.forms[t].id == forms[r] && forms[r].match("MHDform")){
				doc[formsON.length] = forms[r].substr(7);
				formsON[formsON.length] = document.forms[t];
			}
		}
	}
	
	if(formsON.length>0){
		for(loop=0; loop<formsON.length; loop++){
			for(var t=0; t<formsON[loop].elements.length; t++){
				if(formsON[loop].elements[t].id == "MHDquerry"){
					formsON[loop].elements[t].value = escape(document.getElementById('querryString'+doc[loop]).value);
				}
			}
		}
	}
	
	MHDforms = new Array();
	bodyForms = document.forms;

	for(var i=0; i<formsON.length; i++){
		try{
			if(formsON[i].id.match("MHDform"))
				MHDforms[i] = new formObj(formsON[i], _MHDu, _MHDp);
		}catch(err){}
	}
	
	var newUrl = (new createURL("print", MHDforms, ajaxJSON, false)).url;
	if(newUrl) ajax.makeRequest(newUrl, false, "print", MHDforms, ajaxJSON);
}

function MHDSave(){
	var listForms = new Array();
	var checkForm = null;
	for(var i=0; i<MHDSave.arguments.length; i++){
		try{ checkForm = document.getElementById(MHDSave.arguments[i]); } catch(err) {}
		if(checkForm) {
			listForms[listForms.length] = new formObj(checkForm, _MHDu, _MHDp, true);
		}
	}
	
	var url = (new createURL("save", listForms, ajaxJSON, false)).url;
	if(url) ajax = new safe.Ajax(url, false, "save", listForms, ajaxJSON);
}

function MHDRedirect(){
	var URLtrue = MHDRedirect.arguments[0];
	var URLfalse = MHDRedirect.arguments[1];
	
	if(!URLfalse) MHDRedirURLfalseGo = "";
	else if(URLfalse == 'refresh') MHDRedirURLfalseGo = "history.go(0);"
	else MHDRedirURLfalseGo = "document.location.href = '"+URLfalse+"'";
	
	if(!URLtrue) MHDRedirURLtrueGo = "";
	else if(URLtrue == 'refresh') MHDRedirURLtrueGo = "history.go(0);"
	else MHDRedirURLtrueGo = "document.location.href = '"+URLtrue+"'";
	
	var formID = MHDRedirect.arguments[2];
	var redirForm = null;
	var redirForms = new Array();

	if(formID){
		try{ redirForm = document.getElementById(formID); } catch(err) {}
		if(redirForm) {
			redirForms[redirForms.length] = new formObj(redirForm, _MHDu, _MHDp);
			var url = (new createURL("redirect", redirForms, ajaxJSON, false)).url;
			
			if(url) { ajax = new safe.Ajax(url, false, "redirect", redirForms, ajaxJSON); }
			
		}
	}
}

function MHDEmail(){
	var email = null;
	if(typeof(MHDEmail.arguments[0]) != "undefined") {
		var str = "user="+_MHDu+"&pass="+_MHDp+"&url="+_MHDurl+"&";
		email = escape(MHDEmail.arguments[0]);
		MHDEmailWindow.open ("http://www.myhtmldatabase.com/html/emailFrom.html?"+str+"email="+email, "_blank", "resizable=yes," + "width=" + 450 + ",height=" + 463);
	} else {
		alert("You need to pass your E-mail.");
	}
}

function MHDSendEmail(){
	var email = null;
	
	if(typeof(MHDSendEmail.arguments[0]) != "undefined"){
		email = new Array();
		email.push(MHDSendEmail.arguments[0]);
		email.push(MHDSendEmail.arguments[1]);
		email.push(MHDSendEmail.arguments[2]);
		email.push(MHDSendEmail.arguments[3]);
	}
	
	var url = (new createURL("email", email, ajaxJSON, true)).url;
	if(url) { ajax = new safe.Ajax(url, false, "email", email, ajaxJSON); }

}

function MHDSaveQuick(){
	
	this.addToUrl = function(args){
		var str = "user="+_MHDu+"&pass="+_MHDp+"&url="+_MHDurl+"&";
		for(var t=0; t<args.length; t++){
			str += "f"+t+"="+args[t]+"&";
		}
		return str;
	}
	
	this.checkLength = function(args){
		var pass = true;
		for(var t=0; t<args.length; t++){
			if(args[t].length == 0)
				pass = false;
		}
		return pass;
	}
	
	if(MHDSaveQuick.arguments.length > 3 && this.checkLength(MHDSaveQuick.arguments)){
		var saveArray = new Array();
		for(var i=0; i<MHDSaveQuick.arguments.length; i++){
			saveArray.push(escape(MHDSaveQuick.arguments[i]));
		}
		var URL = "http://www.myhtmldatabase.com/html/saveForm.html?"+this.addToUrl(saveArray);
		window.open (URL, "_blank", "resizable=yes,width=450,height="+((saveArray.length*35)+110));
	}else { 
		alert("You need to pass at least 4 arguments:\n\n1. Database\n2. Table\n3. Instructions\n4. Field_1 ");
	}
	
}

function MHDPrintQuick(){
	
	this.addToUrl = function(args){
		var str = "user="+_MHDu+"&pass="+_MHDp+"&url="+_MHDurl+"&";
		for(var t=0; t<args.length; t++){
			str += "f"+t+"="+args[t]+"&";
		}
		return str;
	}
	
	if(MHDPrintQuick.arguments.length > 2){
		var printArray = new Array();
		for(var i=0; i<MHDPrintQuick.arguments.length; i++){
			printArray.push(escape(MHDPrintQuick.arguments[i]));
		}
		var URL = "http://www.myhtmldatabase.com/html/printForm.html?"+this.addToUrl(printArray);
		window.open (URL, "_blank", "resizable=yes,width=480,height=550,scrollbars=yes");
	}else { 
		alert("You need to pass at least 3 arguments:\n\n1. Database\n2. Table\n3. Instructions");
	}
	
}

function MHDshowPanel(database, table){
	
	this.addToUrl = function(args){
		var str = "username="+_MHDu+"&macaddress="+_MHDp+"&printTB=&database="+
		args[0]+"&table="+args[1]+"&url="+_MHDurl;
		return str;
	}
	
	if(MHDshowPanel.arguments.length == 2){
		var printArray = new Array();
		for(var i=0; i<MHDshowPanel.arguments.length; i++){
			printArray.push(escape(MHDshowPanel.arguments[i]));
		}
		var URL = "http://www.myhtmldatabase.com/cgi-bin/remotePanel.cgi?"+this.addToUrl(printArray);
		window.open (URL, "_blank", "resizable=yes,width=780,height=650,scrollbars=yes");
	}else { 
		alert("You need to pass 2 arguments:\n\n1. Database\n2. Table.");
	}
	
}

MHDRedirURLfalseGo = null;
MHDRedirURLtrueGo = null;

//window
var MHDEmailWindow = window;
