/** 
 * ajax.js
 * Getting XMLHttpRequest Object to do wonders
 * Richard Lin
 */
var ajax=false;

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
 try {
  ajax = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   ajax = false;
  }
 }
@end @*/
if (!ajax && typeof XMLHttpRequest != 'undefined') {
  ajax = new XMLHttpRequest();
}

var retrieveDone = false;
var resultId = "ajax_result";
function getMyHTML(serverPage, objID, postfunc) {
  retrieveDone = false;
  var obj = document.getElementById(objID);
  obj.innerHTML = 'Please wait...';
  ajax.open("GET", serverPage);//+"&dom_id="+objID);
  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4){//complete
    	if (ajax.status == 200) {//OK
			obj.innerHTML = ajax.responseText;
			var resultObj = document.getElementById(objID + '-' + resultId);
			if (resultObj != null && postfunc != null)
					postfunc(resultObj.value);
		}else{//Not OK
			obj.innerHTML = 'Error occurred while retrieving! Please report to the admin...';
			alert("There was a problem retrieving data: "+ajax.statusText);
		}
	    retrieveDone = true;
    }
  }
  ajax.send(null);
}

//Testing Only: Don't use this at all.
//trying for subsequent call to prevent overrun the prev call in JS
var pollCount = 0;
function getMyHTMLPoll(serverPage, objID)
{
   if (!retrieveDone && pollCount < 300){//30 seconds for 1st data retrieval
       // Confirmation isn't complete - keep polling
       pollCount++;
       window.setTimeout("getMyHTMLPoll('"+ serverPage+"', '"+objID+"')",100);
       return;
   }
   if (retrieveDone){
//        window.setTimeout("getMyHTML('"+ serverPage+"', '"+objID+"')", 500);
       getMyHTML(serverPage, objID);
   }else{
       alert("There was a problem of retrieving data, retrieval abort!");
       ajax.abort();
   }
   pollCount = 0;
}

var postDone = false;
function postMyHTML(serverPage, param, objID, postfunc) {
  postDone = false;
  var obj = document.getElementById(objID);
  obj.innerHTML = '<p><img src="images/pims/pleasewait.gif" width="50" height="10" alt="Please Wait" align="absmiddle" hspace="5" vspace="10">Please wait...</p>';
  ajax.open("POST", serverPage);
  ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  
  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4){//complete
    	if (ajax.status == 200) {//OK
			obj.innerHTML = ajax.responseText;
			var resultObj = document.getElementById(objID + '-' + resultId);
			if (resultObj != null && postfunc != null)
					postfunc(resultObj.value);
		}else{//Not OK
			alert("There was a problem retrieving data: "+ajax.statusText);
		}
	    postDone = true;
    }
  }
  ajax.send(param+"&dom_id="+objID);
}

//Testing Only: Don't use this at all.
//trying for subsequent call to prevent overrun the prev call in JS
var postPollCount = 0;
function postMyHTMLPoll(serverPage, param, objID)
{
	if (!postDone && postPollCount < 300){//30 seconds for 1st data retrieval
		// Confirmation isn't complete - keep polling
		postPollCount++;
		window.setTimeout("postMyHTMLPoll('"+ serverPage +"', '"+param+"', '"+objID+"')",100);
		return;
	}
	if (postDone){
//		alert(serverPage+param+" in:"+objID);
		postMyHTML(serverPage, param, objID);
	}else{
		alert("There was a problem of retrieving data, retrieval abort!");
		ajax.abort();
	}
	postPollCount = 0;
}

function AJAXLogin(objID){
	var url = "AJAXShow";
	var paramURL = 'pageId=ajaxLoginAction&action=login&';
	var username = document.getElementById('ajax-username').value;
	var password = document.getElementById('ajax-password').value;
	paramURL += 'username='+username+'&password='+password;
	postMyHTML(url, paramURL, objID);
}
/**
  * Added by Dan 2005-04-12
  * Useful when you want to push a request but dont' want to put the response data into the page
  */  
function makeAJAXRequest(serverPage) {
  var ret = '';
  ajax.open("GET", serverPage);
  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4 && ajax.status == 200) {
      ret = ajax.responseText;
    }
  }
  ajax.send(null);
  return ret;
}

/**
 * AJAX interface for CFA Online
 * Daniel Cheail, 2005
 */

/**
 * function eqDOM(_id)
 * Equalizes access to dom objects in a web page crossbrowser
 * @param _id a string containing the id to get access to
 * @returns object reference to that ID
 */
function eqDOM(_id)		
{
	if(document.getElementById)					// mozilla DOM1, ie6
		return document.getElementById(_id);

	else if(document.all)						// ie 4, 5 (i think?!)
		return eval("document.all." + _id);
}

/**
 * function initWin
 * Gives crossbrowser access to window viewport properties
 * @returns object reference to window properties
 */
