//Web Services Group Javascript Prototype-esque Library
//version 1.0beta
//I.T. Services
//University of Windsor
//June, 2007
//Includes 4 sections: DOM Access, Effects, AJAX, Util
//DOM Access has subsections ID-based and class-based access
/*
*************************************************************************
*							DOM Access FUNCTIONS								*
*************************************************************************
*/
//$ returns the object matching the required ID
function $(myID){
	if(document.getElementById(myID)){
		return document.getElementById(myID);	
	}else{
		return false;	
	}
}
//$setClass changes(sets) the class based on the ID
function $setClass(myID, newClassName){
	if($(myID)){
		$(myID).className = newClassName;
	}	
}
//$setID changes(sets) the ID to a new one, based on ID
function $setID(myID, newIDName){
	$(myID).id = newIDName;
}
//returns the value of an element based on the ID
function $V(myID){
	if($(myID)){
		return $(myID).value;	
	}else{
		return false;	
	}
}
//returns the inner HTML of an element based on the ID
function $H(myID){
	if($(myID)){
		return $(myID).innerHTML;	
	}else{
		return false;	
	}
}
//$$ returns the object ARRAY matching the required CSS Class Name
function $$(myClassName){
	var knt = 0, tagKnt = 0;
	var checkMyClass = new Array();
	checkMyClass = document.getElementsByTagName("*");
	var matchingClasses = new Array();
	for(tagKnt = 0; tagKnt < checkMyClass.length; tagKnt++){
		if(checkMyClass[tagKnt].className == myClassName){
			matchingClasses[knt] = checkMyClass[tagKnt]; 
			knt++;
		}
	}
	return matchingClasses;
}
//$$set changes(sets) the Class of all objects with a particular CSS Class Name
function $$setClass(oldClassName, newClassName){
	var myObjects = new Array();
	myObjects = $$(oldClassName);
	for(var knt = 0; knt < myObjects.length; knt++){
		myObjects[knt].className = newClassName;
	}
	return true;
}
//$$setFirstID changes(sets) the ID of the first object matching a class name to a new one, based on className
function $$setFirstID(myClassName, newIDName){
	var myObjects = new Array();
	myObjects = $$(myClassName);
	for(var knt = 0; knt < myObjects.length; knt++){
		myObjects[knt].id = newIDName;
		break;
	}
}
//$$setID changes(sets) the ID of all objects matching a class name to a new one, based on className 
//form newID_#
function $$setID(myClassName, newIDName){
	var myObjects = new Array();
	myObjects = $$(myClassName);
	for(var knt = 0; knt < myObjects.length; knt++){
		myObjects[knt].id = newIDName+'_'+knt;
	}
	knt = parseInt(knt);
	if(!isNaN(knt)){
		return knt;
	}else{
		return false;	
	}
}
//returns the value of elements with a specific className
function $$V(myClassName){
	var myObjects = new Array();
	var forReturn = new Array();
	myObjects = $$(myClassName);
	for(var knt = 0; knt < myObjects.length; knt++){
		if(myObjects[knt].value != 'undefined'){
			forReturn[knt] = myObjects[knt].value
		}
	}
	knt = parseInt(knt);
	if(!isNaN(knt)){
		return forReturn;
	}else{
		return false;	
	}
}
//returns the inenr HTML of elements with a specific className
function $$H(myClassName){
	var myObjects = new Array();
	var forReturn = new Array();
	myObjects = $$(myClassName);
	for(var knt = 0; knt < myObjects.length; knt++){
		if(myObjects[knt].innerHTML != 'undefined'){
			forReturn[knt] = myObjects[knt].innerHTML
		}
	}
	knt = parseInt(knt);
	if(!isNaN(knt)){
		return forReturn;
	}else{
		return false;	
	}
}
/*
*************************************************************************
*							EFFECTS FUNCTIONS							*
*************************************************************************
*/
function $hide(myID){
	if(document.getElementById(myID)){
		document.getElementById(myID).style.display = 'none';
	}
}
function $show(myID){
	if(document.getElementById(myID)){
		document.getElementById(myID).style.display = '';
	}
}
/*
*************************************************************************
*							AJAX FUNCTIONS								*
*************************************************************************
*/
var isBusy = false;		//isBusy flag used for error handling
var ajaxFailComKnt = 0;	//count the number of failed AJAX communication attempts (for auto-resend)
//standard init function for AJAX communication
function createRequestObject() {
	var XmlHttpRequestObject;
	if (typeof XMLHttpRequest != "undefined"){
		XmlHttpRequestObject = new XMLHttpRequest();
	}
	else if (window.ActiveXObject){
	// look up the highest possible MSXML version
		var tryPossibleVersions=["MSXML2.XMLHttp.5.0",
		"MSXML2.XMLHttp.4.0",
		"MSXML2.XMLHttp.3.0",
		"MSXML2.XMLHttp",
		"Microsoft.XMLHttp"];
		for (i=0; i< tryPossibleVersions.length; i++){
			try{
				XmlHttpRequestObject = new ActiveXObject(tryPossibleVersions[i]);
				break;
			}
				catch (xmlHttpRequestObjectError){
			}
		}
	}
	return XmlHttpRequestObject;
}
var EMAIL = 'EMAIL';
var EMAILSEND = 'EMAILSEND';
var RSSFEEDS= 'RSSFEEDS';
function requestDispatch(sendMe){
	sendMe = sendMe.toUpperCase();
	var doWhat = '', doWhatPOST = '';
	switch(sendMe){
		case 'EMAIL':
			doWhat = '/uweb/futurestudents.nsf/rpcDisplayEMailContainer?OpenPage';
			doWhatPOST = timestampAJAX();
			sndSGRReq(doWhat, doWhatPOST);
			break;
		case 'EMAILSEND':
			doWhat = '/uweb/futurestudents.nsf/EmailThisPage_Agent?openAgent';
			doWhatPOST = timestampAJAX();
			doWhatPOST = "&To="+$V('To');
			doWhatPOST += "&youremailaddress="+$V('youremailaddress');
			doWhatPOST += "&textarea="+($V('textarea')).replace('&', 'and');
			doWhatPOST += "&fromName="+($V('fromName')).replace('&', 'and');
			doWhatPOST += "&docID="+$V('docID');
			doWhatPOST += "&title="+(document.title).replace('&', 'and');
			doWhatPOST += "&webdbname="+($V('webdbname')).replace('&', 'and');;
			doWhatPOST += "&myURL="+(document.location.href);
			doWhatPOST += "&radiobutton=no";
			if(checkEMailAddress($('To')) && checkEMailAddress($('youremailaddress'))){
				sndSGRReq(doWhat, doWhatPOST);
				closeWSGLight();
			}
			break;
		case 'RSSFEEDS':
			doWhat = '/uweb/futurestudents.nsf/rpcDisplayRSSFeeds?OpenPage';
			doWhatPOST = timestampAJAX();
			sndSGRReq(doWhat, doWhatPOST);
			break;
		case 'QUICKLINKS':
			doWhat = '/uweb/futurestudents.nsf/rpcDisplayQuickLinks?OpenPage';
			doWhatPOST = timestampAJAX();
			sndSGRReq(doWhat, doWhatPOST);
			break;
		case 'OPINIONFORM':
			doWhat = '/uweb/futurestudents.nsf/rpc_OpinionFormSubmit_Agent?OpenAgent';
			doWhatPOST = timestampAJAX();
			doWhatPOST += "&helpful=";
			if($('pageHelpfulY').checked){
				doWhatPOST += "Yes";
			}else{
				doWhatPOST += "No";
			}
			doWhatPOST += "&suggestion="+($('surveySuggestion').value).replace(/&/g, "~*amp*~");
			doWhatPOST += "&comments="+($('surveyOtherComments').value).replace(/&/g, "~*amp*~");
			doWhatPOST += "&postamble=1";
			sndSGRReq(doWhat, doWhatPOST);
			switchSurveyContent(0);
			if($('surveyLinkContainer')){
				$('surveyLinkContainer').innerHTML= '';
			}
			break;
	}
}
var httpSGR = createRequestObject();		//Send Generic AJAX Request
function sndSGRReq(doWhat, doWhatPOST){
	if(httpSGR){
		if(isBusy){ 
			httpSGR.onreadystatechange = function (){
				httpSGR = createRequestObject();
			}
			httpSGR.abort();
		}
		var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
		isBusy = true;
		httpSGR = createRequestObject();
	    	httpSGR.open('POST', doWhat, true);
     		httpSGR.setRequestHeader("Content-Type", contentType);
	    	httpSGR.send(doWhatPOST);
		isBusy = true;
	    httpSGR.onreadystatechange = handleSGRResponse;
	}else{
		alert('Your request has failed.\n Please refresh this page and try again');	
	}
}
//Handle Load Generic Request Response
function handleSGRResponse() {
	var knt = 0; 	//general purpose counter
	
    if(httpSGR){
		if(httpSGR.readyState == 4){
        	var response = httpSGR.responseText;
		response = response.replace(/\n/g , " ");
        	var responseError = response.toUpperCase();
        	if(response.indexOf("ERROR")==-1 && response.indexOf("WARNING")==-1){
	        	if(response.indexOf("</responseType>") != -1){
	        		update = (response.replace("<responseType>", "")).split("</responseType>");
	        		update[0] = update[0].toUpperCase();
	        		switch(update[0]){
		        		case 'JS':					//straight javascript return
		        			eval(update[1]);
		        			break;
		        		case 'JSON':				//JSON return
		        			eval(update[1]);	
		        			break;				
		        		case 'OPAIR':
	//ORDERED PAIR(s) format ID |V->| content|~ENDITEM~| or ID |H->| content for innerHTML
		        			update[0] = update[0].replace("|v->|", "|V->|");
		        			update[0] = update[0].replace("|h->|", "|H->|");
		        			update[0] = update[0].replace(/|~enditem~|/i, "|~ENDITEM~|");
		        			oPairs = update[0].split('|~ENDITEM~|');
		        			for(knt = 0; knt < oPairs.length; knt++){
			        			if(oPairs[knt].indexOf("|V->|")>-1){
				        			temp = oPairs[knt].split("|V->|");
				        			$V(temp[0]) = temp[1];	
			        			}
			        			if(oPairs[knt].indexOf("|H->|")>-1){
				        			temp = oPairs[knt].split("|H->|");
				        			$H(temp[0]) = temp[1];	
			        			}
		        			}
	        		}
        		}else{}//DEFAULT, ASSUME NO REQUIRED ACTION (SUCH AS A SAVE) 
    		}else{
			alert("Error #102: An Error has occured processing your request.\n Please refresh this page and try again");
    		}
        }
        isBusy = false;
	}else{
			alert("Error #103: An Error has occured processing your request.\n Please refresh this page and try again");
		}
}
/*
*************************************************************************
*							UTIL FUNCTIONS								*
*************************************************************************
*/
//parseRGB returns the HEX value of colours received in decimal 
//RGB format rgb(red, green, blue) | red, green, blue > 0 && red, green, blue < 255
function rgb2HEX(RGBValue){
	RGBValue = RGBValue.replace('rgb(', '');
	RGBValue = RGBValue.replace(')', '');
	RGBValue = RGBValue.replace(' ', '');
	var myValues = new Array();
	myValues = RGBValue.split(',');
	var red = '', green = '', blue = '';
	if(myValues[0] != null){
		myValues[0] = parseInt(myValues[0]);
		red = '' + dec2HEX(parseInt(myValues[0]/16))+dec2HEX(parseInt(myValues[0]%16))
	}else{
		red = '00';	
	}
	if(myValues[1] != null){
		myValues[1] = parseInt(myValues[0]);
		green = '' + dec2HEX(parseInt(myValues[1]/16))+dec2HEX(parseInt(myValues[1]%16))
	}else{
		myValues[2] = parseInt(myValues[0]);
		green = '00';	
	}
	if(myValues[2] != null){
		blue = '' + dec2HEX(parseInt(myValues[2]/16))+dec2HEX(parseInt(myValues[2]%16))
	}else{
		blue = '00';	
	}
	return '#'+red+green+blue;
}
//convert single decimal value to HEX
function dec2HEX(dec){
	dec = parseInt(dec);
	if(dec < 10){
		return dec;	
	}else{
		switch(dec){
			case 10:
				return 'A';
				break;
			case 11:
				return 'B';
				break;
			case 12:
				return 'C';
				break;
			case 13:
				return 'D';
				break;
			case 14:
				return 'E';
				break;
			default:
				return 'F';
				break;			
		}	
	}
	return false;
}
function timestampAJAX(){
	var now = new Date();
	return "&timestamp="+now.getTime();
}
function cancelAJAX(){
	if(httpAJAXObject){
		httpAJAXObject.abort();
	}
	if(httpSGR){
		httpSGR.abort();
	}
	WSGEndLoading();
}
function checkEMailAddress(testMe){
	var str = new String();
	if(testMe){
		str = testMe.value;
	}
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if(str=="to@uwindsor.ca" || str=="from@uwindsor.ca"){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if(str.indexOf(at)==-1){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if(str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if(str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			$(testMe).focus();
		}	
		return false;
	}
	if(str.indexOf(at,(lat+1))!=-1){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if(str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if(str.indexOf(dot,(lat+2))==-1){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
	if (str.indexOf(" ")!=-1){
		alert("Please Enter a Valid E-Mail Address");
		if(testMe){
			testMe.focus();
		}	
		return false;
	}
return true;
}
