// Search Courses Search V2.0 - ajax script
// Author: David Butcher, MSc., BSc., MIEEE,
var browserName=navigator.appName;
var browserVersion=navigator.appVersion;
var currentListType = 'broad';
var ftpt = '';

String.prototype.getHostname = function() {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return this.match(re)[1].toString();
	}


//var path2files = 'http://www.ittralee.ie/en/searchcourses'; //remove TEST for live directory
var path2files = 'http://' + location.hostname + '/en/searchcourses';

var myGlobalHandlers = 
// variable which contain the actions to do for the events Create and Complete of a AJAX query
// here, it permits to display an ajax loader, a gif which will show that something is going on
{
	onCreate: function()
	{
		//Element.show('load'); //shows the ajax loader
		$('load').src = path2files + "/ajax-loader.gif";
		//$('load').src = "ajax-loader.gif";
	},
	onComplete: function()
	{
		if(Ajax.activeRequestCount == 0){//if there is no other ajax query engaged
			//Element.hide('load');//hide the ajax loader
			$('load').src = path2files + "/spacer.gif";
			//$('load').src = "spacer.gif";
		}
	}
};


// create XMLHttpRequest holder
var xmlHttp = '';
xmlHttp = null;

xmlHttp = createXmlHttpRequestObject();
var displayDiv = '';

// creats an XMLHttpRequest instance
function createXmlHttpRequestObject(){

	//var xmlHttp;
	//browser dependent creation
	try{    
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
										"MSXML2.XMLHTTP.5.0",
										"MSXML2.XMLHTTP.4.0",
										"MSXML2.XMLHTTP.3.0",
										"MSXML2.XMLHTTP",
										"Microsoft.XMLHTTP");
		
		
		// try each element
		for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)
		{
			try{
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
 			}
			catch (e){
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	}
	
	//return the created object or display error
	if(!xmlHttp)
		alert("Error creating the XMLHttpRequest Object. myAjax.js");
	else
	{    
		return xmlHttp;
	}	
}

//When the user changes the value in the Level box, the contents of the Dept box are updated
//and the first item is selected.
function listL_onchange()
{
	//displayDiv = getAllDivs();	
    var selectedLevel = document.getElementById("listL").value;
	var selectedDept = document.getElementById("listD").value;
	var listF = document.getElementById("listD");
	//call the PHP file which will ask the database to complete the next listbox
	var query = path2files + "/Listbox.php?Lvalue=" + selectedLevel + "&listD=" + selectedDept + "&listF=" + listF;
	
	//alert("query= " + query + ' ');
	
	//check for void xmlHttp object
	if(xmlHttp){
	    // yes so connect to server
		try{
		   //	xmlHttp.async = false;	
		   	xmlHttp.open("GET", query, true); ;	    	
			xmlHttp.onreadystatechange = handleRequestStateChangeLoadDepartmentListbox;			
			xmlHttp.send(null);			
		}
		// catch any errors
		catch (e){			
			xmlHttp.abort();
		   alert(" Can't connect to server. DisplayCourses myAjax. " + e.toString())
		}
	}
	else
		alert("no xmlHttp object in process");	
		
		listF[0].selected = true; //set the Department listbox on the first value
   
}

function handleRequestStateChangeLoadDepartmentListbox(){
	
 	   var newlist = document.getElementById("listD");
 	    	   
       if(xmlHttp.readyState == 4){
    		//check status is OK
    		if(xmlHttp.status == 200){		
    		
        	   	var result=xmlHttp.responseText; //put the response in the variable result to process it
        		var ArrO=result.split('|'); //split result into array named ArrO for ArrayOptions by char '|'      	   
				
        		//Remove all items from the listbox except item 0 ('ALL LEVELS')
        		for (i=newlist.length;i>0;i--){
        			newlist.remove(i);			
        		}
   		
	 			//Add options to listbox
        		for (i=1; i<(ArrO.length-1); i++)  //For the number of values in the array ArrO
        		{	
        			var NewOpt = document.createElement("OPTION"); //creates a new option
        		    var ArrO2= ArrO[i].split('%'); //split ArrO[i] into array named ArrO2 by char '%'
        			NewOpt.text=ArrO2[0]; //fills the text of the new option
        			NewOpt.value=ArrO2[1]; //fills the value of the new option
        		   
        			try{ //for Internet Explorer
        				newlist.add(NewOpt,null);
        			}catch(ex){ //for Mozilla,Safari...
        				newlist.add(NewOpt);
        			}
        		}    	 
        		
       		}
    	 	else //if the PHP file doesn't answer
    		{        		
        		if(browserName=="Netscape"){
        			alert('No Response from PHP file' + xmlHttp.status);
        		}else{
        			alert('No Response from PHP file' + xmlHttp.status);
            	   //$('zone').style.display="none";
            	   Element.hide('zone');//hide the previous results of AJAX query between the tags with the id 'zone'
            	   $('zone').innerHTML = xmlHttp.status;//change the 'zone' content
            	   Effect.Appear('zone');//show the reason of the AJAX query problem
            	   alert("Status:OK; Error reading the reponse: handleRequestStateChangeSearchCourses:" + e.toString());
        		}
    		} 		 
		}
}


