var old_octet = ['', '', '', ''];
var selected = null;
var current_ns_element = null;
var current_ns_function = null;
var IE=0, NS=0;
var blnDOM = false, blnIE4 = false, blnNN4 = false;
var popup_window;
var temp_popup_window; // PopUp Window that will close when the page is changed
var temp_popup_windows = new Array(); // PopUp Windows that will close when the page is changed
// global timeout for setTimeouts
var timeout = '';

/* SLIDER SPECIFIC VARIABLES (TS) */

var g_iLastMousePosX = 0;
var g_strSelectedSlider = null;
var g_iSelectedSliderNum = null;
var g_bMouseIsDown = false;
var g_iLastPosition = null;



function Handle_Down(e)
{
	if(document.all)
		el = window.event.srcElement;
	else
		el = e.target;

	if(((el.id.indexOf("slider")) == 0) && (el.tagName == "IMG") && (el.src.indexOf("/images/slider_point.gif") != -1))
    {
       start = 13;
       var name = "scana_"+el.id.substring(start, el.id.indexOf("_", start))+"_level";
	   
	   g_iSelectedSliderNum = el.id.substring(el.id.length - 1, el.id.length);
	   
       g_strSelectedSlider = name;
	   g_iLastPosition = g_iSelectedSliderNum;

	   if(document.all)
		   ev = window.event;
	   else
		   ev = e;

		g_bMouseIsDown = true;

	   g_iLastMousePosX = ev.clientX;
    }

	return(false);
}

function Handle_Up(e)
{
	g_bMouseIsDown = false;

	return(false);
}

function Handle_Move(e)
{
	if(!g_bMouseIsDown)
		return;

	if(document.all)
		ev = window.event;
	else
		ev = e;
	
	currentX = ev.clientX;

	diffX = currentX - g_iLastMousePosX;

	spaces = diffX / 11;
	spaces = parseFloat(spaces);
	if((spaces + parseFloat(g_iSelectedSliderNum)) > 10)
	{
		spaces = 10 - g_iSelectedSliderNum;
	}
	else if((parseFloat(g_iSelectedSliderNum) + spaces) < 0)
		spaces = 0 - g_iSelectedSliderNum;

	currentPosition = parseFloat(g_iSelectedSliderNum) + parseFloat(spaces);
	currentPosition = Math.round(currentPosition);

	scana_level_slide(currentPosition, g_strSelectedSlider);

	return(false);
}

function Handle_Slider()
{
}

/* SLIDER SPECIFIC STUFF */

function check_scana_level_value(value, name) {
  for (var i=0; i< scana_level_values[name].length; i++) {
    if (value == scana_level_values[name][i]) {
      return 1;
    }
  }
  return 0;
}

// use this function instead of getElementById if you have a named element
// that has the same name value as an id'd elements id.  IE might return 
// the element with the name=id, instead of with the id=id.
function IE_workaround_getelementbyid(id)
{
    var obj = document.getElementById(id);
    if(obj)
    {
      // if the browser gives us what we want, return it.
      if(obj.attributes['id'] && obj.attributes['id'].value == id)
      {
        return obj;
      }
      else if(document.all)
      {
        //otherwise if it's IE and we have document.all try to find the object that way
        for(var lcv=1; lcv < document.all[id].length; lcv++)
        {
          if(document.all[id][lcv].attributes['id'] && document.all[id][lcv].attributes['id'].value == id)
          {
            return document.all[id][lcv];
          }
        }
      }
    }
    return null;
}

function scana_level_slide(value, name, invalid_warning_str) {
  value = value.toString();
  var original_value = value;
  if (!invalid_warning_str) {
    invalid_warning_str = 'is not a valid value ... restoring';
  }
  var decimal_pos = value.indexOf('.');
  var decimal_part = 0;
  if (decimal_pos >= 0) {
    decimal_part = value.substring(decimal_pos + 1);
    value = value.substring(0, decimal_pos);
  }
  if (!check_scana_level_value(value, name) ||
      decimal_part - 0 != decimal_part ||
      decimal_part < 0 ||
      decimal_part > 9999) {
    // turn __ into ":" for var name
    var id = -1;
    if (-1 >= 0) {
      for (var i=0; i< document.f.elements.length; i++) {
        if (document.f.elements[i].name == "UPDATE_"+name) {
          document.f.elements[i].value = scana_level_content[name];
        }
      }
    }
    else {
	  elem = IE_workaround_getelementbyid("UPDATE_"+name);
	  elem.value = scana_level_content[name];
    }

    alert('"'+ original_value + '" ' + invalid_warning_str);
    return false;
  }
  if (scana_level_value[name]) {
    scana_level_value[name].style.backgroundImage = "url(\"/images/slider_hash.gif\")";
  }
  scana_level_value[name] = IE_workaround_getelementbyid('slider_'+name+'_'+value);
  if (-1 >= 0) {
    for (var i=0; i<document.f.elements.length; i++) {
      if (document.f.elements[i].name == "UPDATE_"+name) {
        scana_level_content[name] = document.f.elements[i].value = original_value;
      }
    }
  }
  else {
    elem = IE_workaround_getelementbyid("UPDATE_"+name);
	elem.value = original_value;
  }
  scana_level_value[name].style.backgroundImage = "url(\"/images/slider_point.gif\")";
  return true;
}

// Detect the browser
IE  = (-1 != navigator.appVersion.indexOf("MSIE")) ? 1 : 0;
NS  = ("Netscape" == navigator.appName) ? 1 : 0;

if (document.getElementById) blnDOM = true;
else if (document.layers) { blnNN4 = true;}
else if (document.all) blnIE4 = true;

document.onkeypress = ns_keypresscheck;
document.onkeydown = ns_keydowncheck;
document.onkeyup = ns_keyupcheck;

/* Given a button Id, replace its display value with 'text' */
function replaceButtonText(buttonId, newText)
{
    var button = document.getElementById(buttonId);
    if (button.value) {
        button.value = newText;
    }
}

function encode_url (sUrl) {
    return escape(sUrl).replace(/\+/g, '%2C').replace(/\"/g, '%22').replace(/\'/g, '%27');
}

function backup_test_popup() {
    new_window=window.open("/cgi-mod/backup_test.cgi");
    if (new_window && window.focus) {
        new_window.focus();
    }
    return false;
}

// put the focus in the user input field if it's empty
// otherwise, do not change the focus
function focus_on_empty(input_obj) {
    if(!input_obj.value) {
        input_obj.focus();
    }
}

function popup(primary_tab, secondary_tab, width, height) {
    // All vars past secondary tab are 'key', 'value' pairs.
    // 'key' is what you want passed to the popup.
    // 'value' is either the value you want passed, or the name of the form
    // element you want interpolated to have its value passed.  (prepend
    // interpolated vars with __)

    var args = [];

    // width and height are optional and numeric keys aren't allowed.
    if (typeof width == 'number') {
        w = width;
        h = height;
    } else {
        w = 750;
        h = 520;
    }
    
    for (var i = 0; i < arguments.length; i++) {
        args[i] = arguments[i];
    }
    args.push(
        'user', '__user',
        'password', '__password',
        'et', '__et',
        'locale', '__locale'
    );
    var variables = [];
    var notresizable = 0;
    for (var i = 2; i < args.length; i += 2) {
        if (typeof args[i] == 'number') {
            continue;
        }
        if (args[i+1].substring(0,2) == '__') {
            // Removes leading __ (substr from pos 2 - end)
            var arg = args[i+1].substring(2,args[i+1].length);
            var value;
            for (var j=0; j < document.f.elements.length; j++) {
               var elt = document.f.elements[j];
                if (elt.type == "radio" && ! elt.checked) {
                   continue;
                }
                if (elt.name != arg) {
                   continue;
                }
                variables[i] = escape(args[i]) + '=' + escape(document.f.elements[j].value) ;
            }
        } else {
            if (args[i] == 'notresizable') {
                if (args[i+1] && args[i+1] != '0' && args[i+1] != 'false') {
                    notresizable = 1;
                }
            } else {
                variables[i] = escape(args[i]) + '=' + escape(args[i+1]);
            }
        }
    }
    variables.unshift(
        "/cgi-mod/index.cgi?",
        "primary_tab=" + primary_tab,
        "secondary_tab=" + secondary_tab,
        "content_only=1"
    )
    var href_string = variables.join('&');
    ex_open_popup_window(href_string, w, h, "", "", 0, 0, 0, 0, notresizable);
    //return false;
}

function goto_screen( primary_tab, secondary_tab, help_screen, help_title_lid, help_transcreen, extra_query
 )
{
        var user = '';
        var password = '';
        var et = '';
        var auth_type = '';
        var locale = '';

        // Collect the variables to build our URL
        for( var i=0; i<document.f.elements.length; i++ )
        {
                if( document.f.elements[i].name == "user")
                {
                        user = escape(document.f.elements[i].value);
                }
                if( document.f.elements[i].name == "password")
                {
                        password = escape(document.f.elements[i].value);
                }
                if( document.f.elements[i].name == "et")
                {
                        et = escape(document.f.elements[i].value);
                }
                if( document.f.elements[i].name == "auth_type")
                {
                        auth_type = escape(document.f.elements[i].value);
                }
                if( document.f.elements[i].name == "locale")
                {
                        locale = escape(document.f.elements[i].value);
                }
        }

        // Open up our desired screen
        var url = "/cgi-mod/index.cgi?user="+user+"&password="+password+"&et="+et+"&auth_type="+auth_type+
"&locale="+locale+"&primary_tab="+primary_tab+"&secondary_tab="+secondary_tab+"&"+extra_query;
        window.location=url;

        // If they want to show the help then pop it up too
        if( help_screen )
        {
                new_window=window.open("/cgi-mod/view_help.cgi?locale="+locale+"&screen="+help_screen+"&title="+help_title_lid
+"&transcreen="+help_transcreen, 'help', 'width=500,height=400,scrollbars=yes,resizable=1');
                if( new_window && window.focus )
                {
                        new_window.focus();
                }
        }

        return false;
}

function ldap_test_popup(domain, user, password, et) {
  var email = '';
  var host = '';
  var port = '';
  var tls_mode = '';
  var tls_require = '';
  var username = '';
  var pass = '';
  var filter = '';
  var searchbase = '';
  var unique_attr = '';
  var email_attr = '';
  for (var i=0; i<document.f.elements.length; i++) {
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_email") {
      email = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_host") {
      host = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_port") {
      port = document.f.elements[i].value;
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_tls_mode" && document.f.elements[i].checked == true) {
      tls_mode = document.f.elements[i].value;
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_tls_require" && document.f.elements[i].checked == true) {
      tls_require = document.f.elements[i].value;
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_username") {
      username = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_password") {
      pass = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_filter") {
      filter = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_searchbase") {
      searchbase = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_unique_attr") {
      unique_attr = escape(document.f.elements[i].value);
    }
    if (document.f.elements[i].name == "UPDATE_mta_ldap_advanced_email_attr") {
      email_attr = escape(document.f.elements[i].value);
    }
  }
  new_window=window.open("/cgi-bin/ldap_test.cgi?host="+host+"&port="+port+"&user="+user+"&password="+password+"&et="+et+"&tls_mode="+tls_mode+"&tls_require="+tls_require+"&username="+username+"&pw="+pass+"&filter="+filter+"&searchbase="+searchbase+"&unique_attr="+unique_attr+"&email_attr="+email_attr+"&domain="+domain+"&email="+email, "ldap_test", "width=600,height=500");
  if (new_window && window.focus) {
    new_window.focus();
  }
  return false;
}

