/*******************
JAVASCRIPT_AJAX.JS

Ajax and related functions
*******************/


// CLOSES A FORM AND REFRESHES THE OPENER WINDOW VIA AJAX
function closeFormAndRefreshOpenerOutput(IfOpenerScriptName) {
	if (window.opener.location == JS_http_path_to_module + '/' + IfOpenerScriptName)
		generateOutput('window.opener.document', IfOpenerScriptName, 'setTimeout(\'closeWin()\', 0)', true);
	else
		setTimeout('closeWin(true)', 0);
}


// SUBMITS A PVR FORM VIA AJAX
// (OBJ form object, STRING id of error container, STRING code to execute after successful form submit)
function submitFormViaAJAX(FormObj, FormErrorContainerObjID, ExecCodeAfterSuccess, Debug) {
	generateWaitDiv();
	resetErrorOutputClassNames();
	AJAX_sendRequest(false, JS_appendQueryStr(getScriptName(null, true), 'formSubmitted=true&' + convertFormDataToGETStr(FormObj)), ((Debug)?'alert(VarForResponseText); ':'') + "deleteWaitDiv(); if (VarForResponseText != '') outputFormErrors(document." + FormObj.name + ", VarForResponseText, document.getElementById('" + FormErrorContainerObjID + "')); else { " + ExecCodeAfterSuccess + " }");
}


// EXECUTES A PVR ACTION
// (STRING confirm text [leave blank for no confirm], STRING append to current url, 
function execPVRAction(ConfirmText, AppeURL) {
	if ((ConfirmText)?confirm(ConfirmText):true) {
		generateWaitDiv();
		AJAX_sendRequest(true, JS_appendQueryStr(getScriptName(), AppeURL), 'if (VarForResponseText != \'\') alert(VarForResponseText); generateOutput(); deleteWaitDiv();');
	}
}


// CALLS AN INSTANCE OF A SCRIPT THAT GENERATES OUTPUT (assumes a present AJAX connection)
// VOID()			
function generateOutput(OverrideTargetBase, OverrideScriptName, ExecExtraCode, DoNotLoadWaitingDiv) {
	
	if (!DoNotLoadWaitingDiv)
		generateWaitDiv('Loading...');
	
	AJAX_sendRequest(true, JS_appendQueryStr((OverrideScriptName)?OverrideScriptName:getScriptName('', true), 'GeneratingOutput=true'), ((OverrideTargetBase)?OverrideTargetBase:'document') + '.getElementById(\'MainOutput\').innerHTML = VarForResponseText; ' + ((DoNotLoadWaitingDiv)?'':'deleteWaitDiv();') + ExecExtraCode);
}

// 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;
}


// 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, 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];
			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) {
				VarForResponseText = UseAJAXHTTPObj.responseText;
				if (EvalCodeFromResponse)
					eval(EvalCodeFromResponse);
				else
					return VarForResponseText;
	
				return;
			}	
		}
	}
}
		

/*
// TOGGLES STATUS VARIABLE USED TO IDENTIFY THE STATUS OF SOMETHING (eg.: an item that's enabled or disabled)
// (STRING status variable identifier, INT id of item, BOOL toggle to start with)
function toggleStatusVar(StatusVarIdent, ItemID, StaticToggleBool) {
	eval(StatusVarIdent + ' = (typeof ' + StatusVarIdent + ' == \'undefined\')?!StaticToggleBool:!' + StatusVarIdent + ';');
}


// CALLS THE AJAX FUNCTIONS TO TOGGLE AN ITEM 
// (STRING intial image id [automatically appended with item id, STRING name of status variable, INT item id, STRING item name, STRING image path when status is true, STRING image path when status is false, STRING text when status if false, STRING text when status if true, STRING action text when status if false, STRING action text when status if true)
function toggleStatus(InitImgID, InitAJAXURL, StatusVarIdent, ItemID, ItemName, StatusBoolImgTRUE, StatusBoolImgFALSE, StatusBoolTextTRUE, ToggleBoolTextFALSE, StatusBoolTextActionTRUE, StatusBoolTextActionFALSE) {
	eval('ToggleTo = ' + StatusVarIdent);
	ToggleTo = (ToggleTo == true)?1:0;
	
	// If there is response text, there was an error
	var AJAXReponseText = AJAX_sendRequest(1, InitAJAXURL + ToggleTo);
	if (AJAXReponseText != '')
		alert('There was an error while trying to complete your request:\n\n' + AJAXReponseText);
	
	// No news is good news (no response, so no error)
	else {
		with (document.getElementById(InitImgID)) {
			src   = (ToggleTo == 0)?StatusBoolImgFALSE:StatusBoolImgTRUE;
			title = ItemName + ' is currently ' + ((ToggleTo == 0)?ToggleBoolTextFALSE:StatusBoolTextTRUE) + '.  Click to ' + ((ToggleTo == 0)?StatusBoolTextActionFALSE:StatusBoolTextActionTRUE) + ' it.'; 
		}
	}
}


// CALLS THE AJAX FUNCTIONS TO DELETE AN ITEM IN A PVR INDEX
// (STRING init url for open(), INT id of item to delete, STRING confirmation message [blank for no confirmation], STRING id of html element to delete, BOOL use css display:none in msie instead of clearing innerhtml)
function deleteItemFromPVRIndex(AJAXURL, ItemID, DeleteMsg, DeleteElmntID, CompensateForIE, InitItemRowName, ParentOfObjToRemove) {
	if ((DeleteMsg)?confirm(DeleteMsg):true) {
		var AJAXReponseText = AJAX_sendRequest(1, AJAXURL);
		if (AJAXReponseText != '')
			alert('There was an error while trying to complete your request:\n\n' + AJAXReponseText);
		
		else if ((typeof RefreshNeeded == 'undefined')?true:!RefreshNeeded) {
			
			ParentOfObjToRemove.removeChild(document.getElementById(DeleteElmntID));
			
			// No items left?
			NoItems = true;
			TBodies = document.getElementsByTagName('tbody');
			for (var i in TBodies) {
				if (TBodies[i].id.substr(0, InitItemRowName.length) == InitItemRowName) {
					NoItems = false;
					break;
				}
			}
			
			if (NoItems)
				document.getElementById('NoItemsMsg').style.display = 'block';
		}
	}
}
*/