var winHelpHNDL = null;
var winUtilityHNDL = null;
var winDebug = null;

//Used for color changes in forms
var highlightcolor="lightYellow";
var ns6=document.getElementById&&!document.all;
var previous='';
var eventobj;
var intended=/INPUT|TEXTAREA|SELECT|OPTION/;

var isIE = false;
var isOther = false;
var isNS4 = false;
var isNS6 = false;
if(document.getElementById)
{
	if(!document.all)
	{
		isNS6=true;
	}
	if(document.all)
	{
		isIE=true;
	}
}
else
{
	if(document.layers)
	{
		isNS4=true;
	}
	else
	{
		isOther=true;
	}
}

// *************************************
// 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 setStatus(s, time) {
    s = '<center>'+s+'</center>';
    overlib(s, FOLLOWSCROLL, STICKY, NOCLOSE, RELX, -15, RELY, 0, TIMEOUT, time, FGCLASS, 'statusFGCLASS', BGCLASS, 'statusBGCLASS', TEXTFONTCLASS, 'statusTEXTFONTCLASS');
}
function resetStatus(s) {
    s = '<center>'+s+'</center>';
    overlib(s, FOLLOWSCROLL, STICKY, NOCLOSE, RELX, -15, RELY, 0, FGCLASS, 'resetstatusFGCLASS', BGCLASS, 'resetstatusBGCLASS', TEXTFONTCLASS, 'resetstatusTEXTFONTCLASS');
}
function unsetStatus(s, time) {
    cClick();
    if (s) {
        s = '<center>'+s+'</center>';
        overlib(s, FOLLOWSCROLL, 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+'&action='+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);       	
}



// 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;
}

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 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 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("document.getElementById('" + 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(intHelpID,features) {
  var strURL = "help.php?helpID="+intHelpID;	
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close(); 
  winHelpHNDL =  window.open(strURL,'winHelp',features);
}

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=""
			document.images[imgid].src="images/collapse.gif";
			document.cookie=cookiename+"=collapse";
		}else{
			document.images[imgid].src="images/expand.gif";
			which.style.display="none";
			document.cookie=cookiename+"=expand";
		}
	}

function hideshowCommon(which,imgid){
	if (!document.getElementById)  return
	if (which.style.display=="none"){
		which.style.display=""
	}else{
		which.style.display="none";
	}
}

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--;
        }
    }
    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 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;
  for (i=0; i<(args.length-2); i+=3) {
      if ((obj=MM_findObj(args[i]))!=null) {
          v=args[i+2];
          if (obj.style) {
              obj=obj.style;
              v=(v=='show')?'visible':(v=='hide')?'hidden':v;
          }
          obj.visibility=v;
      }
  }

 if (args[2]=='show') {
        obj.left =  getAbsoluteLeft(args[3])+"px";
        obj.top = getAbsoluteTop(args[3])+"px";
  }
}

function getAbsoluteLeft(objectId) {
        // Get an object left position from the upper left viewport corner
        // Tested with relative and nested objects

        o = document.getElementById(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 = 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
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/* End dynamic menu */

function lang(phrase)
{
    if (typeof language[phrase] != "undefined") {
        return language[phrase];
    }

    return phrase;
}

// *** 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;
}