function confirm_ldap_test() {
  if (!confirm('Please confirm that you have successfully tested the LDAP configuration by pressing the test button at the end of this row')) {
    return false;
  }
  else {
    return true;
  }
}

/**
 * This is used to create a new browsing window which contains the smtp
 * testing cgi script. It takes several parameters from the document currently
 * being viewed and passes these as URL parameters to the script.
 */
function smtp_test_popup(domain, index, hostname, default_domain, locale, user, password, et) {
  var email = '';
  var host = '';
  var port = '';
  var use_mx = 0;

  for (var i=0; i<document.f.elements.length; i++) {
    // Get the email address
    if (document.f.elements[i].name == "UPDATE_mta_relay_advanced_email" ||
        document.f.elements[i].name == "UPDATE_mta_outbound_relay_email:" + index) {

        email = document.f.elements[i].value;
    }

    // Get the host
    if (document.f.elements[i].name == "UPDATE_mta_relay_advanced_host" ||
        document.f.elements[i].name == "UPDATE_mta_outbound_relay_host:" + index) {

        host = document.f.elements[i].value;
    }

    // Get the port
    if (document.f.elements[i].name == "UPDATE_mta_relay_advanced_port" ||
        document.f.elements[i].name == "UPDATE_mta_outbound_relay_port:" + index) {

        port = document.f.elements[i].value;
    }

    // Use MX lookup?
    if ( (document.f.elements[i].name == "UPDATE_mta_relay_advanced_use_mx" ||
        document.f.elements[i].name == "UPDATE_mta_outbound_relay_use_mx:"  + index) &&
        document.f.elements[i].value == "Yes" &&
        document.f.elements[i].checked) {
        use_mx = 1;
    }
  }

  // Create the popup window
  new_window=window.open("/cgi-mod/smtp_test.cgi?locale="+locale+"&host="+host+"&port="+port+"&domain="+domain+"&email="+email+"&hostname="+hostname+"&default_domain="+default_domain+"&user="+user+"&password="+password+"&et="+et+"&use_mx="+use_mx, "smtp_test", "width=600,height=550");

  // Focus the new window
  if (new_window && window.focus) {
    new_window.focus();
  }
  
  return false;
}

/**
 * this is smtp testing for web filter
 *
 */
function webfilter_smtp_test(host, port, alertemail, threatemail, contactemail, locale, user, pwd, et) {
  var email_list = alertemail + ',' + threatemail + ',' + contactemail;
//  var url_test = '/cgi-bin/mail_test.cgi?locale='+locale+'&host='+host+'&port='+port+'&email='+email_list+'&user='+user+'&password='+pwd+'&et='+et;
  new_window=window.open("/cgi-bin/mail_test.cgi?locale="+locale+"&host="+host+"&port="+port+"&email="+email_list+"&user="+user+"&password="+pwd+"&et="+et, "SMTP_Test","width=600,height=550");
//  new_window=window.open(url_test,"smtp_test","width=600,height=550");
  // Focus the new window
  if (new_window && window.focus) {
    new_window.focus();
  }
  return false;
}

function archiver_smtp_test_popup(domain, email, hostname, default_domain, locale, user, password, et) {
	var host = '';
	var port = '';

	for (var i=0; i<document.f.elements.length; i++) {
		if (document.f.elements[i].name == "UPDATE_notification_relay_host") {
	      host = document.f.elements[i].value;
	    }
	    if (document.f.elements[i].name == "UPDATE_alerts_email_address") {
	      email = document.f.elements[i].value;
	    }
	    if (document.f.elements[i].name == "UPDATE_notification_relay_port") {
	      port = document.f.elements[i].value;
	    }
	}

	var args = {
		"host"			 : host,
		"port" 			 : port,
		"domain" 		 : domain,
		"email"  		 : email,
		"hostname" 		 : hostname,
		"default_domain" : default_domain,
		"locale" 		 : locale,
		"user"			 : user,
		"password" 		 : password,
		"et"	 		 : et
	}
	actual_smtp_test_popup(args);
}


function basic_smtp_test_popup(domain, email, hostname, default_domain, locale, user, password, et) {
	var host = '';
	var port = '';

	for (var i=0; i<document.f.elements.length; i++) {
		if (document.f.elements[i].name == "UPDATE_mta_relay_host") {
	      host = document.f.elements[i].value;
	    }
	    if (document.f.elements[i].name == "UPDATE_mta_relay_email") {
	      email = document.f.elements[i].value;
	    }
	    if (document.f.elements[i].name == "UPDATE_mta_relay_port") {
	      port = document.f.elements[i].value;
	    }
	}

	var args = {
		"host"			 : host,
		"port" 			 : port,
		"domain" 		 : domain,
		"email"  		 : email,
		"hostname" 		 : hostname,
		"default_domain" : default_domain,
		"locale" 		 : locale,
		"user"			 : user,
		"password" 		 : password,
		"et"	 		 : et
	}
	actual_smtp_test_popup(args);
}

function actual_smtp_test_popup( args ) {
	var url = "/cgi-mod/smtp_test.cgi?locale="+args["locale"]+"&host="+args["host"]+"&port="+args["port"]+"&domain="+args["domain"]+"&email="+args["email"]+"&hostname="+args["hostname"]+"&default_domain="+args["default_domain"]+"&user="+args["user"]+"&password="+args["password"]+"&et="+args["et"];
	if (typeof(args["use_mx"]) != "undefined") {
		url += "&use_mx=" + args["use_mx"];
        }
	new_window=window.open(url, "smtp_test", "width=600,height=550,scrollbars=1,resizable=1");
	if (new_window && window.focus) {
		new_window.focus();
	}
	return false;
}

function im_smtp_test_popup(locale, user, password, et) {
    var to_addy = '';
    for (var i=0; i<document.f.elements.length; i++) {
        if (document.f.elements[i].name == "UPDATE_test_recipient") {
            to_addy = document.f.elements[i].value;
        }
    }

    return actual_smtp_test_popup({
        "email" : to_addy,
        "locale" : locale,
        "user" : user,
        "password" : password,
        "et" : et
    });
}

/**
 * This is used to create a new browsing window which contains the status of
 * POP account display script. It takes several parameters from the document currently
 * being viewed and passes these as URL parameters to the script.
 */
function pop_account_status_popup(server, user, row) {

  // Create the popup window
  new_window=window.open("/cgi-bin/pop_account_status.cgi?account="+user+"@"+server+"&hostname="+server, "pop_account_status", "width=600,height=400,scrollbars=yes,resizable=yes");

  // Focus the new window
  if (new_window && window.focus) {
    new_window.focus();
  }

}



function block_ip(ip) {
  window.open('/cgi-mod/index.cgi?primary_tab=BLOCK/ACCEPT&secondary_tab=IP%20Block%2FAccept&UPDATE_new_mta_acl_ip_block_address='+ip+'&UPDATE_new_mta_acl_ip_block_netmask=255.255.255.255&UPDATE_new_mta_acl_ip_block_action=Block&add_mta_acl_ip_block_address=Add', '_top');
}
function unblock_ip(client_whitelist_id) {
  window.open('/cgi-mod/index.cgi?primary_tab=BLOCK/ACCEPT&secondary_tab=IP%20Block%2FAccept&remove_mta_acl_ip_block_address:'+client_whitelist_id+'=Remove', '_top');
}
function whitelist_sender(sender) {
    window.open('/cgi-mod/index.cgi?primary_tab=BLOCK/ACCEPT&secondary_tab=Email%20Sender%20Block%2FAccept&UPDATE_new_mta_acl_email_src_allow_address='+sender+'&add_mta_acl_email_src_allow_address=Add', '_top');
}
function unwhitelist_sender(sender_whitelist_id) {
  window.open('/cgi-mod/index.cgi?primary_tab=BLOCK/ACCEPT&secondary_tab=Email%20Sender%20Block%2FAccept&remove_mta_acl_email_src_allow_address:'+sender_whitelist_id+'=Remove', '_top');
}

function block_ip_error() {
  alert('The IP you wish to unblock is part of a larger blocked subnet.  To unblock just this IP, you must go to the IP Block/Accept page under the BLOCK/ACCEPT tab and break apart the blocked subnet.');
  over_button=1;
}
function fingerprint(id) {
  alert('Message fingerprint has been sent to Barracuda Networks fingerprint server');
  over_button=1;
}
var selected_message_object;
function select_message_row (row_elem) {
    if (selected_message_object) {
        selected_message_object.style.background=selected_message_object.prevBackground;
        selected_message_object.isSelected=false
    }
    selected_message_object=row_elem;
    selected_message_object.isSelected=true;
    selected_message_object.style.background='lightblue';
}
function open_message_detail_window(id, email, locale, machine, port, password, et, realm, secondary_tab, open_new, is_doubleclick,role) {
  window.name='message';//Give default value to window-name.
  if (over_button==1) {
    over_button=0;
    return;
  }
  // see if we have a preview pane (assuming no doubleclick)
  if (!is_doubleclick && show_preview('preview_pane', id)) {
      return true;
  }
  var window_name = window.name + id.replace(/\W/g, "_");//by default, open message in new window.
  if (!open_new) {
      window_name = window.name;//open message in same window.
  }
  message_detail_win = window.open('/cgi-mod/view_message_log_detail.cgi?id='+id+'&user='+email+'&email='+email+'&locale='+locale+'&machine='+machine+'&port='+port+'&password='+password+'&et='+et+'&realm='+realm+'&secondary_tab='+secondary_tab+'&role='+role, window_name, 'width=700,height=600,scrollbars=yes,resizable=yes');
  if (window.focus) {
    message_detail_win.focus();
  }
}

function open_message_detail_window2(id, email, locale, password, et, realm, secondary_tab, open_new, is_doubleclick) {
  // see if we have a preview pane (assuming no doubleclick)
  if (!is_doubleclick && show_preview('preview_pane', id)) {
      return true;
  }
  var window_name = 'message';
  if (open_new) {
      window_name = window_name + id.replace(/\W/g, "_");
  }
  message_detail_win = window.open('/cgi-mod/view_message_log_detail.cgi?id='+id+'&user='+email+'&email='+email+'&locale='+locale+'&password='+password+'&et='+et+'&realm='+realm+'&secondary_tab='+secondary_tab, window_name, 'width=700,height=600,scrollbars=yes,resizable=yes');
  if (window.focus) {
    message_detail_win.focus();
  }
}

function open_queue_message_detail_window(id, email, locale, port, password, et, realm, secondary_tab, open_new, is_doubleclick, role) {
  if (over_button==1) {
    over_button=0;
    return;
  }
  // see if we have a preview pane (assuming no doubleclick)
  if (!is_doubleclick && show_preview('preview_pane', id)) {
      return true;
  }
  var window_name = 'message';
  if (open_new) {
      window_name = window_name + id.replace(/\W/g, "_");
  }
  message_detail_win = window.open('/cgi-mod/view_queue_message_detail.cgi?id='+id+'&user='+email+'&email='+email+'&locale='+locale+'&port='+port+'&password='+password+'&et='+et+'&realm='+realm+'&secondary_tab='+secondary_tab+'&role='+role, window_name, 'width=700,height=600,scrollbars=yes,resizable=yes');
  if (window.focus) {
    message_detail_win.focus();
  }
}


