// User Interface JavaScript

var winModalWindow;
var winWidth;
var winHeight;

// Limit the number of selections made on a multiple select list box in HTML
function checkMaxSelected (select, maxSelected) {
  if (!select.storeSelections) {
    select.storeSelections = new Array(select.options.length);
    select.selectedOptions = 0;
  }
  for (var i = 0; i < select.options.length; i++) {
    if (select.options[i].selected && 
        !select.storeSelections[i]) {
      if (select.selectedOptions < maxSelected) {
        select.storeSelections[i] = true;
        select.selectedOptions++;
      }
      else {
        alert('Selection will be discarded as limit of ' + maxSelected + ' is reached.');
        select.options[i].selected = false;
      }
    }
    else if (!select.options[i].selected &&
             select.storeSelections[i]) {
      select.storeSelections[i] = false;
      select.selectedOptions--;
    }
  }
}

// Modalless window
function windowOpener(message) {
	msgWindow=window.open("","displayWindow","menubar=no,toolbar=no,scrollbars=yes,status=no,width=300,height=100")
	msgWindow.document.write("<head><title>Message Window<\/title><\/head>")
	msgWindow.document.write(message);
}

 
function IgnoreEvents(e) {
	return false
}
 
function ShowModalWindow(anUrl) {
	// Firefox
	if(navigator.userAgent.indexOf("Firefox") != -1) {
		winModalWindow = window.open(anUrl, "displayWindow", "width=400,height=200,modal=yes,location=no,resizable=yes,scrollbars=yes,status=no");
	} else if (window.showModalDialog) {
		// window.showModalDialog(anUrl, null, "status=no;dialogWidth=500px;dialogHeight=400px")
		window.showModalDialog(anUrl, null, "width=400,height=200,modal=yes,resizable=yes,scrollbars=yes,status=no")
	} else {
		window.top.captureEvents (Event.CLICK|Event.FOCUS)
		window.top.onclick=IgnoreEvents
		window.top.onfocus=HandleFocus 
		// winModalWindow = window.open(anUrl, "displayWindow", "modal=yes,menubar=no,toolbar=no,scrollbars=yes,status=no,dependent=yes,width=500,height=400,resizable")
		winModalWindow = window.open(anUrl, "displayWindow", "width=400,height=200,modal=yes,menubar=no,toolbar=no,resizable=yes,scrollbars=yes,status=no")
		if (window.focus) {	
			winModalWindow.focus();
		}
	}
}


function ShowSmallModalWindow(anUrl) {
	if (window.showModalDialog) {
		window.showModalDialog(anUrl, null, "status=no;dialogWidth=360px;dialogHeight=250px")
	} else {
		window.top.captureEvents (Event.CLICK|Event.FOCUS)
		window.top.onclick=IgnoreEvents
		window.top.onfocus=HandleFocus 
		winModalWindow = window.open (anUrl,"displayWindow", "menubar=no,toolbar=no,scrollbars=yes,status=no,modal=yes,width=200,height=100")
		winModalWindow.focus()
	}
}


function ShowModallessWindow(anUrl) {
	if (window.showModallessDialog) {
		window.showModallessDialog(anUrl, null, "status=no;dialogWidth=400px;dialogHeight=300px")
	} else {
		winModallessWindow = window.open ("anUrl","displayWindow", "menubar=no,toolbar=no,scrollbars=yes,status=no,dependent=yes,width=200,height=100")
		winModallessWindow.focus()
	}
}


function ShowPrintPreviewWindow(anUrl) {
	if (window.showModalDialog) {
		window.showModalDialog(anUrl, null, "status=no;dialogWidth=800px;dialogHeight=900px")
	} else {
		window.top.captureEvents (Event.CLICK|Event.FOCUS)
		window.top.onclick=IgnoreEvents
		window.top.onfocus=HandleFocus 
		winModalWindow = window.open (anUrl,"displayWindow", "menubar=no,toolbar=no,scrollbars=yes,status=no,dependent=yes,width=200,height=100")
		winModalWindow.focus()
	}
}


function handleFocus() {
	if (winModalWindow) {
		if (!winModalWindow.closed) {
			winModalWindow.focus()
		} else {
			window.top.releaseEvents (Event.CLICK|Event.FOCUS)
			window.top.onclick = ""
		}
	}
	return false
}


