// Javascript libraries for ARX forms

SteamingPileOfCrap = navigator.appVersion.indexOf('MSIE') != -1;


// CREATES AJAX CONNECTION
// VOID()
function AJAX_initConn() {
	
	// Open IE connection
	if (navigator.appName == 'Microsoft Internet Explorer')
		AJAXHTTPObj = new ActiveXObject("Microsoft.XMLHttp");
	
	// Open connection for any other browser
	else
		AJAXHTTPObj = new XMLHttpRequest;
	
	// Return object
	return AJAXHTTPObj;
}

AJAX_initConn();


// SENDS A GET REQUEST
// (STRING url, BOOL use GET/POST [0 = POST, 1 = GET], OBJ ajax http object [leave blank to use default])
function AJAX_sendRequest(UseGET, url, EvalCodeFromResponse, EvalCodeAfterOpen, GETVarStrForPostSubmit, Alt_AJAXHTTPObj) {
	
	// Which HTTP obj to use?
	UseAJAXHTTPObj = (Alt_AJAXHTTPObj)?Alt_AJAXHTTPObj:AJAXHTTPObj;

	// Generate URL
	if (url.indexOf('?') == 0)
		url = getScriptName() + url;
	
	// Make sure AJAX conn. obj is set
	if (typeof UseAJAXHTTPObj != "undefined") {
		
		// Sending POST request - split the URL
		if (!UseGET) {
			url_array = url.split('?');
			url       = url_array[0] + ((GETVarStrForPostSubmit)?'?' + GETVarStrForPostSubmit:'');
			QueryStr  = url_array[1];
		}
		else
			QueryStr = null;
		
		// Open GET connection and send NULL to start server-side processing...
		UseAJAXHTTPObj.open((UseGET)?'GET':'POST', url, true);
		
		if (EvalCodeAfterOpen)
			eval(EvalCodeAfterOpen);
		
		if (!UseGET)
			AJAXHTTPObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		
		UseAJAXHTTPObj.send(QueryStr);
		
		// On state change, check for ready state and return response text (if any)
		UseAJAXHTTPObj.onreadystatechange = function() {
			if (UseAJAXHTTPObj.readyState == 4) {
				response = UseAJAXHTTPObj.responseText;
				if (EvalCodeFromResponse != null)
					eval(EvalCodeFromResponse);
				else
					return response;
	
				return;
			}	
		}
	}
}


// CONVERTS FORM DATA TO GET STRING
function convertFormDataToQueryStr(formObj, AlternateParentElmntForFields) { 
		
	POSTDataArray = new Array();
	
	// Loop through form fields
	AltCounter = 0;
	ElmntsList = '';
	
	if (AlternateParentElmntForFields)
		LoopInObjectsArray = new Array(formObj.elements,
					       AlternateParentElmntForFields.getElementsByTagName('input'),
					       AlternateParentElmntForFields.getElementsByTagName('textarea'),
					       AlternateParentElmntForFields.getElementsByTagName('select')
					      );

	else
		LoopInObjectsArray = new Array(formObj.elements);
	
 	for (var i in LoopInObjectsArray) {
	
		for (var j = 0; j < LoopInObjectsArray[i].length; j++) {
			
			Elmnt = LoopInObjectsArray[i][j];
	
			Name  = '';
			Value = '';
			
			if (!Elmnt.disabled) {
			
				// Submit different information for various types of fields...
				switch (Elmnt.type) {
					
					// "Normal" field
					default:
						Name  = Elmnt.name;
						Value = Elmnt.value;
					break;
					
					// Radio
					case 'radio':
						if (Elmnt.checked) {
							Name  = Elmnt.name;
							Value = Elmnt.value;
						}
					break;
					
					// Checkbox
					case 'checkbox':
						Name  = Elmnt.name;
						Value = (Elmnt.checked)?Elmnt.value:'';
					break;
				}
				
				if (Name != '' && Name != 'undefined' && Name != undefined && Name != 'null' && Name != null) {
					POSTDataArray[AltCounter] = encodeURIComponent(Name) + '=' + encodeURIComponent(Value);
					AltCounter++;
				}
			}
		}
	}
	
	return POSTDataArray.join('&');
}


// Submits form via AJAX
function formToAJAX(FormObj, ActionURL) {
	
	ActionURL    = (ActionURL != null)?ActionURL:FormObj.action;
	GETVarsArray = ActionURL.split('?');	
	SubmitURL    = GETVarsArray[0] + '?' + convertFormDataToQueryStr(FormObj);
	
	FormObj2 = FormObj;
	
	generateWaitDiv('Processing Form');
	
	AJAX_sendRequest(false,
	
	SubmitURL,
	
	"deleteWaitDiv(); if (response.substr(0,7) == 'ERRORS:') { setErrors(response, FormObj2); } " +
	"else if (response == 'GOOD') { showThanks(); } else { alert(response); } ", null, GETVarsArray[1]);
}


// Sets errors next to form fields
function setErrors(ErrorOutput, FormObj) {
	ErrorsArray = ErrorOutput.substr(7).split('|');
	
	// Clear all error containers
	Divs = FormObj.getElementsByTagName('div');
	for (i in Divs) {
		try {
			if (Divs[i].id.substr(0,6) == 'ERROR_') {
				Divs[i].innerHTML = '';
				Divs[i].style.display = 'none';
			}
		}
		
		catch (e) {
			// do nothing
		}
	}
	
	for (i in ErrorsArray) {
		Error = ErrorsArray[i].split(':');
		
		try {
			with (document.getElementById('ERROR_' + Error[0])) {
				style.display = 'block';
				innerHTML = Error[1];
			}
		}
		catch (e) {
			// do nothing
		}
	}
	
	document.getElementById('ErrorMsg').style.display = 'block';
	location.href = 'javascript:scroll(0,0)';
}


