// Main JScript file - General functions
// Copyright © 2003, Nexus Open Software Ltd. All rights reserved.

/*
when using anonymous authentication, we need to force the browser
to redirect to the login page, just before the session expires.
resetTimer() is in /default.asp when server is set to anonymous authentication
*/
function resetSession() {
	try {
		top.resetTimer((top.SessionTimeout * 60) * 1000); // 19 minutes? (19 * 60) * 1000 '1140000
	}
	catch(e) {}
}
resetSession();

function logOut() {
	try {
		top.frames[0].saveSettings(2);
	}
	catch(e) {}
	//top.location.href='../logout.asp';
}
function logOutQuit() {
	try {
		top.frames[0].saveSettings(1);
	}
	catch(e) {}
}
// Retrieves a value from the hidden settings frame, myDefaultValue is returned if the setting does not exist
function getMySetting(myName, myDefaultValue, save) {
	try {
		if (findTopFrame('MiCoreRoot')) {
			var myValue = eval('top.frames[\'MiCoreRoot\'].frames[\'hiddenSettings\'].document.frmSettings.'+myName+'1.value');
		}
		else {
			var myValue = eval('top.frames[\'hiddenSettings\'].document.frmSettings.'+myName+'1.value');
		}
		return myValue;
	}
	catch(e) {
		createMySetting(myName, myDefaultValue, save)
		return myDefaultValue;
	}
}
// Sets a value in the hidden settings frame, if the setting does not exist, it is created
function setMySetting(myName, myValue, save) {
	try {
		if (findTopFrame('MiCoreRoot')) {
			var mySetting = 'top.frames[\'MiCoreRoot\'].frames[\'hiddenSettings\'].document.frmSettings.'+myName+'1';
		}
		else {
			var mySetting = 'top.frames[\'hiddenSettings\'].document.frmSettings.'+myName+'1';
		}
		if(eval(mySetting).name) {
			eval(mySetting).value = myValue;
		}
	}
	catch(e) {
		//alert('failed to save setting');
		createMySetting(myName, myValue, save);
	}
}
// Creates a setting in the hidden settings frame
function createMySetting(myName, myValue, save) {
	ie=document.all?1:0; 
	ns=document.getElementById&&!document.all?1:0 

	// saved into Session("browser")
	var broswer;
	if(ie) {
		try {
			if (findTopFrame('MiCoreRoot')) {
				top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'0<input type=\"text\" name=\"'+myName+'0\" value=\"0"><br>');
				top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'1<input type=\"text\" name=\"'+myName+'1\" value=\"'+myValue+'\"><br>');
				top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'2<input type=\"text\" name=\"'+myName+'2\" value=\"'+save+'\"><br>');
			}
			else {
				top.frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'0<input type=\"text\" name=\"'+myName+'0\" value=\"0"><br>');
				top.frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'1<input type=\"text\" name=\"'+myName+'1\" value=\"'+myValue+'\"><br>');
				top.frames['hiddenSettings'].document.frmSettings.insertAdjacentHTML('BeforeEnd',myName+'2<input type=\"text\" name=\"'+myName+'2\" value=\"'+save+'\"><br>');
			}		
		}
		catch(e) {}
	}
	else {
		//default to netscape, most compatiable
		var input1 = document.createElement("INPUT");
		var text1  = document.createTextNode(myName+"0");
		input1.setAttribute("type", "text");
		input1.setAttribute("name", myName+"0");
		input1.setAttribute("value", "0");

		var input2 = document.createElement("INPUT");
		var text2  = document.createTextNode(myName+"1");
		input2.setAttribute("type", "text");
		input2.setAttribute("name", myName+"1");
		input2.setAttribute("value", myValue);

		var input3 = document.createElement("INPUT");
		var text3  = document.createTextNode(myName+"2");
		input3.setAttribute("type", "text");
		input3.setAttribute("name", myName+"2");
		input3.setAttribute("value", save);
	    
		if (findTopFrame('MiCoreRoot')) {
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(text1);
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(input1);
			var br = document.createElement("BR")
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(br);
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(text2);
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(input2);
			var br = document.createElement("BR")
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(br);
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(text3);
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(input3);
			var br = document.createElement("BR")
			top.frames['MiCoreRoot'].frames['hiddenSettings'].document.frmSettings.appendChild(br);
		}
		else {
			top.frames['hiddenSettings'].document.frmSettings.appendChild(text1);
			top.frames['hiddenSettings'].document.frmSettings.appendChild(input1);
			var br = document.createElement("BR")
			top.frames['hiddenSettings'].document.frmSettings.appendChild(br);
			top.frames['hiddenSettings'].document.frmSettings.appendChild(text2);
			top.frames['hiddenSettings'].document.frmSettings.appendChild(input2);
			var br = document.createElement("BR")
			top.frames['hiddenSettings'].document.frmSettings.appendChild(br);
			top.frames['hiddenSettings'].document.frmSettings.appendChild(text3);
			top.frames['hiddenSettings'].document.frmSettings.appendChild(input3);
			var br = document.createElement("BR")
			top.frames['hiddenSettings'].document.frmSettings.appendChild(br);
		}
	}
}
function focusFirst() {
	//focus the first text input
	//var els = document.forms[0].elements;
	var els=document.getElementsByTagName('input');
	try {
		for(var i=0;els.length-1;i++) {
			if(els[i].type == 'text') {
				if(!els[i].disabled && !els[i].readOnly) {
					els[i].focus()
					document.execCommand("selectAll",false);
					break;
				}
			}
		}	
	}
	catch(e) {}
}
//refresh the frame where the focus of the cursor last was..
function F5Refresh ()
{
if(document.all) {
	if (document.onkeydown && window.event.keyCode == 116) {
		//116 = F5
		if (116 == event.keyCode)
		{
			event.keyCode=0;
			history.go(0);
		}
		return false;
	}
}
}
if (document.layers)
document.captureEvents(Event.KEYDOWN);
document.onkeydown=F5Refresh;

