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

/**
* 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
});

/**
 * 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.updateEventCache = function() {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionCaches',
        params: {eventssession:$('#session_count').html(), eventstoday:$('#day_count').html()},
        success: function(response, params)
        {
            //ce.log(1,"Saved updateTicketsCache")
        }
    });
}

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

CE.prototype.updateWhoIsOnlineCache = function() {
    Ext.Ajax.request({
        url: 'index.php?fuse=clients&action=updateSessionCaches',
        params: {onlineusers: $('#onlineusers').html(), offlineusers: $('#offlineusers').html(),lastxseenstyle: $('#lastxseen').attr('style')},
        success: function(response, params)
        {
            //ce.log(1,"Saved updateWhoIsOnlineCacheache")
        }
    });
}
CE.prototype.showNewEvent = function(text,header,gravataremail){
        if (!header || header=="") {
            title = "Notice";
        } else {
            title = header;
        }

        if (gravataremail && gravataremail!="") {
            //https://secure.gravatar.com/avatar.php?gravatar_id=a9ce8f0b7217cc561809b2671ae28234size=80default=rating=PG&default=http://localhost/clientexec/images/defaultuserpic.jpg
            pathArray = window.location.pathname.split( '/' );
            newPathname = "";
            for ( var i = 0; i < pathArray.length -1 ; i++ ) {
            newPathname += "/";
            newPathname += pathArray[i];
            }

            defaultpicurl = window.location.protocol + "//" + window.location.host + "/" + newPathname + "/../images/defaultuserpic.jpg";
            $.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: 'http://www.gravatar.com/avatar.php?default='+defaultpicurl+'&gravatar_id=' + MD5(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){
        clearTimeout($('#msg-div').data('timeoutId'));
        $('#msg-div-inner').text(title);
        $('#msg-div').fadeIn('normal');
        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

//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) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

//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 openWindow(theURL,winName,features)
{
  window.open(theURL,winName,features);
}

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 (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);
    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]();
    }
}

// *** AUXILIARY FUNCTIONS *****
function getURLVar(varName)
{
    var input = unescape(location.search.substr(1));
    if (input) {
        var srchArray = input.split('&');
        var tempArray = new Array();
        for (var i = 0; i < srchArray.length; i++) {
            tempArray = srchArray[i].split('=');
            if (tempArray[0] == varName) {
                return tempArray[1];
            }
        }
    }

    return false;
}

// taken from the javascript bible
function isNumber(inputVal)
{
    var oneDecimal = false;
    inputStr = inputVal.toString();
    for (var i = 0; i < inputStr.length; i++) {
        var oneChar = inputStr.charAt(i);
        if (i == 0 && oneChar == '.') {
            continue;
        }
        if (oneChar == '.' && !oneDecimal) {
            oneDecimal = true;
            continue;
        }
        if (oneChar < '0' || oneChar > '9') {
            return false;
        }

        return true;
    }
}

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;
}

// Functions to escape strings.
// Can't use encodeURIComponent if document is not UTF-8.
// escape() works fine with ISO-8859-1 but will most likely break under other charsets,
// but this is the best we can do...
function _escapeString(str)
{
    var isUTF = (isIE && document.charset == 'utf-8') || (!isIE && document.characterSet == 'UTF-8');
    if (isUTF) {
        return encodeURIComponent(str);
    }

    return escape(str);
}

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)
{
    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."));
        }else{
            submitonce(form);

            // call form onsubmit event, if it exists
            try {
                form.onsubmit();
            } catch(e) {
            }

            if (!submitted) {
                form.submit();
                submitted = 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");
    }
}


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;
        if (CardNumber != ""){
            if (! isNum(CardNumber)) {error=1;}
            var  no_digit = CardNumber.length;
            var oddoeven = no_digit & 1;
            var sum = 0;
            if (error==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;
            }
            if (error == 1) msg_addition = form.elements[i].value;
        }else if (!blankallowed) 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 = "";

    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)
{
        var msg_addition = "";
        error=0;
        for (var y = 0; y <= x; y++){if (form.elements[y].name == fieldname) break;}
        var msg_addition = "";
        CardNumber = form.elements[y].value;
        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 if (typeMc){
            if (cctypes.substr(1,1)=="0") return lang("MasterCard is not accepted at this time");
        }else if (typeAmex){
            if (cctypes.substr(2,1)=="0") return lang("American Express is not accepted at this time");
        }else if (typeDisc){
            if (cctypes.substr(3,1)=="0") return lang("Discover is not accepted at this time");
        }else if (typeLaser){
            if (cctypes.substr(4,1)=="0") return lang("LaserCard is not accepted at this time");
        }else if (typeDiners){
            if (cctypes.substr(5,1)=="0") return lang("Diners Club is not accepted at this time");
        }else if (typeSwitch){
            if (cctypes.substr(6,1)=="0") return lang("Switch is not accepted at this time");
        }
}


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

/*

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;
}

// *************************************
// CUSTOMER NOTES FUNCTIONS
// *************************************
function loadClientNotes(customerGroup, includeArchived)
{
    if (!customerGroup) {
        customerGroup = 0;
    }

    new Ajax.Updater(   'clientNotes',
                        'index.php?fuse=clients&view=GetClientNotes&customerGroup='+customerGroup+'&includeArchived=' + (includeArchived? 1 : 0),
                        {
                            onLoading   : function(request) {resetStatus(lang('Loading Notes'))},
                            onComplete  : function(request) {unsetStatus(false)}
                        }
    );
}

function deleteNote(noteId,calledfromfuse,selectedId)
{
    if (!confirm(lang('Are you sure you wish to delete this note?\nBe aware that if the note is linked to a ticket type, all tickets of that type won\'t show this note anymore.'))) {
        return;
    }

    if(selectedId==null) selectedId = 0;

    new Ajax.Request(   'index.php?fuse=clients&action=deleteClientNote',
                        {
                            method      : 'post',
                            parameters  : 'noteId=' + noteId + '&calledfromfuse=' + calledfromfuse + '&selectedId=' + selectedId,
                            onLoading   : function(request) {resetStatus(lang('Deleting Note'))},
                            onComplete  : completedDeleteNote
                        }
    );
}

function completedDeleteNote(responseObj)
{
    unsetStatus(false)

    var responseArr = responseObj.responseText.split('|');

    if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        alert(responseObj.responseText);
    }

	//need to check where I deleted from
    if(responseArr[2] == "client"){
	    //if from client profile
    	loadClientNotes(responseArr[1]);
    }else{
    	//if from support module
    	loadStaffNotesInSupport(responseArr[3]);
    }
}

//General function to shoot out the async function performed on invoices
function PerformAsyncAction(bolShowStatus,items,fuse,action,successfunc,extraargs,ignoreErrors)
{
    if (bolShowStatus){
        setStatus('Working ...');
    }

    var args = 'items='+items;
    if(extraargs!="") args = args+"&"+extraargs;

    var opt = {
         method: 'post',
         postBody: args,
         onSuccess: eval(successfunc)
    }
    new Ajax.Request('index.php?fuse='+fuse+'&action='+action, opt);
}

//only used by switching tab function cSelectTab
function PerformAsyncUpdater(bolShowStatus,items,fuse,view,extraargs,mydiv)
{
   mydiv = mydiv || 'activesnapshot';

   var args = 'items='+items+'&mydiv='+mydiv;
   if(extraargs!="") {
       args = args+"&"+extraargs;
   }

   /*
   var opt = {
         method: 'post',
         postBody: args,
         onComplete:function(){
             if(document.getElementById('message')) {document.getElementById('message').focus();}
             if(document.getElementById('initialsnapshot')) {document.getElementById('initialsnapshot').innerHTML=""}
         },
         evalScripts:true,
         asynchronous:true
    }
    new Ajax.Updater(mydiv, 'index.php?fuse='+fuse+'&view='+view, opt);
    */

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

}

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: ""
    });

    //PerformAsyncUpdater(true,"",fuse,view,args,div);
    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();
}