function getWindowWidth() {
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winWidth = window.innerWidth;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winWidth = document.body.offsetWidth;
		}
	}
	return winWidth
}


function ClickIE() {
	var message = "";
	if (document.all) {
		(message);
		return false;
	}
}

function clickNS(e) {
	var message = "";
	if (document.layers || (document.getElementById && !document.all)) {
		if (e.which==2 || e.which==3) {
			(message);
			return false;
		}
	}
}

// Disable Right Click
function DisableRightClick() {
	if (document.layers) {
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown=clickNS;
	} else {
		document.onmouseup=clickNS;
		document.oncontextmenu=clickIE;
	} 
}

function IsJsEnabled(jsEnabledPage, jsDisabledPage) {
	if (navigator.javaEnabled()) 
		window.location.href = jsEnabledPage;
	else 
		window.location.href = jsDisabledPage;
}


function DetectBrowser() {
   var ua = navigator.userAgent.toLowerCase(); 

   // browser engine name
   this.isGecko       = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
   this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);

   // browser name
   this.isKonqueror   = (ua.indexOf('konqueror') != -1); 
   this.isSafari      = (ua.indexOf('safari') != - 1);
   this.isOmniweb     = (ua.indexOf('omniweb') != - 1);
   this.isOpera       = (ua.indexOf('opera') != -1); 
   this.isIcab        = (ua.indexOf('icab') != -1); 
   this.isAol         = (ua.indexOf('aol') != -1); 
   this.isIE          = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1) ); 
   this.isMozilla     = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
   this.isFirebird    = (ua.indexOf('firebird/') != -1);
   this.isNS          = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
   
   // spoofing and compatible browsers
   this.isIECompatible = ( (ua.indexOf('msie') != -1) && !this.isIE);
   this.isNSCompatible = ( (ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);
   
   // rendering engine versions
   this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
   this.equivalentMozilla = ( (this.isGecko) ? parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) ) : -1 );
   this.appleWebKitVersion = ( (this.isAppleWebKit) ? parseFloat( ua.substring( ua.indexOf('applewebkit/') + 12) ) : -1 );
   
   // browser version
   this.versionMinor = parseFloat(navigator.appVersion); 
   
   // correct version number
   if (this.isGecko && !this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1 ) );
   }
   else if (this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) );
   }
   else if (this.isIE && this.versionMinor >= 4) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
   }
   else if (this.isKonqueror) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
   }
   else if (this.isSafari) {
      this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('safari/') + 7 ) );
   }
   else if (this.isOmniweb) {
      this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('omniweb/') + 8 ) );
   }
   else if (this.isOpera) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera') + 6 ) );
   }
   else if (this.isIcab) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab') + 5 ) );
   }
   this.versionMajor = parseInt(this.versionMinor); 
   // dom support
   this.isDOM1 = (document.getElementById);
   this.isDOM2Event = (document.addEventListener && document.removeEventListener);
   
   // css compatibility mode
   this.mode = document.compatMode ? document.compatMode : 'BackCompat';

   // platform
   this.isWin    = (ua.indexOf('win') != -1);
   this.isWin32  = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
   this.isMac    = (ua.indexOf('mac') != -1);
   this.isUnix   = (ua.indexOf('unix') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
   this.isLinux  = (ua.indexOf('linux') != -1);
   
   // specific browser shortcuts
   this.isNS4x = (this.isNS && this.versionMajor == 4);
   this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
   this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
   this.isNS4up = (this.isNS && this.versionMinor >= 4);
   this.isNS6x = (this.isNS && this.versionMajor == 6);
   this.isNS6up = (this.isNS && this.versionMajor >= 6);
   this.isNS7x = (this.isNS && this.versionMajor == 7);
   this.isNS7up = (this.isNS && this.versionMajor >= 7);
   
   this.isIE4x = (this.isIE && this.versionMajor == 4);
   this.isIE4up = (this.isIE && this.versionMajor >= 4);
   this.isIE5x = (this.isIE && this.versionMajor == 5);
   this.isIE55 = (this.isIE && this.versionMinor == 5.5);
   this.isIE5up = (this.isIE && this.versionMajor >= 5);
   this.isIE55up = (this.isIE && this.versionMinor >= 5.5);
   this.isIE6x = (this.isIE && this.versionMajor == 6);
   this.isIE6up = (this.isIE && this.versionMajor >= 6);
   this.isIE4xMac = (this.isIE4x && this.isMac);
}