// Over class name functions
function Over(That){
	That.className=That.className + 'Over';
}
function Out(That){
	if (That.className.substr(That.className.length-4,4)=='Over'){
		That.className=That.className.substr(0,That.className.length-4);
	}
}

// Navigation Functions
function MainGo(Page){
	parent.frames['main'].location.href=Page;
}
function FakeGo(Page, Path, TargetFrame){
	if (TargetFrame == '_blank')	{
		window.open(Page);
	}
	else if (TargetFrame == 'content') {
		if (findTopFrame('MiCoreRoot')) {
			top.frames['MiCoreRoot'].frames['content'].location.href=Page;
		}
		else {
			top.frames['content'].location.href=Page;
		}
	}
	else if (TargetFrame == 'main') {
		if (findTopFrame('MiCoreRoot')) {
			top.frames['MiCoreRoot'].frames['content'].frames['main'].location.href=Page;
		}
		else {
			top.frames['content'].frames['main'].location.href=Page;
		}
	}
	else {
		if (findTopFrame('MiCoreRoot')) {
			top.frames['MiCoreRoot'].frames['content'].location.href=Path+'frset_fake.asp?theurl='+Page;
		}
		else {
			top.frames['content'].location.href=Path+'frset_fake.asp?theurl='+Page;
		}
	}
}
function TopGo(Page){
	top.window.location.href=Page;
}
function NewWindow(Page){
	window.open(Page);
}
function findTopFrame(thename) {
// Checks if a frame exists - very handy
    for (var i=0;i<top.frames.length;i++) {
         if (top.frames[i].name == thename)
             return true;
    }
    return false;
}
function findFrame(thename) {
// Checks if a frame exists - very handy
    for (var i=0;i<parent.frames.length;i++) {
         if (parent.frames[i].name == thename)
             return true;
    }
    return false;
}
function findRootFrame(thename) {
// Checks if a frame exists - very handy
    for (var i=0;i<top.frames[0].frames[2].frames.length;i++) {
		try {
         if (top.frames[0].frames[2].frames[i].name == thename)
             return true;
        }
        catch(e) {
        	return false;
        }
    }
    return false;
}
function findTheFrame(thename) {
// Checks if a frame exists - very handy
    for (var i=0;i<top.frames[2].frames.length;i++) {
    	try {
         if (top.frames[2].frames[i].name == thename)
             return true;
        }
        catch(e) {
        	return false;
        }
    }
    return false;
}
function toolExpanded(cname) {
//This function toggles a setting, expanded or collapsed.

	if (getMySetting(cname,'collapsed', true) == 'expanded') {
		setMySetting(cname, 'collapsed', true);
	}
    else {
    	setMySetting(cname, 'expanded', true); 
    }
}
function image_big(width, height, id, path) {
	width = parseInt(width);
	height = parseInt(height);
	if (width > 800) {
		width = 800;
	}
	if (height > 600) {
		height = 600;
	}		
	//var centerWidth=(screen.width/2)-(width/2);
	//var centerHeight=(screen.height/2)-(height/2);
	//var sWindow = 'height=' + (height+30) + ',width=' + (width+35) + 'px,scrollbars,status=no,menubar=no,resizable=yes,top=' + centerHeight + ',left=' + centerWidth
	var sURL = path + 'common/image/image_big.asp?I=' + id
	compatModalDialog(sURL, width+40, height+40);
	//var sReturn = window.open(sURL,null,sWindow);
}
function deadLink() {
	alert('This link cannot be accessed from the Internet');
}
function textCounter(field, maxlimit) 
{
    if (field.value.length > maxlimit) {
    field.value = field.value.substring(0, maxlimit);
    alert("Exceeded maximum number of characters"); 
    }
}

