// For Netscape, capture any click events

var eventNN;
if (BrowserIsNN()) {
    captureEvents(Event.MOUSEDOWN);
    window.onmousedown = SaveEvent;
}
function SaveEvent(e) {eventNN=e;}


// Returns a string of the number of characters in length
// SUPERCEDED BY PROTOTYPE
function MakeString(sChar, iNumber) {
    return sChar.times(iNumber)
}

function OpenSettingsWindow(sFilename) {

    // We specify the location after creating the window otherwise the focus
    // will not change from the caller

    var wWindow = window.open("","wSettingsWindow",SetLocation('50%','60%') + ",scrollbars=no,resizable=no,status=yes");
    wWindow.location = sFilename;
    wWindow.focus();
    return false;
}

//
// Gets saved position of window from cookies
// ensures a minimum size of 50x100
//
function GetWindowPosition(sWindowName) {

	var sHeight=GetCookie(sWindowName + "_Height");
	var sWidth=GetCookie(sWindowName + "_Width");
	var sTop=GetCookie(sWindowName + "_Top");
	var sLeft=GetCookie(sWindowName + "_Left");

	if ((sHeight > top.screen.availHeight) || (sHeight < 50)) sHeight = top.screen.availHeight/2;
	if ((sWidth > top.screen.availWidth) || (sWidth < 100)) sWidth = top.screen.availWidth/2;
	if ((sTop > top.screen.availWidth) || (sTop < 1)) sTop = 10;
	if ((sLeft > top.screen.availHeight) || (sLeft < 1)) sLeft = 10;
	return "width=" + sWidth + ",height=" + sHeight + ",top=" + sTop + ",screenY=" + sTop + ",left=" + sLeft + ",screenX=" + sLeft;

}

//
// Saves the position of the window into cookies
//
function SaveWindowPosition(sWindowName) {
var dYearOn = new Date();
var sExpires;

    var sHeight = "";
    var sWidth = "";
    var sTop = "";
    var sLeft = "";
	if (!BrowserIsNN()) {
		sHeight = top.window.document.body.clientHeight;
		sWidth = top.window.document.body.clientWidth;
		sTop = top.window.screenTop - 23;
		sLeft = top.window.screenLeft - 4;
	}

	dYearOn.setFullYear(dYearOn.getFullYear() + 1);
	sExpires = "; expires=" + dYearOn.toGMTString();

	document.cookie = sWindowName + "_Height=" + sHeight + sExpires;
	document.cookie = sWindowName + "_Width=" + sWidth + sExpires;
	document.cookie = sWindowName + "_Top=" + sTop + sExpires;
	document.cookie = sWindowName + "_Left=" + sLeft + sExpires;
}


// Create a clock inside the box specified

function CreateClock(txtBox) {

// Get the current time and split it into its HH:MM:SS	

var dToday = new Date();
var iHours = dToday.getHours()
var iMins = dToday.getMinutes();
var iSecs = dToday.getSeconds();
var sAmPm = (iHours >= 12)?"PM":"AM";


    // Format the numbers correctly for 12 hour clock

    if (iHours > 12) iHours -= 12;
    if (iHours == 0) iHours = 12;
    if (iMins < 10) iMins = "0" + iMins;
    if (iSecs < 10) iSecs = "0" + iSecs;
    

    // Output the time string

    txtBox.value = iHours + ':' + iMins + ':' + iSecs + ' ' + sAmPm;


    // Create a timer to call us back in a second

    setTimeout("CreateClock()", 1000);
}

// Returns true if browser is Internet Explorer

function BrowserIsIE() {
    return (navigator.appName.indexOf("Microsoft") != -1);
}

// Returns true if browser is Netscape Navigator

function BrowserIsNN() {
    return (navigator.appName.indexOf("Netscape") != -1);
}    

// Name of the caller function

function CallerName(objFunction){
var sName = objFunction.toString().match(/function (\w*)/)[1];

    // Check that we found a name

    if ((sName==null) || (sName.length==0)) return "";
    return sName.toLowerCase;
}


// Image changer

function ChangeImage(sName, imgSource){

    // Check to see if there are any images loaded

    if(!document.images) return;

    // Change the source of the associated IMG element

    document.images[sName].src = imgSource.src;
}


// Another Image changer

function ChangeThisImage(objImage, imgSource){

var sEvent = event.type.toString().toLowerCase();

    // Check to see if there are any images loaded

    if(!document.images) return;

    // Change the source of the associated IMG element

    objImage.src = imgSource.src;

    // Set status text to the ALT value of the image depending
    // on where we've been called from

    if (sEvent == 'mouseover')
	    {
        window.status = objImage.alt;
		event.cancelBubble=true;
		}

    else if (sEvent == 'mouseout')
	    {
        window.status = '';
		event.cancelBubble=true;
		}
		
	return true;
}

// Finds the given object based on its name

