// object sensing routine
var isNN4up = (window.Event) ? true : false;
var target_name = new String();

// This object stores all the browser info you most commonly want
// saves you determining things over and over again.
function BrowserDetails()
{
  // default properties and values
  this.cssEnabled = true;
  this.browserType = "[unknown]";
  this.majVersion = null;
  this.DOMable = null;

  //determine the browser
  if( navigator.userAgent.indexOf( "Opera" ) != -1 ) 
  {
    if( navigator.appName == "Opera" ) 
    {
      this.majVersion = parseInt( navigator.appVersion );
    } 
    else 
    {
      this.majVersion = parseInt( navigator.userAgent.substring( navigator.userAgent.indexOf( "Opera" )+6 ) );
    }
    if(this.majVersion >= 5) 
    {
      this.browserType = "O";
    }
  } 
  else if( navigator.appName == "Netscape" && navigator.userAgent.indexOf("WebTV") == -1 ) 
  {
    this.browserType = "NN";
    if( parseInt( navigator.appVersion ) == 3 ) 
    {
      this.majVersion = 3;
      this.cssEnabled = false;
    } 
    else if( parseInt(navigator.appVersion) >= 4 ) 
    {
      this.majVersion = parseInt( navigator.appVersion ) == 4 ? 4 : 5;
      if( this.majVersion >= 5 ) 
      {
        this.DOMable = true;
      }
    }
  } 
  else if( navigator.appName == "Microsoft Internet Explorer" && parseInt( navigator.appVersion ) >= 4 ) 
  {
    if( navigator.userAgent.toLowerCase().indexOf("mac") != -1 ) 
    {
      this.browserType = "NN";
      this.majVersion = 4;
      this.DOMable = false;
    } 
    else 
    {
      this.browserType = "IE";
      this.majVersion = navigator.appVersion.indexOf("MSIE 6.") != -1 ? 6 : ( navigator.appVersion.indexOf("MSIE 5.") != -1 ? 5 : 4 );
      if(this.majVersion >= 5) 
      {
        this.DOMable = true;
      }
    }
  }
}

// BrowserObj
var BrowserObj = new BrowserDetails();

function popup_make_base_target(tgt)
{
  if ( tgt.length > 0 )
  {
    target_name = tgt;
  }
  else
  {
    var target = top.opener;
    if ( target ) target_name = target.name;
  }
}

function shiftHeld(e) 
{
  var isShifted;

  if (isNN4up) 
  {
    isShifted = e.modifiers & ( Event.SHIFT_MASK |  Event.ALT_MASK | Event.CONTROL_MASK );
  } 
  else 
  {
    isShifted = window.event.shiftKey | window.event.ctrlKey | window.event.altKey;
  }

  return isShifted;
}

function closeOnNoShift(e)
{
  if (!shiftHeld(e)) top.close();
}

function onPopClick(e,url)
{
  if ( target_name.length > 0 )
  {
    // alert( "target name = " + target_name );
    window.open( url, target_name );
    closeOnNoShift(e);
    return false;
  }
  else if ( top.opener != null && !top.opener.closed )
  {
    top.opener.location = url;
    closeOnNoShift(e);
    return false;
  }
  return true;
}

function submit_category(form)
{
  var index = form.category_args.selectedIndex;
  var args = form.category_args.options[index].value;

  //parse the category args we are only expecting match and lb separated by a ;
  var args_array = args.split(";");

  for( i = 0; i < args_array.length; ++i)
  {
    if ( args_array[i].substr(0, 3) == "lb=" )
    {
      form.lb.value = args_array[i].slice( 3 );
      form.lb.value = unescape( form.lb.value );
    }
    else if ( args_array[i].substr(0, 6) == "match=" )
    {
      form.match.value = args_array[i].slice(6);
      form.match.value = unescape( form.match.value );
    }
  }

  //alert( "args = " + args );
  //alert( "lb = " + form.lb.value );
  //alert( "match = " + form.match.value );
  return true;
}