function LTrim(ValueToTrim) {
	ValueToTrim = ValueToTrim.toString()
	var WhiteSpace=new String(" \t\r\n");
	var i=0;
	while(WhiteSpace.indexOf(ValueToTrim.charAt(i))>-1) {
	i++;
	}
		return ValueToTrim.substring(i);
}

function RTrim(ValueToTrim) {
	ValueToTrim =ValueToTrim.toString()
	var WhiteSpace=new String(" \t\r\n");
	var i=ValueToTrim.length-1;
    while(WhiteSpace.indexOf(ValueToTrim.charAt(i))>-1) {
		i--;
	}
	return ValueToTrim.substring(0,i+1);
}

function Trim(ValueToTrim) {
	return  LTrim(RTrim(ValueToTrim))
}

function sDate(thedate) {
	var sMonth = thedate.getMonth();
	switch (sMonth) {
	case 0:
		sMonth = ' January ';
		break;
	case 1:
		sMonth = ' February ';
		break;
	case 2:
		sMonth = ' March ';
		break;
	case 3:
		sMonth = ' April ';
		break;
	case 4:
		sMonth = ' May ';
		break;
	case 5:
		sMonth = ' June ';
		break;
	case 6:
		sMonth = ' July ';
		break;
	case 7:
		sMonth = ' August ';
		break;
	case 8:
		sMonth = ' September ';
		break;
	case 9:
		sMonth = ' October ';
		break;
	case 10:
		sMonth = ' November ';
		break;
	case 11:
		sMonth = ' December ';
		break;
	}
	return thedate.getDate() + sMonth + thedate.getFullYear();
}

function sDateTime(thedate) {
	var sMonth = thedate.getMonth();
	switch (sMonth) {
	case 0:
		sMonth = ' Jan ';
		break;
	case 1:
		sMonth = ' Feb ';
		break;
	case 2:
		sMonth = ' Mar ';
		break;
	case 3:
		sMonth = ' Apr ';
		break;
	case 4:
		sMonth = ' May ';
		break;
	case 5:
		sMonth = ' Jun ';
		break;
	case 6:
		sMonth = ' Jul ';
		break;
	case 7:
		sMonth = ' Aug ';
		break;
	case 8:
		sMonth = ' Sep ';
		break;
	case 9:
		sMonth = ' Oct ';
		break;
	case 10:
		sMonth = ' Nov ';
		break;
	case 11:
		sMonth = ' Dec ';
		break;
	}
	return thedate.getDate() + sMonth + thedate.getFullYear() + ' ' + thedate.toTimeString();
}

function determineMonthIndex(sAbbrevMonthName) {
	var i;
	var sMonthNames=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov", "Dec");
	for (i=0;i<12;i++){
		if (sAbbrevMonthName == sMonthNames[i]) {
			return (i);
		}
	}
	return (-1);
}

