//
// Main Javascript for site
//
// Included by all pages
//

var debugEnabled = false;

// Browser detection object
function Is()
{
  var agent = navigator.userAgent.toLowerCase();
  this.major = parseInt(navigator.appVersion);
  this.minor = parseFloat(navigator.appVersion);
  this.mac = (agent.indexOf("mac") != -1);
  this.ns = ((agent.indexOf('mozilla')!=-1) &&
    ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
  this.ns2 = (this.ns && (this.major == 3));
  this.ns3 = (this.ns && (this.major == 3));
  this.ns4 = (this.ns && (this.major >= 4));
  this.ns406 = (this.ns && (this.minor == 4.06));
  this.ns407 = (this.ns && (this.minor == 4.07));
  this.ns408 = (this.ns && (this.minor == 4.08));
  this.ns45 = (this.ns && (this.minor == 4.5));
  this.ie  = (agent.indexOf("msie") != -1);
  this.ie3 = (this.ie && (this.major == 2));
  this.ie4 = (this.ie && (this.major >= 4));
  this.op3 = (agent.indexOf("opera") != -1);
  this.dynamicBrowser = (this.ns4 || this.ie4);
}

// Global variables
var is = new Is();
var siteName = 'LunarLoony';
var siteURL = 'http://www.lunarloony.com';

// Check that we are entering by TNT domain name -
// if we are then redirect us to the LUNARLOONY domain
// (This site must be accessed from its domain or else the SHTML won't work
// as it uses absolute paths).
if (location.protocol == 'http:' && location.hostname.indexOf('www.tnt') != -1)
{
  // We have to strip the '/lunarloony' from the path name
  var url = siteURL + location.pathname.substring(11, location.pathname.length);
  location.href = url;
}

// Check if we are locally accessing this site
if (location.protocol == 'file:')
{
  var re = /^(.*lunarloony)\/.*$/i
  siteURL = location.href.replace(re, '$1');
  //alert('You are locally accessing this web site from "' + siteURL + '"');
}

if (window.name == null || window.name == '')
{
  window.name = 'untitled';
}

/*
if (window.name != 'Evaluator' && location.protocol == 'file:')
{
  debugEnabled = confirm('Do you wish to enable debugging for window "' +
    window.name + '\" ?');
  if (debugEnabled)
  {
    showEvaluator();
  }
}
*/

// Because NS and IE use different text here
var visibleVal = is.ns ? "show" : "visible";
var hiddenVal = is.ns ? "hide" : "hidden";
var inheritVal = "inherit";

if(is.ns4) {
    doc = "document";
    sty = "";
    htm = ".document"
    xpos = "e.pageX";
    ypos = "e.pageY";
} else if(is.ie4) {
    doc = "document.all";
    sty = ".style";
    htm = ""
    xpos = "event.x";
    ypos = "event.y";
}

function onError(msg, url, line)
{
  if (is.ns)
  {
    document.location.href = "javascript:";
  }
  else if (is.ie)
  {
    debug('<b>An error was thrown and caught.</b><br>' +
          'Error: ' + msg + '<br>' +
          'Line: ' + line + '<br>' +
          'URL: ' + url + '<br>');
    return true;
  }
}

// Function to toggle image	
function imageSwitch(imageName, which)
{
  document.images[imageName].src = eval(imageName + which).src;
}

// Function to pulsate the aniGlowText class
function doAniGlow(name, color, strength)
{
  if (is.ie4)
  {
    // If the strength it less than 10
    if (strength < 10)
    {
      // then increase it by one,
      strength += 1;
    }
    else
    {
      // decrease it by one.
      strength -= 1;
    }

    // Give the values of the variable to the filter property
    // Our aniGlowText class is rule 5 of style sheet 1 (main.js)
//    for (i = 0; i < document.styleSheets.length; i++)
//    {
//      alert("Style sheet " + i + " is titled " + document.styleSheet(i).title);
//    }

//    document.styleSheets(0).rules(5).style.filter =  "glow(color='" + color +"', strength=" + strength + ")";

    // Finally, wait 10 milliseconds and start it all again.
    setTimeout("doAniGlow(" + name + ", '" + color + "', " + strength + ")", 100);
  }
}

function getListValue(list) 
{ 
  var listValue = ""; 

  if (list.selectedIndex != -1)
  { 
    listValue = list.options[list.selectedIndex].value; 
  } 

  return (listValue); 
} 

function getProperties(obj)
{ 
  var properties = '<TABLE BORDER="2" WIDTH="90%" COLS="2">' +
    '<TR ALIGN="left" BGCOLOR="lightgrey"><TH>Property</TH><TH>Value</TH></TR>';
    
  for (var objPropName in obj)
  { 
    if (objPropName == "domain")
    {
      properties += "<TR><TD>" + objPropName + "</TD><TD>" +
        "[Domain value not displayed]&nbsp;</TD></TR>";
    }
    else
    {
      properties += "<TR><TD>" + objPropName + "</TD><TD>" +
        obj[objPropName] + "&nbsp;</TD></TR>";
    }
    if (objPropName == "style" ||
        objPropName == "runtimeStyle" ||
        objPropName == "currentStyle")
    {
      for (var stylePropName in obj[objPropName])
      { 
        properties += ("<TR><TD>" + objPropName + "." + stylePropName +
          "</TD><TD>" + obj.style[stylePropName] + "&nbsp;</TD></TR>");
      }
    }
  } 

  properties += "</TABLE>";
  return properties; 
} 

function showProperties(object, name)
{
  if (!debugEnabled)
  {
    return;
  }

  var win = window.open("","Properties",
    "height=350,width=350,status=1,resizable=1,scrollbars=1");
  var doc = win.document;
	
  win.name = "Properties";
  win.title = "Properties for " + name;

  doc.write("<HTML><HEAD><TITLE>" + name + "</TITLE></HEAD><BODY>")
  doc.write(getProperties(object));
  doc.write("</BODY></HTML>");
  doc.close();
}


// Evaluate an expression (including executing a statement)
// and display returned values in 'output' textarea. Provide
// switch for Navigator codebase principal security.
function evaluateIt(form)
{
  if (is.ns && form.security.checked)
  {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
  }

  form.output.value = eval(form.input.value);

  if (is.ns && form.security.checked)
  {
    netscape.security.PrivilegeManager.disablePrivilege("UniversalBrowserRead");
    netscape.security.PrivilegeManager.disablePrivilege("UniversalBrowserWrite");
  }
}

// Event handler looks for Enter key to trigger evaluateIt()
function evalIfReady(form, evt)
{
  if (is.ns ? (evt.which == 13) : (evt.keyCode == 13))
  {
    evaluateIt(form);
    return false;
  }
  
  return true;
}

// List all properties of an object (except for document.domain) 
// in the 'output' textarea.
function showProps(form)
{
  objName = form.inspector.value;
  obj = eval(objName);
  var msg = "";
  var cr = (is.mac) ? "\r\n" : "\n";
  for (var i in obj)
  {
    if (i != "domain")
    {
      msg += objName + "." + i + "=" + obj[i] + cr;
    }
  }
  form.output.value = msg;
}

// Event handler looks for Enter key to trigger showProps()
function showPropsIfReady(form, evt)
{
  if (is.ns ? (evt.which == 13) : (evt.keyCode == 13))
  {
    showProps(form);
    return false;
  }

  return true;
}

// Writes The Evaluator fields to your document wherever you want.
function showEvaluator()
{
  if (!debugEnabled)
  {
    return;
  }

  var win = window.open("","Evaluator",
    "height=400,width=350,status=0,resizable=1,scrollbars=0");
  var doc = win.document;

  win.name = "Evaluator";
  win.title = "Javascript Evaluator for window : " + window.name;
  win.opener = window;
	
  doc.writeln("<HTML><HEAD><TITLE>" + win.title + "</TITLE>");
  doc.writeln("<SCRIPT LANGUAGE='javascript' SRC='" + siteURL +
    "/scripts/main.js'></SCRIPT></HEAD><BODY>");
  doc.writeln("<FORM onSubmit='return false'>");
  doc.writeln("<P>Enter an expression to evaluate:<BR>");
  doc.writeln("<INPUT TYPE='text' NAME='input' SIZE=40");
  if (!(is.ie && is.mac))
  {
    doc.writeln(" onKeyPress='return window.opener.evalIfReady" + 
      "(this.form, event)'");
  }
  doc.writeln("><INPUT TYPE='button' VALUE='Evaluate' ");
  doc.writeln("onClick='window.opener.evaluateIt(this.form)'>");
  if (is.ns)
  {
    doc.writeln("&nbsp;&nbsp;<INPUT TYPE='checkbox' NAME='security'>" +
      "Use Codebase Security");
  }
  doc.writeln("</P><P>Enter a reference to an object:<BR>");
  doc.writeln("<INPUT TYPE='text' NAME='inspector' SIZE=40 ");
  if (!(is.ie && is.mac))
  {
    doc.writeln(" onKeyPress='return window.opener.showPropsIfReady" +
      "(this.form, event)' ");
  }
  doc.writeln("><INPUT TYPE='button' VALUE='Inspect' ");
  doc.writeln("onClick='window.opener.showProps(this.form)'>");
  doc.writeln("</P><P>Results:<BR>");
  doc.writeln("<TEXTAREA NAME='output' COLS=38 ROWS=6 WRAP='virtual'>");
  doc.writeln("</TEXTAREA></P>");
  doc.writeln("<P align='center'><INPUT TYPE='button' VALUE='Close' ");
  doc.writeln("onClick='window.close()'></P>");
  doc.writeln("</FORM>");
  doc.writeln("</BODY></HTML>");
  doc.close();
}

function debug(text)
{
  if (!debugEnabled)
  {
    return;
  }
  if (is.ie)
  {
    /* This writes a line to our own debug window */
    if (!top.debugWin || top.debugWin.closed)
    {
      top.debugWin = window.open('','Debug',
        'height=200,width=500,status=1,resizable=1,scrollbars=1');
    }
	
    top.debugWin.document.body.insertAdjacentHTML('beforeEnd',
      window.name + ': ' + text + '<br>');
    top.debugWin.scrollTo(0, top.debugWin.document.body.scrollHeight);
  }
  else if (is.ns)
  {
    /* This writes a line to the Java console window */
    java.lang.System.out.println(window.name + ': ' + text)
  }
}

// Function called when any page is loaded.
function onLoad()
{
  debug('onLoad()');

  debug('name=' + name);
  debug('href=' + location.href);
  debug('siteURL=' + siteURL);
  debug('referrer=' + document.referrer);
}

// Function called when any page is unloaded.
function onUnLoad()
{
  debug('onUnLoad()');

}
// Create a cookie with the specified name and value.
function setCookie(sName, sValue, days, path)
{
  var cookie = sName + "=" + escape(sValue); 
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    cookie += '; expires=' + date.toGMTString();
  }
  if (path)
  {
    cookie += '; path=' + path;
  }
  else
  {
    cookie += '; path=/';
  }

  document.cookie = cookie;
}

