/*----------------------------------------------------------------------------------------------------------------------------------
	Javascript Tool Library
----------------------------------------------------------------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------------------------------------------------------------
	setCookie:

----------------------------------------------------------------------------------------------------------------------------------*/
function setCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
								 + ";expires="+expire.toGMTString();
}

/*----------------------------------------------------------------------------------------------------------------------------------
	loadComponent:

	Use this function to replace the contents of a dom element with the result of an Ajax call. Handles the issue of the login
	expired and notifies the slots with the signal
----------------------------------------------------------------------------------------------------------------------------------*/
function loadComponent(domId,url,args,flag) {
	if (flag == undefined)
		flag=true;

	// Oops! the dom element to load wasn't specified.
	if (typeof(domId) == "string") {
		if (domId=='') {
			alert('Did you mean to reload the entire page? :'+url+args);
			window.location=url+args;
			return;
		}

		// The request wants to reload the entire page.
		if (domId=='index') {
			// TODO: need to also add 'args'. But if the args are an object hash, they can't just be added onto the end of the url string.
			// Need a routine to strip them out of the hash back into &var=value pairs
			window.location=url;
			return;
		}
	}

	document.body.style.cursor = 'wait';

	// Update the Dom element with the Ajax result.
	// TODO: Need to ensure that args are defined in the correct format as an object hash.
	// E.G. ->	{username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
	new Ajax.Request(url, {
		method: 'post',
		parameters: args, 
		onSuccess: function(response) {
			if (response.responseText.substring(2,9) == 'DOCTYPE') {
				// Oops, a redirect, obviously somethings not right.
				//alert('Oops, we were expecting to load Dom Element:'+domId+'\n, but instead we received an entire html document');
				document.open();
				document.write(response.responseText);
				document.close();
			}
			else {
				// If domid is a string then it's the id of a dom element
				if (typeof(domId) == "string") {
					if ($(domId))
						$(domId).update(response.responseText);
					//else
						//alert('Oops, DOM Element: \''+domId+'\' doesn\'t exist');

					if (flag)
						window.status = 'Loaded:'+domId+', With:'+url;
				}
				else { // It's the actual element passed directly
					domId.update(response.responseText);
					if (flag)
						window.status = 'Loaded: a Dom element, With:'+url;
				}
			}
			document.body.style.cursor = 'auto';
		}
	});

	// Put this as a link at the bottom of the page to help developers find "ajaxed" content. 
	if (flag) {
		var nw = url.replace(/&op=[^&]*/,''); // Just cuts "op="	out of the string. (should also remove the text but this works)
		var sl = $('statusLink');
		if (sl != undefined) 
			sl.update('<a href="'+nw+'">'+nw+'</a>');
	}
}

function processForm(tgt,url,formId) {
	loadComponent(tgt,url,$(formId).serialize(true));
}

function docHeight() {
	var pageHeight = 0;
	if( window.innerHeight && window.scrollMaxY ) { // Firefox 
		pageHeight = window.innerHeight + window.scrollMaxY;
	}
	else if( document.body.scrollHeight > document.body.offsetHeight ) { // all but Explorer Mac
		pageHeight = document.body.scrollHeight;
	}
	else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		pageHeight = document.body.offsetHeight + document.body.offsetTop; 
	}

	if (document.body.clientHeight > pageHeight)
		pageHeight = document.body.clientHeight;

	// Finally Try Prototype
	var s = document.viewport.getDimensions();
	if (s.height > pageHeight)
		pageHeight = s.height;

	return pageHeight;
}

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)

	// At least one @
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
		 return false

	// At least one .
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
			return false

	// Don't want More than one @
	 if (str.indexOf(at,(lat+1))!=-1)
			return false
	
	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
			return false

	 if (str.indexOf(dot,(lat+2))==-1)
			return false
	
	 if (str.indexOf(" ")!=-1)
			return false
	
 	 return true					
}

function selectedOption(sel) {
	var s=0;
	var so=sel.options;
	for (var i=0;i<so.length;i++) {
		if (so[i].selected) {
			s=so[i].value;
			break;
		}
	}
	return s;
}

function showLink(t) {
	window.status = t;
}

function clearLink() {
	window.status = '';
}

function divHilite(e) {
	if (!e)
		var e=window.event;
	var o=e.srcElement||e.target;
	switch (e.type) {
		case "mouseover" :
			o.setAttribute("oldbg",o.style.backgroundColor);
			o.style.backgroundColor="#0af";
		 break;
		case "mouseout" :
			o.style.backgroundColor=o.getAttribute("oldbg");
		 break;
	}
}

function findParentNodeByTagName(ele,tagName) {
	var prt=ele.parentNode;
	while (prt && prt.tagName!=tagName)
		prt=prt.parentNode;
	return (prt);
}

function findNextSiblingByTagName(ele,tagName) {
	var sibling=ele.nextSibling;
	while (sibling && sibling.tagName!=tagName)
		sibling=sibling.nextSibling;
	return(sibling);
}

function findPreviousSiblingByTagName(ele,tagName) {
	var sibling=ele.previousSibling;
	while (sibling && sibling.tagName!=tagName)
		sibling=sibling.previousSibling;
	return(sibling);
}

function isChildOf(parent, child) {
	if( child != null ) {			
		while( child.parentNode ) {
			if( (child = child.parentNode) == parent ) {
				return true;
			}
		}
	}
	return false;
}

function nestedMouseOut(element, event, JavaScript_code) {
	var current_mouse_target = null;
	if( event.toElement ) {				
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {				
		current_mouse_target 			 = event.relatedTarget;
	}
	if( !isChildOf(element, current_mouse_target) && element != current_mouse_target ) {
		eval(JavaScript_code);
	}
}

/*----------------------------------------------------------------------------------------------------------------------------------
	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: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			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.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
