// JavaScript Document

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function setSlideWidth() {
	// set width of slider to that of the sum of width of images inside
	if (!document.getElementById && !document.getElementsByTagName) return false;
	var slider = document.getElementById("slider");
	var imgs = slider.getElementsByTagName('img');
	var width = 0;
	for (var i=0; i<imgs.length; i++) {
		width += parseInt(imgs[i].width);
	}
	slider.style.width = width + 'px';
}

function projectThumbLinks() {
	// Attach handlers to Staff Links
	if (!document.getElementById) return false;
	if (!document.getElementsByTagName) return false;
	var links = document.getElementById("slider");
	if (!links.done) {
		links.done = 1;
		var a = links.getElementsByTagName("a");
		for (var i=0; i<a.length; i++) {
			elm = a[i];
			/* Dont do ajax calls
			if (BrowserDetect.browser != 'Safari') {
				elm.onclick = function () {
					// Image Path comes from page code
					if (httpRequest("GET",this.href+'&ajax=project',true,updateProject)) {
						// Block normal link
						return false;
					} else {
						// allow normal link
						return true;
					}
				};
			}
			*/
			elm.onmouseover = function () {
				img = this.getElementsByTagName('img');
				updateContent("projecthint",img[0].alt);
			};
		}
	}
}

function updateContent(id,val) {
	// replace innerHTML of element(ID) with val
    var elm = document.getElementById(id);
	if (elm) {
		elm.innerHTML=val;
	}
}

function updateImage(id,val) {
	// set src Attribute of image with id
    var elm = document.getElementById(id);
	if (elm) {
		elm.src=val;
	}
}

function updateImageWithSpinner(id,src) {
	// place spinner in image of id and preload image src, then update id with src
	preLoadImage = new Image();
	preLoadImage.onload = function() {
		var elm = document.getElementById(id);
		if (elm) {
			elm.height = preLoadImage.height;
			elm.width = preLoadImage.width;
			elm.src = preLoadImage.src;
			elm.parentNode.style.height = preLoadImage.height + 'px';
			window.location = '#menu';	// make window aline to top of the menu
		}
		var elm = document.getElementById(id);
	}
	showSpinner(id);
	preLoadImage.src = src;	// startup preload
}

function showSpinner(id) {
	var elm = document.getElementById(id);
	if (elm) {
		elm.style.display = 'none';
		elm.src='images/loading.gif';
		elm.width='32';
		elm.height='32';
		elm.style.display = '';
	}
}

function pause(numberMillis) {
	// pause 
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

function updateProjectDetail(title,desc) {
	var elm = document.getElementById('projectdetail');
	if (elm) {
		// remove children
		while(elm.firstChild) elm.removeChild(elm.firstChild);
	}
	// Create heading
	var heading = document.createElement("h1");
	var txt = document.createTextNode(title);
	heading.appendChild(txt);
	elm.appendChild(heading);
	// Create Paras
	for (var i=0; i<desc.length; i++) {
		var para = document.createElement("p");
		var txt = document.createTextNode(desc[i]);
		para.appendChild(txt);
		elm.appendChild(para);
	}
}

//event handler for XMLHttpRequest to Update the Project info
function updateProject(){
    if(request.readyState == 4) {
        if(request.status == 200){
            var resp =  request.responseText;
			//alert(resp);
            var func = new Function("return "+resp);	// resp is in JSON format
            var project = func();	// We now have an object which is the response
			updateImageWithSpinner('largeimage',project.urlfilename);
			pause(300);
			updateProjctDetail(project.title,project.main);
        } else {
			updateProjectDetail('WHOOPS!','We cant serve up the content right now, please check back later.');
        }
    }//end outer if
}

/* Wrapper function for constructing a Request object.
 Parameters:
  reqType: The HTTP request type such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not.
  rfunc the return handler
*/
var request = false;
function httpRequest(reqType,url,asynch,rfunc) {
    //Mozilla-based browsers
	request = false;
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request){
		/* Initialize a Request object that is already constructed */
	   	request.onreadystatechange=rfunc;
    	request.open(reqType,url,asynch);
    	request.send(null);
		return true;
    }  else {
       return false;
	}
}