// Correctly handle PNG transparency in Win IE 5.5 or higher.
function fixPNG(myImage) {
    var browser = new DetectBrowser();
	if (this.isIE55up) {
		var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
		var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
		var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
		var imgStyle = "display:inline-block;" + myImage.style.cssText 
		var strNewHTML = "<span " + imgID + imgClass + imgTitle
		strNewHTML += " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";"
		strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		strNewHTML += "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>" 
		myImage.outerHTML = strNewHTML
	}
}


// Relocate Link
function relocateLink() {
	var relocateURL = "/";
	if(parent.frames.length == 0) {
		if(document.images) {
			location.replace(relocateURL);
		} else {
			location = relocateURL;
		}
	}
} 


// Frame Removal - If a page is loaded in a frame, then reload page in an entire window. 
function removeFrame(target) {
	if (window != top) 
		top.location.href = target;
}

function disableTextSelect() {

	function deselectText(e) {return false;}
	function selectText(){return true;}
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		document.onselectstart=new Function ("return false")
	} else { 
		if (window.sidebar) {
			document.onmousedown=deselectText
			document.onclick=selectText
		}
	}
}

function confirmation(msg) {
	var agree = confirm(msg);
	return agree;
}


function time_in() {
 enter=new Date();
}

function time_out() {
 exit=new Date();
 time_dif=(exit.getTime()-enter.getTime())/1000;
 time_dif=Math.round(time_dif);
 alert ("You've only been here for: " + time_dif + " seconds!!")
}


function emailCheck(emailStr) {
	/*
		The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. 
	*/
	var emailPat="/^(.+)@(.+)$/"
	/* 
		The following string represents the pattern for matching all special
		characters.  We don't want to allow special characters in the address.
		These characters include ( ) < > @ , ; : \ " . [ ]    
	*/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

	/*
		The following string represents the range of characters allowed in a 
		username or domainname.  It really states which chars aren't allowed. 
	*/
	var validChars="\[^\\s" + specialChars + "\]"

	/*
		The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. 
	*/
	var quotedUser="(\"[^\"]*\")"

	/*
		The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. 
	*/
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	
	/*
		The following string represents an atom (basically a series of
		non-special characters.) 
	*/
	var atom=validChars + '+'

	/*
		The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.
		Basically, a word is either an atom or quoted string. 
	*/
	var word="(" + atom + "|" + quotedUser + ")"

	/*
		The following pattern describes the structure of the user
	*/
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

	/*
		The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. 
	*/
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	/*
		Start to validate email address - Begin with the coarse pattern to 
		simply break up user@domain into different pieces that are easy to 
		analyze. 
	*/
	var matchArray=emailStr.match(emailPat)
	
	if (matchArray==null) {
  		// Too many or few @'s or something similiar. 
		alert("Incorrect email address");
		return false;
	}

	var user=matchArray[1]
	var domain=matchArray[2]

	// Verify "user" portion 
	if (user.match(userPat)==null) {
    	// user is not valid
    	alert("The username doesn't seem to be valid.");
    	return false;
	}

	// If the e-mail address is at an IP address (as opposed to a symbolic
	// host name) make sure the IP address is valid. 
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// This is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("The domain name doesn't seem to be valid.");
		return false;
	}

	// Verify the domain suffix to make sure that it ends in a three-letter
	// word (like com, edu, gov) or a two-letter word representing country
	// (ca, uk, nl), and that there's a hostname preceding the domain or 
	// country.  Break up the domain to get a count of how many atoms it 
	// consists of.
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
   		alert("The address must end in a three-letter domain, or two letter country.");
	   	return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		var errStr="This address is missing a hostname!"
		alert(errStr);
		return false
	}
	// Finally a valid email address
	alert('Email is valid');
	return true;
}


function confirmRequest() {
	var agree=confirm("Are you sure you wish to continue?");
	if (agree)
		return true;
	else
		return false;
}

function confirmLogout() {
	var agree=confirm("Are you sure you wish to logout?");
	if (agree)
		return true;
	else
		return false;
}

