window.onload = function () { 
    if (gHash!=undefined) {
        $('<input>').attr({
            type: 'hidden',
            id: 'sessionHash',
            name: 'sessionHash',
            value: gHash
        }).appendTo('form');
    } else { console.log("not defined");}
}
if (gHash!=undefined) {
	$.ajaxSetup({beforeSend: function (xhr) { xhr.setRequestHeader('X-Session-Hash', gHash); } });        
}

/* end security hash block */

/* Error Logging */
/*
$(window).error(function(msg, url, linenumber){
	return ceLogError(msg,url,linenumber);
});
window.onerror = function(msg, url, linenumber) {
	return ceLogError(msg,url,linenumber);
}
function ceLogError(msg,url,linenumber) {
	args = {};
	args.location = window.location.href;
	args.browser = $.browser;
	if (msg) args.msg = msg;
	if (url) args.surl = url;
	if (linenumber) args.linenumber = linenumber;
	$.post('index.php?fuse=admin&action=logJavascriptError', {args:args});
    return true;
}*/
/* Error Logging */

// fixes bug with jquery and deprecated webkit
$(document).ready(function(){
    // remove layerX and layerY
    var all = $.event.props,
        len = all.length,
        res = [];
    while (len--) {
      var el = all[len];
      if (el != 'layerX' && el != 'layerY') res.push(el);
    }
    $.event.props = res;
});
// end fix


/* start defining CE class */
function CE () {}

/* block used to add sessionhash to all forms and ajax requests */
//Ext.onReady(function(){
    if (gHash!=undefined) {
        Ext.Ajax.defaultHeaders = {
            'X-Session-Hash'         : gHash
        };
    }
//});
	      
if(typeof(RichHTML)!= "undefined"){
	$(RichHTML).bind({
	    "mask": function(event) {
			ce.msg('Loading',true);
	    },
	    "unmask": function(event) {
			$("#msg-div").hide();	
	    }	    
	});
}


/**
* Displays the greeting message
*
* @param {Int} level Error level.
* @param {String} ex String message to log.
*/
CE.prototype.log = function(level,ex) {
    if(console!=undefined) console.log(level,ex);
}

/* Add type of IPAddress for Validation Type */
Ext.apply(Ext.form.VTypes, {
    IPAddress:  function(v) {
        return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
    },
    IPAddressText: 'Must be a numeric IP address',
    IPAddressMask: /[\d\.]/i
});

CE.prototype.checkRedirectLogin = function(response) {
    var jsonData;
    try {
        if ( typeof(response.responseText) != 'undefined' ) {
            jsonData = Ext.decode(response.responseText);
            if (typeof(jsonData.redirectToLogin) != "undefined" && jsonData.redirectToLogin) {
                window.location = 'index.php?fuse=admin&view=Login'
            } 
        }
    } catch(e) { }
}

/**
 * Used by ajax request success functions to determine if it should display error
 *
 * @param {String} response Raw Ajax Request response.
 * @param {Bool} display Show alert box with error.
 * @param {String} msg If message is not passed with error then use the passed string.
 * @return {Bool} Returns if there was an error or not
 */
CE.prototype.parseAjaxResponse = function(response, display, msg) {
    var jsonData;
    if (display == undefined) {display = true;}

    try {
        jsonData = Ext.decode(response.responseText);    
        if (typeof(jsonData.error) != "undefined" && jsonData.error) {
            if ((jsonData.message != "") && display) {
                Ext.MessageBox.alert(lang("Errors"), jsonData.message.replace(/\n/gi, "<br /> \n"));
            } else if (display) {
                var error = "There was an error performing this action";
                if (msg != undefined) {
                    error = msg;
                }
                
                Ext.MessageBox.alert(lang("Errors"), error);
            }
        } else if (typeof(jsonData.error) == "undefined") {
            //possible error where we areg getting back valid json
            //but not send via action Send return the jsonData but raise error
            Ext.MessageBox.alert(lang("Errors"), "Data returned is old json data");
        }else {
            //no errors maybe msgbox
            if ((jsonData.message != "") && display) {
                this.msg(jsonData.message);
            }
        }
    } catch(e) {
        jsonData=new Object();
        jsonData.error = true;
        jsonData.message = "Data returned is not valid json<br/>"+e.toString()+'<br />'+response.responseText;
        if (display) {
            Ext.MessageBox.alert(lang("Errors"), jsonData.message);
        }
    }

    return jsonData;

}

CE.prototype.parseActionResponse = function(jsonData, display, msg) {

    if (display == undefined) {display = true;}

    if (typeof(jsonData.error) != "undefined" && jsonData.error) {
        if ((jsonData.message != "") && display) {
        	alert(lang("Errors"), jsonData.message.replace(/\n/gi, "<br /> \n"));
        } else if (display) {
            var error = "There was an error performing this action";
            if (msg != undefined) {
                error = msg;
            }
            
            alert(lang("Errors"), error);
        }
    } else if (typeof(jsonData.error) == "undefined") {
        //possible error where we areg getting back valid json
        //but not send via action Send return the jsonData but raise error
        alert(lang("Errors"), "Data returned is old json data");
    }else {
        //no errors maybe msgbox
        if ((jsonData.message != "") && display) {
            this.msg(jsonData.message);
        }
    }

    return jsonData;

}

CE.prototype.updateSessionVar = function(id,val) {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionVar',
        params: {sessionid:id,value:val},
        success: function(xhr) { ce.checkRedirectLogin(xhr); }
    });
}

CE.prototype.updateEventCache = function() {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionCaches',
        params: {eventssession:$('#session_count').html(), eventstoday:$('#day_count').html()},
        success: function(xhr) { ce.checkRedirectLogin(xhr); }
    });
}

CE.prototype.updateTicketsCache = function() {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionCaches',
        params: {supportticketsummary: $('#supportticketsummary').html()},
        success: function(xhr) { ce.checkRedirectLogin(xhr); }
    });
}

CE.prototype.updateWhoIsOnlineCache = function() {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionCaches',
        params: {myticketcount:$('#cemyticketscount').html(),onlineusers: $('#onlineusers').html(), offlineusers: $('#offlineusers').html(),lastxseenstyle: $('#lastxseen').attr('style')},
        success: function(xhr) { ce.checkRedirectLogin(xhr); }
    });
}

CE.prototype.getGravatarUrl = function(gravataremail,size)
{

	var gravUrl = "", defaultpicurl, pathArray, newPathname = "";
	if (!size) size = 80;

    if (gravataremail && gravataremail!="") {	    
        pathArray = window.location.pathname.split( '/' );
        for ( var i = 0; i < pathArray.length -1 ; i++ ) {
            newPathname += "/";
            newPathname += pathArray[i];
        }
        defaultpicurl = window.location.protocol + "//" + window.location.host + "/" + newPathname + "/../images/defaultuserpic.jpg";
        gravUrl = "https://secure.gravatar.com/avatar.php?gravatar_id="+MD5(gravataremail)+"&size="+size+"&rating=PG&default="+defaultpicurl;
	}
	return gravUrl;
    
}