function moveElement(elementID,final_x,final_y,interval) {
	// Move an element quickly and then progessively slower to a set x,y point
	if (!document.getElementById) return false;
	if (!document.getElementById(elementID)) return false;
	var elem = document.getElementById(elementID);
	if (elem.movement) {
	clearTimeout(elem.movement);
	}
	if (!elem.style.left) {
	elem.style.left = "0px";
	}
	if (!elem.style.top) {
	elem.style.top = "0px";
	}
	var xpos = parseInt(elem.style.left);
	var ypos = parseInt(elem.style.top);
	if (xpos == final_x && ypos == final_y) {
	return true;
	}
	if (xpos < final_x) {
	var dist = Math.ceil((final_x - xpos)/10);
	xpos = xpos + dist;
	}
	if (xpos > final_x) {
	var dist = Math.ceil((xpos - final_x)/10);
	xpos = xpos - dist;
	}
	if (ypos < final_y) {
	var dist = Math.ceil((final_y - ypos)/10);
	ypos = ypos + dist;
	}
	if (ypos > final_y) {
	var dist = Math.ceil((ypos - final_y)/10);
	ypos = ypos - dist;
	}
	elem.style.left = xpos + "px";
	elem.style.top = ypos + "px";
	var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
	elem.movement = setTimeout(repeat,interval);
}

function scrollElement(elementID,final_x,final_y,interval) {
	// Move an element quickly and then progessively slower to a set x,y scroll point
	if (!document.getElementById) return false;
	if (!document.getElementById(elementID)) return false;
	var elem = document.getElementById(elementID);
	if (elem.scrolling) {
	clearTimeout(elem.scrolling);
	}
	if (!elem.scrollLeft) {
	elem.scrollLeft = 0;
	}
	if (!elem.scrollTop) {
	elem.scrollTop = 0;
	}
	var xpos = elem.scrollLeft;
	var ypos = elem.scrollTop;
	if (xpos == final_x && ypos == final_y) {
	return true;
	}
	if (xpos < final_x) {
	var dist = Math.ceil((final_x - xpos)/10);
	xpos = xpos + dist;
	}
	if (xpos > final_x) {
	var dist = Math.ceil((xpos - final_x)/10);
	xpos = xpos - dist;
	}
	if (ypos < final_y) {
	var dist = Math.ceil((final_y - ypos)/10);
	ypos = ypos + dist;
	}
	if (ypos > final_y) {
	var dist = Math.ceil((ypos - final_y)/10);
	ypos = ypos - dist;
	}
	elem.scrollLeft = xpos;
	elem.scrollTop = ypos;
	var repeat = "scrollElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
	elem.scrolling = setTimeout(repeat,interval);
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function thumbInView() {
	// Only works for IE brings thumbnail into view in scroll area
	var id = gup('id');
	if (document.getElementById && id) {
		var elm = document.getElementById('th'+id);
		var slider = document.getElementById('slider');
		if (elm && slider) {
			var scrollAmount = elm.offsetLeft;
			var sliderWidth = parseInt(slider.offsetWidth);
			var sliderParentWidth = parseInt(slider.parentNode.offsetWidth);
			var maxScroll = (sliderWidth > sliderParentWidth) ? sliderWidth - sliderParentWidth : 0;
			if (scrollAmount > maxScroll) scrollAmount = maxScroll;
			scrollElement('window',scrollAmount,0,5);
		}
	}
}

/******************************************

	HTML javascript functions
	by Dave Barnwell http://freshsauce.co.uk
	License : Public Domain

	file version 16/09/2009 09:30:45

******************************************/

function nextElement(elm,n) {
	n=n||0;
	elm = E(elm)
	if (!elm) return null;
	do { 
		elm = elm.nextSibling; 
		if (elm && elm.nodeType == 1) n--;
	}	while (elm && n>=0);
	return elm;
}

function previousElement(elm,n) {
	n=n||0;
	elm = E(elm)
	if (!elm) return null;
	do {
		elm = elm.previousSibling; 
		if (elm && elm.nodeType == 1) n--;
	}	while (elm && n>=0);
	return elm;
}

function downElement(elm,n) {
	n=n||0;
	elm = E(elm)
	if (!elm) return null;
	do {
		elm = elm.firstChild; 
		if (elm && elm.nodeType == 1) n--;
	}	while (elm && n>=0);
	return elm;
}

function upElement(elm,n) {
	n=n||0;
	elm = E(elm)
	if (!elm) return null;
	do {
		elm = elm.parentNode; 
		if (elm && elm.nodeType == 1) n--;
	}	while (elm && n>=0);
	return elm;
}

function E(elm) {
	return elm =  (typeof elm == 'string') ? ((document.getElementById) ? document.getElementById(elm) : null) : elm;
}

/******************

	window load and unload helpers
		
*******************/

function addLoadEvent(func) {
	// Allow multiple loaders
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
			window.onload = function() {
				oldonload();
				func();
			}
	}
}