function open_bulk_edit_window(user, password, auth_type, realm, et, primary_tab, secondary_tab, varname, locale, limited, error_msg, role, domain) {
    if (user == 'guest') {
        // Bail out
        alert(error_msg);

        return false;
    }

    var url = '/cgi-bin/bulk_edit.cgi?user='+user+'&password='+password+'&auth_type='+auth_type+'&realm='+realm+'&et='+et+'&locale='+locale+'&bulk_list_var_name='+varname+'&from_primary_tab='+primary_tab+'&from_secondary_tab='+secondary_tab+'&role='+role;
  if (domain) {
      url = url+'&domain='+domain;
  }

  ex_open_popup_window(url, 600, 400, 'cuda_sf_main','',false,false);
}

function open_popup_window(href) {
  popup_window = window.open(href, 'release_notes', 'width=700,height=700,scrollbars=yes,resizable=yes');
  if (window.focus) {
    popup_window.focus();
  }
}

function ex_open_popup_window(href,w,h,parent_name,page_ref,flag_wait_screen,flag_full,centerX,centerY,notresizable) {
  window.name=parent_name;
  if (parent_name){
      var sep='?';
      if (href.indexOf('?')>0){
          sep='&';
      }
      var url=href + sep + 'parent_name=' + parent_name;
  }else{
      var url=href;
  }
  // Keep the width and height for reopening popups
  url = url + '&popup_width=' + w + '&popup_height=' + h;
  var real_url='';
  var new_window;
  if (page_ref)
    url = url + '#' + page_ref;

  if (flag_wait_screen){
      real_url=url;
      url='about:blank';
  }

  var child_window='child_window'+Math.ceil(Math.random()*1000000);

  var window_options = ',scrollbars=yes';
  if (notresizable) {
      window_options = window_options + ',resizable=no';
  } else {
      window_options = window_options + ',resizable=yes';
  }
  if (centerX) {
     window_options = window_options + ',left='+(screen.width-w)/2;
  }
  if (centerY) {
     window_options = window_options + ',top='+(screen.height-h)/2;
  }
  if (flag_full){
      window_options = window_options + ',location=yes,toolbar=yes,menubar=yes,directories=yes'
  }

  if (parent_name){
    temp_popup_window = new_window = window.open(url, child_window, 'width='+w+',height='+h+window_options);
    temp_popup_windows[temp_popup_windows.length]=new_window;
  } else {
    popup_window = window.open(url, child_window, 'width='+w+',height='+h+window_options);
    new_window=popup_window;
    popup_window.opener = self;
  }

  if (flag_wait_screen){
      var html="<html>";
      html = html + "<body>\n";
      html = html + "<head>\n";
      html = html + "<script>\n";
      html = html + "var cnt=0;\n";
      html = html + "function doDots () { \
                      var dots=''; \
                      cnt++; \
                      for (var i=0;i<cnt;i++){ \
                       dots = dots + '.'; \
                      } \
                      document.getElementById('dots').innerHTML=dots; \
                      setTimeout('doDots()',1000); \
                     }"
      html = html + "</script>\n";
      html = html + "</head>\n";
      html = html + "<table width=100% height=100% border=1 bordercolor=blue style='font-size:10pt;font-family:Verdana,Geneva,Arial,Sans-serif;'><tr><td align=center valign=center>\n";
      html = html + "Please Wait<br><div id=dots></div>\n";
      html = html + "</td></tr></table>\n";
      html = html + "<script>setTimeout('doDots()',1000);</script>\n";
      html = html + "</body>\n";
      html = html + "</html>\n";
      new_window.document.write(html);
      new_window = window.open(real_url, child_window);
  }
}

function close_popup_windows() {
    if ((temp_popup_window) && (temp_popup_window.closed == false) && window.name != temp_popup_window.name) {
        temp_popup_window.window.close();
    }
    for(var i=0;i<temp_popup_windows.length;i++){
        var popup = temp_popup_windows[i];
        if ((popup) && (popup.closed == false) && window.name != popup.name) {
            popup.window.close();
        }
    }
    temp_popup_windows = new Array();
}

var image_lookup = new Array();
function spam_button_pressed(button_object) {
  // parse the button id
  var log_message_id = button_object.name.substr(button_object.name.lastIndexOf('_')+1);
  // clear all the buttons
  image_lookup['na_button_'+log_message_id].src='/images/na.gif';
  image_lookup['spam_button_'+log_message_id].src='/images/spam.gif';
  image_lookup['notspam_button_'+log_message_id].src='/images/notspam.gif';
  // press our button
  button_object.src = button_object.src.replace('.gif','_pressed.gif');
  var form_element = eval("document.f.spam_"+log_message_id);
  if (button_object.name.indexOf('notspam') > -1) {
    form_element.value = "no";
  }
  else {
    if (button_object.name.indexOf('spam') > -1) {
      form_element.value = "yes";
    }
    else {
      form_element.value = "";
    }
  }
}

function spam_button_hover(button_object) {
  // if we are pressed, dont show hover
  if (button_object.src.indexOf('_pressed') > -1) {
    return;
  }
  if (button_object.src.indexOf('_over') > -1) {
    return;
  }
  // hover
  button_object.src = button_object.src.replace('.gif','_over.gif');
}
function spam_button_nohover(button_object) {
  // if we are hovering, restore
  if (button_object.src.indexOf('_over') > -1) {
    button_object.src = button_object.src.replace('_over.gif','.gif');
  }
}

function ns_keypresscheck(e) {
  if (! current_ns_element) return;
  var form_type = current_ns_function || 'format_octet';
  return eval(form_type + '(current_ns_element, e || event)');
}

function ns_keydowncheck(e) {
  if (! current_ns_element) return;
  var form_type = current_ns_function || 'format_octet';
  return eval(form_type + '(current_ns_element, e || event)');
}

function ns_keyupcheck(e) {
  if (! current_ns_element) return;
  var form_type = current_ns_function || 'format_octet';
  return eval(form_type + '(current_ns_element, e || event)');
}

function format_octet(self, event) {
  // handle input for an octet
  // we can derive the name and number of the ip variable we're manipulating
  //   the format is "name__number"
  var octet = self.value;

  // determine the base name of this ip
  var base_name = self.name.replace(/__[0-9]$/, "");
  // determine our octet number from the base name
  var octet_number = self.name.replace(/^.*__/g, "");
  // determine the next octet
  var next_octet_name;
  var next_octet_number;
  if (octet_number < 3) {
    next_octet_number = (parseInt(octet_number) + 1);
    next_octet_name = base_name + "__" + (next_octet_number);
  }
  else {
    next_octet_name = null;
    next_octet_number = 3;
  }
  // determine the previous octet
  var prev_octet_name;
  var prev_octet_number;
  if (octet_number > 0) {
    var prev_octet_number = (parseInt(octet_number) - 1);
    prev_octet_name = base_name + "__" + (prev_octet_number);
  }
  else {
    prev_octet_name = null;
    prev_octet_number = 0;
  }
  // if we need to advance/retreat octets, new_octet_object will be non-null
  var new_octet_object = null;

  var evt = event;
  var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);

  // ignore all but digit (48-57), "." (190), space (32), tab (9),  backspace (8), and delete (46)
  // also allow arrows (37-40)
  // handle tab
  if (charCode == 9) {
    return true;
  }

  // Translate the numeric keypad
     // Handle digits 0 - 9
  if( charCode >= 96 && charCode <= 105 )
    charCode -= 48;
    // Handle the "dot"
  if( charCode == 110 )
      charCode = 190;

  // abort non-digit...
  if (charCode != 9 &&
      charCode != 8 &&
      charCode != 46 &&
      charCode != 190 &&
      charCode != 32 &&
      charCode != 37 &&
      charCode != 38 &&
      charCode != 39 &&
      charCode != 40 &&
      !(charCode >= 48 && charCode <= 57)) {
    return false;
  }

  // allow arrows
  if (charCode == 37 || charCode == 39) {
    return true;
  }

  // convert up/down to left/right
  var new_charCode = -1;
  if (charCode == 38) {
    new_charCode = 37;
  }
  if (charCode == 40) {
    new_charCode = 39;
  }
  if (new_charCode > -1) {
    if (evt.charCode) evt.charCode = new_charCode;
    if (evt.which) evt.which = new_charCode;
    if (evt.keyCode) evt.keyCode = new_charCode;
    return true;
  }

  // cancel if we're a "." (or space) and the octet is empty or selected
  if ((charCode == 190 || charCode == 32) &&
      (octet == "" || selected == self.name)) {
    return false;
  }

  //If the value is already 0, then replace the value with new value
  if (evt.type == 'keydown' && octet=="0" && charCode != 190){
      self.value='';
  }

  // clear out previously selected note
  selected = null;

  // handle backspace
  if (evt.type == 'keydown' && charCode == 8 && octet == "" && prev_octet_name != null) {
    new_octet_object = eval("document.getElementById('"+prev_octet_name+"')");
    new_octet_object.focus();
    new_octet_object.value = new_octet_object.value;
    return true;
  }
  // ignore backspace on keyup
  if (evt.type == 'keyup' && charCode == 8) {
    return false;
  }

  if (evt.type == 'keyup') {
    // if we just typed a "." and we're at the beginning, stay here
    if (octet == "." + old_octet[octet_number] || octet == " " + old_octet[octet_number]) {
      octet = old_octet[octet_number];
      new_octet_object = self;
    }
    // otherwise, advance to next octet
    if ((octet.replace(/\./g, "") != octet || octet.replace(/ /g, "") != octet) && next_octet_name != null) {
      new_octet_object = eval("document.getElementById('"+next_octet_name+"')");
    }
  
    // fix/alert if bad input
    // strip all but numbers
    octet = octet.replace(/[^0-9]/g, "");
    // if we just typed our third digit and it is valid, advance...
    if (octet.length == 3 && octet <= 255 && octet >= 0 && next_octet_name != null) {
      new_octet_object = eval("document.getElementById('"+next_octet_name+"')");
    }
    if (octet.length > 3) {
      if (old_octet[octet_number].length == 3) {
        // if we typed a fourth character, restore the value
        // if we typed it at the end, advance
        if (octet.substr(0,3) == old_octet[octet_number] && next_octet_name != null) {
          new_octet_object = eval("document.getElementById('"+next_octet_name+"')");
        } 
        octet = old_octet[octet_number];
      }
    }
    if (octet > 255 || octet < 0) {
      octet = old_octet[octet_number];
      alert('Valid numbers are between 0 and 255');
    }

    old_octet[octet_number] = octet;

    if (self.value != octet) {
      self.value = octet;
    }

  }
  // advance to next/previous octet if desired
  if (new_octet_object != null) {
    new_octet_object.focus();
    new_octet_object.select();
    selected = new_octet_object.name;
  }

  return true;
  
}

var args;
function get_args () {
  var args = new Object();
  var query = location.search.substring(1);
  var pairs = query.split("&");
  for (var i=0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    if (pos == -1) continue;
    var key = pairs[i].substring(0,pos);
    var value = pairs[i].substring(pos+1);
    args[key] = unescape(value);
  }
  return args;
}

