// Event handler
addEventToObject = function(obj,evt,func) {
	var oldhandler = obj[evt];
	obj[evt] = (typeof obj[evt] != 'function') ? func : function(ev){oldhandler(ev);func(ev);};
}

changeStyle = function(selectorID,selectorClass)
{
	document.getElementById(selectorID).className = selectorClass;
}

findLabels = function()
{
	var el = document.getElementsByTagName("label");
	for (i=0;i<el.length;i++)
	{
		var thisId = el[i].getAttribute("for");
		if ((thisId)==null)
		{
			thisId = el[i].htmlFor;
		}
		if(thisId!="")
		{
			el[i].onmouseover = highlightRelationship;
		}
	}
}
highlightRelationship = function()
{
	var thisId = this.getAttribute("for");
	if ((thisId)==null)
	{
		thisId = this.aspxFor;
	}	
	if (document.getElementById(thisId).type=="text") document.getElementById(thisId).select();
	if (document.getElementById(thisId).type=="password") document.getElementById(thisId).select();
	if (document.getElementById(thisId).tagName=="textarea") document.getElementById(thisId).select();
}

function setfocus(objectid) {
	if(document.getElementById(objectid)) {
		document.getElementById(objectid).focus();
    }
}

// ----------------------------------------------

randomisePhoto = function()
{
	var className = "";
	
	var item = new Array();
	item[0] = "photo01";
	item[1] = "photo02";
	item[2] = "photo04";
	item[3] = "photo05";
	item[4] = "photo06";
	
	now = new Date();
	multiplicationHelper = now.getSeconds();
	
	randomItem = Math.round(Math.random(multiplicationHelper) * item.length);
	if (randomItem == item.length)
		{
			randomItem = 0
		}

	className = item[randomItem];
	changeStyle('photo-container',className);
	Effect.Appear('message',
	{
		duration: 1.2
	});
}

// Handle table zebra striping
// ----------------------------------------------
stripetableBody = function()
{
	if (!document.getElementsByTagName) return false;
	var tableBody = document.getElementsByTagName("tbody");
	for (var i=0; i<tableBody.length; i++)
	{
		if (tableBody[i].getAttribute("class") == "alternateTableRows" || tableBody[i].getAttribute("className") == "alternateTableRows")
		{
			var odd = false;
			var rows = tableBody[i].getElementsByTagName("tr");
			for (var j=0; j<rows.length; j++)
			{
				if (odd == true)
				{
					addClass(rows[j],"odd");
					odd = false;
      			}
				else
				{
					odd = true;
		  		}
			}
	  	}
	}
}

addClass = function(element,value)
{
	if (!element.className)
	{
    	element.className = value;
	}
	else
	{
    	newClassName = element.className;
	    newClassName+= " ";
	    newClassName+= value;
	    element.className = newClassName;
  	}
}

// Assist the behaviour and presentation of form elements
// ----------------------------------------------
scanForFormElements = function()
{
	if (!document.getElementsByTagName) return false;
	var anchors = document.getElementsByTagName("input");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if ((anchor.getAttribute("type") == "text") || (anchor.getAttribute("type") == "password"))
		{
			addClass(anchor,'textfield');
		}
		if ((anchor.getAttribute("type") == "button") || (anchor.getAttribute("type") == "submit"))
		{
			addClass(anchor,'button');
		}
	}
}

// Handle the launching of new browser windows for offsite links as well as non-web files.
// ----------------------------------------------
scanForExternalLinks = function()
{
	if (!document.getElementsByTagName) return false;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		{
			anchor.href = "javascript:getOffsiteLink('"+anchor.getAttribute("href")+"');";
		}
		else if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "nonWebDocument")
		{
			anchor.href = "javascript:getFile('"+anchor.getAttribute("href")+"');";
		}
		else if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "popup")
		{
			anchor.href = "javascript:getFile('"+anchor.getAttribute("href")+"');";
		}
	}
}

getOffsiteLink = function(href)
{
	var screenHeight=window.screen.height;
	var screenWidth=window.screen.width;
	var windowWidth = screenWidth-(screenWidth*.66); // 1/3 of the screen's width
	var windowHeight = screenHeight-(screenHeight*.05);
	var Xcoordinate = 0;
	var Ycoordinate = 0;
	attributes = 'width='+windowWidth+',height='+windowHeight+',scrollbars=auto,toolbar=yes,menubar=yes,status=yes,directories=no,location=yes,resizable=yes';
	poppedWindow = window.open(href,'Spencerbull',attributes);
	poppedWindow.moveTo(Xcoordinate,Ycoordinate);
	poppedWindow.focus();
}

