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 isSafari = false;
var isOpera = false;

var submitted = false;

var onLoadFunctions = new Array();

document.onmousemove = getMouseXY;

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

isSafari = (document.childNodes && !document.all && !navigator.taintEnabled && !navigator.accentColorName)? true : false;
isOpera = navigator.userAgent.toLowerCase().indexOf("opera") != -1;
isIE7 = isIE && document.documentElement && typeof document.documentElement.style.maxHeight!="undefined";

/**
* Sets mouseX and mouseY coords
*/
function getMouseXY(e)
{
    // When page hasn't finished loading this will produce an error,
    // so I wrap in a harmless try-catch
    try {
        if (document.all) {
            _mousePosX = event.clientX + document.body.scrollLeft;
            _mousePosY = event.clientY + document.body.scrollTop;
        } else {
            //window.status = 'x='+e.pageX+' y='+e.pageY;
            _mousePosX = e.pageX;
            _mousePosY = e.pageY;
        }
    } catch (e) {
    }
   
}

// *************************************
// AJAX FUNCTIONS
// *************************************
//setStatus after AJAX events or any other take place
function on404(t){
    alert('Error 404: location "' + t.statusText + '" was not found.');
}

function onFailure(t){
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

function on12152(t){
    // ignore this error, only produced by IE very occasionaly when fetching the snapshot counters in the dashboard
}

function on12002(t){
    // idem
}

function setStatus(s, time) {
    s = '<center>'+s+'</center>';
    overlib(s, FOLLOWSCROLL, FOLLOWSCROLLREFRESH, 1, STICKY, NOCLOSE, RELX, -15, RELY, 0, TIMEOUT, time, FGCLASS, 'statusFGCLASS', BGCLASS, 'statusBGCLASS', TEXTFONTCLASS, 'statusTEXTFONTCLASS');
}
function resetStatus(s) {
    s = '<center>'+s+'</center>';
    overlib(s, FOLLOWSCROLL, FOLLOWSCROLLREFRESH, 1, STICKY, NOCLOSE, RELX, -15, RELY, 0, FGCLASS, 'resetstatusFGCLASS', BGCLASS, 'resetstatusBGCLASS', TEXTFONTCLASS, 'resetstatusTEXTFONTCLASS');
}
function unsetStatus(s, time) {
    try {
        cClick();
    } catch (e) {
    }
    if (s) {
        s = '<center>'+s+'</center>';
        overlib(s, FOLLOWSCROLL, FOLLOWSCROLLREFRESH, 1, STICKY, NOCLOSE, RELX, -15, RELY, 0, TIMEOUT, time, FGCLASS, 'unsetstatusFGCLASS', BGCLASS, 'unsetstatusBGCLASS', TEXTFONTCLASS, 'unsetstatusTEXTFONTCLASS');
    }

    return true;
}

// functions to show success or error messages comming from the action
handlerFunc = function(t) {
    if(t.responseText!="") setStatus(t.responseText, 1000);
}

errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

function tableNav(page,tableid,limit,orderby,ordersort,isdelete,updatelimit,fuse,action,linksid,extraVars)
{
    if(isdelete== '') { isdelete = false;}
    if (limit == '') { limit = $('limit_c').value; }
    if (orderby == '') { orderby = $('orderby_c').value; }
    totalrecs = $('totalrecs_c').value;
    if (ordersort == '') { ordersort = $('osort_c').value; } 
    var pars =  'fuse='+fuse+'&view='+action+'&page='+page+'&tableid='+tableid+'&numRecs='+limit+'&orderSort='+ordersort;
    if ((typeof extraVars != 'undefined') && extraVars != '') {
        pars+= '&'+extraVars;
    }
    if(isdelete) { pars += '&delete=true&delid='+isdelete; }
    if (orderby != '') {   pars += '&orderBy='+orderby; }
    totalPages = Math.ceil(totalrecs/limit);
    if (updatelimit != '') {
        pars += '&updatelimit=' + limit;
    }
    if (($('islastpage_c').value == 1) && (page < totalPages) && (isdelete)) {
      totalPages = totalPages -1;
    }
    
    new Ajax.Updater(tableid, 'index.php',{onLoading:function(request){resetStatus(lang('Loading'))}, onComplete:function(request){genNavLinks(totalrecs, totalPages, page, tableid, linksid, limit, fuse, action, extraVars);unsetStatus(lang('Loaded'),1000)}, method: 'get', parameters:pars, asynchronous:true});
}

// Set Navigation links, numbered or slider nav bar in lists
function genNavLinks(totalRecs, numPages, currentPage, tableId, target, limit, fuse, action, extraVars)
{
    var prevLink;
    var nextLink;
    var tHREF;
    var numLink = '';
    var j;
    var k;
    if (typeof extraVars == 'undefined') {
        extraVars = '';
    }

    if (Math.ceil(currentPage) > 1) {
        prevLink = "<td valign=\"top\"><input type=\"button\" class=\"button_large\" onclick=\"tableNav(" + ((currentPage)-1) + ", '" + tableId + "', '', '', '', '','','"+fuse+"','"+action+"','"+target+"','"+extraVars+"')\" value=\"&lt;&lt;&nbsp;"+lang('Previous')+"\" /></td>\n";
    } else {
        prevLink = "<td valign=\"top\"><input type=\"button\" class=\"button_large\" disabled=\"true\" style=\"filter:alpha(opacity=50);-moz-opacity:0.4\" value=\"&lt;&lt;&nbsp;"+lang('Previous')+"\" /></td>\n";
    }
    if (Math.ceil(numPages) > 5) {
       numLink += "<td valign=\"top\" onMouseDown=\"showsliderStatus();\"><div class=\"slider\" id=\"slider-1\" tabIndex=\"1\" onMouseUp=\"hidesliderStatus('"+fuse+"', '"+action+"', '"+target+"', '"+tableId+"', '"+extraVars+"');\">\n";
       numLink += "<input class=\"slider-input\" id=\"slider-input-1\" name=\"slider-input-1\" type=\"text\"/></div>\n";
       numLink += "<input type=\"hidden\" id=\"inputthepage\" value=\"\"><input type=\"hidden\" id=\"inputslid\" value=\"\">\n";
       numLink += "<input type=\"hidden\" id=\"max_inputslid\" value=\"" + numPages +"\">\n";
       numLink += "<input type=\"hidden\" id=\"orig_inputslid\" value=\""+ currentPage + "\">\n";
       numLink += "<div id=\"thepage\" style=\"position:relative; left:0px; top:-40px; height:15px;  filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);-moz-opacity:0.0; background-color: #F3B35A;\" align=\"center\">dfdfdf</div></td>\n"; 
    } else {
        j = (Math.ceil(currentPage) - 5);
        if (j <= 0) { j = 1;}
        k = (Math.ceil(currentPage) + 5);
        if (k >= Math.ceil(numPages)) { k = numPages; }
        for(i = j; i <= k; i++) {
            tHREF = "href=\"javascript:tableNav(" + i + ", '" + tableId + "', '', '', '', '','','"+fuse+"','"+action+"','"+target+"', '"+extraVars+"')\"";
            if (i != currentPage) {
                numLink += "<td><span class=\"tablenavpagelink\"><a " + tHREF + ">" + i + "</a></span></td>\n";
            } else {
                numLink += "<td><span class=\"tablenavpagelink-active\">" + i + "</span></td>\n";
            }
        }
    }
    if (currentPage < numPages) {
        nextLink = "<td valign=\"top\"><input type=\"button\" class=\"button_large\" onclick=\"tableNav(" + (Math.ceil(currentPage) + 1) + ", '" + tableId + "', '', '', '', '','','"+fuse+"','"+action+"','"+target+"','"+extraVars+"')\" value=\""+lang('Next')+"&nbsp;&gt;&gt;\" /></td>";
    } else {
        nextLink = "<td valign=\"top\"><input type=\"button\"  class=\"button_large\" disabled=\"true\" style=\"filter:alpha(opacity=50);-moz-opacity:0.4\" value=\""+lang('Next')+"&nbsp;&gt;&gt;\" /></td>";
    }       
     theTarget = $(target);
     theTarget.innerHTML = "<table cellpading=\"0\" cellspacign=\"0\" border=\"0\"><tr>"+ prevLink + numLink + nextLink + "</tr></table>";
     if (Math.ceil(numPages) > 5) {
        slid(totalRecs, numPages, currentPage, limit);
     }

     // might not be any buttons
     try {
         ToggleButtons(document.forms[tableId]);
     } catch (e) {}
}

function DeleteSelection(tableid, fuse, action, linksid)
{
    var selItems;
    var delids = '';
    //items returned coma delimited
    var cb = 'cb_' + tableid;
    selItems = GetSelectedItems(document.forms[tableid], cb).split(',');
    for(i=0;i<selItems.length;i++) {
        //remove from dom using effect
        new Effect.Fade('row_'+selItems[i]);
        $('cb_'+selItems[i]).checked=false;
         //remove from db using ajax
        delids += selItems[i].split('_')[1];
        if (i<(selItems.length-1)) { delids += '|';}
    }
    var page = $('page_c').value;
    var lastpage = $('islastpage_c').value;
    var limit = $('limit_c').value;
    var displayed = $('displayedrecs_c').value; 
    if ((lastpage == 1) && (page != 1) && (displayed == selItems.length)) {
        page = page-1;
    }
    return tableNav(page, tableid, '', '', '', delids,'',fuse, action, linksid);        
}

function toggleAllTickets(tableid)
{
    var tagname =document.getElementsByTagName('input');
    form = document.forms['troubletickets'];
    check = form.allbox.checked;
    if(check) {
        for(var i = 0; i < tagname.length; i++) {
            tagname[i].checked = true;
        }
    } else {
        for(var i = 0; i < tagname.length; i++) {
            tagname[i].checked = false;
        }
    }
    ToggleButtons(document.forms[tableid]);
}

// slider functions
function showsliderStatus () {
    new Effect.Opacity('thepage', { duration: 0.0, from: 1.0, to: 1.0 });
}

function hidesliderStatus(fuse, action, linksid,tableid, extraVars)
{
    new Effect.Opacity('thepage',
            { duration: 0.0, 
              from: 1.0, to: 0.0 })
    tableNav($("inputthepage").value, tableid, '', '', '', '','',fuse,action,linksid,extraVars); 
}

// generate slider in lists
function slid(totalRecs, numPages, currentPage, limit) {
    if ($('max_inputslid').value > 5) {
        if ($('inputslid').value == "") {
            $('inputslid').value = $('orig_inputslid').value ;    
            var s = new Slider($("slider-1"),
                    $("slider-input-1"));
                    s.setMinimum(1);
                    s.setMaximum($('max_inputslid').value);
                    s.setValue($('orig_inputslid').value);
                    topLimit = Math.ceil(s.getValue() * limit);
                    if (topLimit > totalRecs) {
                        topLimit = totalRecs;    
                    }
                    $("thepage").innerHTML = "Record " + Math.ceil(Math.ceil(Math.ceil(s.getValue() * limit) - Math.ceil(limit))+1) + " to " + topLimit + " of " + totalRecs;   
        s.onchange = function () {
                    $("inputthepage").value =  s.getValue();
                    topLimit = Math.ceil(s.getValue() * limit);
                    if (topLimit > totalRecs) {
                        topLimit = totalRecs;    
                    }
                    $("thepage").innerHTML = "Record " + Math.ceil(Math.ceil(Math.ceil(s.getValue() * limit) - Math.ceil(limit))+1) + " to " + topLimit + " of " + totalRecs;
        }
        }
    } else {
        return false;
    }
};

function P7_hideSelect(a){ //v1.0 by PVII
  var g,h=(a==1)?"hidden":"visible";
  if(document.getElementsByTagName){
  g=document.getElementsByTagName("select");
  if(g){for(var i=0;i<g.length;i++){
  g[i].style.visibility=h;
  }}}
}

//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 $(id).options[$(id).selectedIndex].value
}