CE.prototype.showNewEvent = function(text,header,gravataremail){
        if (!header || header=="") {
            title = "Notice";
        } else {
            title = header;
        }

        if (gravataremail && gravataremail!="") {            
            $.gritter.add({
				// (string | mandatory) the heading of the notification
				title: title,
				// (string | mandatory) the text inside the notification
				text: text,
				// (string | optional) the image to display on the left
				image: ce.getGravatarUrl(gravataremail),
				// (bool | optional) if you want it to fade out on its own or just sit there
				sticky: false,
				// (int | optional) the time you want it to be alive for before fading out
				time: ''
			});
        } else {
			$.gritter.add({
				// (string | mandatory) the heading of the notification
				title: title,
				// (string | mandatory) the text inside the notification
				text: text
			});
        }
        return false;
}
CE.prototype.msg = function(title, perm){
        clearTimeout($('#msg-div').data('timeoutId'));
        $('#msg-div-inner').text(title);
        $('#msg-div').fadeIn('normal');
        if(!perm) {
            timeoutId = setTimeout(function(){ $('#msg-div').fadeOut('fast');}, 4000);
            $('#msg-div').data('timeoutId', timeoutId);
        }
}

CE.prototype.errormsg = function(title){
        clearTimeout($('#msg-div').data('timeoutId'));
        $('#msg-div-inner').text(title);
        $('#msg-div').fadeIn('normal');
        $('#msg-div').css("cursor","pointer");
        $('#msg-div').click(function() {
            $('#msg-div').fadeOut('fast');
        });
}

CE.prototype.showSnapinHiddenTab = function(tabName){
    $('#tab_'+tabName).show();
    var t =  $.cookie("viewinghiddentabs");
    if (t==null) {
        t = tabName;
    } else {
        t += ","+tabName;
    }
    $.cookie("viewinghiddentabs", t);
}

//create our site util js class
var ce = new CE();
var onLoadFunctions = []; 

//add override for store exceptions
Ext.data.DataProxy.on('exception', function(proxy, type, action, o, response, mixed) {
    if (action == 'read') {
        var res = Ext.util.JSON.decode(response.responseText);
        if(res.success === false){
            ce.parseAjaxResponse(response);
        }
    }
});

//fix for issue with Extjs
Ext.lib.Event.resolveTextNode = Ext.isGecko ? function(node)
{
    if(!node)
    {
        return;
    }
    var s = HTMLElement.prototype.toString.call(node);
    if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]')
    {
        return;
    }
    return node.nodeType == 3 ? node.parentNode : node;
} : function(node){
    return node && node.nodeType == 3 ? node.parentNode : node;
};


//fixes grids so that they can be selectable
if (!Ext.grid.GridView.prototype.templates) {
    Ext.grid.GridView.prototype.templates = {};
}
Ext.grid.GridView.prototype.templates.cell = new Ext.Template(
    '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
    '<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
    '</td>'
);
//end fix

//fixes tooltip scrolling
Ext.override(Ext.Tip, {
    showAt : function(xy){
        Ext.Tip.superclass.show.call(this);
        if(this.measureWidth !== false && (!this.initialConfig || typeof this.initialConfig.width != 'number')){
            this.doAutoWidth();
        }
        if(this.constrainPosition){
            xy = this.el.adjustForConstraints(xy);
        }

        var elWidth = parseInt(this.el.dom.style.width);
        var xPosition = xy[0] + elWidth;
        var bodyWidth = Ext.getBody().getComputedWidth();
        if(xPosition >= bodyWidth) {
            xy[0] = bodyWidth - elWidth - 10;
        }
        var bHeight = Ext.lib.Dom.getViewHeight()
        if((xy[1] + 50 )> bHeight) {
            xy[1] = bHeight - 50;
        }

        this.setPagePosition(xy[0], xy[1]);
    }
});

//need to convert to msg
function setStatus(s, time) { }
function resetStatus(s) {}
function unsetStatus(s, time) {}
function msg(title){
        ce.msg(title);
}
// End msg windows

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) {
            level = 0;
        }

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) {
            level_padding += "    ";
        }

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

//js equivalent to html_entity_decode
function html_entity_decode(str) {
	return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

//Custom jquery functions
function slideToggle(el, bShow){
  var $el = $(el), height = $el.data("originalHeight"), visible = $el.is(":visible");

  // if the bShow isn't present, get the current visibility and reverse it
  if( arguments.length == 1 ) bShow = !visible;

  // if the current visiblilty is the same as the requested state, cancel
  if( bShow == visible ) return false;

  // get the original height
  if( !height ){
    // get original height
    height = $el.show().height();
    // update the height
    $el.data("originalHeight", height);
    // if the element was hidden, hide it again
    if( !visible ) $el.hide().css({height: 0});
  }

  // expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
  if( bShow ){
    $el.show().animate({height: height}, {duration: 250});
  } else {
    $el.animate({height: 0}, {duration: 250, complete:function (){
        $el.hide();
      }
    });
  }
  return true;
}

// When completed, this function will replace the check() function, that doesn't work with fieldset tags
function getFormErrors(form)
{
    var strAlertMessageArr = new Array();

    var elements = form.getElementsByTagName("input");
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].name.substr(0, 2) == "r_") {
            var requiredElementName = elements[i].name.substr(2);
            for (var j = 0; j < elements.length; j++) {
                if (elements[j].name == requiredElementName && elements[j].value == "") {
                    strAlertMessageArr.push(lang('The field % can\'t be empty.', elements[i].value));
                    break;
                }
            }
        }
        if (elements[i].name.substr(0, 2) == "e_") {
            regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
            var elementName = elements[i].name.substr(2);
            for (var j = 0; j < elements.length; j++) {
                if (elements[j].name == elementName && !regexp.test(elements[j].value)) {
                    strAlertMessageArr.push(lang('Invalid E-mail format for field %.', elements[i].value));
                    break;
                }
            }
        }
    }
    return strAlertMessageArr;
}

function lang(phrase)
{
    if ((typeof language != "undefined") && (typeof language[phrase] != "undefined") && (language[phrase] != '')) {
        switch (lang.arguments.length) {
            case 1:
                return language[phrase];
            case 2:
                return _sprintf(language[phrase], lang.arguments[1]);
            case 3:
                return _sprintf(language[phrase], lang.arguments[1], lang.arguments[2]);
        }

        return language[phrase];
    }

    switch (lang.arguments.length) {
        case 1:
            return phrase;
        case 2:
            return _sprintf(phrase, lang.arguments[1]);
        case 3:
            return _sprintf(phrase, lang.arguments[1], lang.arguments[2]);
    }

    return phrase;
}

// Same as lang() but only used for dynamically generated strings, like varLang(foo).
// Doesn't get parsed by update_languages.php script
function varLang(phrase)
{
    return lang(phrase);
}

//CLEANUP BELOW THIS
//TODO DELETE THIS FILE AND CREATE NEW COMMON.JS FILE
var winHelpHNDL = null;
var winUtilityHNDL = null;
var winDebug = null;
var new_fieldname = "";

//var _mousePosX;
//var _mousePosY;

//Used for color changes in forms
var highlightcolor="lightYellow";
var ns6 = document.getElementById&&!document.all;
var previous='';
var eventobj;
var intended=/INPUT|TEXTAREA/;

var isIE = false;
var isIE7 = false;
var isOther = false;
var isNS4 = false;
var isNS6 = false;

var submitted = false;