// Routine to run the script to get a support session started
function troubleshoot_request_support_popup()
{
    // Open the window to start the session
    new_window=window.open("/cgi-bin/support-tunnel.cgi" + window.location.search, "request_support", "width=600,height=500,scrollbars=yes,resizable=yes");
    if (new_window && window.focus)
    {
        new_window.focus();
    }
    return false;
}

function batch_test_popup(user, password, et, locale){
    args=get_args();
    open_popup_window("/cgi-mod/batch_test.cgi?user="+user+"&password="+password+"&et="+et+"&locale="+locale);
}

// Routine to output syslog
function syslog_popup(type)
{
    args = get_args();
    
    // Open the window to view syslog
    new_window=window.open("/cgi-bin/nph-syslog.cgi?user="+args.user+"&password="+args.password+"&et="+args.et+"&locale="+args.locale+"&syslog="+type, "syslog", "width=600,height=500,scrollbars=yes,resizable=yes");
    if (new_window && window.focus)
    {
        new_window.focus();
    }
    return false;
}

// Content Filter screen Block All function for each category group
function blockAll(group, checked)
{
    var form = document.f;
    var name = 'UPDATE_spy_content_cat_action_' + group;
    var radio;

    if (checked)
    {
        for (var i = 0; i < form.elements.length; i++)
        {
            if (form.elements[i].name.indexOf(group) >= 0)
            {
                radio = form.elements[i];
                if (radio.value == checked)
                    radio.checked = true;
            }
        }
    }
} 

// Content Filter screen Block All function for each category group
function blockApp(group, checked)
{
    var form = document.f;
    var name = 'spy_content_app_action_' + group;
    var radio;

    if (checked)
    {
        for (var i = 0; i < form.elements.length; i++)
        {
            if (form.elements[i].name.indexOf(name) >= 0)
            {
                radio = form.elements[i];
                if (radio.value == checked)
                    radio.checked = true;
            }
        }
    }
}

function replaceId (obj, newId) {
    if (obj.id) {
        obj.id = obj.id.replace(/_\d+$/, '_' + newId);
    }
}

// Toggles inbound/oubound filter list based on mode
function show_filter_options (mode)
{
    var selected_mode = mode.options[mode.selectedIndex].value;

    // Get the filter counts
    var filterCount = 0;
    var dropdowns = document.getElementsByTagName("select");
    for (var i = 0; i < dropdowns.length; i++) {
        if (dropdowns[i].id.indexOf("boolean_") == 0) {
            filterCount++;
        }
    }
    
    var inbound_options;
    var outbound_options;
    var var_name;
    var filter_object;
    for (i = 0; i < filterCount; i++) {
      var_name = 'inbound_filters_' + i;
      inbound_options  = document.getElementById(var_name);
      var_name = 'outbound_filters_' + i;
      var outbound_options = document.getElementById(var_name);

      if (selected_mode == 'mode_inbound') {
          outbound_options.style.display = "none";
          inbound_options.style.display  = "";
      }

      if (selected_mode == 'mode_outbound') {
          inbound_options.style.display  = "none";
          outbound_options.style.display = "";
      }

      inbound_options.childNodes[1].selectedIndex  = 0;
      outbound_options.childNodes[1].selectedIndex = 0;

      filter_object = document.getElementById("filter_" + i);
      changePattern(filter_object);
    }


    return true;
}

// Adds a new boolean search filter
function addFilter (norepeats, modeoption) {
    var filterCount = 0;
    var maxNumFilters = 50;
    
    var warningText = document.getElementById("too_many_filters_alert").value;   // "Too many entries for Filter"

    /** Create the new filter control */

    // Get a list of the `select' nodes
    var dropdowns = document.getElementsByTagName("select");

    // Get the filter counts
    for (var i = 0; i < dropdowns.length; i++) {
        if (dropdowns[i].id.indexOf("boolean_") == 0) {
            filterCount++;
        }
    }
    if( filterCount > maxNumFilters ) {
        alert(warningText);
        return false;
    }
     
    // Clone the first row, to make our new row
    var newFilter =
        document.getElementById("filter_control_0").cloneNode(true);
    newFilter.id = "filter_control_" + filterCount;

    /** Gather the nodes */
    var i = 0;
    var booleanNode = newFilter.childNodes[i++];
    if (modeoption) {
        //note mode option list to be removed
        var modeNode = newFilter.childNodes[i++];
    }
    var filterNode  = newFilter.childNodes[i++];
    var patternNode = newFilter.childNodes[i++];
    var addNode     = newFilter.childNodes[i++];
    var applyNode   = newFilter.childNodes[i++];

    // Remove mode filter dropdown option
    if (modeoption) {
        newFilter.removeChild(modeNode);
    }

    // Remove the "Apply Filter" button
    newFilter.removeChild(applyNode);

    /** Create the boolean dropdown */

    // Get the option strings
    var andString       = document.getElementById("boolean_and").value;
    var orString        = document.getElementById("boolean_or").value;
    var andNotString    = document.getElementById("boolean_and_not").value;
    var orNotString     = document.getElementById("boolean_or_not").value;

    // Create the new options
    var andOption       = new Option(andString);
    var orOption        = new Option(orString);
    var andNotOption    = new Option(andNotString);
    var orNotOption     = new Option(orNotString);

    // Set the values
    andOption.value     = "boolean_and";
    orOption.value      = "boolean_or";
    andNotOption.value  = "boolean_and_not";
    orNotOption.value   = "boolean_or_not";

    // Build the new drop down
    var newBoolean          = document.createElement("select");
    newBoolean.id           = "boolean_" + filterCount;
    newBoolean.options[0]   = andOption;
    newBoolean.options[1]   = orOption;
    newBoolean.options[2]   = andNotOption;
    newBoolean.options[3]   = orNotOption;
    newBoolean.style.visibility = document.getElementById('boolean_0').style.visibility;

    // Replace the old boolean dropdown with the new one
    booleanNode.replaceChild(
        newBoolean,
        booleanNode.childNodes[0]
    );

    /** Set the filter dropdown to `none' -- this fixes a cloning issue. */
    filterNode.childNodes[0].childNodes[0].selectedIndex = 0;

    /** Remove already used filters if norepeats is set */

    if(norepeats){
        for(var i = 0; i< filterCount; i++){
            for(var x=0;x<filterNode.childNodes[0].options.length;x++){
                if(filterNode.childNodes[0].options[x].value == 
                   document.getElementById("filter_"+i).options[document.getElementById("filter_"+i).selectedIndex].value){
                       filterNode.childNodes[0].options[x]=null;
                }
            }
            //filterNode.childNodes[0].options[filterNode.childNodes[0].indexOf(document.getElementById("filter_control_"+i).childNodes[2].selected)]=null;
        }
    }

    /** Change the pattern box */

    // Reset the pattern text
    patternNode.childNodes[0].childNodes[1].childNodes[1].value = "";

    /** Create the remove button */

    // Create the remove button
    var newButton           = document.createElement("input");
    newButton.className   = "new_button";
    newButton.type        = "button";
    newButton.value       = '-';
    newButton.onclick     = removeFilter;
    newButton.style.width = "2em";
     
    // Replace the add button with the remove button
    addNode.replaceChild(
        newButton,
        addNode.childNodes[0]
    );

    /** Set new IDs */
    
    // Rename all the IDs - for four levels down
    for (var i = 0; i < newFilter.childNodes.length; i++) {
        replaceId(newFilter.childNodes[i], filterCount);
        if (!newFilter.childNodes[i].childNodes) {continue;}
        for (var j = 0; j < newFilter.childNodes[i].childNodes.length; j++) {
            replaceId(newFilter.childNodes[i].childNodes[j], filterCount);
            if (!newFilter.childNodes[i].childNodes[j].childNodes) {continue;}
            for (var k = 0; k < newFilter.childNodes[i].childNodes[j].childNodes.length; k++) {
                replaceId(newFilter.childNodes[i].childNodes[j].childNodes[k], filterCount);
                if (!newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes) {continue;}
                for (var l = 0; l < newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes.length; l++) {
                    replaceId(newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes[l], filterCount);
                    if (!newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes[l]) {continue;}
                    for (var m = 0; m < newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes.length; m++) {
                        replaceId(newFilter.childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes[m], filterCount);
                    }
                }
            }
        }
    }
    
    /** Insert the new filter control */

    var insertNode = document.getElementById("filter_control_table");
    insertNode.childNodes[0].appendChild(newFilter);
    
    // Force a pattern change
    var filter_object = document.getElementById("filter_" + filterCount);
    changePattern(filter_object);

    return;
}

// requires "%2d" format for mon/day hour:min:sec
function to2d (str) {

    if (str.length == 1) {
        str = "0"+str;
    }

    return str;
}

function updateTimeRange (id) {
    // update the time range pattern from the values of the parts

    // if we aren't a time range, just bail
    id = id.substr(id.lastIndexOf("_")+1);
    if (document.getElementById("filter_"+id).value.indexOf("time_range") == -1) {
        return true;
    }
    var y1 = document.getElementById("time_range_year_"+id).value;
    var mo1 = document.getElementById("time_range_month_"+id).value; 
    var d1 = document.getElementById("time_range_day_"+id).value;
    var h1 = document.getElementById("time_range_hour_"+id).value;
    var m1 = document.getElementById("time_range_minute_"+id).value;
    var s1 = document.getElementById("time_range_second_"+id).value;
    var y2 = document.getElementById("time_range_year2_"+id).value;
    var mo2 = document.getElementById("time_range_month2_"+id).value;
    var d2 = document.getElementById("time_range_day2_"+id).value;
    var h2 = document.getElementById("time_range_hour2_"+id).value;
    var m2 = document.getElementById("time_range_minute2_"+id).value;
    var s2 = document.getElementById("time_range_second2_"+id).value;
    var time1 = y1+"-"+to2d(mo1)+"-"+to2d(d1)+"T"+to2d(h1)+":"+to2d(m1)+":"+to2d(s1);
    var time2 = y2+"-"+to2d(mo2)+"-"+to2d(d2)+"T"+to2d(h2)+":"+to2d(m2)+":"+to2d(s2);
    document.getElementById("pattern_"+id).value = time1+"/"+time2;
    return true;
}

function removeFilter (id) {
    var filterNode  = (typeof(id) == "object" || ! id)
                    ? this.parentNode.parentNode
                    : document.getElementById("filter_control_" + id)
                    ;
    
    // Delete this node
    filterNode.parentNode.removeChild(filterNode);

    // Search and destroy the hidden form variables in the page.
    var inputNodes = document.getElementsByTagName('input');

    for (var i = 0; i < inputNodes.length; i++) {
        if (inputNodes[i].name == 'filter_' + id
        ||  inputNodes[i].name == 'pattern_' + id
        ||  inputNodes[i].name == 'boolean_' + id) {
            inputNodes[i].parentNode.removeChild(inputNodes[i]);
        }
    }
}