function ToggleButtons(form)
{
    //determine if we want to make buttons opaque and 
    //disabled if no items are selected to perform action on
    if(ItemSelected(form, '', true)) {
        new Effect.Opacity('AForm1_delete',
            { duration: 0.0,              
              from: 1.0, to: 1.0 });    
        $('AForm1_delete').disabled=false;
    } else {
        new Effect.Opacity('AForm1_delete',
            { duration: 0.0, 
              from: 0.4, to: 0.4 });
        $('AForm1_delete').disabled=true;             
    }
} 

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 GetSelectedItems(form, fieldname){
    var tagname =document.getElementsByTagName('input');
    var returnArray = "";
    
    if(fieldname) {
        for(var i = 0; i < tagname.length; i++) {
            if(tagname[i].type == "checkbox") {
                if (tagname[i].name.indexOf(fieldname) != -1) {
                    if(tagname[i].checked) {
                        if (returnArray=="") returnArray = tagname[i].value;
                        else returnArray = returnArray+","+tagname[i].value;
                    }
                }
            }
        }
    } else {
        intCount = form.elements.length;
        for(x=1;x<=intCount;x++){
        if(form.elements[x-1].checked){
            if (returnArray=="") returnArray = form.elements[x-1].value;
            else returnArray = returnArray+","+form.elements[x-1].value;
        }
        }
    }
    return returnArray;
}
        
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