if(document.getElementById)
{
    if(!document.all)
    {
        isNS6=true;
    }
    if(document.all)
    {
        isIE=true;
    }
}
else
{
    if(document.layers)
    {
        isNS4=true;
    }
    else
    {
        isOther=true;
    }
}

isIE7 = isIE && document.documentElement && typeof document.documentElement.style.maxHeight!="undefined";

function rmbr(string){
    var regexp = /(<br>)|(<br\/>)/gi;
     // IE needs the newlines explicitly
    if (isIE === true) {
        string = string.replace(regexp, '\n');
    } else {
        string = string.replace(regexp, '');
    }

    return string;
}

function nl2br(string){
    var regexp = /\n/g;
    string = string.replace(regexp, '<br>\n');
    return string;
}

//calls a method to change the records per page in pagination
function alterRecsPerPage(fileName,tableid,limit,extraPars){
    var pars =  extraPars+'&updatelimit='+ limit;
    resetStatus(lang('Loading'));
    Ext.Ajax.request({
       url:fileName+'?'+pars,
       success: function(t) {
            unsetStatus(lang('Loaded'),1000);
            $('#'+tableid).html(t.responseText);
       }
    });
    //new Ajax.Updater(tableid, fileName,{onLoading:function(request){resetStatus(lang('Loading'))}, onComplete:function(request){unsetStatus(lang('Loaded'),1000)}, method: 'get', parameters:pars, asynchronous:true});
}


//calls a method to change the page in pagination
function pageBarAction(tableid,file,pars){
    resetStatus(lang('Loading'));
    Ext.Ajax.request({
       url:file+'?'+pars,
       success: function(t) {
            unsetStatus(lang('Loaded'),1000);
            $('#'+tableid).html(t.responseText);
       }
    });
    //new Ajax.Updater(tableid, file,{onLoading:function(request){resetStatus(lang('Loading'))}, onComplete:function(request){unsetStatus(lang('Loaded'),1000)}, method: 'get', parameters:pars, asynchronous:true});
}

//function used to make sure clicking enter on text box will not force form submit
//use the following in the textbox input section
// onkeypress="return noenter()"
function noenter(e) {
    if(window.event) {
        return !(window.event.keyCode == 13);
    }else{
        return !(e.which == 13);
    }
}

function InArray(tarray,value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    var i;
    for (i=0; i < tarray.length; i++) {
        // Matches identical (===), not just similar (==).
        if (tarray[i] === value) {
            return true;
        }
    }
    return false;
}

// Returns the selected value of a select input field.
function selectedValue(id)
{
    return document.getElementById(id).options[document.getElementById(id).selectedIndex].value
}

function MakeVisable(cur,which){
    strength = (which==0) ? 1 : 0.4;
    if (cur.style.MozOpacity){
        cur.style.MozOpacity=strength;
    }else if(cur.filters){
        cur.filters.alpha.opacity = strength * 100;
    }
}

//function used to ensure that at least one checkbox has been clicked
//to perform the action on
function ItemSelected(form,warningmsg, onlyCb){
    intCount = form.elements.length;
    bolShowMessage=true;
    for(x=1;x<=intCount;x++) {
            if(form.elements[x-1].checked && (!onlyCb || form.elements[x-1].id.substring(0, 3) == 'cb_')) {
                    bolShowMessage=false;
                    continue;
            }
    }

    if (bolShowMessage){
            if(warningmsg!="") alert(warningmsg);
            return false;
    }else{
            return true;
    }
}


function ltrim(inputString){
   if (typeof inputString != "string") {return inputString;}
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   return retValue;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") {return inputString;}
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

<!--hide from old browsers
//Regular expression to highlight only form elements
//Function to check whether element clicked is form element
function submitonce(theform){
    if (document.all||document.getElementById){
        for (i=0;i<theform.length;i++){
            var tempobj=theform.elements[i]
            if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="button")
            tempobj.disabled=true
        }
    }
}

function closeHelpWindow(){
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  if (winUtilityHNDL != null && winUtilityHNDL.open) winUtilityHNDL.close();
}

function openHelpWindow(module, className, settingName, features)
{
  var strURL = "index.php?fuse=newedge&view=HelpWindow&module=" + module + "&className=" + className + "&settingName=" + settingName;
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  winHelpHNDL =  window.open(strURL,'winHelp', features);
}

function oldOpenHelpWindow(intHelpID)
{
  var strURL = "index.php?fuse=newedge&view=HelpWindow&helpID="+intHelpID;
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  winHelpHNDL =  window.open(strURL,'winHelp', 'menubar=no,scrollbars=yes,width=240,height=420');
}

function newOpenHelpWindow(intHelpID)
{
    var helpInfo = new Ext.data.JsonStore({
        id:             "helpInfo",
        root:           'helpinfo',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            helpID: intHelpID
        },
        fields:         [
                            'title',
                            'detail'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url: 'index.php?fuse=newedge&action=HelpWindow'
                        })
    });
    
    helpInfo.on('load',function(){
        recordHelpInfo = helpInfo.getAt(0);
        
        var htmlString = "<style type=\"text/css\"><!--"
                       + "    .body8          {"
                       + "        font-family:      Verdana, Arial, Helvetica, sans-serif;"
                       + "        font-size:        7pt;"
                       + "        line-height:      8pt;"
                       + "        text-decoration:  none"
                       + "    }"
                       + "    "
                       + "    .bodyhighlight  {"
                       + "        font-size:        7pt;"
                       + "        line-height:      8pt;"
                       + "        color:            navy;"
                       + "    }"
                       + "    "
                       + "    TD.tight        {"
                       + "        padding:          10px 5px 5px 10px;"
                       + "    }"
                       + "    "
                       + "    TD.heading      {"
                       + "        padding:          0px 0px 5px 9px;"
                       + "    }"
                       + "    "
                       + "    A               {"
                       + "        text-decoration:  none"
                       + "    }"
                       + "//--></style>"
                       + ""
                       + "<table id=help cellSpacing=0 cellPadding=0 width=\"100%\" border=0 bgcolor='#cccccc'>"
                       + "    <tbody>"
                       + "        <tr>"
                       + "            <td vAlign=top>"
                       + "                <div align=center>"
                       + "                    <table cellSpacing=0 cellPadding=0 width=200 border=0>"
                       + "                        <tbody>"
                       + "                            <tr>"
                       + "                                <td colSpan=2>"
                       + "                                    <img height=30 src=\"../templates/admin/images/help_top.jpg\" width=200 border=0>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                            <tr>"
                       + "                                <td colSpan=2 class=heading height=25 width=200>"
                       + "                                    <font class=body8><b>" + lang('Topic') + ":</b><br>" + recordHelpInfo.get('title') + "</font>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                            <tr>"
                       + "                                <td colspan=2>"
                       + "                                    <table width=100% cellpadding=0 cellspacing=0 border=0>"
                       + "                                        <tr>"
                       + "                                            <td class=tight bgcolor=white>"
                       + "                                                <font class=body8>" + recordHelpInfo.get('detail') + "</font>"
                       + "                                            </td>"
                       + "                                        </tr>"
                       + "                                    </table>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                        </tbody>"
                       + "                    </table>"
                       + "                </div>"
                       + "            </td>"
                       + "        </tr>"
                       + "    </tbody>"
                       + "</table>";
        
        // Window
        var helpWin = new Ext.Window({
            id:           "helpWindow",
            y:            100,
            layout:       'fit',
            resizable:    false,
            autoHeight:   true,
            modal:        true,
            closable:     false,
            title:        recordHelpInfo.get('title'),
            header:       true,
            plain:        true,
            shadow:       false,
            html:         htmlString,
            buttons:      [
                {
                    text:     'Close',
                    handler:  function(){
                        helpWin.hide();
                        helpWin.destroy();
                    }
                }
            ]
        });
        
        helpWin.enable();
        helpWin.show();
    });
    
    helpInfo.load();
}