// Called from navbar-top.pmp
function show_category(target, form)
{
  var listbox = form.categories;
  var url;

  if(listbox.selectedIndex > 0) {
    url = form.action
          + '?side_bar=' + form.side_bar.value + '?taxonomy=' 
          + listbox[listbox.selectedIndex].value + '%3bhide-logo=true'
          + ';body=' + form.body.value;
  }
  else if(listbox.selectedIndex == 0)
  {
    // Put the category list in to the main frame.
    url = listbox[0].value;
  }
  target.location = url ;

  return false; // Always return false to stop forms being submitted, etc.
}

function update_search_text(self)
{
  var search_text;
  search_text = self.match.value;
  //alert("Search text = " + search_text );  
  //alert("Previous text = " + window.parent.document.frames[0].searchForm.match.value );
  if ( window.parent.frames[0] != null )
  {
    if ( window.parent.frames[0].searchForm != null )
    {
      window.parent.frames[0].searchForm.match.value = search_text;
    }
  }
}


// Look for a frame by name -- only start_window and it's children are 
// considered, you must pass in window.top if you want to search all frames.
function get_named_frame( start_window, frame_name )
{
  //  ... is frame_name me?
  if (start_window.name == frame_name) 
  {
    return start_window;
  }

  // ... is the frame a child of the current window?

  var named_frame;
  named_frame = start_window.frames[frame_name];
  if(named_frame)
  {
    return named_frame;
  }

  // ... the frame_name wasn't found, so now look for the frame in the 
  //     frame array of each child frame
  for( i=0; i<start_window.frames.length; ++i )
  {
    named_frame = get_named_frame(start_window.frames[i], frame_name);
    if( named_frame )
    {
      return named_frame;
    }
  }

  // ... no frame was found here, return 0
  return 0;
}

// This function is probably not what you want!
// It searches for a named frame from the top window, which may be 
// dangerous if you have been nested deeper than you expected.
function load_url_in_frame_from_form( my_form )
{
  load_url_in_frame_from_form2(window.top, my_form)
}

// Search for a named frame in or below start_window (including start_window)
function load_url_in_frame_from_form2( start_window, my_form )
{
  //check that the input form has the right (hidden) inputs
  if(!my_form.frame_name)
  {
    document.write("<title>JavaScript Problem</title><body>" + 
                   "<p>Form has no frame_name input.</p></body>");
    document.close(); // ... needed to stop the Mozilla Throbber
    return false;
  }
  if(!my_form.url_to_load)
  {
    document.write("<title>JavaScript Problem</title><body>" +
                   "<p>Form has no url_to_load input.</p></body>");
    document.close(); // ... needed to stop the Mozilla Throbber
    return false;
  }

  // set up short names
  frame_name = my_form.frame_name.value;
  url = escape(my_form.url_to_load.value);
  
  // look for the named frame
  target_window = get_named_frame(start_window, frame_name);
  if(!target_window)
  {
    document.write("<title>JavaScript Problem</title><body>" +
                   "<p>No frame called \"" + frame_name + 
                   "\" was found.</p></body>");
    document.close(); // ... needed to stop the Mozilla Throbber
    return false;
  }

  target_window.location = url;

  return false; // don't submit this form, or follow hyperlinks
}

// Replace the current document referenced by my_doc
function replace_url_in_document( my_doc, my_form )
{
  url = escape(my_form.url_to_load.value);
  my_doc.location = url;
  // See http://www.jennifermadden.com/162/examples/location.html for 
  // "location = url" vs "location.href = url" insight.

  return false; // don't follow hrefs or submit forms
}

function load_frames( uris )
{
  // alert( "Num uris = " + uris.length );
  var max = uris.length;
  if ( frames.length < max )
    max = frames.length;
  for( i = 0; i < max; ++i)
  {
    if (uris[i].length > 0)
      frames[i].location = uris[i];
  }
  return false;
}

