
// +-------------------------------------------------------------------------------------------------+
// | File Name:  ajax.js
// +-------------------------------------------------------------------------------------------------+
// | Project: Pacman
// +-------------------------------------------------------------------------------------------------+
// | Description:
// |	JavaScript library for implementing AJAX functionality in the CFA
// +-------------------------------------------------------------------------------------------------+
// | Author: Stephen Farrell
// +-------------------------------------------------------------------------------------------------+
// | Creation Date:   22/09/2006
// +-------------------------------------------------------------------------------------------------+


/* Constants */
var BROWSER_NAME_FIREFOX = 'Firefox';
var BROWSER_NAME_IE = 'Explorer';

//var http = null;//getHTTPObject();
var XML = 'xml';
var HTML = 'html';
var vCurrentTab = '';
var vExpectedHash = '';

var vRunCount = 0;
//var vDestination;
function MakeRequest(pTarget,pAction,pParams) {
	MakeRequest(pTarget,pAction,pParams, HTML,'tabContent');
}

function MakeRequest(pTarget,pAction,pParams,pDestination){
	MakeRequest(pTarget,pAction,pParams,HTML,pDestination);
}

function MakeRequest(pTarget,pAction,pParams, pResponse,pDestination) {
	//indicator to show the user that something is happening.
	$('activity_indicator').style.display = 'block';

  //alert('Make Request');
  var http = GetHTTPObject();
  rand = Math.round(50*Math.random());
  var vDestination = pDestination;
  var url = "ajax.php?rand=" + rand;
	parameters = "";

	if(pTarget != '')
		parameters  += "&target=" + encodeURI(pTarget);
		
	if(pAction != '')
		parameters  += "&Action=" + encodeURI(pAction);		

	parameters  += "&request_type=" + encodeURI('ajax');	
	
	if(pDestination) {
		parameters += '&Destination=' + encodeURI(pDestination);
	}
		
	if(pParams != ''){
		/*
		if('&' == pParams.charAt(0)) {
			parameters  += encodeURI(pParams);
		} else {
			parameters  += "&" + encodeURI(pParams);
		}
		*/
		parameters  += "&" + encodeURI(pParams);	
	}
	
	//alert('Parameter String = \n' + parameters + '\nDestination: ' + pDestination);
	if(pResponse == XML){
				
		//http.onreadystatechange = HandleXmlHttpResponse
		http.onreadystatechange = function () {
			try{
				if (http.readyState == 4 || http.readyState=="complete") {
					if (http.status == 200) {
						xmlDoc = 	http.responseXML;
						
						//alert(http.responseText);
						vHandler = '';
						// get name of response handler
						try{
							vHandler = xmlDoc.getElementsByTagName('handler').item(0).firstChild.data;
						} catch (e){
							alert('Unable to retrieve handler for XML response. ' + e.description );
						}
						//alert('project = ' + xmlDoc.getElementsByTagName('project_name').item(0).firstChild.data);
						//var func = window[vHandler];
						//func.apply(xmlDoc);						
						
						switch(vHandler){
							case 'Update_Current_Project_From_Xml':
								Update_Current_Project_From_Xml(xmlDoc);
							break;
							case 'Update_Select_List_From_Xml' :
								Update_Select_List_From_Xml(xmlDoc);
							break;
							default:
							
							case 'IGNORE_RESPONSE':
								// do nothing - synchronous calls can cause issues in firefox so we allow a
								// response but we just ignore it
							break;
							
							alert('Invalid handler specified in XML output: ' + vHandler);
							
						}
						
						// we got a response so hide the activity indicator
						$('activity_indicator').style.display = 'none';
					} else if(http.status == 500) {
						alert('Internal Server Error');
					} else if(http.status == 404) {
						alert('File Not Found');
					}
				}								
			} catch(e){
				alert('Unspecified Server Error - ' + e.description);
			}	
		};
		
	} else {
		//http.onreadystatechange =  HandleHtmlHttpResponse;
		
		http.onreadystatechange = function() {
			try{
				if (http.readyState == 4 || http.readyState=="complete") {
					//if (http.status == 200) {
						htmlText = 	http.responseText;
						document.getElementById(vDestination).innerHTML = htmlText;
						//alert(htmlText);
						// we got a response so hide the activity indicator
						$('activity_indicator').style.display = 'none';
						
						
						/*try {
							CoverSelects();
						} catch(e) {
							// do nothing, the function doesn't exist
							alert(e.description);
						}*/
					/*
					} else if(http.status == 500) {
						alert('Internal Server Error');
					} else if(http.status == 404) {
						alert('File Not Found');
					}
					*/
				}								
			} catch(e){
				alert('Unspecified Server Error - ' + e.description);
			}
		}		
		
		
		
	}

	//alert(parameters);
	//alert('Browser = ' + BrowserDetect.browser);
	
	/*
		IE6,7 and firefox support sending the parameters in the body of the post request however
		this is INCREDIBLY slow on IE6.0.28 (Win2k version) so I changed the ajax calls to send
		the parameters back to the server in the url of the request. This worked like a charm in
		IE on both windows xp and 2k but Firefox decided it didnt like this and the requests never
		finish. 
		
		Soooo... we check if the browser is Firefox, if it is we send the data in the request body
		otherwise we send it in the request URL.
	
	*/ 
	//alert(url + parameters);
	if(BROWSER_NAME_FIREFOX == BrowserDetect.browser) {
		http.open('POST', url, true);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		//http.setRequestHeader("Content-length", parameters.length);
		http.setRequestHeader("Connection", "close");
		http.send(parameters);					
	} else {
		http.open('POST', url + parameters, true);
		//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		//http.setRequestHeader("Content-length", parameters.length);
		//http.setRequestHeader("Connection", "close");
		http.send(null);	
	}
}		