function isDate(sDate) {
	var asDateBits;
	var bSuccess =false;
	asDateBits = sDate.split(" ");
	if (asDateBits.length==3) {
		iMonth = determineMonthIndex(asDateBits[1]);
		if (iMonth > -1) {
			try {
				//If the date to be converted is invalid, it will generate an exception and trigger the catch
				var testDate = new Date(asDateBits[2], iMonth, asDateBits[0]);
			} catch (e) {return false}
			bSuccess = true;		
		}
	}
	return (bSuccess);
}


function isTime(sTime) {
	//Returns true if the time is of format nn:nn using 24 hour clock
	//Does not allow single digit hours
	var asTimeBits;
	var bSuccess = false;
	asTimeBits = sTime.split(":");
	if (asTimeBits.length==2) {
		if (!(isNaN(asTimeBits[0]) || isNaN(asTimeBits[1]) || asTimeBits[0] == "" || asTimeBits[1] == "")) {
			if ((asTimeBits[0].length == 2) && (asTimeBits[0].valueOf() >= 0) && (asTimeBits[0].valueOf() < 24)) {
				if ((asTimeBits[1].length == 2) && (asTimeBits[1].valueOf() >=0) && (asTimeBits[1].valueOf() <= 59)) {
					bSuccess = true;
				}
			}
		}
	}
	return (bSuccess);
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}


function compatModalDialog(url, width, height) {
	if(getInternetExplorerVersion() != -1) {
		window.showModalDialog(url,window,
			"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Raised;center:1;help:0;resizable:1;maximize:1;status:0");
	}
	else {
		var left = screen.availWidth/2 - width/2;
		var top = screen.availHeight/2 - height/2;
		document.activeModalWin = window.open(url, "", "status=no,width="+width+",height="+height+",left="+left+",top="+top);
		window.onfocus = function(){if (document.activeModalWin.closed == false){document.activeModalWin.focus();};};
	}

}

/*function : format_number()  
version: 1.0.0  
This function formats a numeric value passed in to it with specified number of  
decimal values. numeric value will not be rounded.  
pnumber : numeric value to be formatted.  
decimals : number of decimal points desired.  

Author: Buddhike de Silva  
Date: 21-Nov-2002 11:16 AM*/  

/*  
revision: 1.1.0  
Author: M. Cassim Farook  
Date: 21-Nov-2002 10:16 PM  
Notes: No offense buddhike...but i had to rewrite the code  
works for ADT (any dam thing)  
usage: x = format_number(123.999, 2)  
*/  

/*  
revision: 1.2.0  
Authors: Buddhike de Silva  
Date: 22-Nov-2002 12:07 PM  
Notes: Optimized for best performence.  
usage: x = format_number(123.999, 2)  
*/  

/* 
 * Revision: 1.3 
 * Author: Mike Robb (JS-X.com) 
 * Date: May 26, 2003 
 * Notes:  Changed to deal with negative numbers. 
 *         Fixed length of final answer. 
 *         Work-around for javascript internal math problem with rounding negative numbers. 
 */ 

/*
 * Revision 1.4
 * Author: LeAnn Roberts
 * Date: September, 2003
 * Note: Modified the if logic: Math.pow()
 */
 
/*
 * Revision 1.4.1
 * Author: Jon Barlow
 * Date: Jan, 2004
 * Note: Very small fix to deal with empty value before/after decimal place 
		 (12. returned 12.NaN, now returns 12.00 and .5 returned NaN.50 now returns 0.50).
 		 Change isNaN and Empty pnumber return values to '0.00'
 */
 