function open_in_new_window_handler(e, url, nav_in_frameset)
{
  var firingObj = ( BrowserObj.browserType == "IE" ) ? event.srcElement : e.target;
  
  if ( BrowserObj.browserType == "NN" && BrowserObj.majVersion > 4 )
    firingObj = firingObj.parentNode;
  
  var event_number = 0;
  if ( BrowserObj.browserType == "IE" )
    event_number = event.button;
  else
    event_number = e.which;

  if ( event_number == 2 || event_number == 3 )
  {
    // get the template name & args from the firingObj href
    // we are expecting hrefs of the form:
    // href="taxonomy.pmp?name=taxonomy:xxx" or href="search.pmp?match=xxx" etc.
    
    var split_array = url.split(/\?/);
    
    if ( split_array.length != 2 )
      alert( "Error in open_in_new_window_handler() - href parsing error." );
      
    //we specially escape ' characters so we need to unencode them first
    split_array[1] = replaceSubstring( split_array[1], "%27", "'" );
    
    var args_str = escape( split_array[1] );  
    
    var template_name = split_array[0];
      
    //will only work in JavaScript 1.2 and above
    //args_str = args_str.replace( /(\;)/gi , "%3B" );
    //args_str = args_str.replace( /(\&)/gi , "%3B" );
    
    args_str = replaceSubstring( args_str, ";", "%3B" );
    args_str = replaceSubstring( args_str, "&", "%3B" );
    
    firingObj.target = "_top";
    var href_val = "/pmp/nav-frames.pmp?side_bar=" + template_name + "?" + args_str + ";body=/blank.html";
    firingObj.href = href_val;
  }
  else
  {
    firingObj.target = (nav_in_frameset) ? "_parent" : "_self";
    firingObj.href = "/pmp/" + url;
  }
  
  return true;
}

function disable_right_click(e)
{
  var browser = navigator.appName.substring ( 0, 9 );    
  var event_number = 0;
  if ( browser == "Microsoft" )
    event_number = event.button;
  else if ( browser == "Netscape" )
    event_number = e.which;

  if ( event_number==2 || event_number==3 )
  {
    alert ("Right Mouse Button Is Disabled");
    return (false);
  }

  return (true);
}

function check_mousekey ()
{
  var mouse_key = 93;
  var keycode = event.keyCode;

  if ( keycode == mouse_key )
    alert ( "Mouse Key Is Disabled" );
}

function trap_page_mouse_key_events ()
{
  var browser = navigator.appName.substring ( 0, 9 );

  document.onmousedown = disable_right_click;

  if ( browser == "Microsoft" )
    document.onkeydown = check_mousekey;
  else if ( browser == "Netscape" )
    document.captureEvents( Event.MOUSEDOWN );
}

function add_in_query_args( args )
{
  var args_to_add = args;
  
  //step past the starting '?'
  if ( args_to_add.charAt(0) == '?' )
    args_to_add = args.substring( 1, args.length );
    
  //fracture up the args string looking for ';' and '&'
  //seperators - once a fracture point is found we need
  //to break up the arg=value pair so that we
  //can create form submission html elements
    
  arg_array = args_to_add.split(/[;&]/);

  for ( var i = 0; i < arg_array.length; i++ )
  {
    arg_val_array = arg_array[i].split("=");
    document.writeln('<input type="hidden" name="' + arg_val_array[0] + '" value="' + unescape(arg_val_array[1]) + '" />'); 
  } 
}

//we can use this function when the browser does not support regular expressions which were
//introduced in JavaScript1.2.

