var counter = -1;
var shouldSubmit=false;     // Submit the form unless a confirmation failed
var mustSubmit=false;       // Non-submit item was clicked (doSelect) so form will not auto submit
var submitAction=false;     // Turns true if no submit action yet located...
var alreadyPosted=false;    // Turns true once we post
var closeFormWindow=false;  // Close window after submitting form
var sessionID='';
var hexDigits = "0123456789ABCDEF";
var dialogActive;       // Open modal dialog
var dialogReturn;       // Modal dialog return function
var dialogArgs;         // Dialog js reads its arguments from here

document.onmousemove=hideStatus;

function doHelp(aValue) {
    doStatus(aValue);
    counter = 30;
}
function doStatus(aValue) {
    window.status = aValue;
}
function hideStatus() {
    counter -= 1;
    if (counter == 0) {
        doStatus("");
    }
}
function doAlert(aMessage) {alert(aMessage);}

function doSubmit(aTarget,aAction,aForm,shouldClose,aWindow){
    if (typeof shouldClose != "undefined") closeFormWindow = shouldClose;
    shouldSubmit=true;  // No need to confirm
    mustSubmit=false;   // NOT a manual submit

    var submitForm=document.forms[aForm];
    submitForm.action=aTarget+sessionID+aAction;
    submitAction=true;

    if (typeof aWindow != "undefined") {
        submitForm.target=aWindow;
    } else {
        submitForm.target='_self';
    }
}
function doConfirmSubmit(aMessage,aTarget,aAction,aForm,shouldClose,aWindow){
    shouldSubmit=confirm(aMessage);
    mustSubmit=false;   // NOT a manual submit

    if(shouldSubmit){
        if (typeof shouldClose != "undefined") closeFormWindow = shouldClose;
        var submitForm=document.forms[aForm];
        submitForm.action=aTarget+sessionID+aAction;
        submitAction=true;
        if ((typeof aWindow != "undefined") &&(aWindow!="")) {
		    submitForm.target=aWindow;
        } else {
            submitForm.target='_self';
        }
    } else {
        document.forms[aForm].action='nowhere';
        alreadyPosted = false;
    }
    // NOTE handleSubmit may fire even when we return false (especially IE)
    return shouldSubmit;
}
function doSelect(aTarget,aAction,aForm,shouldClose,aWindow){
    if (typeof shouldClose != "undefined") closeFormWindow = shouldClose;
    shouldSubmit=true;

    var submitForm=document.forms[aForm];
    submitForm.action=aTarget+sessionID+aAction;
    submitAction=true;
    if (typeof aWindow != "undefined") {
        submitForm.target=aWindow;
    } else {
        submitForm.target='_self';
    }
    // We cannot submitForm.submit(), since that does NOT fire the onSubmit function
    mustSubmit=true;                    // This is a manual submit
    submitForm.onsubmit(submitForm);    // We expect this to be handleSubmit()
}
function doConfirmSelect(aMessage,aTarget,aAction,aForm,shouldClose){
    shouldSubmit=confirm(aMessage);
    submitAction=true;
    if(shouldSubmit){
        if (typeof shouldClose != "undefined") closeFormWindow = shouldClose;

        var submitForm=document.forms[aForm];
        submitForm.action=aTarget+sessionID+aAction;
        if ((typeof aWindow != "undefined") &&(aWindow!="")) {
		    submitForm.target=aWindow;
        } else {
            submitForm.target='_self';
        }
        // We cannot submitForm.submit(), since that does NOT fire the onSubmit function
        mustSubmit=true;                    // This is a manual submit
        submitForm.onsubmit(submitForm);    // We expect this to be handleSubmit()
    } else {
        document.forms[aForm].action='nowhere';
        alreadyPosted = false;
    }
}
function handleSubmit(aForm){
    if (!shouldSubmit) {
        // Action explicitly cancelled
        alreadyPosted = false;
        return( false );
    }
    if (alreadyPosted) {
        // Button bounce/impatient user
        // Unfortunately with IE, the response to the original post does not
        // overwrite the current page, so the user must refresh
        alert( "Request already submitted\nPlease wait"
            + ((document.all)
                ? ", then select a different page."     // IE
                : "." )                                 // Gecko
        );
        alreadyPosted = false;
        return( false );
    }
    // If not opening in a secondary window, try to prevent the bounce
    if (aForm.target == '_self') alreadyPosted = true;

    // Use either the action posted, or if nothing was clicked (ie, user hit Enter)
    // then find the first active button to use
    if(!submitAction){
        shouldSubmit=false;
        var fields=aForm.elements;
        for(i=0;i<fields.length;i++){
            if( !fields[i].disabled
            && ((fields[i].type=='submit')||(fields[i].type=='image'))
            && (typeof fields[i].onclick == "function")){
                // We expect the following function to reset shouldSubmit/mustSubmit
                fields[i].onclick.call();
                break;
            }
        }
    }
    submitAction=false;
    // Fire custom actions
    if (typeof aForm.submitActions != "undefined" ) {
        for(var i=0; i < aForm.submitActions.length; i += 1) {
            aForm.submitActions[i].call();
        }
    }
    // If it was NOT a submit button, then manually submit the form now
    if (mustSubmit) {
        mustSubmit=false;
        aForm.submit();
    }
    if ( closeFormWindow ) window.close();
    return( true );
}
function registerSubmitAction(aFormName,aFunction) {
    var submitForm=document.forms[aFormName];
    if (typeof submitForm.submitActions == "undefined" ) {
        submitForm.submitActions = new Array();
    }
    submitForm.submitActions[submitForm.submitActions.length] = aFunction;
}