function jumpMenu(targ,selObj,restore)
{
    s = new String(selObj.options[selObj.selectedIndex].value);
    s.replace("&amp;","&");
    if (s == "") return false;
    if (selObj.selectedIndex==0) return false;
    eval(targ+".location='"+s+"'");
    if (restore) selObj.selectedIndex=0;
}

function jumpMenu2(targ,selObj,restore)
{
    s = new String(selObj.options[selObj.selectedIndex].value);
    if (s == "") return false;
    s.replace("&amp;","&");
    eval(targ+".location='"+s+"'");
    if (restore) selObj.selectedIndex=0;
}

function hideshow(which,imgid){
    if (!document.getElementById)  return
    if (which.style.display=="none"){
        which.style.display="";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/collapse.gif";
        }
    }else{
        which.style.display="none";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/expand.gif";
        }
    }
}

// *** TABLE CHECKBOX OPERATIONS *****
var checkCount = 0;

function makevisible(cur,which)
{
    strength=(which==0)? 1 : 0.2

    if (cur.style.MozOpacity)
        cur.style.MozOpacity=strength
    else if (cur.filters)
        cur.filters.alpha.opacity=strength*100
}

function updateButtons(form)
{
    if (checkCount > 0) {
        for (i = 0; i < form.length; i++) {
            element = form.elements[i];
            if (element.type == "button" || element.type == "submit") {
                element.disabled = false;
                makevisible(element, 0);
            }
        }
    } else {
        for (i = 0; i < form.length; i++) {
            element = form.elements[i];
            if (element.type == "button" || element.type == "submit") {
                element.disabled = true;
                makevisible(element, 1);
            }
        }
    }
}

function checkCheckBox(checkBox)
{
    if (checkBox.checked) checkCount++;
    else checkCount--;
    updateButtons(checkBox.form);
}

function toggleAll(form)
{
    check = form.toggleAllChk.checked;
    for (i = 0; i < form.length; i++) {
        element = form.elements[i];
        if (element.type == 'checkbox' && element.name != 'toggleAll' && element.checked != check && element.disabled != true) {
            element.checked = check;
            if (check) checkCount++;
            else checkCount = 0;
        }
    }
    updateButtons(form);
}
// *** END TABLE CHECKBOX OPERATIONS *****

function strrpos( haystack, needle, offset){
    var i = (haystack+'').lastIndexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''

    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}

function getAbsoluteTop(objectId) {
        // Get an object top position from the upper left viewport corner
        // Tested with relative and nested objects
        o = document.getElementById(objectId)
        oTop = o.offsetTop            // Get top position from the parent object
        while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
                oParent = o.offsetParent  // Get parent object reference
                oTop += oParent.offsetTop // Add parent top position
                o = oParent
        }
        // Return top position
        return oTop
}
/* End dynamic menu */


function processOnLoadFunctions()
{
    for (var i = 0; i < onLoadFunctions.length; i++) {
        onLoadFunctions[i]();
    }
}

function getElementsByName_iefix(tag, name) {
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

function _sprintf(s)
{
    var re = /%/;
    var i = 0;
    while (re.test(s))
    {
       s = s.replace(re, _sprintf.arguments[++i]);
    }

    return s;
}

function passwordRequest(inputMail)
{
    var newElement = document.getElementById(inputMail);

    var newEmail = newElement.value;

    Ext.Ajax.request({
       url: 'index.php?fuse=admin&action=RequestPassword',
       success: function(t) {
            messageEmailSent(t);
       },
       params: {ajaxRequest:"1",
                emailToSend:newEmail
              }
    });

}

function messageEmailSent(t)
{
    unsetStatus(false);
    var response = t.responseText;
    document.getElementById('message').innerHTML = '<font class="redtext"><b>'+response+'</b></font>';
}


function check(form,x,submit)
{

	if (typeof submit == 'undefined') submit = true;

    script_name = "Form Validator ver 2.0";
    action =  "Checks Required, Integer and Date";
    cpyrght = "(c) 1998 - Art Lubin / Artswork";
    email = "perflunk@aol.com";
    var set_up_var = doall(script_name, cpyrght, email);
    var message = "";
    var more_message = "";
    if (set_up_var == 5872){
        x = x - 1;

        for (var i = 0; i <= x; i++) {

            if (typeof form.elements[i].name == 'undefined') {
                continue;
            }

            var messenger = form.elements[i].name;
            messenger = messenger.substring(0, 2);
            var fieldname = form.elements[i].name;
            fieldname = fieldname.substring(2);
            if((form.elements[i].name == "ccnumber" || form.elements[i].name == "ccmonth" || form.elements[i].name == "ccyear") && document.getElementById("creditcardinfo").style.display == "none")
            {
                form.elements[i].value = "";
            }

            var cctypes = null;
            if (messenger == "r_"){
                if (form.elements[i].value!=""){
                    more_message = r_check(form,x,fieldname,i);
                }
            }else if (messenger == "c_"){
                if (form.elements[i].value!=""){
                    //more_message = c_check(form,x,fieldname,i,false);
                    more_message = c_check(form,x,fieldname,i,true);        //blanks are allowed with this line
                    cctypes = form.elements['validcc'].value
                    if (more_message==""){more_message = CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i);}
                }
            }else if (messenger == "C_"){
                //same as case above but blanks are allowed
                if (form.elements[i].value!=""){
                    more_message = c_check(form,x,fieldname,i,true);
                    cctypes = form.elements['validcc'].value
                    if (more_message==""){more_message = CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i);}
                }
            }else if (messenger == "D_"){
                if (form.elements[i].value!=""){
                    more_message = D_check(form,x,fieldname,i);
                }
            }else if (messenger == "i_"){
                more_message = i_check(form,x,fieldname,i);
            }else if (messenger == "d_"){
                more_message = d_check(form,x,fieldname,i);
            }else if (messenger == "e_"){
                more_message = e_check(form,x,fieldname,i);
            }else if (messenger == "n_"){
                more_message = n_check(form, x, fieldname, i);
            }
            if (more_message != ""){
                if (more_message){
                    if (message == ""){
                        message = more_message;
                        more_message="";
                    }else{
                        message = message + "\n" + more_message;
                        more_message="";
                    }
                }
            }
        }

        if (message != ""){
            alert(lang("The following form field(s) were incomplete or incorrect")+":\n\n" + message + "\n\n"+lang("Please complete or correct the form and submit again."));
            return false;
        }else{
        
        	if (submit) {
	            submitonce(form);
	
	            // call form onsubmit event, if it exists
	            try {
	                form.onsubmit();
	            } catch(e) {
	            }
	
	            if (!submitted) {
	                form.submit();
	                submitted = true;
	            }
            }
            return true;
        }
    }else{
        alert ("The copyright information has been changed. \n In order to use this javascript please keep the copyright information intact. \n\n Script Name: Form Validator ver 2.0 \n Copyright: (c) 1998 - Art Lubin / Artswork \n Email: perflunk@aol.com");
        return false;
    }
}