function replaceSubstring(inputString, fromString, toString) 
{
  // Goes through the inputString and replaces every occurrence of fromString with toString
  var temp = inputString;
  if (fromString == "") 
  {
    return inputString;
  }
  
  if (toString.indexOf(fromString) == -1) 
  { 
    // If the string being replaced is not a part of the replacement string (normal situation)
    while (temp.indexOf(fromString) != -1) 
    {
      var toTheLeft = temp.substring(0, temp.indexOf(fromString));
      var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
      temp = toTheLeft + toString + toTheRight;
    }
  } 
  else 
  { 
    // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
     var midStrings = new Array("~", "`", "_", "^", "#");
     var midStringLen = 1;
     var midString = "";
    
     // Find a string that doesn't exist in the inputString to be used
     // as an "inbetween" string
     
     while (midString == "") 
     {
       for (var i=0; i < midStrings.length; i++) 
       {
         var tempMidString = "";
         
         for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
         
         if (fromString.indexOf(tempMidString) == -1) 
         {
           midString = tempMidString;
           i = midStrings.length + 1;
         }
       }
     } 
     // Keep on going until we build an "inbetween" string that doesn't exist
     
     // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
     while (temp.indexOf(fromString) != -1) 
     {
       var toTheLeft = temp.substring(0, temp.indexOf(fromString));
       var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
       temp = toTheLeft + midString + toTheRight;
     }
      
     // Next, replace the "inbetween" string with the "toString"
     while (temp.indexOf(midString) != -1) 
     {
       var toTheLeft = temp.substring(0, temp.indexOf(midString));
       var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
       temp = toTheLeft + toString + toTheRight;
     }
  } // Ends the check to see if the string being replaced is part of the replacement string or not
   
  return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

function produce_breadcrumb_navigation( path, breadcrumb, template_name, query_args )
{  
  //The path and the breadcrumb arguments could have double CDATA encoding
  //so we need to cope with this here
  path = replaceSubstring( path, "&#38;", "&" );
  path = replaceSubstring( path, "&#amp;", "&" );
  breadcrumb = replaceSubstring( breadcrumb, "&#38;", "&" );
  breadcrumb = replaceSubstring( breadcrumb, "&#amp;", "&" );
  
  //fracture the path into seperate nodes the '/' character is the seperator
  var cat_array = path.split("/");
  var breadcrumb_array = breadcrumb.split("/");

  //construct the href from the original template name and the query args
  //but with the current node argument removed

  var href_content = template_name + "?";

  //step past the starting '?'
  if ( query_args.charAt(0) == '?' )
    query_args = query_args.substring( 1, query_args.length );

  //var re1 = new RegExp ('&#38;', 'gi');
  //var re2 = new RegExp ('&amp;', 'gi');
  //query_args = query_args.replace( re1, "&" );
  //query_args = query_args.replace( re2, "&" );
    
  query_args = replaceSubstring( query_args, "&#38;", "&");
  query_args = replaceSubstring( query_args, "&amp;", "&");
  
  //query_args = query_args.replace( /&#38;/gi, "&" );
  //query_args = query_args.replace( /&amp;/gi, "&" );

  var arg_array = query_args.split(/[;&]/);

  for ( var i = 0; i < arg_array.length; i++ )
  {
    var val_array = arg_array[i].split("=");
    if ( val_array[0] != "node" && val_array[0] != "breadcrumb" && val_array[0] != "match" && val_array[0] != "show-results-only")
      href_content = href_content + val_array[0] + "=" + val_array[1] + ";";
  }

  for ( var i = 0; i < breadcrumb_array.length; i++ )
  {
    var category_path;
  
    if ( i == 0 )
      category_path = "/";
    else if ( i == 1 )
      category_path = escape(cat_array[i-1]);
    else
      category_path += "/" + escape(cat_array[i-1]);

    var new_breadcrumb;
    
    for ( var j = 0; j <= i; ++j )
    {
      if ( j == 0 )
        new_breadcrumb = escape( breadcrumb_array[j] );
      else
        new_breadcrumb = new_breadcrumb + "/" + escape( breadcrumb_array[j] );     
    }

    if ( i == breadcrumb_array.length - 1 )
      document.write('<b class="pm-body-x-small">' + breadcrumb_array[i] + '</b>');
    else
      document.write('<a href="' + href_content + 'node=' + category_path + ';breadcrumb=' + new_breadcrumb + '">' + breadcrumb_array[i] + '</a>');
  
    if ( i < breadcrumb_array.length - 1 )
      document.write(' > ');
  }
}


// Returns a copy of the string without leading or trailing whitespace.

function trim ( str )
{
  var i = 0;
  var j = 0;
  var whitespace = new String(" \t\n\r");

  for( i = 0; ; i++ )
  {
    if ( i == str.length )
      return '';

    if ( whitespace.indexOf(str.charAt(i)) == -1 )
      break;
  }

  for ( j = str.length - 1; j > i; j-- )
  {
    if ( whitespace.indexOf(str.charAt(j)) == -1 )
      break;
  }

  return str.substring( i, j+1 );
} 