function doConfirmAnchor(aMessage,aTarget,aAction) {
    if (confirm(aMessage)) {
        window.location.replace(aTarget+sessionID+aAction);
    }
}
function doOpen(aTarget,aAction,aWindow,aConfig){
    window.open(aTarget+sessionID+aAction,aWindow,aConfig);
}
function doTransition(aURL) {
	window.location.replace(aURL);
}
function doPageLoad(aMessage,ifConfirm,ifClose,errField){
    window.focus();
    if(aMessage!=null){
        if(ifConfirm){
            ifClose=confirm(aMessage);
        }else{
            doAlert(aMessage);
        }
        if(ifClose){
            window.close();
            return;
        }
    }
    submitAction=false;
    var targetField=doPageFocus(errField);
    if(targetField!=null) try {
        targetField.focus();
    }catch(ignore) {}
}
function doPageFocus(errField){
    var targetField=null;
    if(document.forms.length>0){
        var fields=document.forms[0].elements;
        if (fields.length>0) {
            if ((errField!=null)&&(typeof(fields[errField])!='undefined')){
                targetField=fields[errField];
            }
            if ((targetField==null)||(targetField.length==0)||targetField.disabled) {
                for(i = 0;i<fields.length;i++){
                    if (!fields[i].disabled
                    && ((fields[i].type=='text')
                        ||(fields[i].type=='textarea')
                        ||(fields[i].type=='button')
                        ||(fields[i].type=='password')
                        ||(fields[i].type.toString().charAt(0)=='s'))){
                        targetField=fields[i];
                        break;
                    }
                }
            }
		if ((targetField!=null)&&(targetField.length>1))targetField=targetField[0];
        }
    }
    return(targetField);
}

// Simple image swapping (css based)
function swapImgRestore( anchor ) {
	var images = anchor.getElementsByTagName("IMG");
	images.item(0).style.display = "inline";
	images.item(1).style.display = "none";
}
function swapImg( anchor ) {
	var images = anchor.getElementsByTagName("IMG");
	images.item(0).style.display = "none";
	images.item(1).style.display = "inline";
}