getFile = function(href)
{
	var screenHeight=window.screen.height;
	var screenWidth=window.screen.width;
	var windowWidth = screenWidth-(screenWidth*.05);
	var windowHeight = screenHeight-(screenHeight*.05);
	var Xcoordinate = (screenWidth-windowWidth)/2;
	var Ycoordinate = (screenHeight-windowHeight)/2;
 
	attributes = 'width='+windowWidth+',height='+windowHeight+',scrollbars=auto,toolbar=no,menubar=no,status=no,directories=no,location=no,resizable=yes';
	poppedWindow = window.open(href,'Spencerbull',attributes);
	poppedWindow.moveTo(Xcoordinate,Ycoordinate);
	poppedWindow.focus();
}

// Handle the presentation of the site-wide keyword search field
// ----------------------------------------------
var isSafari = ((parseInt(navigator.productSub)>=20020000)&&     // detecting WebCore
               (navigator.vendor.indexOf("Apple Computer")!=-1));

function replaceSearchField()
{
	if (document.getElementById('txtKeyword') != null)
	{
		// Replaces normal input text field with Safari's search field
		if (!document.getElementById)
		return;
		var searchField = document.getElementById('txtKeyword');
		if (isSafari)
		{
			searchField.setAttribute('type', 'search');
			searchField.setAttribute('results', '5'); // Display magnifying glass with dropdown?, How many recent searches should I display?
		}
	}
}

// Sets the value for the keyword search textfield on various user events
var textfield_keywordSearch = {
	init : function()
		{
		var smartKeyword = document.getElementById('txtKeyword');
		if (smartKeyword)
			{
			addEventToObject(smartKeyword,'onclick',textfield_keywordSearch.click);
			addEventToObject(smartKeyword,'onblur',textfield_keywordSearch.blur);
			}	
		},
	click : function()
		{
		var smartKeyword = document.getElementById('txtKeyword');
		if (smartKeyword.value == "Keyword...")
			{
			smartKeyword.value = "";
			}
	  	},
	blur : function()
		{
		var smartKeyword = document.getElementById('txtKeyword');
		if (smartKeyword.value == "" || smartKeyword.value == " ") {smartKeyword.value = "Keyword...";}
		}
	};
	
// Code to work with page sizing and the presentation of modal windows
// ----------------------------------------------
Position.getPageSize = function() {
	var xScroll, yScroll, scrollOffsetY;
	
	if (window.innerHeight && window.scrollMaxY) {  
	  xScroll = document.body.scrollWidth;
	  yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	  xScroll = document.body.scrollWidth;
	  yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	  xScroll = document.body.offsetWidth;
	  yScroll = document.body.offsetHeight;
	}
	
	if (self.pageYOffset) {
	  scrollOffsetY = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
	  scrollOffsetY = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
	  scrollOffsetY = document.body.scrollTop;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) { // all except Explorer
	  windowWidth = self.innerWidth;
	  windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	  windowWidth = document.documentElement.clientWidth;
	  windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
	  windowWidth = document.body.clientWidth;
	  windowHeight = document.body.clientHeight;
	} 
	
	// for small pages with total height less then height of the viewport
	pageHeight = Math.max(windowHeight, yScroll);
	
	// for small pages with total width less then width of the viewport
	pageWidth = Math.max(windowWidth, xScroll);
	
	return { page: { width: pageWidth, height: pageHeight }, 
			 window: { width: windowWidth, height: windowHeight },
			 scroll: { top: scrollOffsetY } };
}

// Modal windows
// ----------------------------------------------
var multiWindow = false;
var CurrentModalWindow = "none";
openModalWindow = function(elementID)
{
	//CurrentModalWindow = elementID;
	var overlayID = 'overlay';
	var v = Position.getPageSize();
	
	// Turn off scrollbars in the viewport as they render above the overlay //
	var tas = document.getElementsByTagName("textarea");
	for (var i = 0;i<tas.length;i++)
	{
		if (tas[i].className == "scrollOK")
		{
		}
		else
		{
			setStyle('textarea','overflow','hidden');
		}	
	}
	
	// Show the overlay and modal window //
	if (CurrentModalWindow!="none")
	{
		// Set style attributes for the overlay and modal window //
		document.getElementById(overlayID).style.height = v.page.height + "px";
		document.getElementById(elementID).style.top = (v.scroll.top+((v.window.height/100)*20)) + "px";
		multiWindow = true;
	}
	else
	{
		// Set style attributes for the overlay and modal window //
		document.getElementById(overlayID).style.height = v.page.height + "px";
		document.getElementById(elementID).style.top = (v.scroll.top+((v.window.height/100)*10)) + "px";
	}
	
	Effect.Appear(overlayID,
	{
		duration: 0.4, from: 0.0, to: 0.60
	});
	
	Effect.Appear(elementID,
	{
		duration: 1.0
	});
	
	CurrentModalWindow = elementID;
}