function isNum(str)
{
    // 0.234, .234, 234, 234.234
    regexp = /(^\d+\.?\d*)|(^\d*\.?\d+)/;
    if (regexp.test(str)) return true;
    else return false;
}

function n_check(form, x, fieldname, i)
{
    var msg_addition = "";
    error=0;
    for (var y = 0; y <= x; y++) {
        if (form.elements[y].name == fieldname) break;
    }
    numberField = form.elements[y].value;
    if(!isNum(numberField)) {error = 1;} else {
        if (numberField.indexOf ('.3') > 1)  error = 1;
    }
    if (error == 1) msg_addition = form.elements[i].value;
    return(msg_addition);
}
function c_check(form,x,fieldname,i,blankallowed)
{
       /*************************************************************************\
       luhn check
       \*************************************************************************/
        var msg_addition = "";
        error=0;
        for (var y = 0; y <= x; y++){if (form.elements[y].name == fieldname) break;}
        CardNumber = form.elements[y].value;
        error = checkCCNumber(CardNumber, blankallowed);
        if (error == 1) {
            msg_addition = form.elements[i].value;
        }
        return(msg_addition);
}

function checkCCNumber(CardNumber, blankallowed)
{
   /*************************************************************************\
   luhn check
   \*************************************************************************/
    error = 0;
    if (CardNumber != "") {
        if (! isNum(CardNumber)) {
            error = 1;
        } else {
            var  no_digit = CardNumber.length;
            var oddoeven = no_digit & 1;
            var sum = 0;
            for (var count = 0; count < no_digit; count++) {
                var digit = parseInt(CardNumber.charAt(count));
                if (!((count & 1) ^ oddoeven)) {
                    digit *= 2;
                    if (digit > 9) digit -= 9;
                }
                sum += digit;
            }
            if (sum % 10 == 0) {
                error = 0;
            } else {
                error = 1;
            }
        }
    } else if (!blankallowed) {
        error = 1;
    }
    return(error);
}



function D_check(form,x,fieldname,i)
{
    for (var y = 0; y <= x; y++)
    {
            if (form.elements[y].name == fieldname) break;
    }
    var msg_addition = "";

    regexp = /^\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (regexp.test(form.elements[y].value))  error = 0;
    else{
         error=1;
    }

    if (error == 1) msg_addition = form.elements[i].value;
    return(msg_addition);
}

function r_check(form,x,fieldname,i)
{
        var msg_addition = "";
        new_fieldname = fieldname;
        for (var y = 0; y <= x; y++)
            {

                if ((form.elements[y].type == "radio" || form.elements[y].type == "checkbox") && form.elements[y].name == new_fieldname && form.elements[y].checked == true)
                    {
                            msg_addition = "";
                            break;
                    }
                else if ((form.elements[y].type == "radio" || form.elements[y].type == "checkbox") && form.elements[y].name == new_fieldname && form.elements[y].checked == false)
                    {
                        msg_addition = form.elements[i].value;
                    }

            else if (form.elements[y].type == "select-one")
                            {
                                var l = form.elements[y].selectedIndex;
                                if (form.elements[y].name == fieldname && form.elements[y].options[l].value != "")
                                    {
                                        msg_addition = "";
                                        break;
                                    }
                                else if (form.elements[y].name == fieldname && form.elements[y].options[l].value == "")
                                    {

                                        msg_addition = form.elements[i].value;

                                    }
                                }
         else if (form.elements[y].name == fieldname && form.elements[y].value == "" && form.elements[y].type != "radio" && form.elements[y].type != "checkbox" && form.elements[y].type != "select-one")
                            {

                                if(form.elements[y].name == 'UserName' || form.elements[y].name == 'Password'){
                                    msg_addition = "";
                                }else{
                                    msg_addition = form.elements[i].value;
                                    break;
                                }
                            }
                else if (form.elements[y].name == fieldname && form.elements[y].value != "" && form.elements[y].type != "radio" && form.elements[y].type != "checkbox" && form.elements[y].type != "select-one")
                            {
                                msg_addition = "";
                            }
                }
            return(msg_addition);
}


function i_check(form,x,fieldname,i)
{
        for (var y = 0; y <= x; y++)
            {
                if (form.elements[y].name == fieldname) break;
            }

    var msg_addition = "";
    var decimal = "";
    inputStr = form.elements[y].value.toString();

    if (inputStr == "")
        {
        }
    else
        {
            for (var c = 0; c < inputStr.length; c++)
                {
                    var oneChar = inputStr.charAt(c);
                    if (c == 0 && oneChar == "-" || oneChar == "."  && decimal == "")
                            {
                                if (oneChar == ".");
                                    {
                                        decimal = "yes";
                                    }
                                continue;

                            }
                                if (oneChar < "0" || oneChar > "9")
                                    {
                                        msg_addition = form.elements[i].value;
                                    }
                }
        }
        return(msg_addition);
}



function e_check(form,x,fieldname,i)
{
            for (var y = 0; y <= x; y++){if (form.elements[y].name == fieldname) break;}
            var msg_addition = "";
            regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;

            if (!regexp.test(form.elements[y].value)){
                msg_addition = form.elements[i].value;
            }

            return(msg_addition);
}

function d_check(form,x,fieldname,i)
{
        for (var y = 0; y <= x; y++)
            {
                if (form.elements[y].name == fieldname) break;
            }

        var msg_addition = "";
        var sDate = form.elements[y].value;
        var int_or_not = isInteger(form.elements[y].value);
        if (int_or_not == "true")
        {
                if ((!(form.elements[y].value.length >= 6)) || (!(form.elements[y].value.length <= 10)))
                {
                        msg_addition = form.elements[i].value;
                }
                else
                {
                     var SlashlPos = form.elements[y].value.indexOf("/",0);
                        if (SlashlPos > 0 && SlashlPos <= 2)
                            {
                                if (SlashlPos == 1)
                                    {
                                        if (form.elements[y].value.charAt(0) < 1 || form.elements[y].value.charAt(0) > 9)
                                            {
                                                msg_addition = form.elements[i].value;
                                            }
                                        else
                                            {
                                                if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/")))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && ((form.elements[y].value.charAt(2) >= 3 && form.elements[y].value.charAt(3) > 1) || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/"))))
                                                    {
                                                        msg_addition = form.elements[i].value + "hi";
                                                    }
                                                else if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && (((form.elements[y].value.charAt(2) > 3 && form.elements[y].value.charAt(3) != "/") || (((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/")) && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else
                                                    {
                                                        if ((form.elements[y].value.charAt(0) == 2 && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/") || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/")))))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else if (form.elements[y].value.charAt(0) == 2 && ((form.elements[y].value.charAt(2) > 2 && form.elements[y].value.charAt(3) != "/") || (((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/") && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else
                                                            {
                                                                if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/")))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && ((form.elements[y].value.charAt(2) >= 3 && form.elements[y].value.charAt(3) > 0) || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/"))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && (((form.elements[y].value.charAt(2) > 3 && form.elements[y].value.charAt(3) != "/") || ((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/") && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                            }
                                                    }
                                            }
                                    }
                                else
                                    {
                                        if (form.elements[y].value.charAt(0) > 1 || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) > 2) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 0))
                                            {
                                                msg_addition = form.elements[i].value;
                                            }
                                        else
                                            {
                                                if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/"))))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) >= 3 && form.elements[y].value.charAt(4) > 1) || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0) || form.elements[y].value.length < 7))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) > 3 && form.elements[y].value.charAt(4) != "/")   || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else
                                                    {
                                                        if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 2) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0)) || form.elements[y].value.length < 7) || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/")))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else if ((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 2) && ((form.elements[y].value.charAt(3) > 2 && form.elements[y].value.charAt(4) != "/") || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else
                                                            {
                                                                if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/"))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) >= 3 && form.elements[y].value.charAt(4) > 0) || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0) || form.elements[y].value.length < 7))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) > 3 && form.elements[y].value.charAt(4) != "/") || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                            }
                                                    }
                                            }
                                    }
                            }
            else
                            {
                                msg_addition = form.elements[i].value;
                            }
                    }
            }
        else
            {
                msg_addition = form.elements[i].value;
            }
        return(msg_addition);
}