// URL manipulation
function localServlet( aURL ) {
    if (typeof aURL == "undefined" ) aURL = document.URL;
    var index = aURL.indexOf("?");
    if (index > 0) aURL = aURL.substring(0,index);
    return( aURL );
}
function localReference( aURL ) {
    aURL = localServlet( aURL );
    var index = aURL.lastIndexOf("/");
    if (index > 0) aURL = aURL.substring(0,index+1);
    return( aURL );
}
function currentPath( aURL ) {
    if (typeof aURL == "undefined" ) aURL = document.URL;
    var index = aURL.indexOf("path=");
    if (index > 0) {
        var end = aURL.indexOf("&",index);
        if ( end < 0 ) end = aURL.length;
        return( aURL.substring(index+5,end) );
    } else {
        return( "" );
    }
}

function openMinimalWindow( url, windowName, width, height, resizable, scrollbars ) {
    if ( typeof windowName == "undefined" ) windowName = "minimal";
    if ( typeof width == "undefined" ) width = "300";
    if ( typeof height == "undefined" ) height = "200";
    if ( typeof resizable == "undefined" ) resizable = "no";
    if ( typeof scrollbars == "undefined" ) scrollbars = "no";
	var minWindow = window.open( url
                    , windowName
                    , "toolbar=no,menubar=no"
                        + ",width=" + width + ",height=" + height
                        + ",resizable=" + resizable
                        + ",scrollbars=" + scrollbars
                        + ((document.all)
                            ? ",location=no,directories=no,status=no"   // IE
                            : ",personalbar=no,status=no" )             // Gecko
                    );
    return( minWindow );
}

//  Dialog html should include 'dialog.js'
function openDialog( url, windowName, returnFunction, args, width, height, resizable, scrollbars ) {
    if ( typeof windowName == "undefined" ) windowName = "dialog";
    if ( typeof width == "undefined" ) width = "300";
    if ( typeof height == "undefined" ) height = "200";
    if ( typeof resizable == "undefined" ) resizable = "yes";
    if ( typeof scrollbars == "undefined" ) scrollbars = "no";
	if ( typeof args == "undefined" ) {
        dialogArgs = window;
	} else {
        dialogArgs = args;
	}
	// Fake modal by intercepting events
    function captureEvents(w) {
        addEvent(w, "click", modalEvent);
        addEvent(w, "mousedown", modalEvent);
        addEvent(w, "mouseup", modalEvent);
        if (document.all) addEvent(w, "focus", modalEvent); // ONLY IE, GECKO blocks keystrokes
        //addEvent(w, "keydown", modalEvent);
        //addEvent(w, "keypress", modalEvent);
    };
	function releaseEvents(w) {
		removeEvent(w, "click", modalEvent);
		removeEvent(w, "mousedown", modalEvent);
		removeEvent(w, "mouseup", modalEvent);
		if (document.all) removeEvent(w, "focus", modalEvent);  // ONLY IE, GECKO blocks keystrokes
		//removeEvent(w, "keydown", modalEvent);
		//removeEvent(w, "keypress", modalEvent);
	};
    // Intercept all events in the main window and beneath
	captureEvents(window);
	for (var i = 0; i < window.frames.length; captureEvents(window.frames[i++]));

	// Function to call upon return
	dialogReturn = function (val) {
		if (val && returnFunction) {
			returnFunction(val);
		}
        // Stop blocking events
        if (dialogActive) {
            releaseEvents(window);
            for (var i = 0; i < window.frames.length; releaseEvents(window.frames[i++]));
            dialogActive = null;
        }
	};
    // Make the window
	dialogActive = openMinimalWindow( url, windowName, width, height, resizable, scrollbars );
    dialogActive.focus();
};
// Event management
addEvent = function(el, evname, func) {
	if (document.all) {
		// IE
		el.attachEvent("on" + evname, func);
	} else {
        // Gecko
		el.addEventListener(evname, func, true);
	}
};
removeEvent = function(el, evname, func) {
	if (document.all) {
		// IE
		el.detachEvent("on" + evname, func);
	} else {
        // Gecko
		el.removeEventListener(evname, func, true);
	}
};
modalEvent = function(event) {
	if (dialogActive && !dialogActive.closed) {
		dialogActive.focus();
        if (document.all) {
            // IE
            event.cancelBubble = true;
            event.returnValue = false;
        } else {
            // Gecko
            event.preventDefault();
            event.stopPropagation();
        }
	}
};