function isEmpty(textField) {
	if ((textField.length==0) ||(textField==null)) {
		return true;
	} else { 
		return false; 
	}
}

function isCurrency(str) {
	var currRegExp = new RegExp(/^\d+(?:\.\d{0,2})?$/);
	return currRegExp.test(str);
}

function isNonZeroDigit(str) {
	var numericRegExp = new RegExp(/^[1-9]\d*$/);
	return numericRegExp.test(str);
}

function isNumeric(strString, blnPure) {
	//  Check for valid numeric strings
	var strChar;
	var blnResult = true;
	var strValidChars;
	if (blnPure) {
		strValidChars = "0123456789";
	} else {
		strValidChars = "0123456789-.";
	}
	if (strString.length == 0) return false;
	// Test strString consists of valid characters listed above\
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}
	
function convertToNumeric(strString) {
	var strChar;
	var strResult = "";
	var strValidChars = "0123456789";
	if (strString.length == 0) return strResult;
	for (i = 0; i < strString.length; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) >= 0) {
			strResult = strResult + strChar;
		}
	}
	return strResult;
}

function formatNorthAmericaPhone(num) { 
	var _return =  false;
	var checking = true;
	if (checking) {
		if ((!IsNumeric(num, true)) && (num.length > 0))  {
			// Convert all to characters to numeric
			num = convertToNumeric(num);
		}
	}
	/* formating phone number here */ 
	if ((num.length == 11) && (num.substring(0,2) == 1)) {
		_return="1(";
		var ini = num.substring(1,4);
		_return+=ini+")";
		var st = num.substring(4,7);
		_return+=st+"-";
		var end = num.substring(7,11);
		_return+=end;
	} else if (num.length == 10) { 
		if (country == 3) {
			_return="(";
			var ini = num.substring(0,2);
			_return+=ini+")";
			var st = num.substring(2,6);
			_return+=st+"-";
			var end = num.substring(6,10);
			_return+=end;
		} else {
			_return="(";
			var ini = num.substring(0,3);
			_return+=ini+")";
			var st = num.substring(3,6);
			_return+=st+"-";
			var end = num.substring(6,10);
			_return+=end;
		}
	} else {
		/* If user did not enter 10 digit phone number then simply print whatever user entered */ 
		_return = num;
	}
	return _return;
}

/* Netscape functions */
function fetchURL(url) {
	if ( (location.host == '' && url.indexOf(location.protocol) == -1)  ||  url.indexOf(location.host) == -1) {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalConnect");
	}
	var dest = new java.net.URL(url);
	var dis = new java.io.DataInputStream(dest.openStream());
	var res = "";
	while ((line = dis.readLine()) != null) {
		res += line;
		res += java.lang.System.getProperty("line.separator");
	}
	dis.close();
	return res;
}

/* Netscape function */ 
function mailPage(address) {
	var body;
	if (document.documentElement && document.all) {
		body = document.documentElement.outerHTML;
	} else if (document.all) {
		body = document.body.innerHTML;
	} else if (document.getElementById) {
		body = '<HTML>' + document.documentElement.innerHTML + '<\/HTML>';
	} else if (document.layers) {
		body = fetchURL(location.href);
	}
	var url = 'mailto:';
	url += address ? address : '';
	url += body ? '?body=' + escape(body) : '';
	location.href = url;
}

function getStyleObject(objectId) {
	if (document.getElementById && document.getElementById(objectId)) {
		return document.getElementById(objectId).style;
	} else if (document.all && document.all(objectId)) {
		return document.all(objectId).style;
	} else {
		return false;
	}
}

function changeDiv(d, c) {
	var the_style = getStyleObject(d);
	if (the_style != false) {
		the_style.display = c;
	}
}

function showPanelDiv(item) {
	if (document.getElementById && document.getElementById(item)) {
		document.getElementById(item).style.display = "block";
	}
}

function hidePanelDiv(item) {
	if (document.getElementById && document.getElementById(item)) {
		document.getElementById(item).style.display = "none";
	}
}

function changeOverflow(item, ostyle){
	if (document.getElementById && document.getElementById(item)) {
		document.getElementById(item).style.overflow = ostyle;
	}
}
