/**
 * Adds the 'trim' method to strin objects
 */
String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

function encode(str) {
    return escape(str);
}

function decode(str) {
    return unescape(str.replace(/\+/g, " "));
}

/**
 * Checks if a string is empty.
 * @param str
 */
function IsEmpty(str)
{
    if (str == undefined) {
        return true;
    }
    if (str == null) {
        return true;
    }
    if (str.trim().length == 0) {
        return true;
    }
    return false;
}

/**
 * Checks if a field is empty. For javascript validation.
 * @param aTextField
 */
function IsEmptyField(aTextField)
{
    if (aTextField == null) {
        return true;
    }
    return IsEmpty(aTextField.value);
}

/**
 * Checks if a field is not numeric. For javascript validation.
 * @param aTextField Text field.
 * @param allowDecimalPoint Boolean indicating if decimals are allowed.
 */
function IsNotNumericField(aTextField, allowDecimalPoint)
{
    if (aTextField == null) {
        return false;
    }

    var strValue = aTextField.value;
    if (strValue.length == 0) {
        return false;
    }

    var strValidChars;
    if (allowDecimalPoint) {
        strValidChars = "0123456789.-";
    } else {
        strValidChars = "0123456789-";
    }
    var strChar;
    var blnResult = false;
    for (i = 0; i < strValue.length && blnResult == false; i++)
    {
        strChar = strValue.charAt(i);
        if (strValidChars.indexOf(strChar) == -1)
        {
            blnResult = true;
        }
    }
    return blnResult;
}

function getSelectedOptionText(aSelectField) {
    for (var i = 0,ii = aSelectField.length; i < ii; i++) {
        var option = aSelectField.options[i];
        if (option.selected) {
            return option.text;
        }
    }
    return "";
}

function getSelectedOptionValue(aSelectField) {
    for (var i = 0,ii = aSelectField.length; i < ii; i++) {
        var option = aSelectField.options[i];
        if (option.selected) {
            return option.value;
        }
    }
    return "";
}

/**
 * Handles javascript exception in an exception dialog.
 * You can throw open this with a new exception to show this dialog,
 * eg handleException(new Error("Unexpected event."));
 * @param e Exception object.
 */
function handleException(e) {
    try {
        idle();
        var msg;
        if (e.name == "Error") {
            msg = "<i><b>" + e.message + "</b></i>";
        } else {
            msg = "<i><b>" + e.message + "</b></i><br><br><i><small>Error Type: " + e.name + "</small></i>";
        }
        showExceptionDialog(msg);
    } catch(exception) {
        showAlert("An Unexpected Error has Occurred.<br><br>" + exception.message + ". Error Type: " + exception.name);
    }
}

/**
 * 'Failure' handler.
 * Handles a basic communication error between the browser and the server.
 * Not to be used for application errors (eg validation, java exceptions).
 * Application errors should be handled in the 'success' handler by examining the
 * xml data returned from the server.
 * @param msg Message
 */
var handleServerCommunicationFailure = function(o) {
    try {
        idle();
        var msg = "<i><b>Error communicating with the server.</b></i><br><br><small>Transaction id: <i>" + o.tId + "</i><br>" +
                  "HTTP status: <i>" + o.status + "</i><br>Message: <i>" + o.statusText + "</i></small>";
        showExceptionDialog(msg);
    } catch(exception) {
        handleException(exception);
    }
}

var exceptionDialog;

/**
 * Shows an exception dialog above all other dialogs.
 * @param msg Message.
 */
function showExceptionDialog(msg) {
    try {

        // Instantiate the Dialog
        var handleContinue = function() {
            hideExceptionDialog();
        };

        // Only allow one exception dialog at a time.
        // Implement this by using a page variable to track the exception dialog.
        if ((exceptionDialog == undefined) || (exceptionDialog == null)) {
            exceptionDialog =
            new YAHOO.widget.SimpleDialog("exceptionDialog",
            { width: "300px",
                fixedcenter: true,
                visible: false,
                draggable: false,
                modal: true,
                close: false,
                text: "<b>A Unexpected Error has Occurred.</b><hr size='1'><br>" + msg,
                icon: YAHOO.widget.SimpleDialog.ICON_WARN,
                constraintoviewport: true,
                zIndex: "999",
                buttons: [ { text:"Continue", handler:handleContinue, isDefault:true }]
            });
            exceptionDialog.render(document.body);
            exceptionDialog.show("fade");
        }
    } catch(exception) {
        showAlert("An Unexpected Error has Occurred.<br><br>Error Name: " + exception.name + ".<br>Error Message: " + exception.message);
    }
}

/**
 * Hides the exception dialog.
 */
function hideExceptionDialog() {
    if (exceptionDialog != undefined) {
        exceptionDialog.hide();
    }
    exceptionDialog = null;
}