//called to read files from server
function DisplayCourses(timeW,broadOrSpecific){
	
	displayDiv = getAllDivs();
    currentListType = broadOrSpecific;
    var selectedLevel = '';
	var selectedDept = '';
   
	
 	if(browserName=="Netscape"){
 		selectedLevel = document.getElementById("listL").value; 		
 	    selectedDept = document.getElementById("listD").value;
 	    sortopt = document.getElementById("SortOpt").value;
	}else{
	   	selectedLevel = $('listL').value;
		selectedDept = $('listD').value;
	    sortopt = $('SortOpt').value;
	} 
	//alert(broadOrSpecific + ' ' + sortopt); 
	//alert("level" + selectedLevel + " Dept" + selectedDept + "sortopt" + sortopt);

	var query = path2files + "/CoursesList.php?Lvalue=" + selectedLevel + "&DValue=" + selectedDept + "&sortopt=" + sortopt + "&ftpt=" + ftpt + "&time=" +  timeW + "&listtype=" + broadOrSpecific;
	
 	//check for void xmlHttp object
	if(xmlHttp){
	    // yes so connect to server
		try{
		   //	xmlHttp.async = false;	
		   	xmlHttp.open("GET", query, true); ;	    	
			xmlHttp.onreadystatechange = handleRequestStateChangeSearchCourses;			
			xmlHttp.send(null);			
		}
		// catch any errors
		catch (e){			
			xmlHttp.abort();
		   alert(" Can't connect to server. DisplayCourses myAjax. " + e.toString())
		}
	}
	else
		alert("no xmlHttp object in process");
}


function handleRequestStateChangeSearchCourses(){

		//get reference to display div
		// need to change to add home page redirect to display page (.src='http://www.ittralee.ie/en/InformationAbout/Courses/index.html');
		
		var dispDiv = document.getElementById('zone');
		var sortopt = document.getElementById('Sort');
		
		if(document.location.href == 'http://www.ittralee.ie/en/contactPhp/DavidsTest.html'){
		     //alert("in detect test");		
			 dispDiv = document.getElementById('zone').src='http://www.ittralee.ie/en/InformationAbout/Courses/index.html';
			 sortopt = document.getElementById('Sort').src='http://www.ittralee.ie/en/InformationAbout/Courses/index.html';
		}
				
    	if(xmlHttp.readyState == 4){
    		//check status is OK
    		if(xmlHttp.status == 200){		
    		
        		//alert(browserName);
        		if(browserName=="Netscape"){
        			//alert(xmlHttp.responseText);
        			//var dispDiv = document.getElementById('zone');
        			dispDiv.style.display = "block";
        			dispDiv.innerHTML = xmlHttp.responseText;       			
        		}else{
        			Element.hide('zone');//hide the previous results AJAX query between the tags with the id 'zone'
        			$('zone').innerHTML = xmlHttp.responseText;//change the 'zone' content
        		}
        		
        		//If the search is the broad type then show the sort options
        		if(browserName=="Netscape"){  
            		if(currentListType == 'broad'){
            			sortopt.style.display = "block";;
            			//show the content between the tags with the id 'Sort' which permit to user to sort his results 
            		}
            		//Otherwise hide the sort options
            		else{
            			sortopt.style.display = "none";
            		}    		
            		//Effect.Appear('zone');//show the results of the AJAX query
            		
            	} else {
            		if(currentListType == 'broad'){
            			//show the content between the tags with the id 'Sort' which permit to user to sort his results 
            			Element.show('Sort');            			
            		}            	   
            		else{ 	
            			//Otherwise hide the sort options
            			Element.hide('Sort');
            		}    		
            		Effect.Appear('zone');//show the results of the AJAX query            	
            	
            	}      		
        		
    		}
    		else //if the PHP file doesn't answer
    		{        		
        		if(browserName=="Netscape"){
        			dispDiv.innerHTML = 'No Response from PHP file' + xmlHttp.status;
        		}else{
            	   //$('zone').style.display="none";
            	   Element.hide('zone');//hide the previous results of AJAX query between the tags with the id 'zone'
            	   $('zone').innerHTML = xmlHttp.status;//change the 'zone' content
            	   Effect.Appear('zone');//show the reason of the AJAX query problem
            	   alert("Status:OK; Error reading the reponse: handleRequestStateChangeSearchCourses:" + e.toString());
        		}
    		} 		
	}
}


// ajax contact details functions do not delete

/* function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load("http://www.ittralee.ie/en/contactPhp/"+sourceURL+"");
} */

function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(sourceURL);
}

function getAjaxCourses(search_terms,searchtype){
	process(search_terms,searchtype);	
}

function getAllDivs(){

    stringbeans=document.getElementsByTagName("div"); 
    for (var w=0;w<stringbeans.length;w++) 
    { 
    	if(stringbeans[w].id.substr(0,5)=='zone'){
    		//costcentre = stringbeans[w].id.substr(6,4);
    		thisdiv = stringbeans[w].id.substr(0,5);
    		//process(thisdiv.toString()); 
    		return thisdiv.toString();   		
    	}else{}
    }
    return true;
}

//When the user clicks the search button, get the results and display them.
function submit_onclick()
{
    var selectedLevel = '';
	var selectedDept = '';
	
 	if(browserName=="Netscape"){
 		selectedLevel = document.getElementById("listL").value; 		
 	    selectedDept = document.getElementById("listD").value;
	}else{
	   	var selectedLevel = $('listL').value;
		var selectedDept = $('listD').value;
	} 
	
	var ft = '0';
	var pt = '0';
	
	if(document.courselist.fulltime.checked==true)
		ft = '1';
	if(document.courselist.parttime.checked==true)
		pt = '1'; 
	   
	ftpt = ft + pt;
   	
 	//Note the use of brackets in the expression
	if(selectedLevel == 'UG' || selectedLevel == 'PG' || (selectedLevel == 'ALL' && selectedDept == 'ALL')){
	   	DisplayCourses(0,'broad');
	}else{
	   	DisplayCourses(0,'specific');
	}	  

}

//Display the current results sorted by the selected sorting option
function sortResults(){
	DisplayCourses(0,currentListType);
}
