/* AJAX Middleman Script
 *
 * Written by Sindeko (J. Bird)
 * sindeko@gmail.com
 * For TutorialRoom.com and GRC students
 * Last updated: March 15, 2008
 *
 * Purpose: Code to handle specific AJAX Requests for Tutorialroom.com
 * For Tutorialroom.com and GRC Students only.
 * 
 * REQUIREMENTS:
 * 1. You must use the open source JQuery Library to handle the actual
 * 	AJAX requests.  You can download the file at JQuery's website
 * 	(www.jquery.com).  Adjust the script.src line below to the 
 * 	location of the JQuery file.
 * 
 * 2. To call the bookmark/permalink, just set your link to javascript:permalink()
 * 	or javascript:bookmark().  It will refresh the page with the linkable url.
 */

// Array of URLs for the permalink
var permaURLs = new Array();

// Array of divs for the permalink
var permaDivs = new Array();


// Attach JQuery file to the page dynamically
function loadjquery(){

	// Create a new script HTML tag
	var script = document.createElement('script');
	
	// Set the script tag attributes
	script.type = 'text/javascript';
	script.src = '../scripts/jquery.js';
	
	// Attach to the page
	document.getElementsByTagName('head')[0].appendChild(script);
}

// AJAX call that runs a given javascript function after it gets the data
function ajax(url,resp){
	
	// Call to simpleajax to retrieve information
	var results = simpleajax(url);
	
	// Run the given function
	resp(results);
}

// Returns text from an AJAX call directly into a div
function divajax(url,tdiv){
	document.getElementById(tdiv).innerHTML = simpleajax(url);
}

// AJAX caller. Returns text found to its caller
function simpleajax(url){

	// Format URL with junk
	url = formaturl(url);
	
	// Call to JQuery ajax function
	var results = $.ajax({url:url,async: false}).responseText;
	
	// Send info back to whoever called this
	return(results);
}

// Generates a random number (1-100000)
function rand(){
	return Math.round(Math.random() * 100000);
}

// URL Formatting, used for IE Cache workaround
function formaturl(url){
	
	// If the url contains query variables, append to them, otherwise create the query string
	// Query variables are the ?a=141&e=13594 part of a url
	if(url.indexOf('?') != -1){
		url+='&'+rand();
	} else {
		url+='?'+rand();
	}
	
	// Can track if the page request is an AJAX call
	url+='&ajaxcall=1';
	
	// Give it back
	return url;
}

// Main function, takes a list of pages and a list of divs and turns it to a batch AJAX process
function getFile(urls,divs){
	// urls is the list of urls, divs is list of target div tags
	
	// Image file extensions recognized
	var imgs = 'jpg,jpeg,gif,png,bmp,tif,tiff,svg';
	
	// Array of extensions, easier to loop through
	var imgsA = imgs.split(',');
	
	// Array of page targets, used for looping
	var links = urls.split(',');
	
	// Array of div targets, looping as well
	var targets = divs.split(',');
	
	// This checks to make sure you have the same number of 
	// links and targets, and will stop if the two do not match
	if (links.length != targets.length) {
		alert('Number of links ('+links.length+') do not match number of targets ('+targets.length+').');
		return false;
	}
	
	// Array of Objects, used for OOP and if there is need to target the objects later on
	var ajaxObjs = new Array(links.length);
	
	// Loop through each of the links
	for(var i = 0;i < links.length; i++) {
		
		// Get extension
		var dot3 = links[i].split('.')[links[i].split('.').length-1];
		
		// Set this to false for each loop through
		var isimg = false;
		
		// Loop through the extensions, and see if the file extension matches one specified
		for(var j=0;j<imgsA.length;j++){
			// One matched, this is an image
			if(imgsA[j]==dot3){isimg=true}
		}
		
		// If an image extension was found, run getImage instead
		// Otherwise, get the file and put it in the div
		if(isimg){
			getImage(links[i],targets[i]);
		} else {
			ajaxObjs[i] = new divajax(links[i],targets[i]);
			saveLink(links[i],targets[i]);
		}
	}
}

// Gets an Image and formats it in HTML so you don't have to
function getImage(urls,divs){
	
	// List of links
	var links = urls.split(',');
		
	// List of divs to put in
	var targets = divs.split(',');
	
	// This checks to make sure you have the same number of 
	// links and targets, and will stop if the two do not match
	if (links.length != targets.length) {
		alert('Number of links ('+links.length+') do not match number of targets ('+targets.length+').');
		return false;
	}
	
	// Make HTML for the image
	for(var i = 0;i < links.length; i++){
		document.getElementById(targets[i]).innerHTML = '<img src="../wsb4754045501/scripts/'+links[i]+'" />';
		saveLink(links[i],targets[i]);
	}
}

function getStyleSheet(files,clearfirst){
	try{
		clearfirst = clearfirst;
	} catch(e) {
		clearfirst = false;
	}
	
	var headtag = document.getElementsByTagName('head')[0];
	var linktags = headtag.getElementsByTagName('link');
	
	if(clearfirst){
		
		for(var i=0;i<linktags.length;i++){
			if($.browser.msie){
				linktags[i].href='';
			} else {
				headtag.removeChild(linktags[i]);
			}
			
		}
	}
	
	listoffiles = files.split(',');
	for(var i=0;i<listoffiles.length;i++){
		var temptag = document.createElement('link');
		temptag.rel = 'stylesheet';
		temptag.type = 'text/css';
		temptag.href = listoffiles[i];
		
		headtag.appendChild(temptag);
	}
}

// Saves dynamic div activity
function saveLink(url,div){
	
	// Flag to see if it's replacing instead of adding
	var addedFlag = false;
	
	// Loop though to see if the div has had activity before
	for(var i=0;i<permaDivs.length;i++){
		
		// Found previous activity, update with new file URL
		if(permaDivs[i] == div){
			
			// Splice URL into array
			permaURLs.splice(i,1,url);
			
			// Mark flag to true, so it will ignore the second part of this function
			addedFlag = true;
		}
		
	}
	
	// If the div has had no activity yet, add to each array
	if(!addedFlag){
		
		// Add URL to URL array
		permaURLs.push(url);
		
		// Add div to div array
		permaDivs.push(div);
		
	}
	
}

// Set the URL to a page that can be permanently linked/bookmarked
function permalink(){
	
	// Get the URL we're at now
	fullURL = new String(document.location.href);
	
	// Attach current file URLs and current targeted divs to the new URL and go to that page.
	document.location = fullURL.split('?')[0]+'?urls='+permaURLs.join(',')+'&divs='+permaDivs.join(',');
		
}

function addDiv(parentID,newID,newClass){
	var temptag = document.createElement('div');
	if(newClass){
		temptag.className = newClass;
	}
	temptag.id = newID;
	
	document.getElementById(parentID).appendChild(temptag);
}

// Aliases for getStyleSheet, any of these can be called.
getstylesheet = getStyleSheet;
getStylesheet = getStyleSheet;
getCSS = getStyleSheet;
getcss = getCSS;

// Can call either permalink() or bookmark()
bookmark = permalink;

// Case sensitivity, can call either getFile or getfile now
getfile = getFile;

// Same for getImage and getimage
getimage=getImage;

// Attach JQuery to the page
loadjquery();