/*
Access Layer Style Properties
Jim Cummins - http://www.conxiondesigns.com
Required components:  Javascript Browser Sniff 1.0
*/
function aLs(layerID)
{
var returnLayer;
    if(isIE)
    {
        returnLayer = eval("document.all." + layerID + ".style");
    }
    if(isNS6)
    {
        returnLayer = eval("$('" + layerID + "').style");
    }
    if(isNS4)
    {
        returnLayer = eval("document." + layerID);
    }
    if(isOther)
    {
        returnLayer = "null";
        alert("-[Error]-\nDue to your browser you will probably not\nbe able to view all of the following page\nas it was designed to be viewed. We regret\nthis error sincerely.");
    }
return returnLayer;
}


<!--hide from old browsers
//Regular expression to highlight only form elements


//Function to check whether element clicked is form element
function checkel(which){
    if (which.style&&intended.test(which.tagName)){
        if (ns6&&eventobj.nodeType==3) { eventobj=eventobj.parentNode.parentNode; }
        return true;
    } else { return false; }
}

//Function to highlight form element
function highlight(e){
    eventobj=ns6? e.target : event.srcElement
    if (previous!=''){
        if (checkel(previous)){ previous.style.backgroundColor=''; }
        previous=eventobj;
        if (checkel(eventobj)){ eventobj.style.backgroundColor=highlightcolor; }
    }else{
        if (checkel(eventobj)){ eventobj.style.backgroundColor=highlightcolor; }
        previous=eventobj;
    }
}

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 get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) {
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}

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 nameWin()
{
    window.name = "launcher";
}

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 changeFuseDescription(text)
{
    if(document.all){
        fusedescription.innerText=text;
    }
}

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