var pleaseWaitDialog;

/**
 * This shows the 'please wait' dialog.
 * Typically used when calling an asynchronous method on the server.
 */
function busy() {
    if (pleaseWaitDialog == undefined) {
        pleaseWaitDialog =
        new YAHOO.widget.SimpleDialog("pleaseWaitDialog",
        { width: "250px",
            fixedcenter: true,
            visible: false,
            draggable: false,
            close: false,
            text: "<center><small><br>Please Wait<br><br><img src='/images/loading.gif'/></small></center>" ,
            constraintoviewport: true,
            zIndex: "999"
        });
        pleaseWaitDialog.render(document.body);
    }
    pleaseWaitDialog.show("fade");
}

/**
 * This hides the 'please wait' dialog.
 * Typically used once an asynchronous method has completed on the server and returned data. 
 */
function idle() {
    if (pleaseWaitDialog != undefined) {
        pleaseWaitDialog.hide();
    }
}

/**
 * This is used to parse the xml returned from the server.
 * The success handler has an response object passed to it and we
 * use this to calculate the root document element.
 * @param o Response object from server.
 */
function getServerResponseRootElement(o)
{
    if (o.responseXML == null) {
        throw new Error("Server response received but could not be parsed.");
    }
    var root = o.responseXML.documentElement;
    if (root == undefined) {
        throw new Error("Server response received but could not determine document root.");
    }
    return root;
}

/**
 * This is used to return the text of the first element matching the element name.
 * Useful for quickly getting a single item, of which there are only one.
 * @param rootElement Root element.
 * @param elementName Element name.
 */
function getServerResponseElementFirstValue(rootElement, elementName)
{
    var val = "";
    var nodes = rootElement.getElementsByTagName(elementName);
    if (nodes.length == 1) {
        if (nodes[0].childNodes.length > 0) {
            val = nodes[0].firstChild.nodeValue;
        }
    }
    return val;
}

/**
 * Shows an alert dialog, ensuring only one of them is visible at once.
 * @param msg Message to be shown.
 */
function showAlert(msg) {
    try {
        var handleClose = function() {
            this.hide();
        };
        var alertDialog =
                new YAHOO.widget.SimpleDialog("exceptionDialog",
                { width: "300px",
                    fixedcenter: true,
                    visible: false,
                    draggable: false,
                    close: true,
                    text: "<b>Alert</b><hr size='1'><br>" + msg,
                    icon: YAHOO.widget.SimpleDialog.ICON_WARN,
                    constraintoviewport: true,
                    zIndex: "999",
                    modal: true,
                    buttons: [ { text:"Close", handler: handleClose, isDefault:true }],
                    effect:{effect:YAHOO.widget.ContainerEffect.SLIDE,duration:0.25}
                });
        alertDialog.render(document.body);
        alertDialog.show("fade");
    } catch(exception) {
        alert("An Unexpected Error has Occurred.<br><br>Error Name: " + exception.name + ".<br>Error Message: " + exception.message);
    }
}

/**
 * This method adds an option to a select field.
 * @param selectField
 * @param text
 * @param value
 */
function selectAdd(selectField, text, value) {
    selectField.options[selectField.options.length] = new Option(text, value);
}

/**
 * This method clears out all the options for a select field.
 * @param selectField
 */
function selectClear(selectField) {
    for (var i = selectField.options.length; i >= 0; i--) {
        selectField.options[i] = null;
    }
}

/**
 * This method deselects the select field's current selection.
 * @param selectField
 */
function selectDeselectSelected(selectField) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return;
    }
    selectField.options[selectedIndex].selected = false;
}

/**
 * This method returns the selected text for a select field.
 * @param selectField
 */
function selectGetText(selectField) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return "";
    }
    return selectField.options[selectedIndex].text;
}

/**
 * This method returns the selected value for a select field.
 * @param selectField
 */
function selectGetValue(selectField) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return "";
    }
    return selectField.options[selectedIndex].value;
}

/**
 * This method indicates if a select field has a selection.
 * @param selectField
 */
function selectIsSelected(selectField) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return false;
    } else {
        return true;
    }
}

/**
 * This method removes the current selection from the select field's options..
 * @param selectField
 */
function selectRemoveSelected(selectField) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return;
    }
    selectField.remove(selectedIndex);
}

/**
 * This method sets the text for the currently selected option.
 * @param selectField
 * @param text
 */
function selectSetSelectedText(selectField, text) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return "";
    }
    return selectField.options[selectedIndex].text = text;
}

/**
 * This method sets the value for the currently selected option.
 * @param selectField
 * @param value
 */
function selectSetSelectedValue(selectField, value) {
    var selectedIndex = selectField.selectedIndex;
    if (selectedIndex == -1) {
        return "";
    }
    return selectField.options[selectedIndex].value = value;
}