function findObj(n, d) {
var p,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 (var i=0; !x && i<d.forms.length; i++)
        x=d.forms[i][n];

    for(var i=0; !x && d.layers && i<d.layers.length; i++)
        x=findObj(n,d.layers[i].document); 

    return x;
}



// Sets the visibility of th objects passed
// e.g. onMouseOut="ShowHideLayers('MainMenu','','hide','HomeLinks','','show')"

function ShowHideLayers() {

var p,v,obj,args=showHideLayers.arguments;

    for (var i=0; i<(args.length-2); i+=3)

        if ((obj=findObj(args[i]))!=null) 
            { 
            v=args[i+2];
            if (obj.style) 
                { 
                obj=obj.style; 
                v=(v=='show')?'visible':(v='hide')?'hidden':v; 
                }
            obj.visibility=v; 
            }
}
// Functions to position an element (or group if DIV type)
// dynamically based on the current scroll position - often used 
// to position a set of buttons as the user scrolls the page
// e.g. on a timer 
//   IE4=(document.all)?1:0
//   NN4=(document.layers)?1:0
//   if (IE4)
//       setInterval('KeepItInIE("BgNavBar",80,18)',1)
//   if (NN4)
//       setInterval('KeepItInNN("BgNavBar",80,18)',1)

function KeepItInIE(theName,theWantTop,theWantLeft) {

	var theRealTop=parseInt(document.body.scrollTop)
	document.all[theName].style.top=theWantTop+theRealTop
	var theRealLeft=parseInt(document.body.scrollLeft)
	document.all[theName].style.left=theWantLeft+theRealLeft
}

function KeepItInNN(theName,theWantX,theWantY) {

	var theRealLay=document.layers[theName]
	var theBadX=self.pageYOffset
	var theBadY=self.pageXOffset
	var theRealX=theBadX+theWantX
	var theRealY=theBadY+theWantY
	theRealLay.moveTo(theRealY,theRealX)
}

//
// Retrieves the given cookie value
//
function GetCookie(sName) {
		
var sReturn = "";
var aAllCookies = document.cookie.split("; ");
var iPos = 0;

    while ((iPos < aAllCookies.length) && (sReturn == ""))
        if (aAllCookies[iPos++].split("=")[0] == sName)
            sReturn = unescape(aAllCookies[iPos-1].split("=")[1]);

	return sReturn;
}

//
// Returns a string which contains window.open paramters
// so the window will appear centered according to the supplied
// height and width
//
function SetLocation(iWidth, iHeight, iPreferredWidth, iPreferredHeight) {

    // Set the width and height to the preferred values if they are in range

    if (iPreferredWidth>0 && iPreferredWidth<screen.width) iWidth=iPreferredWidth;
    if (iPreferredHeight >0 && iPreferredHeight<screen.height) iHeight=iPreferredHeight;

    // Convert the width if it is a percentage

    if (isNaN(iWidth)) {
        if (iWidth.indexOf("%")>0) {
            iWidth = iWidth.substring(0,iWidth.indexOf("%"));
            iWidth = screen.width * iWidth / 100;

	        // Check for multiple screens
	        if (screen.width>(screen.height*2)) iWidth=iWidth/2;
        }
    }

    // Convert the height if it is a percentage

    if (isNaN(iHeight)) {
        if (iHeight.indexOf("%")>0) {
            iHeight = iHeight.substring(0,iHeight.indexOf("%"));
            iHeight = screen.height * iHeight / 100;

	        // Check for multiple screens
	        if (screen.height>(screen.width*2)) iHeight=iHeight/2;
        }
    }
    return "height=" + iHeight +
			",width=" + iWidth + 
			",screenX="+(screen.width-iWidth)/2+
			",left="+(screen.width-iWidth)/2+
			",screenY="+(screen.height-iHeight)/2+
			",top="+(screen.height-iHeight)/2;
}

function ClearForm() {
    for (var iForm=0; iForm<document.forms.length; iForm++) {
        for (var iField=0; iField<document.forms[iForm].elements.length; iField++) {
            var objElement = document.forms[iForm].elements[iField];
            if ((objElement.type=="text") || (objElement.type=="textarea"))
                objElement.value = "";
        }
    }
}

// function to get querystring values
// SUPERCEDED BY PROTOTYPE
function QueryString(sName,objDocument) {
var sReturn = "";
    objDocument=objDocument||document;
    if (objDocument.location.search != "") {
        sReturn=objDocument.location.search.toQueryParams()[sName]
        if (typeof(sReturn)=="undefined") sReturn="";
    }
    return sReturn;
}