function FilterList(pTarget,pField,pParam) {
	vParams = pParam + '=' + $(pParam).value;
	//alert(vParams);
	MakeRequest(pTarget,'',vParams, XML,pField);
}

function ChangeTab(pTarget,pAction,pParams, pCurrentTab){
	vActiveTabs = document.getElementsByClassName("activeTab");
	for (i in vActiveTabs) {
		var vTab = vActiveTabs[i];
		vTab.className = 'tab';
	}
	
	pCurrentTab.className ='tab activeTab';
	//SetHistory(pCurrentTab.id);
	vCurrentTab = pTarget;				
	MakeRequest(pTarget,pAction,pParams, 'html','tabContent');
	
}	

function HandleHtmlHttpResponse() {
	try{
		if (http.readyState == 4 || http.readyState=="complete") {
			//if (http.status == 200) {
				htmlText = 	http.responseText;
				//alert(htmlText);
				document.getElementById(vDestination).innerHTML = htmlText;
				// we got a response so hide the activity indicator
				$('activity_indicator').style.display = 'none';
				
				
				/*try {
					CoverSelects();
				} catch(e) {
					// do nothing, the function doesn't exist
					alert(e.description);
				}*/
			/*
			} else if(http.status == 500) {
				alert('Internal Server Error');
			} else if(http.status == 404) {
				alert('File Not Found');
			}
			*/
		}								
	} catch(e){
		alert('Unspecified Server Error - ' + e.description);
	}
}

function HandleXmlHttpResponse() {
	try{
		if (http.readyState == 4 || http.readyState=="complete") {
			if (http.status == 200) {
				xmlDoc = 	http.responseXML;
				
				alert(http.responseText);
				vHandler = '';
				// get name of response handler
				try{
					vHandler = xmlDoc.getElementsByTagName('handler').item(0).firstChild.data;
				} catch (e){
					alert('Unable to retrieve handler for XML response. ' + e.description );
				}
				//alert('project = ' + xmlDoc.getElementsByTagName('project_name').item(0).firstChild.data);
				//var func = window[vHandler];
				//func.apply(xmlDoc);						
				
				switch(vHandler){
					case 'Update_Current_Project_From_Xml':
						Update_Current_Project_From_Xml(xmlDoc);
					break;
					case 'Update_Select_List_From_Xml' :
						Update_Select_List_From_Xml(xmlDoc);
					break;
					default:
					
					case 'IGNORE_RESPONSE':
						// do nothing - synchronous calls can cause issues in firefox so we allow a
						// response but we just ignore it
					break;
					
					alert('Invalid handler specified in XML output: ' + vHandler);
					
				}
				
				// we got a response so hide the activity indicator
				$('activity_indicator').style.display = 'none';
			} else if(http.status == 500) {
				alert('Internal Server Error');
			} else if(http.status == 404) {
				alert('File Not Found');
			}
		}								
	} catch(e){
		alert('Unspecified Server Error - ' + e.description);
	}	
}

function GetHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
		xmlhttp = false;
	  }
	}
  @else
  xmlhttp = false;
  @end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try 
		{
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
		xmlhttp = false;
		}
	}
	return xmlhttp;
}


function ConvertFormToParamString(pFormName) {
	var vParamString = '';
	var vElements = document.getElementById(pFormName).elements;
	for(var i = 0; i < vElements.length; i++) {
		if(i>0) {
			vParamString += '&';
		}		
		vParamString += vElements[i].name + '=' + vElements[i].value;
	}
	
	return vParamString;
}