closeModalWindow = function(elementID)
{
	if (multiWindow!=true)
	{
		CurrentModalWindow = "none";
		var overlayID = 'overlay';
		Effect.Close(overlayID);
	}
	else
	{
		multiWindow = false;
	}
	Effect.Shrink(elementID);
	// Turn on scrollbars in the viewport back on //
	var tas = document.getElementsByTagName("textarea");
	for (var i = 0;i<tas.length;i++)
	{
		if (tas[i].className == "allowScroll")
		{
			
		}
		else
		{
			setStyle('textarea','overflow','auto');
		}	
	}
}

// Processing 'micro' windows
// ----------------------------------------------
showProcessor = function(containerID)
{
	var overlayID = containerID + "-overlay";
	
	// Offset the overlay to accomdate for CSS padding applied to the container //
	var MarginLeft = -1.4 + "em";
	
	// Turn off scrollbars in the container as they render above the overlay //
	setContainerScrollBarStyle('hidden');

	// Get the width and height of the container //
	var ContainerHeight = document.getElementById(containerID).clientHeight;
	var ContainerWidth = document.getElementById(containerID).clientWidth;

	// Offset the overlay to accomdate for CSS padding applied to the container //
	switch (BrowserDetect.browser)
	{
		case "Safari":			
			var ContainerHeight = document.getElementById(containerID).clientHeight + 0;
			var MarginTop = -ContainerHeight+7 + "px";
		break

		case "Firefox":
			var ContainerHeight = document.getElementById(containerID).clientHeight + 2;
			var MarginTop = -ContainerHeight+8 + "px";
		break

		default:
			var ContainerHeight = document.getElementById(containerID).clientHeight + 0;
			var MarginTop = -ContainerHeight+8 + "px";
		break
	}
	document.getElementById(overlayID).style.height = ContainerHeight + "px";
	document.getElementById(overlayID).style.width = ContainerWidth + "px";

	document.getElementById(overlayID).style.marginTop = MarginTop;
	document.getElementById(overlayID).style.marginLeft = MarginLeft;

	Effect.Appear(overlayID,
	{
		duration: 1.2
	});

function setContainerScrollBarStyle(styleValue)
{
	if (!document.getElementById(containerID)) return false;
	var theContainer = document.getElementById(containerID);
	var theElements = theContainer.getElementsByTagName("textarea");
	for ( var i=0; i < theElements.length; i++)
	{
		theElements[i].style.overflow = styleValue;
	}
}

hideProcessor = function(containerID)
{
	// Restore scrollbars //
	setContainerScrollBarStyle('auto');
	Effect.Fade(overlayID,
	{
		duration: 0.6, from: 1.0, to: 0.0
	});
	}
}

clearContent = function(selectorID)
{
	var theSelector = document.getElementById(selectorID);
	theSelector.value = "";
}

showInlineProcessor = function(buttonID,messageID)
{
	Effect.Fade(buttonID,
	{
		duration: 0.4, to: 0.5
	});
	Effect.Appear(messageID,
	{
		duration: 0.4
	});
}

hideInlineProcessor = function(buttonID,messageID)
{
	Effect.Appear(buttonID,
	{
		duration: 0.4, to: 1.0
	});
	Effect.Fade(messageID,
	{
		duration: 0.4
	});
}

operationConfirm = function(messageIDcurrent,messageIDnext,buttonID)
{
	Effect.Fade(messageIDcurrent,
	{
		duration: 1.0,
		afterFinish:function()
		{
			Effect.Appear(messageIDnext,
			{
				duration: 1.0,
				afterFinish:function(effect)
				{
					new Effect.Highlight(effect.element);
					Effect.Appear(buttonID,
					{
						duration: 0.4
					});
				}
			});
		}
	});
}

showProcessConfirm = function(messageIDcurrent,messageIDnext)
{
	Effect.Fade(messageIDcurrent,
	{
		duration: 1.0,
		afterFinish:function()
		{
			Effect.Appear(messageIDnext,
			{
				duration: 1.0
			});
		}
	});
}

resetSendPage = function(firstID,secondID)
{
	Effect.Fade(firstID,
	{
		duration: 1.0,
		afterFinish:function()
		{
			Effect.Fade(secondID,
			{
				duration: 1.0,
				afterFinish:function()
				{
					closeModalWindow('sendPage');
				}
			});
		}
	});
}

function disableFormSubmit()
{
	Effect.Fade('btnSubmit',
	{
		duration: 0.4, to: 0.5
	});
}