//
// This function is the call back for forms to populate
// an input box with terms selected from the terms pop-up
//
function ReturnTerms(sValue) {

	if (msInputBoxId && sValue) {
	    window.focus();
	    var objInput = document.getElementById(msInputBoxId);
	    if (objInput && sValue.length>0) {

            // Strip off the leading quote
            sValue = sValue.replace(/\|\$\|/g,",");
            if (sValue.charAt(0) == "'")
                sValue=sValue.substr(1);

            // Strip of trailing quote
            if (sValue.charAt(sValue.length -1) == "'")
                sValue=sValue.substr(0, sValue.length - 1);

            if (objInput.type.toLowerCase() == 'textarea') {
                // swap ',' for cr lf seperators
                sValue = sValue.replace(/\'\,\'/g,"\r\n");
                // add to end of existing value
                if (objInput.value != "")
                    sValue = objInput.value + "\r\n" + sValue
                            objInput.value = sValue;
                }

            else if (objInput.type.toLowerCase() == 'select-multiple') {
                // select the values passed back
                sValue = sValue.replace(/\'\,\'/g,",");
                var asVals = sValue.split(',');
                for (var iOption=0; iOption<objInput.length; iOption++) {
                    objInput.options[iOption].selected = false;
                    }
                for (var iOption=0; iOption<objInput.length; iOption++) {
                    for (var iCnt=0; iCnt<asVals.length; iCnt++) {
                        if (asVals[iCnt].toLowerCase() == objInput.options[iOption].value.toLowerCase()) {
                            objInput.options[iOption].selected = true;
                            break;
                            }
                        }
                    }
                }

            else if (objInput.type.toLowerCase() == 'select-one') {
                // select the values passed back
                objInput.value='';
                for (var iOption=0; iOption<objInput.length; iOption++) {
                    if (sValue.toLowerCase() == objInput.options[iOption].value.toLowerCase()) {
                        objInput.options[iOption].selected = true;
                        break;
                        }
                    }
                }
            else {
                // swap ',' for , seperators
                sValue = sValue.replace(/\'\,\'/g,",");
                objInput.value = sValue;
            }
        }
    }
}

var msInputBoxId;
function OpenFieldInfoWindow(sUrl, sInputBoxId) {
    var wWindow = window.open("","wFieldInfoWindow",SetLocation('50%','60%') + ",scrollbars=no,resizable=no,status=no");
    wWindow.location = sUrl + "&InputBoxId=" + sInputBoxId;
    if (!wWindow.opener) wWindow.opener = self;
    if (sInputBoxId) msInputBoxId = sInputBoxId;
    wWindow.focus();
}

function OpenNotepadWindow(sUrl) {
    var wWindow = window.open(sUrl,"wNotepadWindow",SetLocation('430','500') + ",status=yes");
    if (!wWindow.opener) wWindow.opener = self;
    wWindow.focus();
}

function GetAbsoluteTop(objElement) {
var iReturn = 0;
var objCurrent = objElement;

    while (objCurrent != null) {
        iReturn += objCurrent.offsetTop - objCurrent.scrollTop;
        objCurrent = objCurrent.offsetParent;
        // skip very last object in hierachy as it seems to throw it all out
        if (objCurrent && objCurrent.offsetParent == null)
            objCurrent = objCurrent.offsetParent;
    }
    return iReturn;
}

function GetAbsoluteLeft(objElement) {
var iReturn = 0;
var objCurrent = objElement;

    while (objCurrent != null) {
        iReturn += objCurrent.offsetLeft - objCurrent.scrollLeft;
        objCurrent = objCurrent.offsetParent;
    }
    return iReturn;
}

function isVisible(objElement) {
var bReturn = true;
var objCurrent = objElement;

    while (objCurrent != null) {
        if (objCurrent.style.visibility=="hidden") {
            bReturn = false;
            objCurrent=null;
        }
        else
            objCurrent = objCurrent.offsetParent;
    }
    return bReturn;
}

//
// This function will attempt to make a Date object from the supplied
// string.  The function will recognise any of the BASIS formats as
// defined below
//
function getDateFromString(sDate) {

    var dReturn;
    var asPatterns = [
        /^[a-z]{3} [0-9]{1,2}, [0-9]{4}$/i,              // 1 	'M3 D2, Y4' 	12 	Jun 21, 1980
        /^[a-z]{3,9} [0-9]{1,2}, [0-9]{4}$/i,            // 2 	'M9 D2, Y4' 	18 	June 21, 1980
        /^[a-z]{3} [0-9]{1,2} [0-9]{4}$/i,               // 3 	'M3 D2 Y4' 	    11 	Jun 21 1980
        /^[a-z]{3,9} [0-9]{1,2} [0-9]{4}$/i,             // 4 	'M9 D2 Y4' 	    17 	June 21 1980
        /^[0-9]{1,2}-[a-z]{3}-[0-9]{4}$/i,               // 5 	'D2-M3-Y4' 	    11 	21-Jun-1980
        /^[0-9]{1,2}[a-z]{3}[0-9]{4}$/i,                 // 6 	'D2M3Y4' 	    9 	21Jun1980
        /^[0-9]{1,2}[a-z]{3}[0-9]{2}$/i,                 // 7 	'D2M3Y2' 	    7 	21Jun80
        /^[0-9]{1,2}-[a-z]{3}-[0-9]{2}$/i,               // 8 	'D2-M3-Y2' 	    9 	21-Jun-80
        /^[0-9]{1,2} [a-z]{3} [0-9]{2}$/i,               // 9 	'D2 M3 Y2' 	    9 	21 Jun 80
        /^[0-9]{1,2} [a-z]{3} [0-9]{4}$/i,               // 10 'D2 M3 Y4' 	    11 	21 Jun 1980
        /^[0-9]{2}\/[0-9]{2}\/[0-9]{2}$/i,               // 11 'M2/D2/Y2' 	    8 	06/21/80
        /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/i,               // 12 'M2/D2/Y4' 	    10 	06/21/1980
        /^[a-z]{5,9} [a-z]{3,9} [0-9]{1,2} [0-9]{4}$/i,  // 13 'W9 M9 D2 Y4' 	27 	Saturday June 21 1980
        /^[a-z]{5,9} [a-z]{3,9} [0-9]{1,2}, [0-9]{4}$/i, // 14 'W9 M9 D2, Y4' 	28 	Saturday June 21, 1980
        /^[a-z]{5,9} [0-9]{1,2}-[a-z]{3,9}-[0-9]{4}$/i,  // 15 'W9 D2-M9-Y4' 	27 	Saturday 21-June-1980
        /^[a-z]{5,9} [0-9]{1,2}-[a-z]{3}-[0-9]{4}$/i,    // 16 'W9 D2-M3-Y4' 	21 	Saturday 21-Jun-1980
        /^[a-z]{3} [0-9]{1,2}-[a-z]{3}-[0-9]{4}$/i,      // 17 'W3 D2-M3-Y4' 	15 	Sat 21-Jun-1980
        /^[a-z]{3} [0-9]{1,2}-[a-z]{3}-[0-9]{2}$/i,      // 18 'W3 D2-M3-Y2' 	13 	Sat 21-Jun-80
        /^[0-9]{4}-[0-9]{0,3}$/i,                        // 19 'Y4-J3' 	    7 	1980-173
        /^[0-9]{3,5}$/i,                                 // 20 'Y2J3' 	        5 	80173
        /^[0-9]{8}$/i,                                   // 21 'Y4M2D2' 	    8 	19800621
        /^[0-9]{2}\.[0-9]{2}\.[0-9]{2}$/i,               // 22 'D2.M2.Y2' 	    8 	21.06.80
        /^[0-9]{2}\.[0-9]{2}\.[0-9]{4}$/i,               // 23 'D2.M2.Y4' 	    10 	21.06.1980
        /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/i,                 // 24 'Y4-M2-D2' 	    10 	1980-06-21
        /^[0-9]{6}$/i,                                   // 25 'Y2M2D2' 	    6 	800621
        /^[0-9]{1,2}\/[a-z]{3}\/[0-9]{2}$/i,             // 26 'D2/M3/Y2' 	    9 	21/Jun/80
        /^[0-9]{1,2}\/[a-z]{3}\/[0-9]{4}$/i              // 27 'D2/M3/Y4' 	    11 	21/Jun/1980
        ];

    var asMonths = new Array();
    asMonths["january"]=0; asMonths["february"]=1; asMonths["march"]=2; asMonths["april"]=3; asMonths["may"]=4; asMonths["june"]=5;
    asMonths["july"]=6; asMonths["august"]=7; asMonths["september"]=8; asMonths["october"]=9; asMonths["november"]=10; asMonths["december"]=11;
    asMonths["jan"]=0; asMonths["feb"]=1; asMonths["mar"]=2; asMonths["apr"]=3; asMonths["jun"]=5;
    asMonths["jul"]=6; asMonths["aug"]=7; asMonths["sep"]=8; asMonths["oct"]=9; asMonths["nov"]=10; asMonths["dec"]=11;

    // Check the date against the patterns
    if (sDate) {
        var asBits;
        for (var iCnt=0; iCnt<asPatterns.length && !dReturn; iCnt++) {
            if (sDate.search(asPatterns[iCnt])==0) {
                switch (iCnt+1) {
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        dReturn = new Date();
                        asBits = sDate.split(/[ ]|, /);
                        dReturn.setDate(Number(asBits[1]));dReturn.setMonth(asMonths[asBits[0].toLowerCase()]);dReturn.setYear(Number(asBits[2]));
                        break;
                    case 5:
                    case 8:
                    case 9:
                    case 10:
                    case 26:
                    case 27:
                        dReturn = new Date();
                        asBits = sDate.split(/[ -\.\/]/);
                        dReturn.setDate(Number(asBits[0]));dReturn.setMonth(asMonths[asBits[1].toLowerCase()]);dReturn.setYear(Number(asBits[2]));
                        break;
                    case 22:
                    case 23:
                        dReturn = new Date();
                        asBits = sDate.split(/[ -\.\/]/);
                        dReturn.setDate(Number(asBits[0]));dReturn.setMonth(Number(asBits[1])-1);dReturn.setYear(Number(asBits[2]));
                        break;
                    case 6:
                    case 7:
                        dReturn = new Date();
                        asBits = sDate.split(/[a-zA-Z]{3}/);
                        dReturn.setDate(Number(asBits[0]));dReturn.setYear(Number(asBits[1]));
                        asBits = sDate.split(/[0-9][^a-zA-Z]/);
                        dReturn.setMonth(asMonths[asBits[0].toLowerCase()]);
                        break;
                    case 11:
                    case 12:
                        dReturn = new Date();
                        asBits = sDate.split(/\//);
                        dReturn.setDate(Number(asBits[1]));dReturn.setMonth(Number(asBits[0])-1);dReturn.setYear(Number(asBits[2]));
                        break;
                    case 13:
                    case 14:
                        dReturn = new Date();
                        asBits = sDate.split(/[ -]|, /);
                        dReturn.setDate(Number(asBits[2]));dReturn.setMonth(asMonths[asBits[1].toLowerCase()]);dReturn.setYear(Number(asBits[3]));
                        break;
                    case 15:
                    case 16:
                    case 17:
                    case 18:
                        dReturn = new Date();
                        asBits = sDate.split(/[ -]|, /);
                        dReturn.setDate(Number(asBits[1]));dReturn.setMonth(asMonths[asBits[2].toLowerCase()]);dReturn.setYear(Number(asBits[3]));
                        break;
                    case 19:
                        dReturn = new Date();
                        asBits = sDate.split(/-/);
                        dReturn.setDate(1);dReturn.setMonth(0);dReturn.setYear(Number(asBits[0]));
                        dReturn=new Date(Number(dReturn) + (1000*60*60*24*(Number(asBits[1])-1)));
                        break;
                    case 20:
                        dReturn = new Date();
                        dReturn.setDate(1);dReturn.setMonth(0);dReturn.setYear(Number(sDate.substr(0,2)));
                        dReturn=new Date(Number(dReturn) + (1000*60*60*24*(Number(sDate.substr(2))-1)));
                        break;
                    case 21:
                        dReturn = new Date();
                        dReturn.setDate(Number(sDate.substr(6,2)));dReturn.setMonth(sDate.substr(4,2)-1);dReturn.setYear(Number(sDate.substr(0,4)));
                        break;
                    case 24:
                        dReturn = new Date();
                        asBits = sDate.split(/[-]/);
                        dReturn.setDate(Number(asBits[2]));dReturn.setMonth(Number(asBits[1])-1);dReturn.setYear(Number(asBits[0]));
                        break;
                    case 25:
                        dReturn = new Date();
                        dReturn.setDate(Number(sDate.substr(4,2)));dReturn.setMonth(Number(sDate.substr(2,2))-1);dReturn.setYear(Number(sDate.substr(0,2)));
                        break;
                }
            }
        }
    }
    if (dReturn) {
        dReturn.setHours(0);
        dReturn.setMinutes(0);
        dReturn.setSeconds(0);
        dReturn.setMilliseconds(0);
    }
    return dReturn;
}


// -------------------------------------------------------------------
// autoComplete (text_input, select_input, [true|false])
//   Arguments:
//      objInput = text input field object
//      sList = list of valid values
//      bForceMatch = true or false. Set to 'true' to not allow any text
//                    in the text box that does not match an option. Only
//                    supported in IE (possible future Netscape).
// -------------------------------------------------------------------
function autoComplete(objEvent, sList, bForceMatch, objCode, sCode, sDisplaySep) {

    var bFound = false;
    if (sList) {
        var asList;
        var asCode;
        var sSep;
        var iKeyCode=objEvent.charCode||objEvent.keyCode;
        var objInput=Event.element(objEvent)
        var iPos=objInput.lang;
        var asCodeSegments;

        if (sList) {

            // Correct the keycodes
            if (iKeyCode==188) iKeyCode=",".charCodeAt(0);

            // Create the lists
            sSep=(sList.indexOf("|")>-1)?"|":(sList.indexOf(";")>-1)?";":",";
            var objSep=new RegExp(" *" + (sSep=='|'?'\\|':sSep) + " *");
            var objDisplaySep=objSep;
            if (sDisplaySep)
                objDisplaySep=new RegExp(" *" + (sDisplaySep=='|'?'\\|':sDisplaySep) + " *");
            else
                sDisplaySep=sSep;
            asList=sList.split(objSep);
            if (sCode) asCode=sCode.split(objSep);
            if (isNaN(iPos)||iPos<0) iPos = 0;

            // Create the segments we're typing into
            var iSegment=-1;
            var asSegments=(objInput.value + "\n").split(objDisplaySep);
            if (sCode && objCode) asCodeSegments=(objCode.value + "\n").split(objSep);
            var iSegmentEnd=0;
            var iCursorPos=getCaretPosition(objInput).start;
            for (var iSeg=0; iSeg<asSegments.length && iSegment==-1; iSeg++) {
                iSegmentEnd+=asSegments[iSeg].length + sDisplaySep.length;
                if (iCursorPos<iSegmentEnd) iSegment=iSeg;
            }
            iSegmentEnd-=sDisplaySep.length;
            if (iSegment==-1) iSegment=asSegments.length-1;

            // Check for the cursor up/down keys
            if (iKeyCode=="38" || iKeyCode=="40") {
                if (iKeyCode=="38") {
                    if (iPos>0) iPos--;
                }
                else {
                    if (iPos<(asList.length-1)) iPos++;
                }
                iSegmentEnd=iSegmentEnd-asSegments[iSegment].length+asList[iPos].length;
                asSegments[iSegment]=unescape(asList[iPos]);
                objInput.value=asSegments.join(sDisplaySep).trim("\n");
                if (sCode && objCode) {
                    asCodeSegments[iSegment] = asCode[iPos];
                    objCode.value=asCodeSegments.join(sSep).trim("\n");
                }
                setCaretPosition(objInput,iSegmentEnd);
            }
            else {

                // Find the value in the list
                for (var i = 0; i<asList.length; i++) {
                    if ((!sCode||asCode[i]!="~") && asList[i].toUpperCase().indexOf(asSegments[iSegment].trimLead().replace(/\n$/,"").toUpperCase()) == 0) {
                        bFound=true;
                        iPos=i;
                        break;
                    }
                }

                // If we can create a range then select the last part
                if (objInput.createTextRange) {
                    if (bForceMatch && !bFound) {
                        objInput.value=unescape(objInput.value.substring(0,objInput.value.length-1));
                        return;
                    }
                    var sCursorKeys ="8;16;17;33;34;35;36;37;38;39;40;45;46;" + sDisplaySep.charCodeAt(0) + ";";
                    if (sCursorKeys.indexOf(iKeyCode+";") == -1) {
                        var sOldValue = asSegments[iSegment].trim("\n")
                        var sNewValue = bFound ? asList[i] : sOldValue;
                        if (sNewValue != sOldValue) {

                            // Create the display values
                            iSegmentEnd=iSegmentEnd-sOldValue.length+sNewValue.length;
                            asSegments[iSegment]=sNewValue;
                            objInput.value=asSegments.join(sDisplaySep).trim("\n");
                            if (sCode && objCode) {
                                asCodeSegments[iSegment] = asCode[i];
                                objCode.value=asCodeSegments.join(sSep).trim("\n");
                            }

                            // Select the segment
                            var objNew = objInput.createTextRange();
                            objNew.collapse();
                            objNew.moveEnd('character', iSegmentEnd) ;
                            objNew.moveStart('character', iCursorPos) ;
                            window.status=iSegmentEnd
                            objNew.select();
                        }
                    }
                }
            }
            objInput.lang = iPos;
        }
    }
}

// Gets content from the server as a string
function getContent(sURL, sParams, bPost) {
    var sRandom=(Math.random() + "").split("\.")[1];
    if (sParams) {
        if (sParams.charAt(0)=='?') sParams=sParams.substring(1);
        sParams = sParams + '&' + sRandom;
    }
    else if (sURL.indexOf('?')==-1)
        sParams = sRandom;
    else {
        sParams = sURL.split("?")[1] + "&" + sRandom;
        sURL = sURL.split("?")[0];
    }
    var myAjax = new Ajax.Request(
        sURL,
        {
            method: (bPost)?'post':'get',
            parameters: sParams,
            evalScripts: true,
            onFailure: function(request){window.status='Error occurred in AJAX call';},
            asynchronous: false
        });
        return myAjax.transport.responseText;
}

// Gets content from the server as a javascript object
function getJsonContent(sURL, sParams, bPost) {
    return eval('(' + getContent(sURL,sParams,bPost) + ')');
}

// Gets content from the server as a string
function getContentAsync(sURL, sParams, objCallback, bPost) {
    var sRandom=(Math.random() + "").split("\.")[1];
    if (sParams) {
        if (sParams.charAt(0)=='?') sParams=sParams.substring(1);
        sParams = sParams + '&' + sRandom;
    }
    else if (sURL.indexOf('?')==-1)
        sParams = sRandom;
    else {
        sParams = sURL.split("?")[1] + "&" + sRandom;
        sURL = sURL.split("?")[0];
    }
    return new Ajax.Request(
        sURL,
        {
            method: (bPost)?'post':'get',
            parameters: sParams,
            asynchronous: true,
            evalScripts: true,
            onFailure: function(request){window.status='Error occurred in AJAX call';},
            onComplete: objCallback
        });
}

// Updates the specified element with data from the server
function updateContent(sElementId, sURL, sParams) {
    Element.update(sElementId, getContent(sURL, sParams));
}

// Updates the specified element with data from the server
function updateContentAsync(sElementId, sURL, sParams, objCallback) {
    var sRandom=(Math.random() + "").split("\.")[1];
    if (sParams) {
        if (sParams.charAt(0)=='?') sParams=sParams.substring(1);
        sParams = sParams + '&' + sRandom;
    }
    else if (sURL.indexOf('?')==-1)
        sParams = sRandom;
    else {
        sParams = sURL.split("?")[1] + "&" + sRandom;
        sURL = sURL.split("?")[0];
    }
    var myAjax = new Ajax.Updater (
        {success: sElementId},
        sURL,
        {
            method: 'get',
            parameters: sParams,
            asynchronous: true,
            evalScripts: true,
            onFailure: function(request){window.status='Error occurred in AJAX call';},
            onComplete: objCallback
        });
}

// A useful object that works out the size of the window for different browsers
function WindowDimensions() {
    this.width = 0; this.height = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        this.width = window.innerWidth;
        this.height = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        this.width = document.documentElement.clientWidth;
        this.height = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        this.width = document.body.clientWidth;
        this.height = document.body.clientHeight;
    }
}

// Create an object to do everything for us
function Pane(sName) {

    this.name = sName;
    this.div = document.getElementById(sName);
    this.exists = (this.div!=null);
    this.visible = (this.exists && this.div.style.visibility!="hidden" && this.div.style.display!="none");
    if (this.exists) {
        this.style = this.div.style;
        this.left = (this.style.left) ? parseInt(this.style.left) : parseInt("0" + this.div.left);
        this.top = (this.style.top) ? parseInt(this.style.top) : parseInt("0" + this.div.top);
        this.width = (this.style.width) ? parseInt(this.style.width) : Element.getWidth(sName);
        this.height = (this.style.height) ? parseInt(this.style.height) : Element.getHeight(sName);
    }
    this.move = function(left, top, width, height) {
        if (typeof(left)=="object") {
            this.move(left.left, left.top, left.width, left.height);
        }
        else {
            if ((left || left==0) && left!=-1) this.style.left = left + "px";
            if ((top || top==0) && top!=-1) this.style.top = top + "px";
            if (width && width!=-1) this.style.width = width + "px";
            if (height && height!=-1) this.style.height = height + "px";
            this.left = parseInt(this.style.left);
            this.top = parseInt(this.style.top);
            this.width = parseInt(this.style.width);
            this.height = parseInt(this.style.height);
        }
    }
    this.hide = function() {
        if (this.exists) {
            this.style.visibility = "hidden";
            this.style.display = "none";
        }
    }
    this.show = function() {
        if (this.exists) {
            this.style.visibility = "visible";
            this.style.display = "block";
        }
    }
}

// Attach this handler to the onLoad window event

function addLoadEvent(func) {
    Event.observe(window,"load",func);
}

// Attach this handler to the onResize window event

function addResizeEvent(func) {
    Event.observe(window,"resize",func);
}

function FindFocusBox() {
    var iNewX,iNewY,iX,iY,objSelected;
    iX=10000; iY=10000;
    objSelected=null;
    for (var iForm=0; iForm<document.forms.length; iForm++) {
        for (var iCtl=0; iCtl<document.forms[iForm].length; iCtl++) {
            var objElement = document.forms[iForm].elements[iCtl];
            if ((objElement.type  == 'text' || objElement.type == 'textarea') && isVisible(objElement)) {
                iNewY = GetAbsoluteTop(objElement);
                iNewX = GetAbsoluteLeft(objElement);
                if (iNewX<iX || iNewY<iY) {
                    iX=iNewX; iY=iNewY;
                    objSelected=objElement;
                }
            }
        }
    }
    try {if (objSelected) objSelected.focus();}
    catch(X) {}
}

// Some useful String extensions
String.prototype.trim = function() {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}
String.prototype.trimLead = function() {
    return this.replace(/(?:(?:^|\n)\s+)/g,"");
}
String.prototype.trimTail = function() {
    return this.replace(/(\s+(?:$|\n))/g,"");
}
String.prototype.fulltrim = function() {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}

// proper case string prptotype (JScript 5.5+)
String.prototype.toProperCase = function() {
  return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
}

// Returns the values of the form objects concatanated with commas
function getFormValues(sForm, sName) {
    var sReturn;
    var objElement = document.forms[sForm][sName];
    if (typeof(objElement.length)=="undefined" || typeof(objElement.options)!="undefined")
        sReturn=objElement.value;
    else {
        for (var iCnt=0; iCnt<objElement.length; iCnt++) {
            if (iCnt==0)
                sReturn = objElement[iCnt].value;
            else
                sReturn = sReturn + "," + objElement[iCnt].value;
        }
    }
    return sReturn;
}

// This function is used to get round the problem of the "click to activate"
// This is explained in http://capitalhead.com/articles/click-to-activate-and-use-this-control---kb912812.aspx
function loadInnerContent(objElement, sContent) {
    objElement.innerHTML = sContent;
}


// This function trawls through all the elements on a form creating
// a suitable parameters list for GET/POST via Ajax
// SUPERCEDED BY PROTOTYPE
function getFormParams(objForm) {
    return Form.serialize(objForm);
}

// This function returns the value of a radio button
function getRadioValue(objRadio) {

    try {
        for (var iCnt=0; iCnt<objRadio.length; iCnt++) 
            if (objRadio[iCnt].checked) return objRadio[iCnt].value;
    } catch(X) {}

    return "";
}            

// This function sets the value of a radio button
function setRadioValue(objRadio, sValue) {

    try {
        for (var iCnt=0; iCnt<objRadio.length; iCnt++) 
            if (objRadio[iCnt].value == sValue) objRadio[iCnt].checked = true;
    } catch(X) {}
}            

// Sets the caret position within a textbox or textarea
function setCaretPosition(elem, caretPos) {
    if (typeof(elem)=="string") elem = document.getElementById(elem);

    if(elem != null) {
        if (!caretPos) caretPos=elem.value.length;
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

// Return the cursor position within an input box
function getCaretPosition(input) {
    var result = { start: 0, end: 0 };
    if (input.setSelectionRange) {
        result.start = input.selectionStart;
        result.end = input.selectionEnd;
    }
    else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        var r2 = range.duplicate();
        result.start = 0 - r2.moveStart('character', -100000);
        result.end = result.start + range.text.length;
    }
    return result;
}

// Copies the content of the elemtn to the clipboard
function copyToClipboard(inElement) {
    if (document.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(inElement);
        range.execCommand('Copy');
    } else {
        var flashcopier = 'flashcopier';
        if(!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
    return false;
}

//===================
// Start of formatNumber functions
//===================
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(number, format, print) {  // use: formatNumber(number, "format")
    if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br>");

    var dec = 0;
    var nleftEnd = 0;
    var nrightEnd = 0;

    if (number - 0 != number) return null;  // if number is NaN return null
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

	// Modification to get rid of engineering format - only works on > ie 5.5
	if (document.all && document.getElementById) {
		if (number.toString().indexOf("e-") != -1) {
			 // split input value into LHS and RHS using decpoint as divider
			dec = Number(number).toFixed(srightEnd.length).indexOf(decpoint) != -1;
			nleftEnd = (dec) ? Number(number).toFixed(srightEnd.length).substring(0, Number(number).toFixed(srightEnd.length).indexOf(".")) : number;
			nrightEnd = (dec) ? Number(number).toFixed(srightEnd.length).substring(Number(number).toFixed(srightEnd.length).indexOf(".") + 1) : "";
		} else {
			 // split input value into LHS and RHS using decpoint as divider
			dec = number.indexOf(decpoint) != -1;
			nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
			nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";
		}
	}

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }

function PopupWindow(ID, loc, scrollBar, width, height ){
	ID = window.open( loc, ID, 'toolbar=no,location=no,directories=no,status=no,scrollbars=' + scrollBar + ',resizable=no,copyhistory=no,width=' + width + ',height=' + height );
	ID.focus();
}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}



var iMaxWidth=0;
var iMaxHeight=0;
var iWidthIncrement;
var iHeightIncrement;
var bAtTop=false;
var bClosed=false;

function showPlayerImage() {
	var iWidth=0;
	var iHeight=0;
    var objImage=document.getElementById('playerimage');
    if (iMaxWidth==0) {
	    var objTmp=new Image();
	    objTmp.src=objImage.src;
        iMaxWidth=objTmp.width;
        iMaxHeight=objTmp.height;
        if (iMaxHeight>140) {
            iMaxWidth=parseInt((100 / iMaxHeight) * iMaxWidth);
			iMaxHeight=100;
		}
        iWidthIncrement=parseInt(iMaxWidth / 10);
        iHeightIncrement=parseInt(iMaxHeight / 10);
    }
    else {
        iWidth=parseInt(objImage.style.width);
        iHeight=parseInt(objImage.style.height);
    }
    if (!bAtTop) {
        iWidth+=iWidthIncrement;
        if (iWidth>iMaxWidth) iWidth=iMaxWidth;
        iHeight+=iHeightIncrement;
        if (iHeight>iMaxHeight) iHeight=iMaxHeight;
        objImage.style.width=iWidth + 'px';
        objImage.style.height=iHeight + 'px';
        objImage.style.display='block';
        bAtTop=(iWidth==iMaxWidth && iHeight==iMaxHeight);
        setTimeout(showPlayerImage,50)
    }
    else if (!bClosed) {
        setTimeout(function(){document.getElementById('playerimage').style.display='none'},5000);
        bClosed=true;
    }
}