var clear_filter_after_change = [];
function changePattern (filterObj) {
    var idIndex = filterObj.id.substring(7);
    var filter_val = filterObj.value;

    // Enable the pattern
    if (filter_val.indexOf("search") > -1) {
        document.getElementById("pattern_" + idIndex).disabled = false;
        document.getElementById("pattern_" + idIndex).style.backgroundColor = "#ffffff";
        // Clear pattern if prev. filter wasn't a text entry. Don't persist special values.
        if (clear_filter_after_change[idIndex]) {
            document.getElementById("pattern_"+idIndex).value = '';
        }
    }
    else {
        document.getElementById("pattern_" + idIndex).value = '';
        document.getElementById("pattern_" + idIndex).disabled = true;
        document.getElementById("pattern_" + idIndex).style.backgroundColor = "#cccccc";
    }

    // Enable the time range
    if (filter_val.indexOf("time_range") > -1) {
        document.getElementById("select_section_" + idIndex).style.display = "none";
        document.getElementById("time_range_section_" + idIndex).style.display = "inline";
        document.getElementById("pattern_section_" + idIndex).style.display = "none";
        // make sure that the pattern is enabled - we will actually ship the data back-and-forth in the
        // pattern field
        document.getElementById("pattern_" + idIndex).disabled = false;
        clear_filter_after_change[idIndex] = true;
    }
    // Enable the select
    else if (filter_val.indexOf("select_") > -1) {
        document.getElementById("select_section_" + idIndex).style.display = "inline";
        for(var i=0;i<document.getElementById(filterObj).length;i++){
            var val = document.getElementById(filterObj).options[i].value;
            if(document.getElementById(val + "_" + idIndex)){
                document.getElementById(val + "_" + idIndex).style.display = 
                    (document.getElementById(filterObj).selectedIndex == i) ? 'inline' : 'none';
            }
        }
        document.getElementById("time_range_section_" + idIndex).style.display = "none";
        document.getElementById("pattern_section_" + idIndex).style.display = "none";
        // make sure that the pattern is enabled - we will actually ship the data back-and-forth in the
        // pattern field
        document.getElementById("pattern_" + idIndex).disabled = false;
        document.getElementById("pattern_" + idIndex).value = document.getElementById(filter_val + "_" + idIndex).options[0].value;
        clear_filter_after_change[idIndex] = true;
    }
    else {
        document.getElementById("select_section_" + idIndex).style.display = "none";
        document.getElementById("time_range_section_" + idIndex).style.display = "none";
        document.getElementById("pattern_section_" + idIndex).style.display = "inline";
        clear_filter_after_change[idIndex] = false;
    }
}

function applyFilter (urlString) {
    var filterCount = 0;

    // Grab the warning text
    var warningText = document.f.filter_lid_2497.value;   // "[Bad filter]"

    // Check the filters
    if (! checkFilterInput()) {
        return;
    }

    // Get the boolean dropdowns
    var dropdowns = document.getElementsByTagName("select");

    // Get the filter control count
    for (var i = 0; i < dropdowns.length; i++) {
        if (dropdowns[i].id.indexOf("boolean_") != -1) {
            var booleanIndex = dropdowns[i].id.substring(8);

            // Set the highest found index
            if (filterCount < booleanIndex) {
                filterCount = booleanIndex;
            }
        }
    }
    
    // Go through the filters
    for (var i = 0; i < filterCount + 1; i++) {
        // Check this boolean
        if (document.getElementById("boolean_" + i)) {

            // Check for a valid filter string
            if (! checkFilterPattern(document.getElementById("pattern_" + i).value)
            &&  document.getElementById("filter_" + i).value.indexOf("search") > -1
            ) {
                // Bail out
                alert(warningText);

                return false;
            }

            // Grab the filter
            var pattern = new String(encodeURIComponent(document.getElementById("pattern_" + i).value));

            // Escape the pluses
            pattern = pattern.replace(/\+/g, "%2b");
            
            // Remove trailing spaces (already encoded)
            pattern = pattern.replace(/(%20)+$/, '');

            urlString += "&boolean_" + i + "=" + document.getElementById("boolean_" + i).value;
            urlString += "&filter_" + i + "=" + document.getElementById("filter_" + i).value;
            urlString += "&pattern_" + i + "=" + pattern;
        }
    }
    
    // Apply the filter
    window.open(urlString, "_top");
}

function validDomain(domain, error)
{
    var result = false;

    if (!domain || domain.match(/^[\w\.-]+\.[\w]+$/))
    {
        result = true;
    }
    else
    {
        alert(error);
    }

    return result;
}

function ipblocking(ip, netmask, ip2, netmask2, port, error, error2)
{
    var result = false;
    if ((netmask && !ip)||(netmask2 && !ip2))
    {
        alert(error);
    }
    else if(!ip && !netmask && !ip2 && !netmask2 && !port){
        alert(error2);
    }
    else
    {
        result = true;
    }
    return result;
}

function ipexempting(ip, netmask, ip2, netmask2, port, error, error2)
{
    var result = false;
    if ((netmask && !ip)||(netmask2 && !ip2))
    {
        alert(error);
    }
    else if(!ip && !netmask && !ip2 && !netmask2 && !port){
        alert(error2);
    }
    else
    {
        result = true;
    }
    return result;
}

function exempt(ip1,ip2,ip3,ip4,error)
{
    var result = false;
    var ip = [new decimal(parseFloat(ip1)).toBinary(),new decimal(parseFloat(ip2)).toBinary(),
              new decimal(parseFloat(ip3)).toBinary(),new decimal(parseFloat(ip4)).toBinary()];
    for(var i=1; i<4 ;i++){
        while(ip[i].length<8){
           ip[i] = "0" + ip[i];
        }
    }
    var bin = new binary(ip[0]+ip[1]+ip[2]+ip[3]).toDecimal();
    var total = 4294967295 - bin + 1;
    var text = error.replace("__1__",total);
    if(!total || total<=1){
        return 1;
    }
    return confirm(text);
}

function decimal(dec)
{
    this.dec=dec;
    this.toBinary=function() { return this.dec.toString(2); }
    this.toHex=function() { return this.dec.toString(16).toUpperCase(); }
    this.toOctal=function() { return this.dec.toString(8); }
}

function binary(bin)
{
    this.bin=bin;
    this.toDecimal=function() { return parseInt(this.bin, 2); }
    this.toHex=function() { return this.toDecimal().toString(16).toUpperCase(); }
    this.toOctal=function() { return this.toDecimal().toString(8); }
}

function checkPort(port){
    if(port == 80 || port == 8001|| port == 22 || port == 25 || port == 443)
        return false;
    return true;  
}

function checkFilterInput () {
    var filterCount = 0;
    var scoreType   = /score/i;
    var datetimeType   = /time_range/i;
    var isOk        = true;

    // Get the boolean dropdowns
    var dropdowns = document.getElementsByTagName("select");

    // Get the filter control count
    for (var i = 0; i < dropdowns.length; i++) {
        if (dropdowns[i].id.indexOf("boolean_") != -1) {
            var booleanIndex = dropdowns[i].id.substring(8);

            // Set the highest found index
            if (filterCount < booleanIndex) {
                filterCount = booleanIndex;
            }
        }
    }
    
    // Check for score and time ranges
    for (var i = 0; i <= filterCount; i++) {
        // Be sure this filter exists
        if (document.getElementById("filter_" + i)) {
            var filterType  = document.getElementById("filter_" + i).value;
            var scoreMatches     = scoreType.exec(filterType);
            var datetimeMatches  = datetimeType.exec(filterType);
            
            // Check the input type
            if (scoreMatches != null) {
                // Check the input
                var pattern = document.getElementById("pattern_" + i).value;
                if (! isNumerical(pattern)) {
                    isOk = false;
                    break;
                }
            }
            if (datetimeMatches != null) {
                // first make sure we generate the single-input field combined value
                updateTimeRange('time_range_year_' + i);
                // Check the input
                var pattern = document.getElementById("pattern_" + i).value;

                if (! isValidDate(pattern)) {
                    isOk = false;
                    break;
                }
            }
        }
    }

    return isOk;
}

/** This function checks a string passed to it for only numerics.
 * It's best used with a submit button, but can be used anywhere
 * where a boolean return is acceptable.
 */
function isNumerical (string) {
    var numerical = /^[\d., -]+$/;
    
    // Try matching
    var matches = numerical.exec(string);
    
    // Check and make sure it's all numeric
    if (matches == null) {
        // Get the alert text
        var alertText = document.getElementById("numerical_filter_alert").value;
        
        // Give an error
        alert(alertText);

        return false;
    }

    return true;
}

/** This function checks a string passed to it to ensure it is a date
 * in the format used by date/time message log filter.
 * It's best used with a submit button, but can be used anywhere
 * where a boolean return is acceptable.
 */
function isValidDate (string) {
    var dateTimeRe = /^(19|20)\d{2}\-(0[1-9]|1[0-2])\-(0[1-9]|[1-2][0-9]|3[0-1])T(0\d|1\d|2[0-3]):([0-5]\d):([0-5]\d)\/(19|20)\d{2}\-(0[1-9]|1[0-2])\-(0[1-9]|[1-2][0-9]|3[0-1])T(0\d|1\d|2[0-3]):([0-5]\d):([0-5]\d)/;

    // Try matching
    var matches = dateTimeRe.exec(string);

    // Get the start date and end date
    var dates = string.split('/');

    // validating day against given month/year
    var valid_date = isValidDay(dates[0]) && isValidDay(dates[1]);

    // Check and make sure it's all numeric and start date is earlier than end date
    if (matches == null || dates[0] >= dates[1] || !valid_date) {
        // Get the alert text
        var alertText = document.getElementById("invalid_date_alert").value;
        
        // Give an error
        alert(alertText);

        return false;
    } 

    return true;
}

/* This function adds another check to Date validation by
 * checking if the day is valid against month/year
 *
 * returns false if invalid, true otherwise
 */
function isValidDay (date_time_str) {

    var ret_val = true;

    var date_str = date_time_str.split("T");
    var date_parts = date_str[0].split("-");
    var yy = parseInt(date_parts[0]);
    var mm = parseInt(date_parts[1]);
    var dd = parseInt(date_parts[2]);

    switch (mm) {
        case 2:
            if (!checkLeapYear(dd, yy) ){
                ret_val = false;
            }
            break;
        case 4: case 6: case 9: case 11:
            if (dd > 30){
                ret_val = false;
            }
            break;
        default:
            if (dd > 31){
                ret_val = false;
            }
    }

    return ret_val;
}

/* This function checks if the given day is a valid day under Feb month
 * checking if the year is leap year or nor.
 *
 * returns true if valid, false otherwise
 */
function checkLeapYear(day, year) {

    if (day <= 28){
        return true;
    }

    if ( !(year % 400) && (day <= 29) ) {
        return true;
    }

    if ( !(year%4) && (year % 100) && (day <= 29) ) {
        return true;
    }

    return false;
}

/* Check to see if this is a valid pattern (for the filter control). Returns
 * true or false.
 */
function checkFilterPattern (pattern) {
    // Make sure the filter pattern is a legal pattern
    if (pattern.match(/^\s*$/)) {
        return false;
    }
    else {
        return true;
    }
}

// joe 7-27-06 b6164 update date select box when changing month or year
function updateDaySelect(year, month, dayField) {
    var tmpDate = new Date(year, month, 1, 12);
    var origDay = dayField.value;
    var i,selDay;
    // remove the old select options
    while (dayField.childNodes.length > 0) {
        dayField.removeChild(dayField.childNodes[0]);
    }
    // check for ie
    ie = (navigator.appName == "Microsoft Internet Explorer");
    // build the select options
    tmpDate.setDate(0);
    selDay = (origDay > tmpDate.getDate()) ? tmpDate.getDate() : origDay;
    for (i=1; i <= tmpDate.getDate(); i++) {
        if (ie) {
            var newObj = document.createElement("OPTION");
            newObj.text = i;
            newObj.value = (i<10)?"0"+i:i;
            dayField.add(newObj);
        } else {
            var newObj = new Option(i,(i<10)?"0"+i:i,false,(selDay==i)?true:false);
            dayField.appendChild(newObj);
        }
    }
    if (ie) {
        dayField.selectedIndex = selDay-1;
    }
}