function enableFormSubmit()
{
	Effect.Appear('btnSubmit',
	{
		duration: 0.2, to: 1.0
	});
}

// ----------------------------------------------
setStyle = function(selector,property,value)
{
	var t = document.getElementsByTagName(selector);
	for (var i=0; i<t.length; i++) 
	{
		switch (property)
		{
			case "overflow":
				if (t[i].className == "allowScroll")
					{
						t[i].style.overflow = "auto";
					}
				else
					{
						t[i].style.overflow = value;
					}
			break
			
			case "visibility":
				t[i].style.visibility = value;
			break
		}
	}
}

// Animate number values
// ----------------------------------------------

changeValue = function(elementID,newValue)
{
	new Effect.NumberCounter(elementID,newValue,
	{ 
		afterFinish:function(effect)
		{
			new Effect.Highlight(effect.element);
		}
	});
}

// Feedback functions
// ----------------------------------------------
showFeedback = function(actionContainerID)
{
	var div = document.createElement("div");
	div.className = "feedback-processing";
	div.innerHTML = "Verifying&#8230;";
	div.id = "submitFeedback";
	div.style.display = "none";
	//alert(actionContainerID);
	document.getElementById(actionContainerID).appendChild(div);
	
	var buttons;
	switch (BrowserDetect.browser)
	{
		case "Safari":
			buttons = document.getElementById(actionContainerID).childNodes[1].id
		break
		
		case "Firefox":
			buttons = document.getElementById(actionContainerID).childNodes[1].id
		break
		
		default:
			buttons = document.getElementById(actionContainerID).childNodes[0].id
		break
	}
	
	Effect.Fade(buttons,
	{
		duration: 0.4,
		afterFinish:function()
		{
			Effect.Appear('submitFeedback',
			{
				duration: 0.4
			});
		}
	});
}

updateFeedbackMessage = function(message)
{
	document.getElementById("submitFeedback").innerHTML = message + "&#8230;";
}

setFeedbackComplete = function(message)
{
	document.getElementById("submitFeedback").className = 'feedback-complete';
	document.getElementById("submitFeedback").innerHTML = message;
}

setFeedbackFailed = function()
{
	document.getElementById("submitFeedback").className = 'feedback-failed';
	document.getElementById("submitFeedback").innerHTML = 'Failed';
}

restoreButtons = function(actionContainerID)
{
	//hide processor feedback and restore buttons
	var buttons;
	switch (BrowserDetect.browser)
	{
		case "Safari":
			buttons = document.getElementById(actionContainerID).childNodes[1].id
		break
		
		case "Firefox":
			buttons = document.getElementById(actionContainerID).childNodes[1].id
		break
		
		default:
			buttons = document.getElementById(actionContainerID).childNodes[0].id
		break
	}
	Effect.Fade('submitFeedback',
	{
		duration: 0.4,
		afterFinish:function()
		{
			Effect.Appear(buttons,
			{
				duration: 0.4
			});
			
		}
	});
	
	window.setTimeout(function()
	{
		removeFeedback(actionContainerID)
	},1600);
}

removeFeedback = function(selectorID)
{
	var ac = document.getElementById(selectorID);
	var sf = document.getElementById("submitFeedback");
	ac.removeChild(sf);
}
				
cleanupFeedback = function(selectorID)
{
	window.setTimeout(function()
	{
		cleanupFeedbackInner(selectorID)
	},1000);	
}

cleanupFeedbackInner = function(selectorID)
{
	removeFeedback(selectorID);
	var selectorChildID;

	switch (BrowserDetect.browser)
	{
		case "Safari":
			selectorChildID = document.getElementById(selectorID).childNodes[1].id
		break
		
		case "Firefox":
			selectorChildID = document.getElementById(selectorID).childNodes[1].id
		break
		
		default:
			selectorChildID = document.getElementById(selectorID).childNodes[0].id
		break
	}
	Effect.Appear(selectorChildID,
	{
		duration: 0
	});
}

feedbackValid = function(message1, message2)
{
	window.setTimeout(function(){updateFeedbackMessage(message1)}, 2000);
	window.setTimeout(function(){setFeedbackComplete(message2)}, 3000);
}

feedbackInvalid = function(buttonContainerID)
{
	window.setTimeout(function(){setFeedbackFailed()}, 1000);			
	window.setTimeout(function(){restoreButtons(buttonContainerID)}, 2000);
}

// Browser detection
// ----------------------------------------------
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();

// Attach functions to window onload
// ----------------------------------------------
addEventToObject(window,'onload',scanForFormElements);
addEventToObject(window,'onload',textfield_keywordSearch.init);
addEventToObject(window,'onload',replaceSearchField);
addEventToObject(window,'onload',scanForExternalLinks);