function isEmpty(s){
  return ((s == null) || (s.length == 0));
}

function isDigit (c){
  return ((c >= "0") && (c <= "9"));
}

function isFloat (s){
  var i;
  var seenDecimalPoint = false;
  var decimalPointDelimiter = "."  
  if (isEmpty(s))
    if (isFloat.arguments.length == 1) return false;
    else return (isFloat.arguments[1] == true);
  if (s == decimalPointDelimiter) return false;
  for (i = 0; i < s.length; i++){
    var c = s.charAt(i);
    if ((c == decimalPointDelimiter) && !seenDecimalPoint)
          seenDecimalPoint = true;
    else if (!isDigit(c)) return false;
  }
  return true;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

// *** 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 debug(str)
{
    if (!winDebug) {
        winDebug = window.open('', 'debugging', 'width=400, height=500, scrollbars=yes, resizable=yes');
        winDebug.document.write('<pre>\n');
    }
    winDebug.document.write(str + '\n');    
}

/* Used for snapshot menu */
function addClassName(el, sClassName)
{
    var s = el.className;
    var p = s.split(" ");
    var l = p.length;
    for (var i = 0; i < l; i++) {
        if (p[i] == sClassName)
            return;
    }
    p[p.length] = sClassName;
    el.className = p.join(" ");

}

function removeClassName(el, sClassName)
{
    var s = el.className;
    var p = s.split(" ");
    var np = [];
    var l = p.length;
    var j = 0;
    for (var i = 0; i < l; i++) {
        if (p[i] != sClassName)
            np[j++] = p[i];
    }
    el.className = np.join(" ");
}

/* Used for dynamic menu */
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  if(args[4]!=null){
  	bgimage = args[4];
  	$(args[3]).style.backgroundImage = "url("+bgimage+")"; 	
  }  
 if (args[2]=='show') {
  		$(args[0]).style.visibility = "visible"; 
        $(args[0]).style.left =  getAbsoluteLeft(args[3])+"px";
        $(args[0]).style.top = eval(getAbsoluteTop(args[3])+28)+"px";        
  }else{
  	$(args[0]).style.visibility = "hidden";
  	$(args[3]).style.backgroundImage = "";  
  }
}

function getAbsoluteLeft(objectId) {
        // Get an object left position from the upper left viewport corner
        // Tested with relative and nested objects

        o = $(objectId)
        oLeft = o.offsetLeft            // Get left 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
                oLeft += oParent.offsetLeft // Add parent left position
                o = oParent
        }
        // Return left postion
        return oLeft
}

function getAbsoluteTop(objectId) {
        // Get an object top position from the upper left viewport corner
        // Tested with relative and nested objects
        o = $(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 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);
}

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 = $(inputMail);
    
    var newEmail = newElement.value;
    
    var opt = {
     	 onSuccess	: messageEmailSent,
     	 onLoading  : function() {resetStatus(lang('Loading'));}
    }

    new Ajax.Request('index.php?fuse=admin&action=RequestPassword&ajaxRequest=1&emailToSend='+newEmail, opt);
   
}

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