// Retrieve the value of the cookie with the specified name.
function getCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equals sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

// Delete a cookie
function delCookie(sName)
{
  SetCookie(sName, '', -1);
}

function docLoad(doc, html)
{
  if (!doc)
    doc = document;
  if (!html)
    html = '<html></html>';
  doc.open();
  doc.writeln(html);
  doc.close();
}

function insertSiteURL(doc, url, target)
{
  if (!doc)
    doc = document;
  if (!url)
    url = ''
  if (!target)
    target = "_blank";
  doc.write('<a href="' + siteURL + '/' + url + '" target="' + target + '">');
}

function insertDateAndTime(doc)
{
  if (!doc)
    doc = document;
  var d = Date();
  doc.write(d.toString());
}

// A function to insert the current date in to a document
function insertDate(doc)
{
  var d = Date();
  var s = d.toString();
  doc.write(s.replace(/ \d\d:\d\d:\d\d /, ' '));
}

function getYearDay(date)
{
  // Convert date to day of year
  var cd = new Date(date.getYear(), date.getMonth(), date.getDate());
  var fd = new Date(date.getYear(), 0, 1);
  var yearsecs = (cd - fd);
  var daymsecs = (1000 * 60 * 60 * 24);
  return (yearsecs / daymsecs);
}

function fixPath(p)
{
  return (p.substring(0,2) == '/:') ? p.substring(p.indexOf('/', 2), p.length) : p;
}

function getParm(theStr, parm, delim)
{
  // returns value of parm from string
  if (theStr.length == 0)
  {
    return('');
  }

  var sPos = theStr.indexOf(parm + "=");
  if (sPos == -1)
  {
    return('');
  }

  sPos = sPos + parm.length + 1;
  
  var ePos = theStr.indexOf(delim, sPos);
  if (ePos == -1)
  {
    ePos = theStr.length;
  }

  return unescape(theStr.substring(sPos, ePos));
}

window.onerror = onError;