// Simple color handlers
function makeColor(id) {
    var r = document.getElementById(id + "R").value;
    if (r) {
        r = "" + hexDigits.charAt(r / 16) + hexDigits.charAt(r & 0x0f);
    } else {
        r = "00";
    }
    var g = document.getElementById(id + "G").value;
    if (g) {
        g = "" + hexDigits.charAt(g / 16) + hexDigits.charAt(g & 0x0f);
    } else {
        g = "00";
    }
    var b = document.getElementById(id + "B").value;
    if (b) {
        b = "" + hexDigits.charAt(b / 16) + hexDigits.charAt(b & 0x0f);
    } else {
        b = "00";
    }
    return( "#" + r + g + b );
}
function postColor(id,color) {
    var r = (hexDigits.indexOf(color.charAt(0)) * 16) + hexDigits.indexOf(color.charAt(1));
    var g = (hexDigits.indexOf(color.charAt(2)) * 16) + hexDigits.indexOf(color.charAt(3));
    var b = (hexDigits.indexOf(color.charAt(4)) * 16) + hexDigits.indexOf(color.charAt(5));
    document.getElementById(id + "R").value = r;
    document.getElementById(id + "G").value = g;
    document.getElementById(id + "B").value = b;

    var splotch = document.getElementById(id + "S");
    if (splotch) {
        splotch.style.backgroundColor = '#' + color;
        splotch.style.display = 'inline';
    }
}

// Function to set the active option in a select list, adding the option
// if the given value is not yet supported.
// NOTE that the onchange event is fired as well...
function setSelector(selectorID,newValue,placeholder) {
    if (typeof placeholder == "undefined") placeholder = "   ";
    var selector = document.getElementById(selectorID);
    var option;
    for( var i = 0; i < selector.length; i += 1 ) {
        option = selector.options[i];
        if ( option.value == newValue ) {
            option.selected = true;
            break;
        } else {
            option = null;
        }
    }
    if ( !option ) {
        option = new Option(placeholder,newValue,true);
        selector.options[selector.length]=option;
    }
    selector.value = newValue;
    if (typeof selector.onchange == "function") selector.onchange.call();
}
// Basic element access (cross browser)
function getElement(anID) {
    if ( document.all ) {
        return document.all[anID];
    } else {
        return document.getElementById(anID);
    }
}
function getIFrame( anID ) {
    var aFrame = getElement(anID);
    var innerFrame= (aFrame.contentWindow)
                       ? aFrame.contentWindow
                       : ((aFrame.contentDocument.document)
                              ? aFrame.contentDocument.document
                              : aFrame.contentDocument);
    return( innerFrame );
}
// Apply a function against a matching node, diving into child nodes if present
function applyDeepFixup( pItem, pFunction, pApplyWithinMatch, pWrapperTag, pClass ) {
  if ( (pItem.nodeName == pWrapperTag) 
  && ((typeof pClass == "undefined") || (pItem.className == pClass)) ) {
    pFunction( pItem );
    if ( !pApplyWithinMatch ) return;
  }
  var childList = pItem.childNodes;
  for( var x=0; x < childList.length; x++ ) {
    var childNode = childList[x];
    applyDeepFixup( childNode, pFunction, pApplyWithinMatch, pWrapperTag, pClass );
  }
}