function changeCheckBox(parent, checkBox, grandParent)
{
    var parentChecked   = $(parent);
    var currentDiv = $(checkBox);
    var siblingDivs = 0;
    
    if(parentChecked.checked){
        while(currentDiv = currentDiv.nextSibling) {
    
            if(currentDiv.nodeName == "DIV"){
                var newArrayCollection = currentDiv.getElementsByTagName("input");
                newArrayCollection[0].disabled = false;
            }
            siblingDivs++;
        }
    } else if( !parentChecked.checked ) {
        newElement = $(grandParent);
        var newArrayCollectionImg = newElement.getElementsByTagName("img");
        
        var newArrayCollection = newElement.getElementsByTagName("input");
        if(newArrayCollection.length > 1){
            if(!deletePermissions()) {
                parentChecked.checked = true;
                return false;
            }else{
                newArrayCollectionImg[0].style.display = "";
            }
        }

        for(var i=1; i < newArrayCollection.length; i++) {
            newArrayCollection[i].disabled = true;
            newArrayCollection[i].checked  = false;
        }   
    }
}


function deletePermissions()
{
    if (confirm(lang('By disabling this permission you will disable all permissions that depend on it. \n \n Are you sure you want to do this?'))) {
        return true;
    }
    return false;
}

function viewSubPermissions(element)
{
    var currentDiv = $(element);

    while(currentDiv = currentDiv.nextSibling) {
        if(currentDiv.nodeName == "DIV") {
            if(!currentDiv.style.display) {
                currentDiv.style.display="none";   
            }else{
                currentDiv.style.display="";  
            } 
        }
    }
}

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

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

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

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

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

    return strAlertMessageArr;
}

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;
    }
    var msg_addition = "";
    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;  }
        var msg_addition = "";
        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;
        visa = isVisa(CardNumber);
        mc = isMasterCard(CardNumber);
        amex = isAmericanExpress(CardNumber);
        disc = isDiscover(CardNumber);
        //c_1000_ = visa
        //c_0100_ = mastercard
        //c_0010_ = americanexpress
        //c_0001_ = discover
        if (visa){
            if (cctypes.substr(0,1)=="0") return lang("Visa is not accepted at this time");
        }else if (mc){
            if (cctypes.substr(1,1)=="0") return lang("MasterCard is not accepted at this time");
        }else if (amex){
            if (cctypes.substr(2,1)=="0") return lang("American Express is not accepted at this time");
        }else if (disc){
            if (cctypes.substr(3,1)=="0") return lang("Discover is not accepted at this time");
        }
}

/*  ================================================================
    FUNCTION:  isVisa()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid VISA number.

          false, otherwise

    Sample number: 4111 1111 1111 1111 (16 digits)
    ================================================================ */

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))  return true;
  return false;
}  // END FUNCTION isVisa()

/*  ================================================================
    FUNCTION:  isMasterCard()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid MasterCard
            number.

          false, otherwise

    Sample number: 5500 0000 0000 0004 (16 digits)
    ================================================================ */

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5))) return true;
  return false;

} // END FUNCTION isMasterCard()





/*  ================================================================
    FUNCTION:  isAmericanExpress()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid American
            Express number.

          false, otherwise

    Sample number: 340000000000009 (15 digits)
    ================================================================ */

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7))) return true;
  if ((cc.length == 16) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7))) return true;
  return false;

} // END FUNCTION isAmericanExpress()


/*  ================================================================
    FUNCTION:  isDiscover()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Discover
            card number.

          false, otherwise

    Sample number: 6011000000000004 (16 digits)
    ================================================================ */

function isDiscover(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011")) return true;
  return false;

} // END FUNCTION isDiscover()

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

function selAll(target)
{
    var target = $(target);
    var targetOptions = target.options;
    var targetLength = targetOptions.length;
    for (var i = 0; i < targetLength; i++) {
        targetOptions[i].selected = true;
    }
}