function isInteger(sDate)
{
    var new_msg = true;
    inputStr = sDate.toString();
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i);
        if ((oneChar < "0" || oneChar > "9") && oneChar != "/")
                {
                    new_msg = false;
                }
        }
    return (new_msg);
}

function doall(script_name, copyright, email)
{
    var code = 0;
    var test = script_name + copyright + email;
    for (var a = 0; a < test.length; a++)
        {
        var each_char = test.charAt(a);
        var x = asc(each_char);
        code += x;
        }
    return (code);
}

function asc(each_char)
{
    var n = 0;
        var char_str = charSetStr();
        for (i = 0; i < char_str.length; i++)
            {
                if (each_char == char_str.substring(i, i+1))
                    {
                        break;
                    }
            }
        return i + 32;
}

function charSetStr()
{
        var str;
    str = ' !"#$%&' + "'" + '()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
        return str;
}


function CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i)
{
        for (var y = 0; y <= x; y++){if (form.elements[y].name == fieldname) break;}
        CardNumber = form.elements[y].value;
        
        return CheckAllowedCCTypes(CardNumber, cctypes);
}

function CheckAllowedCCTypes(CardNumber, cctypes)
{
        error=0;
        typeVisa   = checkCreditCard(CardNumber, 'Visa');
        typeMc     = checkCreditCard(CardNumber, 'MasterCard');
        typeAmex   = checkCreditCard(CardNumber, 'AmEx');
        typeDisc   = checkCreditCard(CardNumber, 'Discover');
        
        typeLaser  = checkCreditCard(CardNumber, 'LaserCard');
        typeDiners = checkCreditCard(CardNumber, 'DinersClub');
        typeSwitch = checkCreditCard(CardNumber, 'Switch');
        
        //c_1000000_ = visa
        //c_0100000_ = mastercard
        //c_0010000_ = americanexpress
        //c_0001000_ = discover
        
        //c_0000100_ = lasercard
        //c_0000010_ = dinersclub
        //c_0000001_ = switch
        
        if (typeVisa){
            if (cctypes.substr(0,1)=="0") return lang("Visa is not accepted at this time");
            else return '';
        }else if (typeMc){
            if (cctypes.substr(1,1)=="0") return lang("MasterCard is not accepted at this time");
            else return '';
        }else if (typeAmex){
            if (cctypes.substr(2,1)=="0") return lang("American Express is not accepted at this time");
            else return '';
        }else if (typeDisc){
            if (cctypes.substr(3,1)=="0") return lang("Discover is not accepted at this time");
            else return '';
        }else if (typeLaser){
            if (cctypes.substr(4,1)=="0") return lang("LaserCard is not accepted at this time");
            else return '';
        }else if (typeDiners){
            if (cctypes.substr(5,1)=="0") return lang("Diners Club is not accepted at this time");
            else return '';
        }else if (typeSwitch){
            if (cctypes.substr(6,1)=="0") return lang("Switch is not accepted at this time");
            else return '';
        }
}

/*================================================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on the web, although the 
best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia
Updated:    11th Sep. 2010      Typos removed from Diners and Solo definitions (thanks to Noe Leon)

*/

/*
   If a credit card number is invalid, an error reason is loaded into the global ccErrorNo variable. 
   This can be be used to index into the global error  string array to report the reason to the user 
   if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types as follows.
  
  //  Name:         As in the selection box of the form - must be same as user's
  //  Length:       List of possible valid lengths of the card number for the card
  //  prefixes:     List of possible prefixes for the card
  //  checkdigit:   Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305,36,38,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334,6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the length if all else was 
  // hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*================================================================================================*/

/*
function move(moveaction,movefrom,moveto)
{
    var moveto = document.getElementById(moveto);
    if(moveaction == 'remove') {
        for(x = 0;x<(document.getElementById(movefrom).length);x++) {
            if(document.getElementById(movefrom).options[x].selected) {
                with(moveto) {
                    options[options.length] = new Option(document.getElementById(movefrom).options[x].text,document.getElementById(movefrom).options[x].value);
                }
                document.getElementById(movefrom).options[x] = null;
                x = -1;
            }
        }
    }
    if(moveaction == 'add') {
        for(x = 0;x<(moveto.length);x++) {
            if(moveto.options[x].selected) {
                with(document.getElementById(movefrom)) {
                    options[options.length] = new Option(moveto.options[x].text,moveto.options[x].value);
                }
                moveto.options[x] = null;
                x = -1;
            }
        }
    }
    return true;
}*/

function cSelectTab(fuse,view,tabid,grouptabname,div,args,selectclassname)
{
	if(args==null){
		args="snapshot="+tabid
	}else{
		args+="&snapshot="+tabid
	}

    cToggleTabs(tabid,grouptabname,selectclassname);
    Ext.get(div).load({
        url: 'index.php?fuse='+fuse+'&view='+view,
        scripts: true,
        showLoadIndicator: false,
        params: args,
        text: ""
    });

    return false;
}

function cToggleTabs(tabid,grouptabname,selectclassname)
{
    //unselect tab
    items = getElementsByName_iefix("li",grouptabname);
    for(x=0;x<items.length;x++){
        items[x].className = "";
    }
    if(selectclassname != undefined){
        document.getElementById(tabid+"_tab").className = selectclassname;
    }else{
        document.getElementById(tabid+"_tab").className = "active";
    }
}