Ext.onReady(function(){
   Ext.QuickTips.init();
});

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

//http://wonko.com/post/lazyload-200-released
//LazyLoad=function(){var f=document,g,b={},e={css:[],js:[]},a;function j(l,k){var m=f.createElement(l),d;for(d in k){if(k.hasOwnProperty(d)){m.setAttribute(d,k[d])}}return m}function h(d){var l=b[d];if(!l){return}var m=l.callback,k=l.urls;k.shift();if(!k.length){if(m){m.call(l.scope||window,l.obj)}b[d]=null;if(e[d].length){i(d)}}}function c(){if(a){return}var k=navigator.userAgent,l=parseFloat,d;a={gecko:0,ie:0,opera:0,webkit:0};d=k.match(/AppleWebKit\/(\S*)/);if(d&&d[1]){a.webkit=l(d[1])}else{d=k.match(/MSIE\s([^;]*)/);if(d&&d[1]){a.ie=l(d[1])}else{if((/Gecko\/(\S*)/).test(k)){a.gecko=1;d=k.match(/rv:([^\s\)]*)/);if(d&&d[1]){a.gecko=l(d[1])}}else{if(d=k.match(/Opera\/(\S*)/)){a.opera=l(d[1])}}}}}function i(r,q,s,m,t){var n,o,l,k,d;c();if(q){q=q.constructor===Array?q:[q];if(r==="css"||a.gecko||a.opera){e[r].push({urls:[].concat(q),callback:s,obj:m,scope:t})}else{for(n=0,o=q.length;n<o;++n){e[r].push({urls:[q[n]],callback:n===o-1?s:null,obj:m,scope:t})}}}if(b[r]||!(k=b[r]=e[r].shift())){return}g=g||f.getElementsByTagName("head")[0];q=k.urls;for(n=0,o=q.length;n<o;++n){d=q[n];if(r==="css"){l=j("link",{href:d,rel:"stylesheet",type:"text/css"})}else{l=j("script",{src:d})}if(a.ie){l.onreadystatechange=function(){var p=this.readyState;if(p==="loaded"||p==="complete"){this.onreadystatechange=null;h(r)}}}else{if(r==="css"&&(a.gecko||a.webkit)){setTimeout(function(){h(r)},50*o)}else{l.onload=l.onerror=function(){h(r)}}}g.appendChild(l)}}return{css:function(l,m,k,d){i("css",l,m,k,d)},js:function(l,m,k,d){i("js",l,m,k,d)}}}();
LazyLoad=function(){function r(c,b){c=i.createElement(c);var a;for(a in b)b.hasOwnProperty(a)&&c.setAttribute(a,b[a]);return c}function k(c){var b=h[c],a,e;if(b){a=b.callback;e=b.urls;e.shift();l=0;if(!e.length){if(a)a.call(b.context||window,b.obj);h[c]=null;j[c].length&&m(c)}}}function w(){if(!d){var c=navigator.userAgent,b=parseFloat,a;d={gecko:0,ie:0,opera:0,webkit:0};if((a=c.match(/AppleWebKit\/(\S*)/))&&a[1])d.webkit=b(a[1]);else if((a=c.match(/MSIE\s([^;]*)/))&&a[1])d.ie=b(a[1]);else if(/Gecko\/(\S*)/.test(c)){d.gecko=
1;if((a=c.match(/rv:([^\s\)]*)/))&&a[1])d.gecko=b(a[1])}else if(a=c.match(/Opera\/(\S*)/))d.opera=b(a[1])}}function m(c,b,a,e,s){var n=function(){k(c)},o=c==="css",f,g,p;w();if(b){b=b.constructor===Array?b:[b];if(o||d.gecko&&d.gecko<2||d.opera)j[c].push({urls:[].concat(b),callback:a,obj:e,context:s});else{f=0;for(g=b.length;f<g;++f)j[c].push({urls:[b[f]],callback:f===g-1?a:null,obj:e,context:s})}}if(!(h[c]||!(p=h[c]=j[c].shift()))){q=q||i.head||i.getElementsByTagName("head")[0];b=p.urls;f=0;for(g=
b.length;f<g;++f){a=b[f];a=o?r("link",{charset:"utf-8","class":"lazyload",href:a,rel:"stylesheet",type:"text/css"}):r("script",{charset:"utf-8","class":"lazyload",src:a});if(d.ie)a.onreadystatechange=function(){var t=this.readyState;if(t==="loaded"||t==="complete"){this.onreadystatechange=null;n()}};else if(o&&(d.gecko||d.webkit))if(d.webkit){p.urls[f]=a.href;u()}else setTimeout(n,50*g);else a.onload=a.onerror=n;q.appendChild(a)}}}function u(){var c=h.css,b;if(c){for(b=v.length;--b;)if(v[b].href===
c.urls[0]){k("css");break}l+=1;if(c)l<200?setTimeout(u,50):k("css")}}var i=document,q,h={},l=0,j={css:[],js:[]},v=i.styleSheets,d;return{css:function(c,b,a,e){m("css",c,b,a,e)},js:function(c,b,a,e){m("js",c,b,a,e)}}}();