// Variable to remember table, row and original
// colour of previous element.
var oldRow = { r:null , c:null };

function highlightRow(r){

   // If oldRow has been set, restore previous row
   if ( oldRow.r ) {
     oldRow.r.style.backgroundColor = oldRow.c;
   }

   // If a row was clicked on
   if ( r && 'tr' == r.nodeName.toLowerCase() ){
     // Store reference to row and its colour
     oldRow.r = r;
     oldRow.c = r.style.backgroundColor;
     // Highlight clicked on row
     r.style.backgroundColor = '#999999';

     // Otherwise, reset oldRow values
   } else {
     oldRow.r = null;
     oldRow.c = null;
   }

}

function move(direction,order,message) {
   var table = document.all ? document.all['iTable'] : document.getElementById('iTable');
   var trs = table.tBodies[0].getElementsByTagName("tr");
   if(oldRow.r){
       var row = oldRow.r.rowIndex;
       if(direction == "up" && row>3){
           document.getElementById('modify_'+order).disabled=false;
           var tmpNode = table.tBodies[0].replaceChild(trs[row-2], trs[row]);
           if(typeof(trs[row-2]) != "undefined") {
               table.tBodies[0].insertBefore(tmpNode, trs[row-2]);
           } else {
               table.appendChild(tmpNode);
           }
       }
       else if(direction == "down" && row<table.rows.length-5){
           document.getElementById('modify_'+order).disabled=false;
           var tmpNode = table.tBodies[0].replaceChild(trs[row+2], trs[row]);
           if(typeof(trs[row+2]) != "undefined") {
               table.tBodies[0].insertBefore(tmpNode, trs[row+2]);
           } else {
               table.appendChild(tmpNode);
           }
       }
       var list = new Array();
       var count=0;
       for(var i=3;i<table.rows.length-4;i+=2){
           list[count]=table.rows[i].cells[19].firstChild.nodeValue;
           count++;
       }
       document.getElementById('UPDATE_'+order).value=list;
   }
}

function move_groups(from,to,variable,maxsize,limit) {
    var selected= new Array();
    var count = 0;
    var v = '';
    var size = document.getElementById(to).length+selected.length;
    //copy destination list
    for(var i=0;i<document.getElementById(to).length;i++){
            if(limit && count >= limit){
                break;
            }
            selected[count]=new Array(document.getElementById(to).options[i].text,document.getElementById(to).options[i].value);
            count++;
    }
    //add new selections to array
    for(var i=0;i<document.getElementById(from).length;i++){
        if(document.getElementById(from).options[i].selected && (!limit || count<limit)){
            selected[count]=new Array(document.getElementById(from).options[i].text,document.getElementById(from).options[i].value);
            //remove previously selected items
            document.getElementById(from).options[i] = null;
            count++;
        }
    }
    selected.sort(function(a,b) { if(a < b){return -1;}if(a > b){return 1;}return 0; });
    //update destination list
    for(var i=0;i<selected.length;i++){
    document.getElementById(to).options[i]=new Option(selected[i][0],selected[i][1]);
    }
    //resize both lists
    var max = Math.max(document.getElementById(from).length,document.getElementById(to).length);
    max = Math.min(max,maxsize);
    document.getElementById(from).size=max;
    document.getElementById(to).size=max;
    //Update hidden field for submission
    var groups = new Array();
    for(var i=0;i<document.getElementById('current').length;i++){
        groups[i]=document.getElementById('current').options[i].value;
    }
    if(groups.length == 0){
        groups[0]='---none---';
    }
    document.getElementById('UPDATE_'+variable).value=groups;
} 

/* On "Not Spam" click; checks to see whether any selected spam messages
 * were "confidently" spam (high spam score, or intent reasons). */
function check_for_confident_spam() {
    var found = false;
    var confirmed = new Array;

    // Get our hidden form element.
    var hidden = document.getElementsByName("spam_analysis_confirmed");
    if (hidden.length == 0) {
    } else {
        hidden = hidden[0];
    }

    // Fetch the ids of checked boxes, and compare against
    // confidently-spam ids.
    var inputs = document.getElementsByTagName("input");
    for (var inp = 0; inp < inputs.length; ++inp) {
        var i = inputs[inp];
        // Is this a checkbox input?
        if (i.type == "checkbox" && i.checked) {
            // Strip off "machine" part of name.
            var id = i.name;
            var colonLoc = id.lastIndexOf(":");
            id = id.substr(0, colonLoc);

            // Does it refer to "confidently" designated spam?
            for (j = 0; j < confidently_spam_ids.length; ++j) {
                var cfd = confidently_spam_ids[j];
                if ('quarantine_message_' + cfd == id) {
                    found = true;
                    confirmed.push(cfd);
                    break;
                }
            }
        }
    }

    if (found) {
        if (window.confirm(confirm_confidently_spam_msg)) {
            hidden.value=confirmed.join("\n");
        }
    }

    return true;
}

function rotate_text (object, text_array) {
    // rotate through a text array for the content of an HTML object
    var curr_index = 0;
    for (var i = 0; i < text_array.length; i++) {
        if (object.innerHTML == text_array[i]) {
            curr_index = i;
            break;
        }
    }
    var new_index = curr_index + 1;
    if (new_index >= text_array.length) {
        new_index = 0;
    }
    // we need to delay the change to keep FF from screwing up hilighting
    window.setTimeout(function (object, html) {return function() {object.innerHTML = html; select_text(object)}}(object, text_array[new_index]), 0);
}

function select_text (object) {
    if (!object) {return;}
    
    // ie only
    if (!IE) {return;}
    var range = document.body.createTextRange();
    if (!range) {return;}
    range.moveToElementText(object);
    range.select();
    object.focus();
}

function show_preview (preview_elem, message_id) {
    var prv1=document.getElementById(preview_elem);
    if (!prv1) {
        return false;
    }
    var content = '<iframe id="preview_frame" marginwidth=0 marginheight=0 src="/cgi-mod/openwebmail/openwebmail-read.pl?user=admin&message_id=' + message_id + '&action=readmessage&headers=simple&attmode=simple&readwithmsgcharset=1&showhtmlastext=0&charset=iso-8859-1" width=100% height=100% frameborder=0></iframe>';
    prv1.innerHTML = content;
    return true;
}

var MAX_DUMP_DEPTH = 2;
function dumpObj(obj, name, indent, depth) {
    if (depth > MAX_DUMP_DEPTH) {
        return indent + name + ": <Maximum Depth Reached>\n";
    }
    if (typeof obj == "object") {
        var child = null;
        var output = indent + name + "\n";
        indent += "\t";
        for (var item in obj)
        {
            try {
                child = obj[item];
            } catch (e) {
                child = "<Unable to Evaluate>";
            }
            if (typeof child == "object") {
//                output += dumpObj(child, item, indent, depth + 1);
            } else {
                var childstr = child + " ";
                output += indent + item + ": " + childstr.substring(0,20) + "\n";
            }
        }
        return output;
    } else {
        return obj;
    }
}

function GetElementLeft(eElement)
{
    if (!eElement && this)                       // if argument is invalid
    {                                            // (not specified, is null or is 0)
        eElement = this;                         // and function is a method
    }                                            // identify the element as the method owner

    var nLeftPos = eElement.offsetLeft;          // initialize var to store calculations
    var eParElement = eElement.offsetParent;     // identify first offset parent element
    while (eParElement != null)
    {                                            // move up through element hierarchy
        nLeftPos += eParElement.offsetLeft;      // appending left offset of each parent
        eParElement = eParElement.offsetParent;  // until no more offset parents exist
    }
    return nLeftPos;                             // return the number calculated
}


function GetElementTop(eElement)
{
    if (!eElement && this)
    {
        eElement = this;
    }

    var nTopPos = eElement.offsetTop;
    var eParElement = eElement.offsetParent;
    while (eParElement != null)
    {
        nTopPos += eParElement.offsetTop;
        eParElement = eParElement.offsetParent;
    }
    return nTopPos;
}

function mouseX(evt) {
if (evt.screenX) return evt.screenX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.screenY) return evt.screenY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}

function getcheckedValues(varname) {

 var elems = document.getElementsByTagName("input");
 for (var k = 0; k < varname.length; k++)
 {
  var checkgroup = new Array();
  for (var i=0,j=0; i< elems.length; i++)
  {
    if (elems[i].type == "checkbox" && elems[i].name == varname[k])
    {
      checkgroup[j++] = elems[i];
    }
  }
  var checkedValue = "";
  for (var i=0; i < checkgroup.length; i++)
  { 
    if (checkgroup[i].checked == true)
    {
     checkedValue = checkedValue + checkgroup[i].value+"\n";
    }
  }
  var varname_elem = document.getElementsByName(varname[k]);
  for ( var i =0; i < varname_elem.length; i++)
  {
    varname_elem[i].value = checkedValue;
  }
 }
}


function addWindowEvent(event_name, func) {
    var oldonload = eval("window."+event_name);
    if (typeof oldonload != 'function') {
        eval("window."+event_name+" = func");
    }
    else {
        eval("window."+event_name+" = function() { if (oldonload) { oldonload(); } func(); }");
    }
}

// Flash detection
var flashInstalled = 0;
var flashversion = 0;
if (navigator.plugins && navigator.plugins.length)
{
    x = navigator.plugins["Shockwave Flash"];
    if (x)
    {
        flashInstalled = 1;
        if (x.description)
        {
            y = x.description;
            flashversion = y.charAt(y.indexOf('.')-1);
        }
    }
    else
        flashInstalled = 1;
    if (navigator.plugins["Shockwave Flash 2.0"])
    {
        flashInstalled = 1;
        flashversion = 1;
    }
}
else if (navigator.mimeTypes && navigator.mimeTypes.length)
{
    x = navigator.mimeTypes['application/x-shockwave-flash'];
    if (x && x.enabledPlugin)
        flashInstalled = 1;
    else
        flashInstalled = 0;
}
else {
    //IE
    for(var i=7; i>0; i--){
        try{
            var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
            flashInstalled = 1;
            flashversion = i;
        }
        catch(e){
        }
    }
}

function encode_utf8(instring) {
    string = instring.replace(/\r\n/g,"\n");
    var utftext = "";
    
    for (var n = 0; n < string.length; n++) {
    
        var c = string.charCodeAt(n);
    
        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    
    }
    
    return utftext;
}

function decode_utf8(utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
    
    while ( i < utftext.length ) {
    
        c = utftext.charCodeAt(i);
    
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    
    }

    return string;
}