function addUnloadEvent(func) {
	// Allow multiple unloaders
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
	} else {
			window.onunload = function() {
				oldonunload();
				func();
			}
	}
}


/******************
		CSS Helpers
*******************/

function hasClass(elm,v) {
	elm = E(elm)
	return elm.className.match(new RegExp('(\\s|^)'+v+'(\\s|$)'));
}

function addClass(elm,v) {
	elm = E(elm)
	if (!hasClass(elm,v)) elm.className += (elm.className) ? " "+v : v;
}
 
function removeClass(elm,v) {
	elm = E(elm)
	if (hasClass(elm,v))	elm.className=elm.className.replace(new RegExp('(\\s|^)'+v+'(\\s|$)'),' ');
}

function getElementsByClassName(className,container,tag) {
	var m=[];
	c=container||document; 	// default container to document
	tag=tag||'*';		// default tag to *
	if (c.getElementsByTagName) {
		var elms = c.getElementsByTagName(tag);	// find tags in container
		for (i=0; i<elms.length; i++) {
			if (hasClass(elms[i],className)) m.push(elms[i]); // collect for class
		}
	}
	return m;
}

function hideElm(elm) {
	elm = E(elm)
	elm.style.display = 'none';
}

function showElm(elm) {
	elm = E(elm)
	elm.style.display = '';
}

function toggleElm(elm) {
	elm = E(elm)
	elm.style.display = (elm.style.display != "none") ? "none" : "";
}

function stripeTableRows(className,rowClass) {
	// Find all tables assigned className, then add classses to rows based on names in array rowClass,
	// if rowClass is null it defaults to ['row0','row1']
	if (!document.getElementsByTagName) return false;
	rowClass=rowClass||[,'row0','row1'];	// default 2 classes
	// Get a reference to the menu container
	var elms = getElementsByClassName(className,document,'TABLE');
	if (!elms) return false;
	for(var t=0;t<elms.length;t++){ 
		var rows = elms[t].getElementsByTagName('TR');
		for(var i=0; i<rows.length; i++) {
			rows[i].className=rowClass[i%rowClass.length];
		}
	}
	return true;
}

function higlightExternalLinks() {
	// add class 'external' to all external links
	var localhost = false;
	if (window.location) {
		localhost = window.location.hostname;
	}
	if (!localhost) return false;	// if we cant get the local host exit
	if (document.getElementsByTagName && document.getElementById) {
		var content = document.getElementById('container-content');
		if (content) {
			var links = content.getElementsByTagName('a'); // only links inside 'detailcol'
			for (i=0; i<links.length; i++) {
				if (links[i].hostname != localhost && links[i].hostname != '' && !(downElement(links[i]) && downElement(links[i]).nodeName == "IMG")) {
					addClass(links[i],'external');
					links[i].target="_blank"; // set to open in new window
				}
			}
		}
	}
}

// Add page handlers
addLoadEvent(setSlideWidth);
addLoadEvent(projectThumbLinks);
addLoadEvent(thumbInView);
addLoadEvent(higlightExternalLinks);