/* -*- Mode: java -*-
 $Id: util.js,v 1.1 2007-02-01 20:22:01 williamz Exp $

 Copyright ? 2002 Casero Corporation

 All rights reserved.  This document contains proprietary and confidential
 information, and shall not be reproduced, transferred, or disclosed to
 others, without the prior written consent of Casero Corporation.
*/

/** Returns a copy of the string with leading and trailing whitespace removed.  */
String.prototype.trim = function() {
    return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

/** Returns a copy of the string with leading and trailing whitespace removed.  */
String.prototype.trimAll = function() {
    var start = 0, last = this.length-1;
    for (; this.charAt(start) == ' '; start++);
    for (; this.charAt(start) == '\r'; start++);
    for (; this.charAt(start) == '\n'; start++);
    for (; this.charAt(last) == ' '; last--) ;
    for (; this.charAt(last) == '\r'; last--) ;
    for (; this.charAt(last) == '\n'; last--) ;
    return (start < this.length) ? this.substring(start, last+1) : "";
}

/** Returns true of this string starts with the specified string. */
String.prototype.startsWith = function(s) {
    return this.substring(0,s.length) == s;
}

/** Returns true of this string ends with the specified string. */
String.prototype.endsWith = function(s) {
    return this.substring(this.length-s.length) == s;
}

/** Truncates the string to maxLength. */
String.prototype.truncate = function(maxLength) {
   var s = this.slice(0, maxLength);
   if (this.length > maxLength) {
           s += '...';
   }
   return s;
}

/** Escapes the given string so that the string can be displayed in HTML. */
String.prototype.escapeHTML = function() {
    var result = this.replace(/&/g, "&amp;");
    result = result.replace(/</g, "&lt;");
    result = result.replace(/>/g, "&gt;");
    result = result.replace(/"/g, "&quot;");
    result = result.replace(/'/g, "&#39;");
    result = result.replace(/\r\n/g, "<br/>");
    return result;
}

String.prototype.escapeQuotes = function() {
    var result = this.replace(/\'/g, "\'");
    result = result.replace(/\"/g, "\"");
    return result;
}

/** Unescapes the given string so that the string from HTML safe representation. */
String.prototype.unescapeHTML = function() {
    var result = this.replace(/&lt;/g, "<");
    result = result.replace(/&gt;/g, ">");
    result = result.replace(/&quot;/g, "\"");
    result = result.replace(/&#39;/g, "'");
    result = result.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n")
    result = result.replace(/&amp;/g, "&");
    return result;
}

function util_escapeHTML(s, escapeNewLine) {
    var result = s.replace(/&/g, "&amp;");
    result = result.replace(/</g, "&lt;");
    result = result.replace(/>/g, "&gt;");
    result = result.replace(/"/g, "&quot;");
    result = result.replace(/'/g, "&#39;");
    if (escapeNewLine) {
	    result = result.replace(/\r\n/g, "<br/>");
	}
    return result;
}

function util_escapeQuotes(s) {
    var result = s.replace(/\'/g, "\'");
    result = result.replace(/\"/g, "\"");
    return result;
}

function util_unescapeHTML(s) {
    var result = s.replace(/&lt;/g, "<");
    result = result.replace(/&gt;/g, ">");
    result = result.replace(/&quot;/g, "\"");
    result = result.replace(/&#39;/g, "'");
    result = result.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n")
    result = result.replace(/&amp;/g, "&");
    return result;
}

function stripNewLines(s) {
	return s.replace(/\r\n/g, " ");
}

/** Returns true if the parameter string is empty or only consists of spaces, */
function util_isEmpty(s) {
  return s == undefined || s == null || s.toString().trim() == "";
}

/** Returns true if the array object is empty. */
function util_isEmptyArray(arrayObj) {
  for(var i in arrayObj) {
    if(!util_isEmpty(arrayObj[i])) {
        return false;
    }
  }
  return true;
}

/** Returns true if URL contains 127.0.0.1 */
function util_using5keyRC() {
    return String(window.location).indexOf("127.0.0.1") != -1;
}

/** Sets the fields in obj1 with the values in obj2. */
function util_setFields(obj1, obj2) {
    for (var field in obj2) {
        obj1[field] = obj2[field];
    }
    return obj1;
}

/** Returns the window's URI parameters as an object.
 * getInternalParams - if not true, params starting with "_" are ignored
 */
function util_getParams(getInternalParams) {
    var ret = new Object();
    loc = location.search.substring(1);
    if (!loc)
        return ret;
    var params = loc.split("&");
    for (var i=0; i < params.length; i++) {
        var v = params[i].split("=");
        if (getInternalParams != true && v[0].charAt(0) == "_")
            continue;
        ret[v[0]] = (v[1] != undefined) ? decodeURIComponent(v[1]) : undefined;
    }
    return ret;
}

// Extracts the values from the form's elements into an object
// data - if present, the form's values will be set in this object
// A radio button's value will be read only if it is checked
function util_getFormData(form, data, doc) {
    var obj = (data != undefined) ? data : new Object();
    if (form != undefined) {
        for (var i=0; i < form.elements.length; i++) {
            var elem = form.elements[i];
            if (elem.name == undefined)
                continue;
            if ((elem.type == "radio" || elem.type == "checkbox") && !elem.checked) {
                continue;
            }
            var v = elem.value;
            if (elem.selectedIndex >= 0 && util_isEmpty(v)) {
                v = elem.options[elem.selectedIndex].text;
            }
            obj[elem.name] = v.toString().trim();
        }
    }
    if (doc == undefined) doc = document;
    var widgets = doc.widgets;
    for (var i=0; widgets && i < widgets.length; i++) {
        if (widgets[i].getValue != undefined)
            obj[widgets[i].name] = widgets[i].getValue();
    }
    return obj;
}

/* Sets the values in the form's elements from the object's fields
 * If multiple radio button exist with the same name,
 * the button will be set whose value matches the data field's
 */
function util_setFormData(form, data, doc) {
    if (form != undefined) {
        for (var field in data) {
            var elem = form.elements[field];
            if (!elem) {
                continue;
            }
            else if (elem.length > 0 && elem[0].type == "radio") {
                for (var i=0; i < elem.length; i++) {
                    elem[i].checked = (elem[i].value == data[field]);
                }
            }
            else if (elem.type == "checkbox") {
                elem.checked = (elem.value == data[field]);
            }
            else if (elem.type && elem.type.startsWith("select")) {
                if (util_isEmpty(data[field]) || !elem.options) {
                    continue;
                }
                else if (elem.value) {
                    elem.value = data[field];
                }
                else {
                    for (var i=0; i < elem.options.length; i++) {
                        if (elem.options[i].text == data[field]) {
                            elem.selectedIndex = i;
                            break;
                        }
                    }
                }
            }
            else {
                elem.value = data[field] ? data[field] : "";
            }
        }
    }
    if (doc == undefined) doc = document;
    var widgets = document.widgets;
    for (var i=0; widgets && i < widgets.length; i++) {
        if (widgets[i].setValue != undefined)
            widgets[i].setValue(data[widgets[i].name]);
    }
}

/* Sets the values in the document's IDs with values from the object's fields */
function util_setDocumentData(data, doc) {
    if (doc == undefined) doc = document;
    for (var field in data) {
        var elem = util_findObj(field, doc);
        if (elem != undefined)
            elem.innerHTML = data[field];
    }
}

/** Returns true if obj is in array. */
function util_arrayContains(obj, array) {
    if (!obj || !array) return false;
    for (var i=0; i < array.length; i++){
        if (obj == array[i]) {
            return true;
        }
    }
    return false;
}

/** Returns true if string 's' contains only the chars in string 'test' */
function util_containsOnly(s, test) {
    if (s == undefined)
        return true;
    for (var k=0; k < s.length; k++) {
        if (test.indexOf(s.charAt(k)) == -1) {
            return false;
        }
    }
    return true;
}

/**
 * Calls the validate method of each enabled child component,
 * and displays an error dialog if necessary.
 * Focus is set to the first invalid component
 * @param messages array of error messages
 * @param doc if undefined, the current window's document is used
 * If the parent window defines a validate() method, it is called and an error
 * is displayed if the method returns a String
 * or an object with fields {message:<text>, component:<focusComponent>}
 * @return false if an error occurred
 */
function util_validate(messages, doc) {
    if (messages == undefined) messages = new Array();
    if (doc == undefined) doc = document;
    if (!util_validateForm(doc.forms[0], messages)) {
        return false;
    }

    var widgets = doc.widgets;
    for (var i=0; widgets && i < widgets.length; i++) {
        var msg;
        if (widgets[i].validate != undefined)
            msg = widgets[i].validate(messages);
        if (msg != undefined) {
            util_showMessageBox(msg);
            if (widgets[i].focus)
                widgets[i].focus();
            return false;
        }
    }

    var w = doc.parentWindow ? doc.parentWindow : doc.defaultView;
    if (w.validate == undefined)
        return true;

    var ret = w.validate();
    var message;
    if (typeof(ret) == "string") ret = {message:ret};
    if (ret != undefined) {
        if (ret.message != undefined) {
            message = messages[ret.message] != undefined ?
                messages[ret.message] : ret.message;
        }
        focusComponent = ret.component;
    }

    if (!util_isEmpty(message)) {
        util_showMessageBox(message);
        return false;
    }
    return true;
}

/** Validates the values.
 * @param pattern:
 * 'mandatory' - field cannot be blank
 * 'integer [min:<x> [max:<x>]]'
 * 'e-mail'
 * 'phone'
 * 'username:<name>' - name is prepended to message
 * @param messages array of error messages
 * returns - Error message, or undefined if valid
 */
function util_validateValue(pattern, value, messages) {
    if (!pattern) return undefined;
    var msg;
    if (pattern.indexOf("integer") != -1) {
        var v = parseInt(value);
        if (isNaN(v)) {
            msg = "NotaNumber";
        }
        var k = pattern.indexOf("min:");
        var minValue = (k != -1) ? parseInt(pattern.substring(k+4)) : undefined;
        var k = pattern.indexOf("max:");
        var maxValue = (k != -1) ? parseInt(pattern.substring(k+4)) : undefined;
        if (minValue != undefined && !isNaN(minValue) && v < minValue) {
            msg = (maxValue != undefined) ? "OutOfRange" : "MinValue";
        }
        else if (maxValue != undefined && !isNaN(maxValue) && v > maxValue) {
            msg = (minValue != undefined) ? "OutOfRange" : "MaxValue";
        }
        if (msg) {
            msg = messages[msg] ? messages[msg] : msg;
            msg = msg.replace("MINVALUE", minValue) .replace("MAXVALUE", maxValue);
        }
    }
    else if (pattern.indexOf("phone") != -1
             && !util_containsOnly(value, util_phoneChars())) {
        msg = "InvalidPhone";
    }
    else if (pattern.indexOf("e-mail") != -1) {
        if (!util_containsOnly(value, util_emailChars())) {
            msg = "InvalidEmail";
        }
    }
    if (pattern.indexOf("mandatory") != -1 && value == "") {
        msg = "EmptyField";
    }

    if (msg) {
        if (messages[msg]) msg = messages[msg];
        var k = pattern.indexOf("username:");
        if (k != -1) {
            var name = pattern.substring(k+9);
            if (name.indexOf(" ") != -1)
                name = name.substring(0, name.indexOf(" "));
            msg = name + ": " + msg;
        }
    }
    return msg;
}

/** Validates the form's element's values using the ID values:
 * 'mandatory' - field cannot be blank
 * 'integer [min:<x> [max:<x>]]'
 * 'e-mail'
 * 'phone'
 * 'username:<name>' - name is prepended to message
 */
function util_validateForm(form, messages) {
    if (!form)
        return true;
    var msg;
    var elem = form.elements;
    for (var i=0; msg == undefined && i < elem.length; i++) {
        var value = elem[i].value.toString().trim();
        msg = util_validateValue(elem[i].id, value, messages);
    }
    if (msg != undefined) {
        util_showMessageBox(msg);
        elem[i-1].focus();
    }
    return msg == undefined;
}

/**
 * Writes the values of the visible child components to the specified object
 * @param obj created if undefined
 * @param doc if undefined, the current window's document is used
 * @return the persistence object
 */
function util_getValue(obj, doc) {
    if (doc == undefined) doc = document;
    if (obj == undefined) {
        obj = new Object();
    }
    util_getFormData(doc.forms[0], obj, doc);
    var w = doc.parentWindow ? doc.parentWindow : doc.defaultView;
    if (w.getValue)
        w.getValue(obj);
    return obj;
}

/**
 * Calls the parent's setValue method with the specified object.
 * If the methood does not return false,
 * setValue reads values from the specified object, and sets each child component's value.
 * doc - if undefined, the current window's document is used
 */
function util_setValue(obj, doc) {
    if (doc == undefined) doc = document;
    var w = doc.parentWindow ? doc.parentWindow : doc.defaultView;
    if (w.setValue != undefined && w.setValue(obj) == false) {
        return;
    }
    util_setFormData(doc.forms[0], obj, doc);
}

// Returns false if the key is not a numeral
// key - may be an integer or an event
function util_checkInteger(key) {
    if (typeof(key) != "number")
        key = util_getKey(key);
    return !(key > 31 && (key < 48 || key > 57));
}

// Returns a string containing valid e-mail characters
function util_emailChars() {
    var test = "0123456789@.";
    for (var k="a".charCodeAt(); k <= "z".charCodeAt(); k++) {
        var s = String.fromCharCode(k);
        test += s + s.toUpperCase();
    }
    return test;
}

// Returns false if the string contains invalid e-mail characters
// s - may be a string or a keyboard event
function util_checkEmail(s) {
    if (typeof(s) != "string")
        s = util_getKeyChar(s);
    return util_containsOnly(s, util_emailChars());
}

// Returns a string containing valid phone characters
function util_phoneChars() {
    return " 0123456789().+-";
}

// Returns false if the string contains invalid phone characters
// s - may be a string or a keyboard event
function util_checkPhone(s) {
    if (typeof(s) != "string")
        s = util_getKeyChar(s);
    return util_containsOnly(s, util_phoneChars());
}

/** Displays an AbodeDialog box if one was created, otherwise shows javascript alert.
 * @param icon 'error' (default), 'warning', 'info' or 'question' (in which case a javascript confirm dialog is displayed)
 */
function util_showMessageBox(text, icon) {
    if (icon == "question") {
        return confirm(text);
    }

    var dialogs = document.dialogs;

    // If dialogs were not found in a frame, search up the heirarchy
    if (!dialogs && top != self) {
        for (var w = parent; w && !dialogs; w = w.parent) {
            dialogs = w.document.dialogs;
        }
    }

    if (dialogs && dialogs.length > 0) {
        // Check that window is not in a frame (which could be invisible)
        if (!icon) icon = "error";
        dialogs[0].show({message: text, icon: "../dialogs/"+icon+".gif", buttons: ["OK"]});
    }
    else {
        alert(text);
    }
}

// Displays an error dialog if an error occurred in the params
function util_checkStatus() {
    var params = util_getParams(true);
    if (params._status != undefined && ""+params._status != "0") {
        // Check that window is not in a frame (which could be invisible)
        if (top == self) {
            util_showMessageBox(params._message);
        }
        else {
            window.open(window.location, "_top");
        }
    }
}

/*
 * Opens a window centered in the screen if width and height are specified.
 */
function util_openDialog(URL, windowName, width, height, attributes) {
    if (width != undefined && height != undefined) {
        var left = parseInt((screen.availWidth/2) - (width/2));
        var top = parseInt((screen.availHeight/2) - (height/2));
        var attr = "width=" + width + ",height=" + height +
            ",left=" + left + ",top=" + top +
            "screenX=" + left + ",screenY=" + top;
        if (attributes)
            attr += ","+attributes;
        attributes = attr;
    }
    return window.open(URL, windowName, attributes);
}

var KEY_RIGHT = 39;
var KEY_UP = 38;
var KEY_LEFT = 37;
var KEY_DOWN = 40;

/** Gets the numeric value of the key that was hit. */
function util_getKey(e) {
    if (!e) e = window.event;
    return e.which ? e.which : e.keyCode;
}

/** Gets the character value of the key that was hit, or undefined if not a char. */
function util_getKeyChar(e) {
    if (!e) e = window.event;
    var c = (e.charCode != undefined) ? e.charCode : e.keyCode;
    return (c >= 32) ? String.fromCharCode(c) : undefined;
}

// focusTable[name] = object with fields 'left', 'right', 'up' and 'down'
function util_keyHandler(e, focusTable) {
    if (!e) e = window.event;
    var src = e.target ? e.target : e.srcElement;
    if (src.name == undefined || focusTable[src.name] == undefined)
        return;
    var key = util_getKey(e);
    var comp;
    if (key == KEY_RIGHT) {
        comp = focusTable[src.name].right;
    }
    else if (key == KEY_LEFT) {
        comp = focusTable[src.name].left;
    }
    else if (key == KEY_UP) {
        comp = focusTable[src.name].up;
    }
    else if (key == KEY_DOWN) {
        comp = focusTable[src.name].down;
    }
    comp = util_findObj(comp);
    if (comp != undefined)
        comp.focus();
}

/** Locates a given object in the DOM.
* doc - if undefined, the current window's document is used
*/
function util_findObj(name, doc) {
    if (name == undefined) return;
    var p, x;
    if (!doc) {
        doc = document;
    }
    else if (doc.toolbar) {
        doc = doc.document;
    }
    if ( (p = name.indexOf("?")) > 0 && parent.frames.length) {
        doc = parent.frames[name.substring(p+1)].document;
    name = name.substring(0, p);
  }

  if (!(x = doc[name]) && doc.all)
    x = doc.all[name];
  for (var i = 0; !x && doc.forms != undefined && i < doc.forms.length; i++)
    x = doc.forms[i][name];
    if (!x && doc.getElementById)
      x = doc.getElementById(name);
    return x;
}

/**
 * Writes the values of each field in the object.
 */
function util_dump(obj, name) {
    var s = name + " values:\n";
    for (var field in obj) {
        if (typeof(obj[field]) == "object") {
            s += ("["+field+"]:");
            util_dump(obj[field], name);
        }
        else {
            s += field + "=" + obj[field] + "\n";
        }
    }
    alert(s);
}

function getIEVersion() {
    var ua = navigator.userAgent;
    var k = ua.indexOf("MSIE ");
    return (k == -1) ? 0 : parseFloat(ua.substring(k+5));
}

function getMozillaVersion() {
    var ua = navigator.userAgent;
    var k = ua.indexOf("rv:");
    return (k == -1) ? 0 : parseFloat(ua.substring(k+3));
}

function getNNVersion() {
    var appVer = parseFloat(navigator.appVersion);
    if (appVer < 5) {
        return appVer;
    }
    else if (navigator.vendorSub != undefined) {
        return parseFloat(navigator.vendorSub);
    }
    return 0;
}

// Returns false if the browser is not supported
function util_checkBrowser() {
    if (navigator.userAgent.indexOf("Mac") != -1) {
        return false;
    }
    else if (document.all) {
        return getIEVersion() >= 5.5;
    }
    else if (navigator.userAgent.indexOf("Netscape") != -1) {
        return getNNVersion() >= 6;
    }
    else if (navigator.userAgent.indexOf("Gecko") != -1) {
        return getMozillaVersion() >= 1.3;
    }
    return false;
}

// Calls all necessary methods
function util_onLoad() {
    if (!util_checkBrowser()) {
        window.open("../dialogs/wrongBrowser.html", "_top");
    }
    else {
        util_checkStatus();
    }
}

/** Replaces all occurrences of inString with outString. */
function util_replaceString(str, inString, outString) {
    return str ? str.split(inString).join(outString) : str;
}

/** Gets a frame's window. */
function util_getFrameWindow(frame) {
    var doc = frame.contentDocument ? frame.contentDocument : frame.Document;
    return doc.parentWindow ? doc.parentWindow : doc.defaultView;
}

/** Gets a frame's document. */
function util_getFrameDocument(frame) {
    return frame.contentDocument ? frame.contentDocument : frame.Document;
}

/** Gets the location of the element in the browser window. */
function util_getLocation(elem) {
  var left = elem.offsetLeft, top = elem.offsetTop;
  while (elem = elem.offsetParent) {
        left += elem.offsetLeft;
        top += elem.offsetTop;
    }
  return {left: left, top: top};
}

/** Gets the current file. */
function util_getCurrentFile() {
    var l = location.pathname.split("/");
    return l[l.length-1];
}

/** Bookmarks the given page */
function util_bookmarkPage(page, title) {
  if (document.all) {
    window.external.AddFavorite(page, title);
  }
  else if (window.sidebar) {
    window.sidebar.addPanel(title, page, "");
  }
}

/** Converts bytes to MB with 2 decimal places */
function util_sizeInMB(size) {
    size = size/1024/1024;
    var totalMB = new String(size);
    if ((totalMB.indexOf('.')) != -1) {
        var tot_int = totalMB.split(".")[0];
        var tot_dec = totalMB.split(".")[1].substr(0,2);
    }
    else {
        tot_int = totalMB;
        tot_dec = "00";
    }
    return parseFloat(tot_int + '.' + tot_dec);
}

/** Verifies the given string is a valid email address. */
function util_verifyEmail(email) {
  var userIDRegEx = /^[\w\+\-]+(\.?[\w\+\-]+)*$/;
  var domainRegEx = /^[a-zA-z0-9\-]*$/;

    if (util_isEmpty( email )) {
        return false;
    }

    //Split email address into local-part and domain
    var emailParts = email.split("@");

    //Check correct number of parts
    if (emailParts.length != 2 ) {
        return false;
    }

    //Hack: Also check that there's no @ at the end of the address.
    if (email.lastIndexOf("@") == email.length -1 ) {
        return false;
    }

    for (var i = 0 ; i < emailParts.length; i++) {
        if (emailParts[i].length == 0) {
            return false;
        }
    }

    //Verify local-part of address
    if (!userIDRegEx.test(emailParts[0])) {
        return false;
    }

    //Verify domain portion of address. This is based on RFC 1035
    var domainParts = emailParts[1].split("\.");
    if (domainParts.length < 2) {
        return false;
    }

    for (var i = 0; i < domainParts.length; i++) {
        if (domainParts[i].length == 0 || domainParts[i].length > 63) {
            return false;
        }

        if (!domainRegEx.test(domainParts[i])) {
            return false;
        }
    }

    return true;
}

/** Submits the page form when enter is pressed. */
function util_keyboardSubmit(formElement) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (((keyCode == 13) && (formElement == 'input')) || ((keyCode == 32) && (formElement == 'button'))) {
        document.forms[0].submit();
    }
}


/** Submits the page form when enter is pressed. */
function util_keyboardSubmit(formElement, e) {
    var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

    if (((keyCode == 13) && (formElement == 'input')) || ((keyCode == 32) && (formElement == 'button'))) {
        document.forms[0].submit();
    }
}

/** Finds the path from website root to current directory and appends requested page path. */
function util_relativePath(page) {
    var itemRef = '';
    var count = 0;
    //find number of directory levels
    for (i = 0; i < location.pathname.length; i++) {
        if (location.pathname.charAt(i) == '/') {
            count++;
        }
    }
    //assemble path from here to root
    for (i = 1; i < count; i++) {
        itemRef += '../';
    }
    //add requested page path
    itemRef += page;
    return itemRef;
}

/** Finds the path from website root to current directory, appends requested page path
    and sets the href to this value. */
function util_relativeLink(page) {
    var itemRef = util_relativePath(page);
    location.href = itemRef;
}

/** Finds the path from website root to current directory, appends requested page path
    and sets the source frame to this value. */
function util_relativeSrc(page, srcFrame) {
    var itemRef = util_relativePath(page);
    if (srcFrame) {
        document.getElementById(srcFrame).src = itemRef;
    }
    else {
        return itemRef;
    }
}

function util_formatLocalDate(longDate) {
  var localDate = new Date(longDate);
  return convertMonth(localDate.getMonth() + 1, "toWord") + " " + localDate.getDate() + ", " + localDate.getFullYear();
}

/*fomat date 2005:10:05 to Oct 5, 2005*/
function util_formatDate(newDate) {
  var formatYear  = newDate.substring(0, newDate.indexOf(':'));
  var formatMonth = newDate.substring(newDate.indexOf(':')+1, newDate.lastIndexOf(':'));
  var formatDate = newDate.substring(newDate.lastIndexOf(':')+1);
  return util_getMonth(formatMonth) + " " + formatDate + ", " + formatYear ;
}
function util_getMonth(month){
  switch(month){
    case "01" :
      return 'Jan';
    case "02" :
      return 'Feb';
    case "03" :
      return 'Mar';
    case "04" :
      return 'Apr';
    case "05" :
      return 'May';
    case "06" :
      return 'Jun';
    case "07" :
      return 'Jul';
    case "08" :
      return 'Aug';
    case "09" :
      return 'Sep';
    case "10" :
      return 'Oct';
    case "11" :
      return 'Nov';
    case "12" :
      return 'Dec';
    default:
      return 'Jan';
  }
}
/** Finds the first visible form element on the page and sets the focus to it */
function util_setFormFocus() {
  var bFound = false;
    // for each form
    for (f = 0; f < document.forms.length; f++) {
        // for each element in each form
        for(i = 0; i < document.forms[f].length; i++) {
            // if it's not a hidden element checkbox or radio
            if ((document.forms[f][i].type != "hidden") &&
      (document.forms[f][i].parentNode.style.visibility != "hidden") &&
      (document.forms[f][i].type != "radio") &&
      (document.forms[f][i].type != "checkbox")) {
                // and it's not disabled
                if (document.forms[f][i].disabled != true) {
                    // set the focus to it
                    document.forms[f][i].focus();
                    var bFound = true;
                }
            }
            // if found in this element, stop looking
            if (bFound == true) {
                break;
            }
         }
        // if found in this form, stop looking
        if (bFound == true) {
            break;
        }
    }
}

function util_clearResultMessage() {
    var msg = document.getElementById("errorMessage");
    if( msg != null ) {
        msg.innerHTML="";
    }
    msg = document.getElementById("successMessage");
    if( msg != null ) {
        msg.innerHTML="";
    }
		
		try {document.getElementById('statusMessage_div').style.display = "none";} catch(e){}
}

function ajax_onFailure(request) {
  // refresh the current page
  window.location.href = window.location;
}





/*Validation of text field */
var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
function util_isValid(parm,val) {
    if (parm == "") return true;
        for (i=0; i<parm.length; i++) {
            if (val.indexOf(parm.charAt(i),0) == -1) return false;
        }
    return true;
}

function util_isNum(parm) {return util_isValid(parm,numb);}
function util_isLower(parm) {return util_isValid(parm,lwr);}
function util_isUpper(parm) {return util_isValid(parm,upr);}
function util_isAlpha(parm) {return util_isValid(parm,lwr+upr);}
function util_isAlphanum(parm) {return util_isValid(parm,lwr+upr+numb);}

function util_isWinXP(){
	var bReturn;
	
	if ( navigator.appVersion.indexOf("Windows NT 5.1") != -1 ) {
		bReturn = true;
	} else {
		bReturn = false;
	} 
		
	return bReturn;
}

/*UnCheck All Form Checkboxes*/
function util_uncheckAll(theForm) {
  for(i=0; i<theForm.elements.length; i++){
		if (theForm.elements[i].type == "checkbox"){
			theForm.elements[i].checked = false;
		}
	}
}

/*Check All Form Checkboxes*/
function util_checkAll(theForm) {
	for(i=0; i<theForm.elements.length; i++){
		if (theForm.elements[i].type == "checkbox"){
			theForm.elements[i].checked = true;
		}
	}
}

// Returns true if at least one checkbox is checked; false otherwise
function util_isChecked(theCheckBox) {

    if (theCheckBox) {

        // only one item in the list
        if (theCheckBox.checked) {
            return true;
        }
        else if (theCheckBox.length) {
            for (var i = 0; i < theCheckBox.length; i++) {
                if (theCheckBox[i].checked) {
                    return true;
                }
            }
        }
    }
    
    return false;
}

/* Generate canonical title. NOTE: This code is duplicated in BlogManager.java
   and MediaManager.java. Having it duplicate here is a kludge.  */
function util_composeCanonicalTitle(title) {
	var FRIENDLY_URL_CHARS = 'abcdefghijklmnopqrstuvwxyz1234567890';	
	title = title.toLowerCase().trim();
	
	var out = "";
	
    for (i = 0; i < title.length; i++) {
        var s = title.charAt(i);

        if (FRIENDLY_URL_CHARS.indexOf(s, 0) == -1) {
            out += '_';
        }
        else {
            out += s;
        }
    }
    
    return out;
}

function util_breakOut() {
    if (window != top) {
        top.location.href = location.href;
    }
}