function initWin()
{
	var xwin = new Object();
		
	if (window.pageYOffset && window.innerHeight) 
	{
		xwin.innerHeight = window.innerHeight;
		xwin.innerWidth = window.innerWidth;
		xwin.pageXOffset = window.pageXOffset;
		xwin.pageYOffset = window.pageYOffset;
	}
	
	else if (document.body) // all other Explorers
	{
		xwin.innerHeight = document.body.clientHeight;
		xwin.innerWidth =  document.body.clientWidth;
		xwin.pageXOffset = document.body.scrollLeft;
		xwin.pageYOffset = document.body.scrollTop;
	}
	
	return xwin;
}

/**
 * function pb_showBox
 * Part of the popbox 'namespace'
 * Displays a div, suitable for changing details then pushing to server via AJAX
 * @param box a string containing the id of the box
 * @param dataSource a string containing a reference to a data row to use to prepopluate fields
 * @param width an int, width of box
 * @param height an int, height of box
 * @param title a string, title of box
 */
function pb_showBox(box, dataSource, width, height, title)
{	
	// get window paramaters
	_xwin = initWin();

	// show command bar
	// eqDOM(box + '-commands').style.display = 'block';

	// reset the text in the statusbar of the popup box
	pb_updateStatusBox(box, null);
	
	// set the title
	eqDOM(box + '-title').innerHTML = title;
	
	// set the target row to update once information has been committed to the DB throug AJAX
	eqDOM(box + '-target').value = dataSource;

	// prepare the visual aspects of the box
	_box = eqDOM(box).style;
	_shadow = eqDOM(box + '-shadow').style;						
	_blur = eqDOM('doc-blur').style;
	
	// set width and height of box, and subsequently shadow
	_box.width = width + 'px';
	_box.height = height + 'px';
	_shadow.width = width + 'px';
	_shadow.height = height + 'px';

	// set position of box and shadow -- in the dead centre of the screen!
	boxX = (_xwin.innerWidth / 2) - (width / 2) + _xwin.pageXOffset;
	boxY = (_xwin.innerHeight / 2) - (height / 2 ) + _xwin.pageYOffset;
	
	shadowX = boxX + 20 + 'px';
	shadowY = boxY + 20 + 'px';

	boxX += 'px';
	boxY += 'px';	

	// 'blur' the page out
	_blur.display = "block";
	_blur.top = _xwin.pageYOffset;
	_blur.width = _xwin.innerWidth;
	_blur.height = _xwin.innerHeight;


	// hack for ie
	if(document.all)
	{
		// hide all selects
		x = document.getElementsByTagName('select');
		for(i = 0; i < x.length; i++)
		{
			x[i].style.visibility = 'hidden';
		}
	}

	// show the shadow
	_shadow.left = shadowX;
	_shadow.top =  shadowY;
	_shadow.display = "block";

	// now, show the box
	_box.left = boxX;
	_box.top =  boxY;
	_box.display = "block";
}

/**
 * function pb_doAjax
 * Part of the popbox 'namespace'
 * AJAX handler for a visible popbox
 * @param box a string containing the id of the box to source data from
 * @param url a string, url to execute AJAX request through
 * @returns boolean true on success, false if fail for whatever reason
 */
function pb_doAjax(box, url)
{
	// success variable init
	var success = true;
	
	// hide the command bar so we can't click it
	eqDOM(box + '-commands').style.display = 'none';

	// handle XMLHTTP stuff here
	success = makeAJAXRequest(url);
	//alert("result: "+success);
	return success;
}

/**
 * function pb_updateStatusBox
 * Part of the popbox 'namespace'
 * updates the status content of a popbox
 * @param box a string containing the id of the box
 * @param message a string containing the message to append to the status text
 */
function pb_updateStatusBox(box, message)
{
	sb = eqDOM(box + '-status');	
	if(message == null) 
		sb.innerHTML = "&nbsp;";
	else
		sb.innerHTML += message;
}

/**
 * function pb_closeBox
 * Part of the popbox 'namespace'
 * closes an open popbox
 * @param box a string containing the id of the box to close
 */
function pb_closeBox(box)
{
	eqDOM(box).style.display = 'none'; 
	eqDOM(box + '-shadow').style.display = 'none';	
	eqDOM('doc-blur').style.display = 'none';
	
	// for some reason, mozilla is't hiding these... manually re-hide
	// eqDOM(box + '-commands').style.display = 'none';
	
	// hack for ie
	if(document.all)
	{
		// re-show all selects
		x = document.getElementsByTagName('select');
		for(i = 0; i < x.length; i++)
		{
			x[i].style.visibility = 'visible';
		}
		
		// show/hdie the body!
		y = document.getElementsByTagName('body');
		y[0].style.visibility = 'hidden';
		y[0].style.visibility = 'visible';		
	}
	
}
