// Generic useful javascript

var sp = ' ';
var csp = ', ';

// Allows us to supply the name of an element or the element itself to most functions
function $(id) {
	if (typeof id == 'string') return document.getElementById(id);
	return id;
}

function name$(name) {
	if (typeof name == 'string') return document.getElementsByName(name);
	return id;
}

function goBack() {
	history.go(-1);
}

function hide(el) {
	el = $(el);
	if (el) el.style.display = 'none';
}

function show(el) {
	el = $(el);
	if (el) el.style.display = '';
}

function toggle(el) {
	el = $(el);
	if (el) el.style.display = (el.style.display == 'none'?'':'none');
}

function space2nbsp(s) {
	while (s.indexOf(' ') >= 0) s = s.replace(' ','&nbsp;');
	return s;
}

function maxLength(s,len) {
	if (s.length > len) return s.substring(0,len-2) + '...';
	return s;
}

function HTMLEncode(str) {
	var output = '';
	if (typeof str == 'string') {
		for (var i=0;i<str.length;i++) output += '&#'+str.charCodeAt(i)+';';
	}
	return output;
}

// functions for select, checkbox, radiobox
function setSelected(which, selected) {
	var el = $(which);	
	for(var i=0; i<el.options.length; i++) {
		if (el.options[i].value == selected) {
			el.selectedIndex = i;
			break;
		}
	}	
}
function setInputValue(which, value) {
	$(which).value = value;	
}
function getInputValue(which, value) {
	return $(which).value;	
}

function setCheckboxValues(which, value) {
	var theInput = name$(which);
	
	if (theInput.length) {
		for (var i=0; i<theInput.length; i++) {
			theInput[i].checked = false;
		}
		
		if (typeof value == "string") {
			for (var i=0; i<theInput.length; i++) {
				if (theInput[i].value == value) {
					theInput[i].checked = true;
				}
			}
		} else {
			for (var i=0; i<theInput.length; i++) {
				for (var temp in value) {				
					if (theInput[i].value == value[temp]) {
						theInput[i].checked = true;
					} 
				}
			}
		}
	} else {
		theInput.checked = false;
		if (typeof value == "string") {
			if (theInput.value == value) {
				theInput.checked = true;
			}
		} else {			
			for (var temp in value) {
				if (theInput.value == value[temp]) {
					theInput.checked = true;
				}
			}
		
		}
	}
}
function getCheckboxValues(which) {
	var theInput = name$(which);
	var values = new Array();
	if (theInput.length) {
		for (var i=0; i<theInput.length; i++) {				
			if (theInput[i].checked == true) {
				values[values.length] = theInput[i].value;
			} 			
		}
	} else {
		if (theInput.checked == true) {
				values[values.length] = theInput.value;
		} 
	}
	return values;
}

//function openWindow(args) {

	/*	Default args
		args = {name:"myPopupWin", url:"required", width:"520", height:"400"
				, resizable:"yes",  scrollbars:"yes", modalDialog:"false"
				};

	*/