function format_number(pnumber,decimals) {  
	if (isNaN(pnumber)) { return '0.00'};  
	if (pnumber=='') { return '0.00'};  
	
	var IsNegative=(parseInt(pnumber)<0); 
	if(IsNegative)pnumber=-pnumber; 
	
	var snum = new String(pnumber);
	var sec = snum.split('.');  
	var whole = parseInt(sec[0]); 
	if (isNaN(whole)) { whole = '0'};  
	var result = ''; 
	
	if(sec.length > 1){  
	if(sec[1].length == 1) {
    	var dec = new String(sec[1]+'0'); 
	    dec = parseInt(dec)/Math.pow(10,parseInt(dec.length-decimals-1)); 
		Math.round(dec); 
		dec = parseInt(dec)/10;     	 
    }
	else {
		var dec = new String(sec[1]);
	}

	
	if(IsNegative) 
	{ 
	  var x = 0-dec; 
	      x = Math.round(x); 
	  dec = - x; 
	} 
	else 
	{ 
		//window.status = 'dec: '+decimals;
	      if(dec.length > decimals) {
			alert('this is where it all goes wrong');
	      	dec = dec.substr(0,decimals);
	      }
	} 
	
	/* 
	 * If the number was rounded up from 9 to 10, and it was for 1 'decimal' 
	 * then we need to add 1 to the 'whole' and set the dec to 0. 
	 */ 
	if(dec==Math.pow(10, parseInt(decimals)))
	{ 
	  whole+=1; 
	  dec="0"; 
	} 
	

	    dec = String(whole) + "." + String(dec);  
	    var dot = dec.indexOf('.');  
	    if(dot == -1){  
	      dec += '.';  
	      dot = dec.indexOf('.');  
	    } 
	var l=parseInt(dot)+parseInt(decimals); 
	    while(dec.length <= l) { dec += '0'; }  
	    result = dec;  
	  } else{  
	    var dot;  
	    var dec = new String(whole);  
	    dec += '.';  
	    dot = dec.indexOf('.');  
	var l=parseInt(dot)+parseInt(decimals); 
	    while(dec.length <= l) { dec += '0'; }  
	    result = dec;  
	  }  
	  if(IsNegative)result="-"+result; 
	  return result;  
}

function expandItClass(el,eid,eheight,esource) {
    whichEl = document.getElementById(el + 'Child');
    if (cssjs('check',whichEl,'dashCollapsed')) {
		if(eid) {
			var whichFra = document.getElementById(eid);
			if(whichFra.src != esource) {
				//whichFra.src = esource;
				whichFra.contentWindow.document.location.replace(esource);
			}
			whichFra.height = eheight;
		}
		cssjs('swap',whichEl,'dashCollapsed','dashExpanded');
		//new Effect.SlideDown(whichEl, {duration:1});
    }
    else {
    	//new Effect.SlideUp(whichEl, {duration:1});
		cssjs('swap',whichEl,'dashExpanded','dashCollapsed');     
    }
}

function expandItClassNoFrame(el) {
    whichEl = document.getElementById(el + 'Child');
    if (cssjs('check',whichEl,'dashCollapsed')) {
		cssjs('swap',whichEl,'dashCollapsed','dashExpanded');
    }
    else {
		cssjs('swap',whichEl,'dashExpanded','dashCollapsed');     
    }
}

function cssjs(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!cssjs('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

function checkForSpaces(myText) {
	var temp = "";
	myText = '' + myText;
	splitstring = myText.split(" ");
	
	for(i = 0; i < splitstring.length; i++)
		temp += splitstring[i];
		
	if (temp.length < 1) {
		// Textbox only has spaces.
		return false;
	}
	else
	{
		return true;
	}	
}


function addEvent(elm, evType, fn, useCapture) {
    // cross-browser event handling for IE5+, NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener) {
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } 
    else if (elm.attachEvent) {
      var r = elm.attachEvent('on' + evType, fn);
      return r;
    } 
    else {
      elm['on' + evType] = fn;
    }
}

function replaceMe(myString,withChar) {
	// used to replace whitespaces, with 'withChar'
	// e.g. replaceMe('1 2 3 4 5 6 7 8 9 10', ',')
	// returns 1,2,3,4,5,6,7,8,9,10
		
	var pattern = /\s/g;
	var newString = myString.replace(pattern,withChar);
	return newString;
}
function doit(form) {
	form.keywords.value = replaceMe(form.keys.value, ',');
	form.submit();
}
function entsub2(myform) {
	if (window.event && window.event.keyCode == 13)
		doit(myform);
	else
		return true;
}

//  © Macromedia Functions
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  resetSession();
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
    pop1 = window.open(theURL,winName,features);
}
function MM_2openBrWindow(theURL,winName,features,width, height) { //v2.0
	s_top = (screen.width/2)-width/2;
	s_left =(screen.height/2)-height/2;
	sbits = ',top='+s_top+',left='+s_left;
	xName = window.open(theURL,winName,features+sbits);
	if (window.focus) {xName.focus()}
}
function PopupConfirmMsg(msg) { //v1.0
  document.MM_returnValue = confirm(msg);
}