// *************************************
// RICH TEXT EDITOR FUNCTIONS
// *************************************
function showRichTextEditor(objName, width, height, buttonArr, textareaId, mode)
{
    if (isSafari) {
        return;
    }

    if (typeof mode == "undefined") {
        mode = "HTML";
    }

    eval(objName + " = new InnovaEditor('" + objName + "')");
    var tempEditorObj = eval(objName);
    tempEditorObj.width = width;
    tempEditorObj.height = height;

    /***************************************************
        RECONFIGURE TOOLBAR BUTTONS
    ***************************************************/
    tempEditorObj.features = buttonArr; // => Custom Button Placement

    /***************************************************
        OTHER SETTINGS
    ***************************************************/
    tempEditorObj.mode = mode; //Editing mode. Possible values: "HTMLBody" (default), "XHTMLBody", "HTML", "XHTML"

    tempEditorObj.REPLACE(textareaId);
}

function selectPlainTextTab(hrefObj, areaId)
{
    var ulChildren = hrefObj.parentNode.parentNode.getElementsByTagName("li");
    ulChildren[0].className = '';
    ulChildren[1].className = 'selected';
    $('richTextWrapper_' + areaId).style.display = 'none';
    $(areaId + '[1]').style.display = 'block';
}

function selectHTMLTab(hrefObj, areaId)
{
    var ulChildren = hrefObj.parentNode.parentNode.getElementsByTagName("li");
    ulChildren[0].className = 'selected';
    ulChildren[1].className = '';
    $(areaId + '[1]').style.display = 'none';
    $('richTextWrapper_' + areaId).style.display = 'block';
}


// *************************************
// JAVASCRIPT POPUPS FUNCTIONS
// Based on Chris Campbell's lightbox script
// found at http://particletree.com
// *************************************
var lightbox;
function jsPopup(content, isURL)
{
	bod                 = document.getElementsByTagName('body')[0];
	overlay             = document.createElement('div');
	overlay.id          = 'overlay';
	lb                  = document.createElement('div');
	lb.id               = 'lightbox';
	lb.className        = 'loading';
	lb.innerHTML        = '<div id="lbLoadMessage">' +
						  '<p>Loading</p>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);

    lightbox = Class.create();

    lightbox.prototype = {

        yPos : 0,
        xPos : 0,

        initialize: function(content, isURL) {
            this.content = content;
            if (typeof isURL == 'undefined') {
                isURL = true;
            }
            this.isURL = isURL;
            this.activate();
        },
        
        // Turn everything on - mainly the IE fixes
        activate: function(){
            if (isIE){
                this.getScroll();
                this.prepareIE('100%', 'hidden');
                this.setScroll(0,0);
                if (!isIE7) {
                    this.hideSelects('hidden');
                }
            }
            this.displayLightbox("block");
        },
        
        // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
        prepareIE: function(height, overflow){
            bod = document.getElementsByTagName('body')[0];
            bod.style.height = height;
            bod.style.overflow = overflow;
      
            htm = document.getElementsByTagName('html')[0];
            htm.style.height = height;
            htm.style.overflow = overflow; 
        },
        
        // In IE, select elements hover on top of the lightbox
        hideSelects: function(visibility){
            selects = document.getElementsByTagName('select');
            for(i = 0; i < selects.length; i++) {
                selects[i].style.visibility = visibility;
            }
        },
        
        // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
        getScroll: function(){
            if (self.pageYOffset) {
                this.yPos = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop){
                this.yPos = document.documentElement.scrollTop; 
            } else if (document.body) {
                this.yPos = document.body.scrollTop;
            }
        },
        
        setScroll: function(x, y){
            window.scrollTo(x, y); 
        },
        
        displayLightbox: function(display){
            $('overlay').style.display = display;
            $('lightbox').style.display = display;
            if(display != 'none') this.loadInfo();
        },
        
        loadInfo: function() {
            if (this.isURL) {
                var myAjax = new Ajax.Request(  this.content,
                                                {
                                                    method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)
                                                }
                            );
            } else {
                this.showPopup(this.content);
            }
            
        },
        
        // Display Ajax response
        processInfo: function(response){
            this.showPopup(response.responseText);
        },

        showPopup: function(strContent){
            info = "<div id='lbContent'>" + strContent + "</div>";
            new Insertion.Before($('lbLoadMessage'), info)
            $('lightbox').className = "done";	
            this.actions();			
        },
        
        // Search through new links within the lightbox, and attach click event
        actions: function(){
            lbActions = document.getElementsByClassName('lbAction');

            for(i = 0; i < lbActions.length; i++) {
                Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
                lbActions[i].onclick = function(){return false;};
            }

        },
        
        save: function(e){
           link = Event.element(e).parentNode;
           Element.remove($('lbContent'));
         
           var myAjax = new Ajax.Request(   link.href,
                                            {
                                                    method      : 'post',
                                                    parameters  : "",
                                                    onComplete  : this.processInfo.bindAsEventListener(this)
                                            }
                        );
         
        },
        
        deactivate: function(){
            Element.remove($('lbContent'));
            
            if (isIE){
                this.setScroll(0,this.yPos);
                this.prepareIE("auto", "auto");
                if (!isIE7) {
                    this.hideSelects("visible");
                }
            }
            
            this.displayLightbox("none");
        }
    }

    valid = new lightbox(content, isURL);
}