// include any javascript on demand
function run_script (script_src) {
    var headID = document.getElementsByTagName('head')[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = script_src;
    headID.appendChild(newScript);
}

// add class of display_block if not already there
function display_as_block (elem) {
    if ( elem.className.match("display_block") ) {
        // do nothing
    }
    else if ( elem.className.match("display_none") ) {
        elem.className = elem.className.replace(/display_none/, "display_block");
    }
    else {
        elem.className += " display_block";
    }
    return;
}

// add class of display_none if not already there
function display_as_none (elem) {
    if ( elem.className.match("display_none") ) {
        // do nothing
    }
    else if ( elem.className.match("display_block") ) {
        elem.className = elem.className.replace(/display_block/, "display_none");
    }
    else {
        elem.className += " display_none";
    }
    return;
}

// removes display_none class to display elem naturally
// this works for table row display toggling where block can be broken in ff
// and table-row broken in ie
function display_as_default (elem) {
    if ( elem.className.match("display_none") ) {
        elem.className = elem.className.replace(/display_none/, "");
    }

    return;
}

// gets all the elements on the page in a class that matches the given class
// can restrict by tag
// it's much much faster if restricted by tag on our crowded pages
function getElementsByClass (class_name, tag_name){
    if (!tag_name) {
        tag_name = "*";
    }
    var test_elements = document.getElementsByTagName(tag_name);
    var elements_in_class = new Array();
    
    for (ii=0; ii<test_elements.length; ii++) {
        var elem = test_elements[ii];
        if ( elem.className.match(class_name) ) {
            elements_in_class.push(elem);
        }
    }
    return elements_in_class;
}

// hides all but one config module in a set
// assumes config modules are wrapped in tr container
// module ids in set should have pattern of <id_set_text><unique_text> (numbering works)
function display_one_module_of_set (display_id, id_set_txt) {
    // find the config module table rows in our id set 
    var test_elements = document.getElementsByTagName("tr");
    var elements_in_class = new Array();
    
    for (ii=0; ii<test_elements.length; ii++) {
        var elem = test_elements[ii];

        // hide all the set rows
        if (elem.id.indexOf(id_set_txt) == 0) {
            display_as_none(document.getElementById(elem.id));
        }
    }
    // show the display row
    display_as_default(document.getElementById(display_id));
}

function enableIPInput(elem_prefix) {
	for (var ii=0; ii<=3; ii++) {
		var obj = document.getElementById(elem_prefix+'__'+ii);
		if (obj) 
			obj.disabled = false;
	}
}

function disableIPInput(elem_prefix) {
	for (var ii=0; ii<=3; ii++) {
		var obj = document.getElementById(elem_prefix+'__'+ii);
		if (obj) 
			obj.disabled = true;
	}
}

// For check box
// To check all the checkboxes in the table when header table is checked and viceversa
function checkAll(tableId,headerCKBId)
{
 var headerCKB = document.getElementById(headerCKBId);
 var cklist = getCklist(tableId);
 if(headerCKB.checked==true)
 {
  for(i=0;i<cklist.length;i++)
  {
   if(cklist[i].checked == false)
   {
    cklist[i].checked = true;
   }
  }
 }
 else
 {
  for(i=0;i<cklist.length;i++)
  {
   if(cklist[i].checked == true)
   {
    cklist[i].checked = false;
   }
  }
 }
}

//To uncheck the header when anyof the table is unchecked
function checkMain(tableId,headerCKBId,currentCKB)
{
 headerCKB = document.getElementById(headerCKBId);
 currentID = document.getElementById(currentCKB);  
 cklist = getCklist(tableId);
 if(currentID.checked == false)
 {
  headerCKB.checked = false;
 }
 if(currentID.checked == true)
 {
  for(i=0;i<cklist.length;i++)
  {
   if(cklist[i].checked == false)
   {
    return;
   }
  }
  headerCKB.checked = true;
 }
}

function getCklist(tableId)
{
 var inputTypes = document.getElementById(tableId).getElementsByTagName("input");
 var cklist = new Array();
 for(i=1,j=0;i<inputTypes.length;i++)
 {
  if(inputTypes[i].getAttribute("type")=="checkbox" && inputTypes[i].getAttribute("disabled")!="disabled")
  {
   cklist[j++]=inputTypes[i];
  }
 }
 return cklist;
}

function hitenter(e,button){
    var keycode;
    if (!e) keycode = window.event.keyCode;
    else if( typeof( e.which ) == 'number' ) keycode = e.which;
    else if( typeof( e.keyCode ) == 'number' ) keycode = e.keyCode;
    else if( typeof( e.charCode ) == 'number' ) keycode = e.charCode;
    else return true;
    if (keycode == 13)
    {
        e.cancelBubble = true;
        e.returnValue = false;
        document.getElementById(button).click();
    }
    return false;
}

function textCounter(field, countfield, maxlimit) {
    felem = document.getElementById(field);
    celem = document.getElementById(countfield);
    if (felem.value.length > maxlimit) 
        felem.value = felem.value.substring(0, maxlimit);
    else 
        celem.value = maxlimit - felem.value.length;
}

// Check if a given pair of IP/Network address and Mask is valid
// Useful for httpd/snmpd or static route which reject or silently ignore invalid pairs
function isValidNetworkAndMask( network, netmask, error )
{
   var endOfOnes = false;
   var all255 = true;
   var all0 = true;
   if( document.getElementById( network + '__0' ).value == 0 ) {
       alert(error);
       return false;
   }
   for( var i = 0; i < 4; i++ ) {
       var net = parseInt(document.getElementById( network + '__' + i ).value);
       var mask = parseInt(document.getElementById( netmask + '__' + i ).value);

       if( endOfOnes && ( mask || net) || !mask && net ){
           alert(error);
           return false;
       } 

       if ( net != 255 ) {
            all255 = false;
       }
       if ( net != 0 ) {
            all1 = false;
       }
       if ( mask != 255 ) {
            endOfOnes = true;
       }
   }
   if( all1 || all255) {
       alert(error);
       return false;
   } else {
       return true;
   }
}

// Prevent right-click window to pop up
// Useful for disabling right-click copy into IP input field
function popupMenu(e){
    if (window.event) {
        event.returnValue=false;
        event.cancelBubble=true;
    }
    else {
        e.preventDefault();
        e.stopPropagation();
    }
}

// Disable/enable an element
// Useful for screens with many element controls
function disableElem( elem, flag ) 
{
    if( flag ) {
        elem.disabled = true;
    } 
    else {
        elem.disabled = false;
    }
}

function get_ip(id,with_blanks,placeholder)
{
    var values = new Array;
    for (var ii=0; ii<=3; ii++) {
        if(document.getElementById(id+'__'+ii) && document.getElementById(id+'__'+ii).value){
            values.push(document.getElementById(id+'__'+ii).value);
        }
        else if(with_blanks) {
            values.push(placeholder||'');
        }
        else {
            return '';
        }
    }
    return values.join(".");
}

// Get a hash containing the id and checked value of each 'grouped' checkbox.
//
// The JSON version of the checkbox widget provides a 'group_by_id' attribute.
// If 'group_by_id' is used, its value becomes the id of a div surrounding the checkboxes.
// Now we can get the status of each checkbox in the group without using hidden inputs
// and without assigning an onClick to every checkbox in the group.
//
// This function will return a hash of { $checkbox_id => $checked_state }.
function get_check_group(group_id) {
    var check_boxes = $H();
    $$('#' + group_id + ' input').each( function(input) {
        if (input.type == 'checkbox')
            check_boxes.set(input.id, (input.checked ? 1 : 0));
    });
    return check_boxes;
}

// javascript is stupid and does not seem to provide a pad or sprintf w/out including
// another library. This method simply ensures the lenght of the string passed in
// equals 2. The year value returned from date is always 4 digits (if you used
// date.getFullYear()) so this is only needed for the 2-digit fields.
function pad_date_part(part) {
    if (part.toString().length == 1) part = "0" + part;
    return part;
}

// formats a date as 'yyyy-mm-dd hh:MM'
function format_date(date) {
    // js uses 0-based month...
    return date.getFullYear() + "-" + pad_date_part(date.getMonth() + 1) + "-" + pad_date_part(date.getDate()) + " " + 
        pad_date_part(date.getHours()) + ":" + pad_date_part(date.getMinutes());
}

///Function for extended match widget
//STARTS
function showEdit(config_module_row,variable) {
    var elem = document.getElementById(config_module_row);
    if( elem.style.display == 'none' ) {
        elem.style.display = ''; 
        var header = document.getElementById(variable);
        document.getElementById('header_expression').value = header.value;
                
        updateList();
        } else {
            elem.style.display = 'none'; 
        }
}
function updateList() {
    var divEname=document.getElementById('Ename');
    var cEtype = document.getElementById('Etype');
    var text = cEtype[cEtype.selectedIndex].text;
    var Ename_text = document.getElementById('Etext');
    var Ename_box = document.getElementById('config_module_row_extended_rule__4');
    var value_text = document.getElementById('value_text');
    var value_box = document.getElementById('config_module_row_extended_rule__6');
    var EradioCnt = document.getElementById('ERadio');
    var valueCnt = document.getElementById('value_cont');
    var vckType = document.getElementById('VckType');
    var eckType = document.getElementById('EckType');

    // setting to default values
    EradioCnt.style.display = "none";
    valueCnt.style.display = "none";
    disableElem(Ename_text, true);
    disableElem(value_text, true);
    Ename_text.value = "";
    value_text.value = "";
    vckType.checked = false;
    eckType.checked = false;
// display relative items under ename and value
    switch(text) { 
        case "Client-IP":
            Ename_box.style.display = 'none';
            value_box.style.display = '';
            disableElem(Ename_text, true);
            disableElem(value_text, false);
            break;
        case "Method" :
            Ename_box.style.display = 'none';
            valueCnt.style.display = "inline";
            showType(text); 
            disableElem(Ename_text, true);                
            disableElem(value_text, true);
            break;
        case "HTTP-Version" :
            Ename_box.style.display = 'none';
            valueCnt.style.display = "inline";
            showType(text); 
            disableElem(Ename_text, true);
            disableElem(value_text, true);                
            break;
        case "URI" :
            Ename_box.style.display = 'none';
            value_box.style.display = '';
            disableElem(Ename_text, true);
            disableElem(value_text, false);
            break;
        case "Parameter" :
            Ename_box.style.display = '';
            EradioCnt.style.display="inline";                   
            showType(text);
            disableElem(Ename_text, true);     
            disableElem(value_text, false);
            break;
        case "Pathinfo" : 
            Ename_box.style.display = 'none';
            value_box.style.display = '';
            disableElem(Ename_text, true);
            disableElem(value_text, false);
            break;
        case "Header" :
            Ename_box.style.display = '';
            EradioCnt.style.display="inline";                   
            showType(text);
            disableElem(Ename_text, true);     
            disableElem(value_text, false);   
            break;
      }
}

function showType(text) {
    var Ename_parameter = document.getElementById('Ename_parameter');
    var Ename_header = document.getElementById('Ename_header');
    var value_method = document.getElementById('value_method');
    var value_httpversion = document.getElementById('value_httpversion');
    if(text == "Parameter") {
        Ename_header.style.display = "none";
        Ename_parameter.style.display = "inline";
    }
    else if(text == "Header") {
        Ename_header.style.display = "inline";
        Ename_parameter.style.display = "none";
    }
    else if(text == "Method") {
        value_method.style.display = "inline";
        value_httpversion.style.display = "none";
    }
    else if(text == "HTTP-Version") {
        value_method.style.display = "none";
        value_httpversion.style.display = "inline";
    }
}
//Fuction to insert expression into Header Expression text box
function insertExpression(error) {
    var cEtype = document.getElementById('Etype');
    var text = cEtype[cEtype.selectedIndex].text;
    var cOperation=document.getElementById('Operation');
    var oper = cOperation[cOperation.selectedIndex].value;
    var oper_text = cOperation[cOperation.selectedIndex].text;
    var value_text = document.getElementById('value_text');
    var ename_text = document.getElementById('Etext');
    var eckType = document.getElementById('EckType');
    var vckType = document.getElementById('VckType');
    var ename_header = document.getElementById('Ename_header');
    var ename_parameter = document.getElementById('Ename_parameter');
    var value_method = document.getElementById('value_method');
    var value_httpversion = document.getElementById('value_httpversion');
    var header_expression = document.getElementById('header_expression');
    var hexp = "";
    
    if(header_expression.value == "*") {
	header_expression.value = "";	
    }
                                 
    if( header_expression.value != "" ) {
        var radios = document.getElementsByName("oper");
        if(radios[0].checked == true) {
            hexp = radios[0].value;
        } else {
            hexp = radios[1].value;
        }
    }
    switch(text) {
        case "Client-IP":
            hexp = hexp+" ("+text+" ";
            hexp = hexp +oper+" ";
            if(isValidValue(value_text.value,oper_text)) {
                hexp = hexp+value_text.value+") ";
            } else {
                showErrMsg(error);
                return;
            }         
            break;
        case "Method":
            hexp = hexp+" ("+text+" ";
            hexp = hexp +oper+" ";
            var tempValue;
            if(!vckType.checked) {
                tempValue = value_method[value_method.selectedIndex].text;
            } else {
                tempValue = value_text.value;
            }
            if(isValidValue(tempValue,oper_text)) {
                hexp = hexp+tempValue+") ";
            } else {
                showErrMsg(error);
            return;
            }         
            break;
        case "HTTP-Version":
            hexp = hexp+" ("+text+" ";
            hexp = hexp +oper+" ";
            var tempValue;
            if(!vckType.checked) {
                tempValue = value_httpversion[value_httpversion.selectedIndex].text;
            } else {
                tempValue = value_text.value;
            }
            if(isValidValue(tempValue,oper_text)) {
                hexp = hexp+tempValue+") ";
            } else {
                showErrMsg(error);
                return;
            }         
            break;
        case "URI":
            hexp = hexp+" ("+text+" ";
            hexp = hexp +oper+" ";
            if(isValidValue(value_text.value,oper_text)) {
                hexp = hexp+value_text.value+") ";
            } else {
                showErrMsg(error);
                return;
            }         
            break;
        case "Parameter":
            hexp = hexp+" ("+text+" ";
            var tempEname;
            if(!eckType.checked) {
                tempEname = ename_parameter[ename_parameter.selectedIndex].text;
            } else {
                tempEname = ename_text.value;
            }
            if(isValidEname(tempEname)) {
                hexp = hexp+" "+tempEname+" ";
            } else {
                showErrMsg(error);
                return;
            }         
            hexp = hexp +oper+" ";
            if(isValidValue(value_text.value,oper_text)) {
                hexp = hexp+value_text.value+") ";
            } else {
                showErrMsg(error);
            return;
            }         
            break;
        case "Pathinfo":
            hexp = hexp+" ("+text+" ";
            hexp = hexp +oper+" ";
            if(isValidValue(value_text.value,oper_text)) {
                hexp = hexp+value_text.value+") ";
            } else {
                showErrMsg(error);
                return;
            }         
            break;
        case "Header":
            hexp = hexp+" ("+text+" ";
            var tempEname;
            if(!eckType.checked) {
                tempEname = ename_header[ename_header.selectedIndex].text;
            } else {
                tempEname = ename_text.value;
            }
            if( isValidEname(tempEname)) {
                hexp = hexp+" "+tempEname+" ";
            } else {
                showErrMsg(error);
                return;
            }         
            hexp = hexp +oper+" ";
            if(isValidValue(value_text.value,oper_text)) {
                hexp = hexp+value_text.value+") ";
            } else {
                showErrMsg(error);
                return;
            }         
            break;
    }
    header_expression.value = header_expression.value+hexp;
}

function isValidEname(value)
{
  if(""==value)
  {
  return false;
  }
  return true;
}

//Function to enable the text filed if others checkbox is enabled for value
function enableTextField( elem, ckbox ) {
    var textField = document.getElementById(elem);
    if( ckbox.checked ) {
        disableElem( textField, false );
    } else {
        disableElem( textField, true );
    }
}
//Funcion to check whether the validate the value entered
function isValidValue( value, text ) {
    var retValue = true;
    if( (!text.match("exists")) && (value == "") ) {
        return false;
    }
    return retValue;
}
//Function to show error message when invalid extended match is inserted
function showErrMsg(error) {
    alert(error);
}
//Function to insert the extended match into text box 
function copyValue( elem, row, variable ) {
    var block = document.getElementById(row);
    if( elem.value == 'Apply') {
        var header = document.getElementById(variable);
        header.value = document.getElementById('header_expression').value;
    }
    block.style.display = "none";
}
//Function to show the options when element type is selected
function disableElem( elem, flag )
{
    if( flag ) {
        elem.disabled = true;
    }
    else {
        elem.disabled = false;
    }
}

//Pattern regex match widget related functions
function showRegExp()
{
 var regularEx =  document.getElementById("regularExp");
 if (regularEx.style.display == 'none')
 {
   regularEx.style.display="block";
   var rexp1 = document.getElementById("UPDATE_new_input_pattern_regex");
   var rexp2 = document.getElementById("rexp2");
   rexp2.value=rexp1.value;
 }
 else
 {
   regularEx.style.display="none";
 }
}

function copyRegexValue(button, regexid)
{
 var regularEx =  document.getElementById("regularExp");
 var rexp1 = document.getElementById(regexid);
 var rexp2 = document.getElementById("rexp2");
 regularEx.style.display="none";
 if(button.value=="Apply")
 {
  rexp1.value=rexp2.value;
 }
}

function insertValues()
{
  var cclist= document.getElementsByName("cc");
  var ccrlist= document.getElementsByName("ccr");
  var rexp2=document.getElementById("rexp2");

  var ccselected,ccrselected;

  for(i=0;i<cclist.length;i++)
  {
    if(cclist[i].checked == true)
    {
      ccselected=cclist[i].value;
      break;
    }
  }

  for(i=0;i<ccrlist.length;i++)
  {
    if(ccrlist[i].checked==true)
    {
      ccrselected=ccrlist[i].value;
      break;
    }
  }

  var cc=getValueOfCc(ccselected);

  var ccr=getValueOfCcr(ccrselected,cc);
  rexp2.value=rexp2.value+ccr;
  rexp2.select();

}

function getValueOfCc(ccselected)
{
  if(ccselected == "specificString")
  {
    var value = document.getElementById("specificString").value;
    return escapedString(value);
  }
  else if(ccselected == "specificClass")
  {
    var spClass = document.getElementById("specificClass");
    return spClass.options[spClass.selectedIndex].text;
  }
  else
  {
    return ccselected;
  }
}

function escapedString(value)
{
  var escapeChars = new Array('+', '*', '?', '.', '[', ']', '^', '$', '(', ')', '{', '}', '|', '\\', '&');
  var escapedString = "";

  for(var i=0; i<value.length; i++)
  {
    if(escapeChars.indexOf(value[i] == -1))
    {
      escapedString = escapedString + value[i];
    }
    else
    {
      escapedString = escapedString + '\\' + value[i];
    }
  }
  return escapedString;
}

function getValueOfCcr(ccrselected,cc)
{
  var str;
  if(ccrselected=="JO")
  {
    return cc;
  }
  else if(ccrselected == "En")
  {
    str="("+cc+"){"+document.getElementById("En").value+"}";
    return str;
  }
  else if(ccrselected == "An")
  {
    return "("+cc+"){"+document.getElementById("An").value+",}";
  }
  else if(ccrselected=="Bnm")
  {
    return "("+cc+"){"+document.getElementById("n").value+","+document.getElementById("m").value+"}";
  }
  else
  {
    return "("+cc+")"+ccrselected;
  }
}

function togglePatternWidget()
{
   var divStatus = document.getElementById('regularExp').style.display;
   if(divStatus == 'block')
   {
        document.getElementById('regularExp').style.display = 'none';
   }
   else
   {
        document.getElementById('regularExp').style.display = 'block';
   }
}

//Functions related to metachar widget
function selectAll(select)
{
  var sel = select;

  var table = document.getElementById("chartable");
  for (var i = 0; i < table.rows.length; i++)
  {
    var x = document.getElementById("chartable").rows[i];

    if (table)
    {
      for (var r = 0; r < x.cells.length; r++)
      {
        if (sel == 0)
        {
          x.cells[r].bgColor = "#B0B0B0";
          x.cells[r].setAttribute("toggle","true");
        }
        else if (sel == 1)
        {
          x.cells[r].bgColor = "#FFFFFF";
          x.cells[r].setAttribute("toggle","false");
        }
      }
    }
  }
}

function toggleColor(evt)
{
  var targ;
  var e = evt;
  if (!e)
  {
    e = window.event;
  }

  if (e.target)
  {
    targ = e.target;
  }
  else if (e.srcElement)
  {
    targ = e.srcElement;
  }

  if (targ.nodeType == 3) // defeat Safari bug
  {
    targ = targ.parentNode;
  }

  if (targ.getAttribute("toggle") == "false")
  {
    targ.bgColor = "#B0B0B0";
    targ.setAttribute("toggle","true");
  }
  else
  {
    targ.bgColor = "#FFFFFF";
    targ.setAttribute("toggle","false");
  }
}

function getSelected(text_input)
{
  var finalString="";
  var table = document.getElementById("chartable");

  for (var i = 0; i < table.rows.length; i++)
  {
    var row=document.getElementById("chartable").rows[i];

    if (table)
    {
      for (var j=0; j<row.cells.length; j++)
      {
        if(row.cells[j].getAttribute("toggle")=="true")
        {
          finalString = finalString + row.cells[j].getAttribute("value");
        }
      }
    }
  }
  document.getElementById(text_input).value = finalString;
}

function getSelectedValues(text_input)
{
  var value = document.getElementById(text_input).value;
  var metaChars = new Array();
  while(value.indexOf('%')!=-1)
  {
     var index = value.indexOf('%');
     metaChars.push(value.substring(index, index+3));
     value = value.substring(index+3, value.length);
  }
  return metaChars;
}

function setSelected(text_input)
{
  var metaChars = getSelectedValues(text_input);

  var table = document.getElementById("chartable");
  for (var i = 0; i < table.rows.length; i++)
  {
    var x = document.getElementById("chartable").rows[i];

    if (table)
    {
      for (var r = 0; r < x.cells.length; r++)
      {
        for(var j = 0; j < metaChars.length; j++)
        {
            var value = x.cells[r].getAttribute("value");
            if (metaChars[j] == x.cells[r].getAttribute("value"))
            {
                x.cells[r].bgColor = "#B0B0B0";
                x.cells[r].setAttribute("toggle","true");
            }
        }
      }
    }
  }

}

function hideCharMap()
{
  var layer = document.getElementById("charmap");
  layer.style.display = "none";
}

function toggleCharMap()
{
   var divStatus = document.getElementById('charmap').style.display;
   if(divStatus == 'block')
   {
        document.getElementById('charmap').style.display = 'none';
   }
   else
   {
        document.getElementById('charmap').style.display = 'block';
   }
}
///ENDS 
