/*
This file holds functions used throughout the site, most notably the AJAX-related code 
which does the dynamic Logged in/out features.  It also contains all functions which were previously in
TrimPage.js.

Please note that you'll also need to ensure that pages include the script "Prototype.js"
*/

// ***********************************************************
// AUTOMATICALLY RUN
// ***********************************************************

// Make sure pages show the right-hand side menu for being logged in or not
addLoadEvent(showMenuOnlineServices);
// This next line would show a login or logout button on the banner, but it won't be used at this stage.
// addLoadEvent(showLoginLogout);

// ***********************************************************
// HELPER FUNCTIONS
// ***********************************************************

// This lets you add additional functions to a Page's onload. You can call it at the end of a page, just before </body>
// From http://simonwillison.net/2004/May/26/addLoadEvent/
/*
	// Example: 
	
	addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
	addLoadEvent(function() {
	  // more code to run on page load 
	});
*/
function addLoadEvent(func) {

var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


// Show the logged in or logged out menu on the far right hand side
function showMenuOnlineServices() {
    try
    {
        //var dest = getMarkerParent("showOnlineServicesMenu");
        var dest = document.getElementById('showOnlineServicesMenu');
    	if (dest != null) {
    		getAspx('/Interactive/Menus/MenuOnlineServices.ashx', dest);
    	} else {
    		// Also check for special versions
    	    //dest = getMarkerParent("showOnlineServicesMenuLoginForm");
        	var dest = document.getElementById('showOnlineServicesMenu');
    		if (dest != null) {
    			// This would be the home page login form.
    			// Because the home page has a form there by default, there's a chance that
    			// the user might start typing in their details, then the AJAX snippet finishes downloading and
    			// puts a blank form there, thus losing the user's text.  
   				getAspx('/Interactive/Menus/MenuOnlineServices.ashx?OnLoggedOut=MenuLoginForm', dest);
    		}
    	}
    }
    catch (didntWork)
    {
        // This feature isn't vital
    }        
}

// This checks for special case pages which need the Online Services menu. Such pages
// have have a div with a certain ID
function getMarkerParent(markerId) {
    // if a page has a div with this id, then return the div's parent so we should insert the Online Services menu
    if (document.getElementById(markerId))
    {
        var markerDiv = document.getElementById(markerId);
        // Now we need its parent
        var markerParent = markerDiv.parentNode;

        // Some pages have an extraneous div class="sf1" around the marker. If so, go one higher
        if (markerParent.className == "sf1") {
            markerParent = markerParent.parentNode;
        }
        
        return markerParent;
    }
    else
    {
        return null;
    }

}

// Pass this a main checkbox (which does the Select All/Select None, such as in the header for a GridView column).
// Also pass it the ID of the HTML container object (e.g. the gridview's ClientId) which contains all 
// the checkboxes you want to change (it doesn't matter
// if your main checkbox is inside that object or not). Whatever the main checkbox is, all the checkboxes
// inside the container will be set to.
function ToggleCheckboxes(theMainCheckbox, theNameOfTheThingHoldingAllCheckboxes) {

    var allCheckboxes = document.getElementById(theNameOfTheThingHoldingAllCheckboxes).getElementsByTagName('input');
    
    for(var i=0; i<allCheckboxes.length; i++){
        allCheckboxes[i].checked=theMainCheckbox.checked;
    }
}


// ***********************************************************
// This will show the Login or Logout text on the page's banner
function showLoginLogout() {
    try {
        if (isStaticPage()) {
            getAspx('/Interactive/Menus/LoginLogoutMessage.ashx', 'AreaLoginLogout');
        }
    } catch (didntWork) {
        // This feature isn't important
    }
}

// Checks if a given host name should be considered as being non-SSL
function canSSL(theHostName) {
	var locals = new Array(1);

	locals[0] = "localhost";
	locals[1] = "stage.qct.qld.edu.au";
	locals[2] = "p5dt21op755";

	for (var i = 0; i < locals.length; i++) {
		if (theHostName.indexOf(locals[i]) == 0) {
			return false;
		}
	}

	return true;

}

// Ensures that the given form's action is the https:// version of its action
function makeFormHttps(theForm) {

	var currentHost = document.location.host;
	var currentProtocol = document.protocol;

	if ((currentProtocol.indexOf("https") != 0) && (canSSL(currentHost))) {
		theForm.action = theForm.action.replace("http://", "https://");
		// alert(theForm.id + " is now " + theForm.action);
	}	

}


function goToPath(theRelativePath) {

	var currentHost = document.location.host;
	var currentProtocol = document.protocol;
	var secureProtocol = "https://";

	if (canSSL(currentHost)) {
		location.href = secureProtocol + currentHost + theRelativePath;
	} else {
		location.href = currentProtocol + currentHost + theRelativePath;
	}
}

function goToPage(theFullUrl) {
	if (canSSL(document.location.host)) {
		location.href = theFullUrl.replace("http://", "https://");
	} else {
		location.href = theFullUrl;
	}
}

// *********************************************************
// Cookie handling
// Some functions to make it easier to work with cookies
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

// *********************************************************
// AJAX functions, formerly in TrimPage.js
function trimAndInsert(rawContent,containerID,startText,endText,theUrl){
	var theContainer=document.getElementById(containerID);
	var theContent=rawContent;
	var theStart=theContent.indexOf(startText);
	var theEnd=theContent.indexOf(endText);
	var theSlice=theContent.slice(theStart,theEnd);
	theContainer.innerHTML=theSlice;
}

// *********************************************************
// AJAX functions, formerly in TrimPage.js
function getPage(url,placeHolderID,startText,endText){
	new Ajax.Request(url,
	    {
	    method: 'get',
	    onSuccess: function(processPage){
	       	var theResponseText=processPage.responseText || 'Nothing was returned';
           	trimAndInsert(theResponseText,placeHolderID,startText,endText,url);
           },
	    onFailure: function(){
			document.getElementById(placeHolderID).innerHTML='There was a problem getting information from the server.<br />Please try again in a few moments.';
	    }
	});
}

// *********************************************************
// AJAX functions, formerly in TrimPage.js
function getAspx(url, placeHolderID) {

	/*{success: placeHolderID} means that the container div will only be updated if thers is a successful response to the XMLhttpRequest call. */
	new Ajax.Updater({success: placeHolderID},url,{
		evalScripts: true
	});
}


/*********************************************************************************************/
/*********************************************************************************************/
/**                                                                                         **/
/** JavaScript Email Obscuring function                                                     **/
/** Added by Rod Coate                                                                      **/
/** 16 July 2007                                                                            **/
/** Based on code from :                                                                    **/
/** http://diagrammes-modernes.blogspot.com/2006/05/obscuring-your-email-from-spammers.html **/
/**                                                                                         **/
/*********************************************************************************************/
/*********************************************************************************************/
function InsertEmail(d,a) {  
//d = Display Text
//a = Address (first part)
    var chardot = '.'; 
    var charat = '@'; 
    var TheArray = new Array('au', 'edu', 'qct'); 
    document.write('<a href="ma'); 
    document.write('ilto:'); 
    document.write(a); 
    document.write(charat); 
    document.write(TheArray[2]); 
    document.write(chardot); 
    document.write(TheArray[1]);
    document.write(chardot);
    document.write(TheArray[0]); 
    document.write('">'); 
    document.write(d); 
    document.write('</a>');
}

function Clickheretoprint()
{ 
		var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
		    disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25"; 
		var content_vlue = document.getElementById("content").innerHTML; 
		
		var docprint=window.open("","",disp_setting); 
			docprint.document.open(); 
			docprint.document.write('<html><head><title>QCT: The College</title>'); 
			docprint.document.write('</head><body onLoad="self.print()"><left>');          
			docprint.document.write(content_vlue);          
			docprint.document.write('</left></body></html>'); 
			docprint.document.close(); 
			docprint.focus(); 
}