// *************************************
// CUSTOMER NOTES FUNCTIONS
// *************************************

function submitNote(form)
{
    if (form.noteContent.value == '') {
        alert(lang('Note is empty'));
        return;
    }

    var ticketTypes = "";
    for (i = 0; i < form.ticketTypes.options.length; i++) {
        if (form.ticketTypes.options[i].selected) {
            ticketTypes += "&ticketTypes[]=" + form.ticketTypes.options[i].value;
        }
    }

    var content = encodeURIComponent(form.noteContent.value);

    new Ajax.Request(   'index.php?fuse=clients&action=SaveClientNote',
                        {
                            method      : 'post',
                            parameters  : 'customerGroup=' + form.customerGroup.value + '&noteContent=' + content + '&visibleCustomer=' + (form.visibleCustomer.checked? '1' : '0') + '&associateTicketTypes=' + (form.associateTicketTypes.checked? '1' : '0') + ticketTypes,
                            onLoading   : function(){resetStatus(lang('Saving'))},
                            onComplete  : completedSubmitNote
                        }
                    );
}

function completedSubmitNote(responseObj)
{
    unsetStatus(false);

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

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

    // dunno why I have to use prototype here or else it won't work...
    lightbox.prototype.deactivate();

    if ($('clientNotes')) {
        loadClientNotes(responseArr[1]);
    }
}

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

function toggleTicketTypesCombo(checkbox)
{
    if (checkbox.checked) {
        $('tdTicketTypesCombo').style.display = '';
    } else {
        $('tdTicketTypesCombo').style.display = 'none';
    }
}

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

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

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

function PerformAsyncUpdater(bolShowStatus,items,fuse,view,extraargs,mydiv)
{
   mydiv = mydiv || 'activesnapshot';
   
   if (bolShowStatus){
        setStatus(lang('Working ...'));
   }

   var args = 'items='+items+'&mydiv='+mydiv;
   if(extraargs!="") {
       args = args+"&"+extraargs;
   }
   
   var opt = {
         method: 'post',
         postBody: args,
         onComplete:function(){if($('initialsnapshot')) {$('initialsnapshot').innerHTML=""};unsetStatus('', 1);},
         on404: on404,
         evalScripts:true,
         asynchronous:true,
         onFailure: onFailure
    }
    new Ajax.Updater(mydiv, 'index.php?fuse='+fuse+'&view='+view, opt);
}

function cSelectTab(fuse,view,tabid,grouptabname,div,args)
{
	if(args==null){ 
		args="snapshot="+tabid
	}else{
		args+="&snapshot="+tabid
	}
	
    cToggleTabs(tabid,grouptabname);               
    PerformAsyncUpdater(true,"",fuse,view,args,div);
    return false;    
}

function cToggleTabs(tabid,grouptabname)
{
    //unselect tab
    items = getElementsByName_iefix("li",grouptabname);
    for(x=0;x<items.length;x++){
        items[x].className = "";        
    }
    $(tabid+"_tab").className = "selected";         
}

   function ToggleSideBar()
    {
        // the table-cell and table-column things are not very coherent, but it's the only way
        // I could have Opera work

        if($('sidepanel1').style.display=='none') {
            if (isOpera) {
                $('sidepanel1').style.display='table-cell';
            } else {
                $('sidepanel1').style.display='';
            }
        } else {
            $('sidepanel1').style.display='none';
        }

        if($('sidepanel2').style.display=='none') {
            if (isOpera) {
                $('sidepanel2').style.display='table-column';
            } else {
                $('sidepanel2').style.display='';
            }
        } else {
            $('sidepanel2').style.display='none';
        }

        var newdisplay = $('sidepanel2').style.display;

        var opt = {
            method      : 'post',
            postBody    : 'display='+newdisplay,
            on404       : on404,
            onFailure   : onFailure
        }

        new Ajax.Request('index.php?fuse=clients&action=ToggleSideBar', opt);

        return false;
    }

    function toggleMenu(strMenu)
    {
        if (strMenu == 'main') {
            $('mainMenu').style.display = 'block';
            var selectedMenu = 'main';
            $('adminMenu').style.display = 'none';
            $('adminTab').className = '';
            $('mainTab').className = 'selected';
        } else if (strMenu == 'admin') {
            $('mainMenu').style.display = 'none';
            $('adminMenu').style.display = 'block';
            var selectedMenu = 'admin';
            $('adminTab').className = 'selected';
            $('mainTab').className = '';
        } else {
            alert('Error #2348: invalid strMenu');
        }

        var opt = {
            method      : 'post',
            postBody    : 'selectedMenu='+selectedMenu,
            on404       : on404,
            onFailure   : onFailure
        }

        new Ajax.Request('index.php?fuse=admin&action=ToggleMenu', opt);

        return false;
    }

    function submitToView()
    {        
        var view = $('view').value;
        $('searchForm').action = 'index.php?fuse=clients&view=' + view;
        $('searchForm').submit();
        return false;
    }

    // Event object processor for NN4, IE4+, NN6
    function isEnterKey(evt) {
        evt = (evt) ? evt : (window.event) ? window.event : "";
        var theKey;
        if (evt) {
            theKey = (evt.which) ? evt.which : evt.keyCode;
        }
        return (theKey == 13);
    }
    
    function processOnEnter(evt) {
        if (isEnterKey(evt)) {
            return submitToView();
        }
        return true;
    }    
    