function openWindow(url,name,width,height,resizable,scrollbars,enableModal) {	
	
	if (!name) name="Popup_32" + Math.round(Math.random());
	if (!width) width = 800;
	if (!height) height = 600;
	if (!resizable) resizable = 'no';
	if (!scrollbars) scrollbars = 'no';
	if (!resizable) resizable = 'no';
	if (!enableModal) enableModal = false;
	
	x = parseInt(screen.width / 2.0) - (width / 2.0);
	y = parseInt(screen.height / 2.0) - (height / 2.0);
		
	if (window.showModalDialog && resizable == 'no') {
		if (enableModal) {
	        var features = "resizable:" + resizable
	            + ";scroll:"
	            + scrollbars + ";status:yes;center:yes;help:no;dialogWidth:"
	            + width + "px;dialogHeight:" + height + "px;";
			window.showModalDialog(url, window, features);
		} else {
			var win = window.open(url, name, "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",minimizable=" + resizable + ",width=" + width + ",height=" + height + ",resizable=" + resizable);
			win.focus();
			try { win.resizeTo(width, height); } catch(e) { }
		}
	} else {
		var modalDialog = '';
		if (enableModal) {
			modalDialog=',dialog=yes,modal=yes';
		}
		var win = window.open(url, name, "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",minimizable=" + resizable + ",width=" + width + ",height=" + height + ",resizable=" + resizable + modalDialog);
		try { win.resizeTo(width, height); } catch(e) { }

		win.focus();

	}
	/*
	var modalDialog = '';
	if (args['modalDialog'] == 'true') {
		modalDialog=',dialog=yes,modal=yes';
	}
	
	win = window.open(url, name, "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",minimizable=" + resizable + ",width=" + width + ",height=" + height + ",resizable=" + resizable + modalDialog);
	try { win.resizeTo(width, height); } catch(e) { }
	win.focus();
	*/
}

function BrowserDetector() {

	this.browser = '';
	this.os = '';

	var detect = navigator.userAgent.toLowerCase();

	function checkIt(aString) {
		return detect.indexOf(aString) + 1;
	}

	if (checkIt('konqueror')) {
		this.browser = "Konqueror";
		this.os = "Linux";
	} else if (checkIt('safari')) this.browser = "Safari"
	else if (checkIt('omniweb')) this.browser = "OmniWeb"
	else if (checkIt('opera')) this.browser = "Opera"
	else if (checkIt('webtv')) this.browser = "WebTV";
	else if (checkIt('icab')) this.browser = "iCab"
	else if (checkIt('msie')) this.browser = "Internet Explorer"
	else if (checkIt('firefox')) this.browser = "Firefox"
	else if (!checkIt('compatible')) {
		this.browser = "Netscape Navigator"
	} else {
		this.browser = "Unknown";
	}

	if (!this.os) {
		if (checkIt('linux')) this.os = "Linux";
			else if (checkIt('x11')) this.os = "Unix";
			else if (checkIt('mac')) this.os = "Mac"
			else if (checkIt('win')) this.os = "Windows"
			else this.os = "Unknown";
	}

	this.isIE = this.browser == "Internet Explorer";
	this.isGecko = checkIt('gecko');
}

var browser = new BrowserDetector();

// Return the x coordinate of an element relative to the page.
function getPageOffsetLeft(el) {
	el = $(el);
	var x;
	x = el.offsetLeft;
	if (el.offsetParent != null) x += getPageOffsetLeft(el.offsetParent);
	return x;
}

function getPageOffsetTop(el) {
	el = $(el);
	var y;
	// Return the x coordinate of an element relative to the page.
	y = el.offsetTop;
	if (el.offsetParent != null)  y += getPageOffsetTop(el.offsetParent);
	return y;
}

function objectDump(o,theMaxDepth,theDepth) {
	var maxDepth = theMaxDepth
	if (maxDepth == null) maxDepth = 2;

	var depth = theDepth;
	if (depth == null) depth = 1;
	var s = '';
	if (typeof o == "string") {
		s = '<code>'+escapeHTML(o)+'</code>';
	} else {
		for (var prop in o) {
			try {
				if (typeof o[prop] != 'string' && depth < maxDepth) {
					s += prop + ' = [object] <ul>' + objectDump(o[prop],maxDepth,depth+1) + '</ul>';
				} else {
					s += prop + ' = ['+(typeof o[prop])+'] <code>' + escapeHTML(o[prop]) + '</code><br>';
				}
			} catch (exception) {
				s += prop + ' = [error displaying value]' + '<br>';
			}
		}
	}
	return s;
}

function dump(o,desc,target,maxDepth) {
	var s = '';
	if (typeof desc != 'undefined') s+= desc+' =  ';

	s += '['+(typeof o)+']';
	s += '<ul>'+objectDump(o,maxDepth)+'</ul>';

	if (target) {
		$(target).innerHTML = s;
	} else {
		var newwin = window.open();
		newwin.document.write(s);
	}
}



function makeDivWithClass(className) {
	var div = document.createElement("div");
	div.className = className;
	return div;
}


function makeNestedDivsWithClasses(classNames,innerDiv) {
	var divs = new Array();
	var i;
	for (i=0; i<classNames.length; i++) divs[i] = makeDivWithClass(classNames[i]);
	for (i=0; i<classNames.length-1; i++) divs[i].appendChild(divs[i+1]);
	if (innerDiv) divs[classNames.length-1].appendChild(innerDiv);
	return divs[0];
}

var W3CDOM = (document.createElement && document.getElementsByTagName);

var mouseOvers = new Array();
var mouseOuts = new Array();

var mouseover_call;
function loadMouseOvers(container,modifier,className,callOnMouseOver) {
	if (!W3CDOM) return;
	var imgs = $(container).getElementsByTagName('img');

	mouseover_call = callOnMouseOver;
	if (!mouseover_call) mouseover_call = null;
	for (var i=0; i<imgs.length; i++) {
		if (imgs[i].className == className) {
			imgs[i].style.cursor = 'pointer';
			var suffix = imgs[i].src.substring(imgs[i].src.lastIndexOf('.'));
			var j = mouseOvers.length;
			mouseOuts[j] = new Image();
			mouseOuts[j].src = imgs[i].src;
			mouseOvers[j] = new Image();
			mouseOvers[j].src = imgs[i].src.substring(0,imgs[i].src.lastIndexOf('.')) + modifier + suffix;
			imgs[i].number = j;
			imgs[i].onmouseover = mouseGoesOverImage;
			imgs[i].onmouseout = mouseGoesOutImage;
		}
	}
}

function mouseGoesOverImage() {
	if (mouseOvers && mouseOvers[this.number] && this.src != mouseOvers[this.number].src) this.src = mouseOvers[this.number].src;
	if (mouseover_call != null) mouseover_call(this);
}

function mouseGoesOutImage() {
	if (mouseOuts && mouseOuts[this.number] && this.src != mouseOuts[this.number].src) this.src = mouseOuts[this.number].src;
}


var hover_call_onmouseover;
function loadHovers(container,elType,className,hoverClassName,callOnMouseOver) {

	if (!W3CDOM) return;
	var els = $(container).getElementsByTagName(elType);
	hover_call_onmouseover = callOnMouseOver;
	if (!hover_call_onmouseover) hover_call_onmouseover = null;

	for (var i=0; i<els.length; i++) {
		if (els[i].className == className || className == '') {
			els[i].originalClassName = els[i].className;
			els[i].hoverClassName = els[i].className+' '+hoverClassName;
			els[i].onmouseover = mouseGoesOverElement;
			els[i].onmouseout = mouseGoesOutElement;
		}

	}
}
function mouseGoesOverElement() {
	if (this.hoverClassName) this.className = this.hoverClassName;
	if (hover_call_onmouseover != null) hover_call_onmouseover(this);
}
function mouseGoesOutElement() {
	if (this.originalClassName) this.className = this.originalClassName;
}


function loadHoversCustom(container,elType,className,mouseOverEl,mouseOutEl,initEl) {

	if (!W3CDOM) return;
	var els = $(container).getElementsByTagName(elType);

	for (var i=0; i<els.length; i++) {
		if (els[i].className == className || className == '') {
			if (initEl) initEl(els[i]);
			els[i].onmouseover = mouseOverEl;
			els[i].onmouseout = mouseOutEl;
		}
	}
}


// Stop people highlighting things by accident
function disableselect(e) {
}
function reEnable(){
	return true;
}

var omitformtags= "input|textarea|select";
function stopHighlight(target) {
	target = $(target);
	if (typeof target.onselectstart != "undefined") {
		// IE
		target.onselectstart = function () {
			if (omitformtags.indexOf(window.event.srcElement.tagName.toLowerCase())==-1) return false;
		}
	} else {
		// others
		target.onmousedown = function(e) {
			if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1) return false;
		}
		target.onmouseup = function() {
			return true;
		}
	}
}

function addClassName(el,name) {
	el.className += ' '+name;
}

function removeClassName(el,name) {
	if (el.className == null) return;
	var before = el.className.split(" ");
	var after = new Array();
	for (var i = 0; i < before.length; i++) {
		if (before[i] != name) after.push(before[i]);
	}
	el.className = after.join(" ");
}
var is_ie = (navigator.appName == "Microsoft Internet Explorer");

function getURLContent(url) {
	var req = null;
	if(is_ie) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		req = new XMLHttpRequest();
	}

	// Synchronous!
	req.open('GET', url, false);
	req.send(null);
	if (req.status == 200) {
		return req.responseText;
	} else {
		return '';
	}
}