/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

	function RotateLeft(lValue, iShiftBits) {
		return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
	}

	function AddUnsigned(lX,lY) {
		var lX4,lY4,lX8,lY8,lResult;
		lX8 = (lX & 0x80000000);
		lY8 = (lY & 0x80000000);
		lX4 = (lX & 0x40000000);
		lY4 = (lY & 0x40000000);
		lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
		if (lX4 & lY4) {
			return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
		}
		if (lX4 | lY4) {
			if (lResult & 0x40000000) {
				return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			}
		} else {
			return (lResult ^ lX8 ^ lY8);
		}
 	}

 	function F(x,y,z) {return (x & y) | ((~x) & z);}
 	function G(x,y,z) {return (x & z) | (y & (~z));}
 	function H(x,y,z) {return (x ^ y ^ z);}
	function I(x,y,z) {return (y ^ (x | (~z)));}

	function FF(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function GG(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function HH(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function II(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};

	function ConvertToWordArray(string) {
		var lWordCount;
		var lMessageLength = string.length;
		var lNumberOfWords_temp1=lMessageLength + 8;
		var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
		var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
		var lWordArray=Array(lNumberOfWords-1);
		var lBytePosition = 0;
		var lByteCount = 0;
		while ( lByteCount < lMessageLength ) {
			lWordCount = (lByteCount-(lByteCount % 4))/4;
			lBytePosition = (lByteCount % 4)*8;
			lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
			lByteCount++;
		}
		lWordCount = (lByteCount-(lByteCount % 4))/4;
		lBytePosition = (lByteCount % 4)*8;
		lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
		lWordArray[lNumberOfWords-2] = lMessageLength<<3;
		lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
		return lWordArray;
	};

	function WordToHex(lValue) {
		var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
		for (lCount = 0;lCount<=3;lCount++) {
			lByte = (lValue>>>(lCount*8)) & 255;
			WordToHexValue_temp = "0" + lByte.toString(16);
			WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
		}
		return WordToHexValue;
	};

	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	};

	var x=Array();
	var k,AA,BB,CC,DD,a,b,c,d;
	var S11=7, S12=12, S13=17, S14=22;
	var S21=5, S22=9 , S23=14, S24=20;
	var S31=4, S32=11, S33=16, S34=23;
	var S41=6, S42=10, S43=15, S44=21;

	string = Utf8Encode(string);

	x = ConvertToWordArray(string);

	a = 0x67452301;b = 0xEFCDAB89;c = 0x98BADCFE;d = 0x10325476;

	for (k=0;k<x.length;k+=16) {
		AA=a;BB=b;CC=c;DD=d;
		a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
		d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
		c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
		b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
		a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
		d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
		c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
		b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
		a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
		d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
		c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
		b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
		a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
		d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
		c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
		b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
		a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
		d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
		c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
		b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
		a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
		d=GG(d,a,b,c,x[k+10],S22,0x2441453);
		c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
		b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
		a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
		d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
		c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
		b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
		a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
		d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
		c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
		b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
		a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
		d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
		c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
		b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
		a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
		d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
		c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
		b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
		a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
		d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
		c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
		b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
		a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
		d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
		c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
		b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
		a=II(a,b,c,d,x[k+0], S41,0xF4292244);
		d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
		c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
		b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
		a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
		d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
		c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
		b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
		a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
		d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
		c=II(c,d,a,b,x[k+6], S43,0xA3014314);
		b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
		a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
		d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
		c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
		b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
		a=AddUnsigned(a,AA);
		b=AddUnsigned(b,BB);
		c=AddUnsigned(c,CC);
		d=AddUnsigned(d,DD);
	}

	var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

	return temp.toLowerCase();
}

jQuery.extend(
    jQuery.expr[ ":" ],
    { reallyvisible : function (a) {
        return !(jQuery(a).is(":hidden") || jQuery(a).parents(":hidden").length || jQuery(a).css('display')=='none');
    }}
  );

/** LazyLoad makes it easy and painless to lazily load one or more external
JavaScript or CSS files on demand either during or after the rendering of a web
page.

Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile
Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and
are not officially supported.

Visit https://github.com/rgrove/lazyload/ for more info.

Copyright (c) 2011 Ryan Grove <ryan@wonko.com>
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@module lazyload
@class LazyLoad
@static
@version 2.0.1 (2011-03-05)
*/

LazyLoad = (function (win, doc) {
  // -- Private Variables ------------------------------------------------------

  // User agent and feature test information.
  var env,

  // Reference to the <head> element (populated lazily).
  head,

  // Requests currently in progress, if any.
  pending = {},

  // Number of times we've polled to check whether a pending stylesheet has
  // finished loading in WebKit. If this gets too high, we're probably stalled.
  pollCount = 0,

  // Queued requests.
  queue = {css: [], js: []},

  // Reference to the browser's list of stylesheets.
  styleSheets = doc.styleSheets;

  // -- Private Methods --------------------------------------------------------

  /**
  Creates and returns an HTML element with the specified name and attributes.

  @method createNode
  @param {String} name element name
  @param {Object} attrs name/value mapping of element attributes
  @return {HTMLElement}
  @private
  */
  function createNode(name, attrs) {
    var node = doc.createElement(name), attr;

    for (attr in attrs) {
      if (attrs.hasOwnProperty(attr)) {
        node.setAttribute(attr, attrs[attr]);
      }
    }

    return node;
  }

  /**
  Called when the current pending resource of the specified type has finished
  loading. Executes the associated callback (if any) and loads the next
  resource in the queue.

  @method finish
  @param {String} type resource type ('css' or 'js')
  @private
  */
  function finish(type) {
    var p = pending[type],
        callback,
        urls;

    if (p) {
      callback = p.callback;
      urls     = p.urls;

      urls.shift();
      pollCount = 0;

      // If this is the last of the pending URLs, execute the callback and
      // start the next request in the queue (if any).
      if (!urls.length) {
        if (callback) {
          callback.call(p.context, p.obj);
        }

        pending[type] = null;

        if (queue[type].length) {
          load(type);
        }
      }
    }
  }

  /**
  Populates the <code>env</code> variable with user agent and feature test
  information.

  @method getEnv
  @private
  */
  function getEnv() {
    // No need to run again if already populated.
    if (env) { return; }

    var ua = navigator.userAgent;

    env = {
      // True if this browser supports disabling async mode on dynamically
      // created script nodes. See
      // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
      async: doc.createElement('script').async === true
    };

    (env.webkit = /AppleWebKit\//.test(ua))
      || (env.ie = /MSIE/.test(ua))
      || (env.opera = /Opera/.test(ua))
      || (env.gecko = /Gecko\//.test(ua))
      || (env.unknown = true);
  }

  /**
  Loads the specified resources, or the next resource of the specified type
  in the queue if no resources are specified. If a resource of the specified
  type is already being loaded, the new request will be queued until the
  first request has been finished.

  When an array of resource URLs is specified, those URLs will be loaded in
  parallel if it is possible to do so while preserving execution order. All
  browsers support parallel loading of CSS, but only Firefox and Opera
  support parallel loading of scripts. In other browsers, scripts will be
  queued and loaded one at a time to ensure correct execution order.

  @method load
  @param {String} type resource type ('css' or 'js')
  @param {String|Array} urls (optional) URL or array of URLs to load
  @param {Function} callback (optional) callback function to execute when the
    resource is loaded
  @param {Object} obj (optional) object to pass to the callback function
  @param {Object} context (optional) if provided, the callback function will
    be executed in this object's context
  @private
  */
  function load(type, urls, callback, obj, context) {
    var _finish = function () { finish(type); },
        isCSS   = type === 'css',
        i, len, node, p, pendingUrls, url;

    getEnv();

    if (urls) {
      // If urls is a string, wrap it in an array. Otherwise assume it's an
      // array and create a copy of it so modifications won't be made to the
      // original.
      urls = typeof urls === 'string' ? [urls] : urls.concat();

      // Create a request object for each URL. If multiple URLs are specified,
      // the callback will only be executed after all URLs have been loaded.
      //
      // Sadly, Firefox and Opera are the only browsers capable of loading
      // scripts in parallel while preserving execution order. In all other
      // browsers, scripts must be loaded sequentially.
      //
      // All browsers respect CSS specificity based on the order of the link
      // elements in the DOM, regardless of the order in which the stylesheets
      // are actually downloaded.
      if (isCSS || env.async || env.gecko || env.opera) {
        // Load in parallel.
        queue[type].push({
          urls    : urls,
          callback: callback,
          obj     : obj,
          context : context
        });
      } else {
        // Load sequentially.
        for (i = 0, len = urls.length; i < len; ++i) {
          queue[type].push({
            urls    : [urls[i]],
            callback: i === len - 1 ? callback : null, // callback is only added to the last URL
            obj     : obj,
            context : context
          });
        }
      }
    }

    // If a previous load request of this type is currently in progress, we'll
    // wait our turn. Otherwise, grab the next item in the queue.
    if (pending[type] || !(p = pending[type] = queue[type].shift())) {
      return;
    }

    head || (head = doc.head || doc.getElementsByTagName('head')[0]);
    pendingUrls = p.urls;

    for (i = 0, len = pendingUrls.length; i < len; ++i) {
      url = pendingUrls[i];

      if (isCSS) {
        node = createNode('link', {
          charset: 'utf-8',
          'class': 'lazyload',
          href   : url,
          rel    : 'stylesheet',
          type   : 'text/css'
        });
      } else {
        node = createNode('script', {
          charset: 'utf-8',
          'class': 'lazyload',
          src    : url
        });

        node.async = false;
      }

      if (env.ie) {
        node.onreadystatechange = function () {
          var readyState = this.readyState;

          if (readyState === 'loaded' || readyState === 'complete') {
            this.onreadystatechange = null;
            _finish();
          }
        };
      } else if (isCSS && (env.gecko || env.webkit)) {
        // Gecko and WebKit don't support the onload event on link nodes. In
        // WebKit, we can poll for changes to document.styleSheets to figure out
        // when stylesheets have loaded, but in Gecko we just have to finish
        // after a brief delay and hope for the best.
        if (env.webkit) {
          p.urls[i] = node.href; // resolve relative URLs (or polling won't work)
          poll();
        } else {
          setTimeout(_finish, 50 * len);
        }
      } else {
        node.onload = node.onerror = _finish;
      }

      head.appendChild(node);
    }
  }

  /**
  Begins polling to determine when pending stylesheets have finished loading
  in WebKit. Polling stops when all pending stylesheets have loaded.

  @method poll
  @private
  */
  function poll() {
    var css = pending.css, i;

    if (!css) {
      return;
    }

    i = styleSheets.length;

    // Look for a stylesheet matching the pending URL.
    while (i && --i) {
      if (styleSheets[i].href === css.urls[0]) {
        finish('css');
        break;
      }
    }

    pollCount += 1;

    if (css) {
      if (pollCount < 200) {
        setTimeout(poll, 50);
      } else {
        // We've been polling for 10 seconds and nothing's happened, which may
        // indicate that the stylesheet has been removed from the document
        // before it had a chance to load. Stop polling and finish the pending
        // request to prevent blocking further requests.
        finish('css');
      }
    }
  }

  return {

    /**
    Requests the specified CSS URL or URLs and executes the specified
    callback (if any) when they have finished loading. If an array of URLs is
    specified, the stylesheets will be loaded in parallel and the callback
    will be executed after all stylesheets have finished loading.

    Currently, Firefox doesn't provide any way to reliably determine when a
    stylesheet has finished loading. In Firefox, the callback will be
    executed after a brief delay. For information on a manual technique you
    can use to detect when CSS has actually finished loading in Firefox, see
    http://wonko.com/post/how-to-prevent-yui-get-race-conditions (which
    applies to LazyLoad as well, despite being originally written in in
    reference to the YUI Get utility).

    @method css
    @param {String|Array} urls CSS URL or array of CSS URLs to load
    @param {Function} callback (optional) callback function to execute when
      the specified stylesheets are loaded
    @param {Object} obj (optional) object to pass to the callback function
    @param {Object} context (optional) if provided, the callback function
      will be executed in this object's context
    @static
    */
    css: function (urls, callback, obj, context) {
      load('css', urls, callback, obj, context);
    },

    /**
    Requests the specified JavaScript URL or URLs and executes the specified
    callback (if any) when they have finished loading. If an array of URLs is
    specified and the browser supports it, the scripts will be loaded in
    parallel and the callback will be executed after all scripts have
    finished loading.

    Currently, only Firefox and Opera support parallel loading of scripts while
    preserving execution order. In other browsers, scripts will be
    queued and loaded one at a time to ensure correct execution order.

    @method js
    @param {String|Array} urls JS URL or array of JS URLs to load
    @param {Function} callback (optional) callback function to execute when
      the specified scripts are loaded
    @param {Object} obj (optional) object to pass to the callback function
    @param {Object} context (optional) if provided, the callback function
      will be executed in this object's context
    @static
    */
    js: function (urls, callback, obj, context) {
      load('js', urls, callback, obj, context);
    }

  };
})(this, this.document);

CE.prototype.lazyLoad = function() {
	var last3Char,url;
    // best way to check if something is not an array
    if (Object.prototype.toString.apply(arguments[0]) !== '[object Array]') {
        arguments[0] = [arguments[0]];
    }
    for (var i = 0; i < arguments[0].length; i++) {
		//if last 3 chars are .js then do ?
		//else we need to assume there are other args and pass &
		url = arguments[0][i];
		last3Char = url.substr(url.length - 3);
		if (last3Char === ".js") {
			arguments[0][i] += '?ver=' + gVer;
		} else {
			arguments[0][i] += '&ver=' + gVer;		
		}
    }

    return LazyLoad.js.apply(null, arguments);
}

CE.prototype.getMonth = function(month,short)
{
	if (typeof(short) === "undefined") {
		short = false;
	}
	switch (month) {
		case 1:
			return (short) ? "Jan." : "January";
			exit;
		case 2:
			return (short) ? "Feb." : "February";
			exit;
		case 3:
			return (short) ? "Mar." : "March";
			exit;
		case 4:
			return (short) ? "Apr." : "April";
			exit;
		case 5:
			return (short) ? "May" : "May";
			exit;
		case 6:
			return (short) ? "June" : "June";
			exit;
		case 7:
			return (short) ? "July" : "July";
			exit;													
		case 8:
			return (short) ? "Aug." : "August";
			exit;			
		case 9:
			return (short) ? "Sept." : "September";
			exit;			
		case 10:
			return (short) ? "Oct." : "October";
			exit;			
		case 11:
			return (short) ? "Nov." : "November";
			exit;			
		case 12:
			return (short) ? "Dec." : "December";
			exit;			
	}
}

// IE Fix for createContextualFragment is undefined
// ToDo: Remove this when/if we upgrade extJS to 4.x
if (typeof Range != "undefined") {
    if (typeof Range.prototype.createContextualFragment == "undefined") {
        Range.prototype.createContextualFragment = function (html) {
            var doc = window.document;
            var container = doc.createElement("div");
            container.innerHTML = html;
            var frag = doc.createDocumentFragment(), n;
            while ((n = container.firstChild)) {
                frag.appendChild(n);
            }
            return frag;
        };
    }
}