function NEIsChar (Data)
{
	varChars = "éèàùûôoöëabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";	
	var isChar = true;
	var index = 0;
	while ((index < Data.length) && (isChar))
    {
     	isChar = (varChars.indexOf(Data.charAt(index)) != -1);
     	index ++;
    }
	
	if (!isChar)
    {     	
     	return false;
    }else{
    	return true;
    }
}    

// *************************************
// KNOWLEDGE BASE FUNCTIONS
// USED IN DIFFERENT PLACES
// *************************************
var lastsent="";
var request=0;

function setKBRequest(t)
{
    if (document.getElementById('ajaxLoader')) {
        $('ajaxLoader').style.display = 'none';
    } else {
        unsetStatus('', 1);   
    }

    var newcontent = "";

	if(t.responseText!=""){
    	var responseArr = t.responseText.split('|');    	
    	if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        	alert(t.responseText.stripTags());
        	return;
    	}
        if (responseArr[1] == "") {
            return;
        }

        newcontent = responseArr[1];    	
	}	

    $('kb_wrap').innerHTML = newcontent;   
    if (document.getElementById('kb_wrap_wrap')) {
        $('kb_wrap_wrap').style.display = "block";
    }
}

function sendKBRequest(str,public, path)
{
	if(str=="")return;
	lastsent=str;
	request++;

    var timeStamp = new Date();

    if (document.getElementById('ajaxLoader')) {
        $('ajaxLoader').style.display = 'block';
    } else {
        resetStatus(lang('Loading'));
    }

    if (document.getElementById('latestArticles')) {
        $('latestArticles').style.display = 'none';
    }

    new Ajax.Request(path + 'index.php?request='+request+'&fuse=knowledgebase&subject='+encodeURIComponent(str)+'&view=KB_AutoSuggestion'+(public? '&public=1' : '')+'&path='+encodeURIComponent(path),
        {
            onSuccess   : setKBRequest
        });	
}

function loadKBArticles(e, inputField, public, path)
{
	var str = ltrim(inputField.value);

    if(str == lastsent || str == "") {
        return; 
    }

    var lastChar = str.substr(str.length -1);
    if (lastChar != " ") {
        setTimeout("checkIfTypingStopped('"+inputField.id+"','"+str+"',"+public+",'"+path+"')", 500);
    } else {
        sendKBRequest(str, public, path);
    }
}

function checkIfTypingStopped(fieldName, str, public, path)
{
    if ($(fieldName).value != str) {
        return;
    }

    sendKBRequest(str, public, path);
}

function showRichTextEditorForSettings(areaId, isDual)
{
    var fieldId = isDual? areaId + '[0]' : areaId;
    showRichTextEditor("oEdit" + areaId, 650, '250px',
                        [
                            'Undo','Redo','|','Hyperlink','|','JustifyLeft','JustifyCenter','JustifyRight','JustifyFull','|','Numbering','Bullets','|','LTR','RTL','|','XHTMLFullSource','StyleAndFormatting','TextFormatting','ListFormatting','BoxFormatting','ParagraphFormatting','CssText','|','FontName','FontSize','|','Bold','Italic','Underline','|','ForeColor','BackColor'
                        ],
                        "value_" + fieldId);
}