var http_request = false;
var http_request_callOnReady;

function urlRequest(url, callOnReady) {
    http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        //alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }

    http_request_callOnReady = callOnReady;
    http_request.onreadystatechange = function() {
	  if (http_request.readyState == 4) {
	    if (http_request.status == 200) {
	    	http_request_callOnReady(http_request.responseText);
	    }
	  }
    }

    //eval(callOnReady);
    http_request.open('GET', url, true);
    http_request.send(null);
    return true;
}
//function callResult

function strippx(string) {
	return parseFloat(string.replace('px',''));
}

function getInputHelp(helpid) {
	alert('get help' +helpid);
}

function disableBackspace() {
	document.onkeydown = function() {
		var omitformtags= "input,textarea";
		if (window.event && window.event.keyCode == 8) { // try to cancel the backspace
			if (omitformtags.indexOf(window.event.srcElement.tagName.toLowerCase())==-1) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
				return false;
			}
		}
	}
}

function MDIFixForIE() {
	if (browser.isIE) $('MDIDocumentContent').style.overflow = 'auto';
}

function isDefined(varName) {
	return (typeof(eval(varName)) != 'undefined');
}

function showandhide(which, msg, duration) {
	
	var preMSG = $(which).innerHTML;
	$(which).innerHTML = msg;
	show(which);
	if (!duration) duration = 3;
	setTimeout("hide('"+which+"');$('"+which+"').innerHTML = '"+preMSG+"';",duration*1000); // duration is in second and arg is in millisecond	

}