// Shows the "thank-you" message
function showThanks() {
	with (document) {
		getElementById('MainFormOutput').style.display = 'none';
		getElementById('ThankYouDiv').style.display    = 'block';
		location.href = 'javascript:scroll(0,0)';
	}
}




// Generates a div containing a "please wait..." message
function generateWaitDiv(OverrideText, DoNotGenerateDisableDiv, CustomCSSArray, OverrideInnerHTML, DoNotAnimate) {

	var NewDiv = document.createElement('div');

	if (!OverrideInnerHTML)
		var ContainedText = document.createTextNode(((OverrideText)?OverrideText:'Please Wait') + '...');
	
	with (NewDiv.style) {
		width         = '180px';
		position      = 'absolute';
		border        = '1px solid #BCBCFF';
		background    = '#EFEFFF';
		fontWeight    = 'bold';
		textAlign     = 'center';
		verticalAlign = 'middle';
		paddingTop    = '20px';
		paddingBottom = '20px';
		zIndex        = '10';
		
		// Override CSS...
		if (typeof CustomCSSArray == 'object') {
			for (CSSDirective in CustomCSSArray)
				eval(CSSDirective + ' = \'' + CustomCSSArray[CSSDirective] + '\'');
		}		
		
		left = (getWindowDimension('x')/2)-((parseInt(width)+20)/2) + 'px';
		top  = String(parseInt(document.body.scrollTop) + parseInt((getWindowDimension('y')/2)-(parseInt(paddingTop)+parseInt(paddingBottom)+10))) + 'px';
	}
	
	NewDiv.setAttribute('id', 'WaitDiv');
	
	if (!OverrideInnerHTML)
		NewDiv.appendChild(ContainedText);	
	
	if (!DoNotGenerateDisableDiv) {
		var NewDisableDiv = document.createElement('div');
		
		with (NewDisableDiv.style) {
			top      = '0px';
			left     = '0px';
			width    = '100%';
			position = 'absolute';
			zIndex   = '9';
			
			if (SteamingPileOfCrap) {
				//background = "url('" + JS_http_path_to_provisioner + "/admin/images/space.gif')";
				toggleSelectMenuVisibility(true, 'hidden');
			}
		}
		
		NewDisableDiv.style.height = document.body.scrollHeight;
	}
	
	NewDisableDiv.setAttribute('id', 'DisableDiv');
	
	if (OverrideInnerHTML)
		NewDiv.innerHTML = OverrideInnerHTML;
	
	document.body.appendChild(NewDiv);
	document.body.appendChild(NewDisableDiv);
	
// 	if (!DoNotAnimate)
// 		WaitAnimateInterval = setInterval(animateProgressThingy, 333);
}


// DELETES WAIT DIV
function deleteWaitDiv() {
	document.body.removeChild(document.getElementById('WaitDiv'));
	document.body.removeChild(document.getElementById('DisableDiv'));
	toggleSelectMenuVisibility(true, 'visible');
	
// 	if (typeof WaitAnimateInterval != 'undefined')
// 		clearInterval(WaitAnimateInterval);
}

// GETS WINDOW DIMENSIONS
function getWindowDimension(Dim) {
	if (Dim == 'x')
		return (SteamingPileOfCrap)?document.body.offsetWidth:window.innerWidth;
	else
		return (SteamingPileOfCrap)?document.body.offsetHeight:window.innerHeight;
}

// TOGGLES VISIBILITY OF ALL SELECT MENUS
function toggleSelectMenuVisibility(OnlyForIE, OverrideVisibility) {
	if (navigator.appName == "Microsoft Internet Explorer" || !OnlyForIE) {
		for (i = 0; i < document.forms.length; i++) {
			for (j = 0; j < document.forms[i].elements.length; j++) {
				Obj       = document.forms[i].elements[j];
				ElmntType = Obj.type;
	
				if (ElmntType == "select-one" || ElmntType == "select-multiple") {					
					if (OverrideVisibility)
						Obj.style.visibility = OverrideVisibility;
					else {
						NoVisibility = (document.forms[i].elements[j].style.visibility == "")?true:false;
						Obj.style.visibility = (NoVisibility)?'hidden':'visible';
					}
				}
			}
		}
	}
}

// Gets the name of script/page from a URL
function getScriptName(OverrideURL, IncludeQueryStr, ReturnOnlyQueryStr) {
	UseURL         = (OverrideURL)?OverrideURL:document.location.href;
	UseURL         = UseURL.replace(/#.*/, '');
	QueryStrExists = UseURL.indexOf('?') != -1;
	
	QueryStr = '';

	if (QueryStrExists) {
		QueryStr = UseURL.substr(UseURL.indexOf('?'));
		UseURL   = UseURL.substr(0, UseURL.indexOf('?'));
	}

	if (QueryStrExists && IncludeQueryStr)
		return (ReturnOnlyQueryStr)?QueryStr:UseURL.substr(UseURL.lastIndexOf('/')+1) + QueryStr;
	else
		return (ReturnOnlyQueryStr)?QueryStr:UseURL.substr(UseURL.lastIndexOf('/')+1);
}