function Update_Select_List_From_Xml(pXml) {
	var vI;
	
	//store the xml for later - so we don't have to requery the server
	vXml = pXml; 
	
	vNumErrors = 0;
	vNumItems = 0;
	vSelectList = '';
	vErrors = '';
	try {
		vNumErrors = pXml.getElementsByTagName('numerrors').item(0).firstChild.data;
		vNumResults = pXml.getElementsByTagName('numitems').item(0).firstChild.data;
		vSelectList = pXml.getElementsByTagName('id').item(0).firstChild.data;
	} catch (ex) {
		vNumErrors = 1;
		vErrors = 'Error retrieving details, please try again.';			
	}	
	
	document.getElementById(vSelectList).disabled = '';
	
	//clear the existing list
	vNumItems = document.getElementById(vSelectList).length;
	var vList=document.getElementById(vSelectList);
	// loop through each option and remove it
	while (vList.hasChildNodes()) {
		vList.removeChild(vList.childNodes[0]);
	}	
	
	
	if(0 == vNumErrors) {
		try {
			//vProject = pXml.getElementsByTagName('project_name').item(0).firstChild.data;
			vItems = pXml.getElementsByTagName('list_item');
			
			//Add a blank option
			var optn = document.createElement("OPTION");
			optn.text = 'Select...';
			optn.value = '';
			vList.options.add(optn);					
			
			//repopulate with the new options
			for(vI=0; vI<vNumResults; vI++) {
				vTechCode = '';
				vName = '';
				vId = null;
				try {
					vName = vItems[vI].getElementsByTagName('sel_name').item(0).firstChild.data;
					vId = vItems[vI].getElementsByTagName('sel_id').item(0).firstChild.data;
				} catch (e) {
					alert ('Error retrieving list item xml - ' +  e.description);
				}
				//add the sales rep to the list									
				var optn = document.createElement("OPTION");
				optn.text = vName;
				optn.value = vId;
				vList.options.add(optn);					
			}
			
		} catch (ex) {
			vErrors = 'Error Retrieving List Items';
			alert(ex.description);
		}
	}		
}

function HandleHistory() {
	return false;
	//alert('hash changed from ' + vExpectedHash + ' to ' + window.location.hash);
	if ( window.location.hash != ('#' + vExpectedHash) && vExpectedHash != '') {
		//if the hash is blank then we just jump to the first tab by reloading the screen
		var vNewHash = window.location.hash.substring(1);
		vExpectedHash = vNewHash;
		if('' == vNewHash) {
			window.location = window.location;
		} else {
			//expected tab is not the same as the tab specified in the browser which means the user
			//has used back or forward buttons to navigate away from the page.
			//alert('hash changed from ' + vExpectedHash + ' to ' + vNewHash);
			vOnClick = '';
			try {
				vOnClick = $(vExpectedHash).onclick.toString();
	
				var vStartOfTarget = (vOnClick.indexOf("ChangeTab(") + 10);
				var vEndOfTarget = vOnClick.indexOf('"',vStartOfTarget+1); //position of opening quote
				vEndOfTarget = vOnClick.indexOf('"',vEndOfTarget); // position of closing quote
							
				var vTarget = vOnClick.substring(vStartOfTarget+1,vEndOfTarget);
				/*alert(vTarget);*/
				
				var vStartOfAction = (vOnClick.indexOf(",",vEndOfTarget));
				var vStartOfActionQuotes = vOnClick.indexOf('"',vStartOfAction+1); //position of opening quote
				var vEndOfAction = vOnClick.indexOf('"',vStartOfActionQuotes + 1); // position of closing quote			
				var vAction = vOnClick.substring(vStartOfActionQuotes+1,vEndOfAction);
				/*alert(vAction);*/
				
				
				var vStartOfParams = (vOnClick.indexOf(",",vEndOfAction));
				var vStartOfParamQuotes = vOnClick.indexOf('"',vStartOfParams+1); //position of opening quote
				var vEndOfParams = vOnClick.indexOf('"',vStartOfParamQuotes + 1); // position of closing quote			
				//alert('start of action ' + vStartOfAction + ' end of action ' + vEndOfAction);
				var vParams = vOnClick.substring(vStartOfParamQuotes+1,vEndOfParams);
				/*alert(vParams);			*/
				
				//parse the onclick code		
				ChangeTab(vTarget,vAction,vParams,$(vExpectedHash));
	
			} catch (ex) {
				alert(ex.description);
			}
		}
	}
	vRunCount++;
	return true;
}

function PollHistory() {
	return false;
	HandleHistory();
	window.setInterval("HandleHistory()", 300);
	return true;
}

function SetHistory(pHash) {
	return false;
	window.location.hash = pHash;
	vExpectedHash = pHash;
	//alert($(pHash).onclick);
}