function hidePleaseWait() {
	hide('PleaseWait');
}

function showPleaseWait() {
	show('PleaseWait');	
}

function validateKeypress(regExp,event,err) {
	var key; 
	if (window.event) key = window.event.keyCode; else if (event) key = event.which; else return true;
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) return true;
	
	var re = new RegExp(regExp);		
	if (re.exec(String.fromCharCode(key)) == null) {
		return true; 
	} else {
		if (err.length > 0) alert(err);
		return false;		   
	}
}

function enableAdminButton(name) {
	$(name).disabled = false;
	$(name+'AdminButtonDiv').className = 'adminButtonNew';	
}
function disableAdminButton(name) {
	$(name).disabled = true;
	$(name+'AdminButtonDiv').className = 'adminButtonNewDisabled';	
}
function hideAdminButton(name) {
	hide(name+'AdminButtonDiv');
}
function showAdminButton(name) {
	show(name+'AdminButtonDiv');
}

function makeValidString(regExp,s,err) {
	var re = new RegExp(regExp);
	var result = '';
	var gotError = false;
	for (var i=0; i<s.length; i++) {
		if (re.exec(s.charAt(i)) == null) 			
			result += s.charAt(i);	
		else {
			if (!gotError && err.length > 0) alert(err);
			gotError = true;
		}
	}
	return result;
}
				
				
var menu_preloaded_images = new Array();

function menuPreloadImages(theImages) {
	for (var i in theImages) {
		var tmp = new Image();
		tmp.src = theImages[i];
		menu_preloaded_images[menu_preloaded_images.length] = tmp;
	}
}

function plimg(theImages) {
	menuPreloadImages(theImages);
}

function init_sfhovers() {
	if (typeof sfmenus != 'undefined') {
		for(var j=0; j<sfmenus.length; j++) {
			var sfEls = document.getElementById("menu_"+sfmenus[j]).getElementsByTagName("LI");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() { this.className+=" sfhover"; }
				sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); }
			}
		}
	}
}

function enterkeyPressed(e) {
    var key;
    var keychar;
    
    if (window.event)
       key = window.event.keyCode;
    else if (e)
       key = e.which;
    else
       return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();
    
    // control keys
    if ((key==13))
       return true;
            
    return false;
    
}


/*       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19. */


function URLEncode(value) {
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;	
};

function URLDecode(value)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;   
};

function escapeHTML(str) {
	var result = str.replace(/&/g,"&amp;");
	result = result.replace(/</g,"&lt;");
	result = result.replace(/>/g,"&gt;");
	result = result.replace(/"/g,"&quot;");	
	return result;
}