
// here's our function to update the screen size...
function updateScreen()
  {
  if (firstRun != true)
    {
    document.getElementById('bottomLeft').style.left = xPlaygroundSize + 'px';
    document.getElementById('bottomLeft').style.top = yPlaygroundSize + 'px';
    }
  setTimeout("updateScreen()",100);
  } // end function


// javascript:flyTo('bottomLeft');
function flyTo(divID) 
  {
  firstRun = false;
  
  // figure out where we are...
  currentXValue = (document.all)?document.body.scrollLeft:window.pageXOffset;
  currentYValue = (document.all)?document.body.scrollTop:window.pageYOffset;
  
  // provide a way to go home, if we need it...
  if (divID == 'home' || !divID || divID == '1')
    {
    xDestination = 0;
    yDestination = 0;
    document.title = 'jon roig dot com : home';
    }
  else
    {
    // get the location of the div + cleanup the stuff
    xDestination = document.getElementById(divID).style.left;
    yDestination = document.getElementById(divID).style.top;
    xDestination = xDestination.replace(/px/g,'');
    yDestination = yDestination.replace(/px/g,'');
    xDestination = xDestination - 40;
    yDestination = yDestination - 40;
    } // end else

  
  // calculate the distance that has to be moved with each step
  // if we're going to do [speed] number of steps...
  totalDistanceX = xDestination - currentXValue;
  totalDistanceY = yDestination - currentYValue;
  speed = 100;
  moveChunkX = totalDistanceX/speed;
  moveChunkY = totalDistanceY/speed;
  
  
  // move horizontal
  var x = 0;
  while(x <= speed)
    {
    newXPos = (x * moveChunkX) + currentXValue;
    window.scrollTo(newXPos, currentYValue);
    x++;
    } // end while      
  
  // move vert
  var x = 0;
  while(x <= speed)
    {
    newYPos = (x * moveChunkY) + currentYValue;
    window.scrollTo(newXPos, newYPos);
    x++;
    } // end while        
  
  // finally, just in case we screwed up, let's move to the final position
  window.scrollTo(xDestination,yDestination);
  
  // finally, we'll set a cookie so we can restore the session later...
  createCookie('lastVisited',divID,365);
  } // end function


// setup the request object... 
// this came from rasmus's tutorial on these things....
function createRequestObject()
  {
  var ro;
  var browser = navigator.appName;
  if(browser == "Microsoft Internet Explorer")
    {
    ro = new ActiveXObject("Microsoft.XMLHTTP");
    }
  else
    {
    ro = new XMLHttpRequest();
    }
  return ro;
  } // end function

// initialize the xml request
var http = createRequestObject();

// pass the story request to the engine the grabs those things....
function getStory(getID)
  {
  if (getID == '0' || getID == 'guestbook'){showCommentsOnArrival = true;}
  if (getID == '1')
    {
    getID = '1';
    flyTo('1');
    }
  else
    {
    cacheTime = new Date();
    http.open('get', 'getStory.php?id='+getID + '&noCache=' + cacheTime.getUTCSeconds() );
    http.onreadystatechange = handleGetStoryResponse;
    http.send(null);
    } // end else
  } // end function

function getTopic(categoryID)
  {
  cacheTime = new Date();
  http.open('get', 'getStory.php?id='+categoryID + '&getCategory=yup' + '&noCache=' + cacheTime.getUTCSeconds());
  http.onreadystatechange = handleGetStoryResponse;
  http.send(null);
  }


// and this is that engine...
function handleGetStoryResponse()
  {
  if(http.readyState == 4)
    {
    var response = http.responseText;
    var update = new Array();
    
    // since the object is json, we can process it like an object...
    var divObject = response.parseJSON();
    temp = playgroundProcessDiv(divObject);
    } // end if
  } // end function





  
// HERE'S THE DISPLAY ENGINE CODE


// here's where we process divs and whatnot...
function playgroundProcessDiv(divObject)
  {
  if (firstRun == true && divObject.divID)
    {
    document.getElementById('bottomLeft').style.left = xPlaygroundSize + 'px';
    document.getElementById('bottomLeft').style.top = yPlaygroundSize + 'px';
    firstRun = false;
    }
  // we wanna make sure divname isn't undefined...
  if (divObject.divID)
    {
    
    // check to see if the div exists
    checkDiv = playgroundCheckDiv(divObject.divID);
    if (!checkDiv)
      {
      playgroundAddDiv(divObject);
      
      }
    else
      {
      // don't do shit...
      }
    
    // go the div, wherever it is...;
    flyTo(divObject.divID);
    if (showCommentsOnArrival == true)
      {
      displayComments(divObject.divID);
      showCommentsOnArrival = false;
      }
    } // end if(divName)
  } // end function



// check to see if the div exists already
function playgroundCheckDiv(divName)
  {
  numNodes = document.getElementById('playgroundBackground').childNodes.length;
  var foundDiv = false;
  var i = numNodes; 
  while(i--)
    {
    if (divName == document.getElementById('playgroundBackground').childNodes[i].id)
      {
      foundDiv = true;
      }
    } // end while
  return foundDiv;
  } // end function



function playgroundAddDiv(divObject)
  {
  // generate the x and y coords
  randLeft = Math.round(xPlaygroundSize*Math.random());
  randTop = Math.round(yPlaygroundSize*Math.random());

  
  // get the element going
  newDiv = document.createElement("div");
      
  // give it an ID
  newDiv.setAttribute('id',divObject.divID);
  
  // setup the style attributes
  
  newDiv.setAttribute('style','position:absolute;');
  newDiv.style.position = 'absolute';
  newDiv.style.top = randTop + 'px';
  newDiv.style.left = randLeft + 'px';
  newDiv.style.width = '600px';
  newDiv.style.height = 'auto';
  newDiv.style.border = '3px';
  newDiv.style.borderStyle = 'solid';
  newDiv.style.borderColor = 'white';
  newDiv.style.fontFamily = 'Verdana, Arial, Helv, Helvetica, sans-serif';
  newDiv.style.fontSize = '14px';
  newDiv.innerHTML = '';
  
  // add our div to the document      
  document.getElementById('playgroundBackground').appendChild(newDiv);
  
  // now let's build the display for the item...
  menuDiv = document.createElement("div");
  menuDiv.setAttribute('id',divObject.divID + '_menu');
  menuDiv.setAttribute('style','position:relative;');
  menuDiv.style.position = 'relative';
  menuDiv.style.color = 'white';
  
  menuHTML = '<table cellspacing="3" width="100%"><tr>';
  menuHTML += '<td width="33%" class="smallText">';
  if (divObject.prevID && divObject.prevID != '')
    {
    menuHTML += makeLink(divObject.prevID, 'Previous Story', 'Previous Story: ' + divObject.prevTitle.replace("'",''));
    
    
    //if (detect.indexOf("msie")>-1){menuHTML += "<a href=\"javascript:getStory('" + divObject.prevID + "');\" onmouseover=\"window.status='Previous Story: " + divObject.prevTitle.replace("'",'') + "'; return true;\" onmouseout=\"window.status=''; return true;\">Previous Story</a>";}
    //else{menuHTML += "<a href=\"/index.php#" + divObject.prevID + "\">Previous Story</a>";}
    
    }
  
  menuHTML += '</td><td width="33%" class="smallText" align="center">';
  //menuHTML += "<a href=\"javascript:flyTo('home')\" onmouseover=\"window.status='Go Home'; return true;\" onmouseout=\"window.status=''; return true;\">Home</a>";
  menuHTML += makeLink('1', 'Go Home', 'Go Home');
    
  if (divObject.pn_topicid && divObject.pn_topicid != '')
    {
    menuHTML += " : ";
    menuHTML += makeLink('cat_' + divObject.pn_topicid, divObject.pn_topictext, "Category: " + divObject.pn_topictext.replace("'",''))
    // <a href=\"javascript:getTopic('" + divObject.pn_topicid + "');\" onmouseover=\"window.status='Category: " + divObject.pn_topictext.replace("'",'') + "'; return true;\" onmouseout=\"window.status=''; return true;\">" + divObject.pn_topictext + "</a>";
    
    }
  menuHTML += '</td><td width="33%" align="right" class="smallText">';
  if (divObject.nextID && divObject.nextID != '')
    {
    menuHTML += makeLink(divObject.nextID, 'Next Story', 'Next Story: ' + divObject.nextTitle.replace("'",''));
    }
  

  menuHTML += '</td></tr></table>';
  
  menuDiv.innerHTML = menuHTML;
  document.getElementById(divObject.divID).appendChild(menuDiv);
  
  // the title
  titleDiv = document.createElement("h1");
  titleDiv.setAttribute('id',divObject.divID + '_title');
  titleDiv.innerHTML = divObject.pn_title;
  document.getElementById(divObject.divID).appendChild(titleDiv);
  document.title = 'jon roig dot com : ' + divObject.pn_title;
  
  
  // the submenu with next/prev stories
  timeDiv = document.createElement("div");
  timeDiv.setAttribute('id',divObject.divID + '_time');
  timeDiv.setAttribute('style','position:relative;');
  timeDiv.style.color = 'white';
  timeDiv.style.fontFamily = 'Verdana, Arial, Helv, Helvetica, sans-serif';
  timeDiv.style.fontSize = '9px';
  timeDiv.style.position = 'relative';
  
  timeHTML = '<table cellspacing="3" width="100%"><tr>';
  timeHTML += '<td width="33%" class="smallText" style="color: white;">';
  if (divObject.pn_time != '0000-00-00 00:00:00'){timeHTML += divObject.pn_time;}
  timeHTML += '</td><td width="33%" class="smallText" align="center">';
  if (divObject.commentCount)
    {
    /*
    if (detect.indexOf("msie")>-1)
      {
      timeHTML += '<a href="javascript:displayComments(' + divObject.divID + ');" onmouseover="window.status=\'View Comments\'; return true;" onmouseout="window.status=\'\'; return true;"> ' + divObject.commentCount;
      
      }
    else
      {
      timeHTML += "<a href=\"/index.php#comment_" + divObject.divID + '" onClick="displayComments(\'' + divObject.divID + '\')">' + divObject.commentCount;
      }
    */
    timeHTML += '<a href="javascript:displayComments(' + divObject.divID + ');" onmouseover="window.status=\'View Comments\'; return true;" onmouseout="window.status=\'\'; return true;"> ' + divObject.commentCount;
      
    if (divObject.commentCount == '1'){timeHTML += ' Comment</a>';}
    else {timeHTML += ' Comments</a>';}
    }
  timeHTML += '</td><td width="33%" align="right" class="smallText" style="color: white;">' + divObject.pn_counter + ' hits ';
  timeHTML += '</td></tr></table>';
  timeDiv.innerHTML = timeHTML;
  document.getElementById(divObject.divID).appendChild(timeDiv);
  
  bodyDiv = document.createElement("div");
  bodyDiv.setAttribute('id',divObject.divID + '_body');
  bodyDiv.style.color = 'white';
  bodyDiv.style.fontFamily = 'Verdana, Arial, Helv, Helvetica, sans-serif';
  bodyDiv.style.fontSize = '14px';
  bodyDiv.style.marginLeft = '3px';
  bodyDiv.style.fontWeight = 'bold';
  
  bodyDiv.innerHTML = divObject.hometext + divObject.bodytext;
  document.getElementById(divObject.divID).appendChild(bodyDiv);
  
  
  // generate the permanent link at the bottom
  permLink = document.createElement("div");
  permLink.setAttribute('id',divObject.divID + '_time');
  permLink.setAttribute('style','position:relative;');
  permLink.style.color = 'white';
  permLink.style.fontFamily = 'Verdana, Arial, Helv, Helvetica, sans-serif';
  permLink.style.fontSize = '9px';
  timeDiv.style.position = 'relative';
  
  if (divObject.divID && divObject.divID != '' && divObject.divID.indexOf("cat_") == -1)
    {
    permLinkHTML = '<br/><br/><table cellspacing="3" width="100%"><tr>';
    permLinkHTML += '<td width="10%" class="smallText" style="color: white;">&nbsp';
    permLinkHTML += '</td><td width="33%" class="smallText" align="center">';
    permLinkHTML += '<a href="/index.php?getStory=' + divObject.divID + '">permanent link</a> ';
    permLinkHTML += ' | <a href="/lofi.php?';
    permLinkHTML += '&getStory=' + divObject.divID;
    permLinkHTML += '">lo-fi view</a>';
    permLinkHTML += '</td><td width="10%" align="right" class="smallText" style="color: white;">&nbsp;';
    permLinkHTML += '</td></tr></table>';
    permLink.innerHTML = permLinkHTML;
    document.getElementById(divObject.divID).appendChild(permLink);
    } 
  
  
  // finally, let's check this badboy to make sure it's all cool
  // you know, position-wise
  var conflictCount = 0;
  while ( checkForDivConflicts(divObject.divID) == false )
    {
    
    randLeft = Math.round(xPlaygroundSize*Math.random());
    if (randLeft < 10){randLeft = '20';}
    if (randLeft > (xPlaygroundSize - 1200)){randLeft = randLeft - 1200;}
    randTop = Math.round(yPlaygroundSize*Math.random());
    if (randTop > (xPlaygroundSize - 1200)){randTop = randTop - 1200;}
    if (randTop < 10){randTop = '40';}
    
    newDiv.style.top = randTop + 'px';
    newDiv.style.left = randLeft + 'px';
    
    // if it repeats too many times, we wanna just grow the size of the playground...
    conflictCount++;
    if (conflictCount > 5)
      {
      xPlaygroundSize = xPlaygroundSize + 2000;
      yPlaygroundSize = yPlaygroundSize + 2000;
      conflictCount = 0;
      }
    } // end while
  } //end function


// this is going to go through every div on the playground -- 
// at least the first round of children, to make sure the new div doesn't conflict with the 
// existing ones...
function checkForDivConflicts(inputDiv)
  {
  // gather the basic coordinates of the divs as they exist...
  checkDiv = document.getElementById(inputDiv);
  
  var noConflict = true;
  
  numNodes = document.getElementById('playgroundBackground').childNodes.length;
  var i = numNodes; 
  while(i--)
    {
    try
      {
      compareDivID = document.getElementById('playgroundBackground').childNodes[i].id;
      compareDiv = document.getElementById(compareDivID);
      }
    catch(e)
      {
      // don't do shit
      }
    // the checkDiv is the incoming
    // and the compareDiv is the one that's there...
    if (compareDivID != checkDiv.id && compareDivID)
      {
      // top left
      if (
        mkNum(checkDiv.style.top) >= mkNum(compareDiv.style.top) && 
        mkNum(checkDiv.style.top) <= (compareDiv.offsetHeight + mkNum(compareDiv.style.top)) &&
        mkNum(checkDiv.style.left) >= mkNum(compareDiv.style.left) &&
        mkNum(checkDiv.style.left) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // top right
      if (
        mkNum(checkDiv.style.top) >= mkNum(compareDiv.style.top) &&
        mkNum(checkDiv.style.top) <= ( mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        ( mkNum(checkDiv.style.left) + checkDiv.offsetWidth) >= mkNum(compareDiv.style.left) &&
        ( mkNum(checkDiv.style.left) + checkDiv.offsetWidth) <= ( mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // bottom left
      if (
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) >= mkNum(compareDiv.style.top) &&
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) <= (mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        mkNum(checkDiv.style.left) >= mkNum(compareDiv.style.left) &&
        mkNum(checkDiv.style.left) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // bottom right : javascript:alert( document.getElementById('181').offsetWidth) 
      /*
      checkiv.offsetHeight = 544
      checkdiv.top = 3305
      checkdiv.left = 479
      offsetWidth = 606
      
      compareDiv.top = 3765
      compareDiv.offsetH = 810
      javascript:alert( document.getElementById('182').style.left) 
      offsetWidth = 606
      left = 526
      */
      if (
         (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) >= mkNum(compareDiv.style.top) &&
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) <= (mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        (mkNum(checkDiv.style.left) + compareDiv.offsetWidth) >= mkNum(compareDiv.style.left) &&
        (mkNum(checkDiv.style.left) + compareDiv.offsetWidth) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // REVERSE!
      tempDiv = checkDiv;
      checkDiv = compareDiv;
      compareDiv = tempDiv;
      
      // top left
      if (
        mkNum(checkDiv.style.top) >= mkNum(compareDiv.style.top) && 
        mkNum(checkDiv.style.top) <= (compareDiv.offsetHeight + mkNum(compareDiv.style.top)) &&
        mkNum(checkDiv.style.left) >= mkNum(compareDiv.style.left) &&
        mkNum(checkDiv.style.left) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // top right
      if (
        mkNum(checkDiv.style.top) >= mkNum(compareDiv.style.top) &&
        mkNum(checkDiv.style.top) <= ( mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        ( mkNum(checkDiv.style.left) + checkDiv.offsetWidth) >= mkNum(compareDiv.style.left) &&
        ( mkNum(checkDiv.style.left) + checkDiv.offsetWidth) <= ( mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // bottom left
      if (
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) >= mkNum(compareDiv.style.top) &&
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) <= (mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        mkNum(checkDiv.style.left) >= mkNum(compareDiv.style.left) &&
        mkNum(checkDiv.style.left) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // bottom right
      if (
         (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) >= mkNum(compareDiv.style.top) &&
        (mkNum(checkDiv.style.top) + checkDiv.offsetHeight) <= (mkNum(compareDiv.style.top) + compareDiv.offsetHeight) &&
        (mkNum(checkDiv.style.left) + compareDiv.offsetWidth) >= mkNum(compareDiv.style.left) &&
        (mkNum(checkDiv.style.left) + compareDiv.offsetWidth) <= (mkNum(compareDiv.style.left) + compareDiv.offsetWidth)
        )
        {
        noConflict = false;
        }
      
      // put it back
      tempDiv = checkDiv;
      checkDiv = compareDiv;
      compareDiv = tempDiv;
      
      
      } // end if (compareDivID != checkDiv.id && compareDivID)
    
    } // end while
  
  // javascript:alert(document.getElementById('163').style.left + ' ' + document.getElementById('163').offsetWidth + ' ' + xPlaygroundSize);
  if ((mkNum(checkDiv.style.top) + checkDiv.offsetHeight) > yPlaygroundSize - 40 - self.screen.availHeight){noConflict = false;}
  if ((mkNum(checkDiv.style.left) + checkDiv.offsetWidth) > (xPlaygroundSize -40 - self.screen.availWidth)){noConflict = false;}
  if (mkNum(checkDiv.style.left) < 50){noConflict = false;}
  if (mkNum(checkDiv.style.top) < 50){noConflict = false;}

  return noConflict;
  } // end function

// turns a pixel width/height into a straight up number...
function mkNum(inputData)
  {
  return inputData.replace(/px/g,'') * 1;
  }

// this is how the cookie crumbles -- I grabbed this code from quirksmode.org
// i doubt you'll have to guess which one does what...
function createCookie(name,value,days)
  {
	if (days)
    {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
  } // end function create cookie.

function readCookie(name)
  {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
    {
    var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
  return null;
  } // end readCookie

function eraseCookie(name)
  {
	createCookie(name,"",-1);
  }
// END O' THE QUIRKSMODE CODE


// here's where we control the comments box... it's a pre-existing div 
// that just got hidden...
// so we just move it and repopulate it...
function displayComments(divName)
  {
  //aquire the target
  commentDiv = document.getElementById('commentBox');
  divToBeCommentedOn = document.getElementById(divName);
  
  document.getElementById('commentViewArea').innerHTML = 'Fetching Comments...';
  
  // make it visible
  commentDiv.style.visibility  = 'visible';
  
  // move it to the right place
  titleDiv = document.getElementById(divName+ '_title');
  menuDiv = document.getElementById(divName+ '_menu');
  commentDiv.style.top = mkNum(divToBeCommentedOn.style.top) + titleDiv.offsetHeight + menuDiv.offsetHeight + 'px' ;
  commentDiv.style.left = mkNum(divToBeCommentedOn.style.left) + 'px';

  document.getElementById('commentSubmitLink').href = 'javascript:submitComment(\'' + divName + '\');';
  document.getElementById('commentSubmitLink').innerHTML = 'Submit Comment';
  
  if (divName == 0)
    {
    document.getElementById('commentHideLink').innerHTML = '';
    }
  else
    {
    document.getElementById('commentHideLink').innerHTML = 'Hide';
    }
  // change the link in mozilla...
  /*
  if (detect.indexOf("msie") == -1)
    {
    document.getElementById('commentHideLink').href = "/index.php#" + divName;
    } 
  */
  // populate it with data...
  cacheTime = new Date();
  http.open('get', 'handleComments.php?id='+divName + '&action=getComments&noCache='+ cacheTime.getUTCSeconds() );
  http.onreadystatechange = handleGetCommentResponse;
  http.send(null);
  
  } // end function

// and build the action comment display
function handleGetCommentResponse()
  {
  if(http.readyState == 4)
    {
    var response = http.responseText;
    var update = new Array();
    
    // since the object is json, we can process it like an object...
    var divObject = response.parseJSON();
    
    // we're gonna iterate through these things to display 'em...
    var i = 0
    var commentMessage = '';
    if (divObject.length == 0)
      {
      commentMessage += 'There are no messages yet. Why not leave one below?';
      }
    while (i < divObject.length)
      {
      commentMessage += divObject[i].pn_comment;
      commentMessage += '<br/><br/>';
      commentMessage += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - ';
      if (divObject[i].pn_url != '')
        {
        commentMessage += '<a href="' + divObject[i].pn_url + '" target="' + divObject[i].pn_url + '" style="color: #6289b4">';
        }
      if (divObject[i].pn_name != '')
        {
        commentMessage += divObject[i].pn_name;
        }
      else
        {
        commentMessage += 'Anonymous';
        }
      if (divObject[i].pn_url != '')
        {
        commentMessage += '</a>';
        }
      commentMessage += ' (' + divObject[i].pn_date + ')';
      
      i++;
      if (i != divObject.length){commentMessage += "<hr/>";}
      }
    
    // size the comment reading area appropriately
    document.getElementById('commentViewArea').innerHTML = commentMessage;
    if (document.getElementById('commentViewArea').offsetHeight >= 250)
      {document.getElementById('commentViewArea').style.height = '250px';}
    else  
      {document.getElementById('commentViewArea').style.height = 'auto';}
    
    
    
    } // end if
  } // end function

function hideComments()
  {
  document.getElementById('commentBox').style.visibility  = 'hidden';
  document.getElementById('commentViewArea').style.height = 'auto';
  } // end function

function submitComment(divName)
  {
  // populate it with data...
  var commentRequest = 'handleComments.php?id='+divName + '&action=addComment';
  commentRequest += '&pn_name=' + escape(document.commentSubmission.commentName.value);
  commentRequest += '&pn_url='  + escape(document.commentSubmission.commentURL.value);
  commentRequest += '&secretNumber='  + escape(document.commentSubmission.secretNumber.value);
  commentRequest += '&pn_comment='  + escape(document.commentSubmission.commentText.value);

  http.open('get', commentRequest);
  http.onreadystatechange = handleSubmitCommentResponse;
  http.send(null);
  } // end function
  
function handleSubmitCommentResponse()
  {
  if(http.readyState == 4)
    {
    var response = http.responseText;
    if (response == ''){alert('Something went horribly wrong with your comment. Sorry. Here is the error:' + response);}
    else
      {
    
      // since the object is json, we can process it like an object...
      var responseObject = response.parseJSON();
      if (!responseObject['status'] || !responseObject['storyID']){alert('Something went awry. Sorry. Here is the error:' + response);}
      else if (responseObject['status'] != 'ok' || responseObject['storyID'] == '')
        {
        alert("Got an unexpected answer from the comment posting system. Weird, eh?");
        }
      else
        {
        
        
        // now let's clear out the form 
        document.commentSubmission.commentText.value = '';
        document.getElementById('commentSubmitLink').innerHTML = 'Submitted successfully. (Look up)';
        

        // (re)populate it with data...
       document.getElementById('commentViewArea').innerHTML = 'Reloading...';
       cacheTime = new Date();
        http.open('get', 'handleComments.php?id='+ responseObject['storyID']  + '&action=getComments&noCache='+ cacheTime.getUTCSeconds());
        http.onreadystatechange = handleGetCommentResponse;
        http.send(null);
        
        } // end else
      } // end else
    } // end if
  } // end function

function makeLink(divIDInput, textLink, mouseOverText)
  {
  linkOutput = '';
  
  if (detect.indexOf("msie")>-1)
    {
    if (divIDInput.indexOf('cat_')>-1){ linkOutput = "<a href=\"javascript:getTopic('" + divIDInput.replace('cat_','') + "');\" onmouseover=\"window.status='"+ mouseOverText.replace("'",'') + "'; return true;\" onmouseout=\"window.status=''; return true;\">" + textLink + "</a>";}
    else{linkOutput = "<a href=\"javascript:getStory('" + divIDInput + "');\" >" + textLink + "</a>";}
    }
  else {linkOutput = "<a href=\"/index.php#" + divIDInput + "\">" + textLink + "</a>";}
  return linkOutput;
  }



// now we're gonna implement the history fix described http://www.contentwithstyle.co.uk/Articles/38/
// ... adapted for our use, of course. I've gotta give this guy props -- it's a lovely hack
// from someone who just wouldn't give up on the problem.

// I reformated it to better understand what's up... this is a clever set of solutions.

/* CROSS-BROWSER EVENT HANDLER */
function addEvent(obj, evType, fn)
  {
	if (obj.addEventListener)
    {
		obj.addEventListener(evType, fn, true);
		return true;
	  }
  else if (obj.attachEvent)
    {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
		}
  else
    {
		return false;
		}
	} // end function addEvent
	/* END EVENT HANDLER */
	
	
	/* JPSPAN */
function doGetPage(i)
  {
  if (i && i == "guestbook")
    {
    showCommentsOnArrival = true;
    getStory('0');
    }
  else if (i && i == "biography")
    {
    getStory('2');
    }
  else if (i && i == "resume")
    {
    getStory('196');
    }
  else if (i && i == 0)
    {
    showCommentsOnArrival = true;
    getStory(i);
    }
  
	else if(i && i != 1)
    {
    hideComments();
    if (i.indexOf("cat_") >-1){getTopic(i.replace('cat_',''))}
    else if (i.indexOf("comment_") >-1)
      {
      var divToGrab =i.replace('comment_','');
      showCommentsOnArrival = true;
      getStory(divToGrab);
      } 
    else{getStory(i);}
	  }
	else
	 {
	 flyTo('home');
	 }
  }

var PageHolderHandler = {
	ashtml: function(result)
    {
		setContent(result);
	  }
  }
	/* END JPSPAN */
	
	
	/* PAGELOCATOR */
function PageLocator(propertyToUse, dividingCharacter)
  {
	this.propertyToUse = propertyToUse;
	this.defaultQS = 1;
	this.dividingCharacter = dividingCharacter;
  }

PageLocator.prototype.getLocation = function()
  {
	return eval(this.propertyToUse);
  }

PageLocator.prototype.getHash = function()
  {
	var url = this.getLocation();
	if(url.indexOf(this.dividingCharacter)>-1)
    {
    var url_elements = url.split(this.dividingCharacter);
	  return url_elements[url_elements.length-1];
	  }
  else
    {
		return this.defaultQS;
		}
	}

PageLocator.prototype.getHref = function()
  {
	var url = this.getLocation();
	var url_elements = url.split(this.dividingCharacter)
	return url_elements[0];
	}

PageLocator.prototype.makeNewLocation = function(new_qs)
  {
	return this.getHref() + this.dividingCharacter + new_qs;
	}
/* END PAGELOCATOR */
	
	
	/* AjaxIframesFixer  this is for IE*/
function AjaxIframesFixer(iframeid)
  {
  this.iframeid = iframeid;
  if (document.getElementById('ajaxnav'))
    {
    //this.fixLinks();

    this.locator = new PageLocator("document.frames['"+this.iframeid+"'].getLocation()", "?hash=");
    this.windowlocator = new PageLocator("window.location.href", "#");
    this.timer = new Timer(this);

    this.delayInit(); // required or IE doesn't fire
    }
  }

AjaxIframesFixer.prototype.fixLinks = function (iframeid)
  {
	var links = document.getElementsByTagName("A");
	for(var i=0; i<links.length; i++)
    {
		var href = links[i].getAttribute("href");
		if (divObject.divID.indexOf("hash=") > -1)
		  {
		  var hash = href.substr(href.indexOf("hash=")+5);
		  }
		links[i].setAttribute("href","javascript:document.getElementById('"+this.iframeid+"').setAttribute('src', 'mock-page.php?hash="+hash+"');");
		}
	}

AjaxIframesFixer.prototype.delayInit = function()
  {
	this.timer.setTimeout("checkBookmark", 100, "");
	}

AjaxIframesFixer.prototype.checkBookmark = function()
  {
	window.location = this.windowlocator.makeNewLocation(this.locator.getHash());
	this.checkWhetherChanged(0);
	}

AjaxIframesFixer.prototype.checkWhetherChanged = function(location)
  {
  //document.getElementById('welcome').innerHTML += 'getHash:' + this.locator.getHash() + 'location:'+location+'<br/>';
	
  if(this.locator.getHash() != location)
    {
		doGetPage(this.locator.getHash()); // this is what gets the page...
		window.location = this.windowlocator.makeNewLocation(this.locator.getHash());
		}
	
  this.timer.setTimeout("checkWhetherChanged", 1000, this.locator.getHash()); //200
	
  }
	/* END AjaxIframesFixer */
	
	
	/* AjaxUrlFixer */
function AjaxUrlFixer()
  {
	//this.fixLinks();
			
  this.locator = new PageLocator("window.location.href", "#");
  this.timer = new Timer(this);
  this.checkWhetherChanged(0);
  }

AjaxUrlFixer.prototype.fixLinks = function ()
  {
	var links = document.getElementsByTagName("A");
	for(var i=0; i<links.length; i++)
    {
		var href = links[i].getAttribute("href");
		var hash = href.substr(href.indexOf("hash=")+5);
		links[i].setAttribute("href","#"+hash);
		}
	}

AjaxUrlFixer.prototype.checkWhetherChanged = function(location)
  {
	if(this.locator.getHash() != location)
    {
		doGetPage(this.locator.getHash());
		}
	this.timer.setTimeout("checkWhetherChanged", 200, this.locator.getHash());
	}
	/* END AjaxUrlFixer */
	
function setContent(new_content)
  {
	if(!document.getElementById || !document.getElementsByTagName) return;
	var container = document.getElementById("container");
	container.innerHTML = new_content;
	}

function FixBackAndBookmarking()
  {
	if(!document.getElementById || !document.getElementsByTagName) return;
	if(document.iframesfix)
    {
		fix = new AjaxIframesFixer('ajaxnav');
	  }
  else
    {
		fix = new AjaxUrlFixer();
		}
	}
	
var detect = navigator.userAgent.toLowerCase();
if(detect.indexOf("msie")>-1) document.iframesfix = true;
addEvent(window, "load", FixBackAndBookmarking);



/*
		Timer by Algorithm
		http://www.codingforums.com/archive/index.php/t-10531.html
	*/
	function Timer(){
		this.obj = (arguments.length)?arguments[0]:window;
		return this;
	}
	
	// The set functions should be called with:
	// - The name of the object method (as a string) (required)
	// - The millisecond delay (required)
	// - Any number of extra arguments, which will all be
	// passed to the method when it is evaluated.
	
	Timer.prototype.setInterval = function(func, msec){
		var i = Timer.getNew();
		var t = Timer.buildCall(this.obj, i, arguments);
		Timer.set[i].timer = window.setInterval(t,msec);
		return i;
	}
	Timer.prototype.setTimeout = function(func, msec){
		var i = Timer.getNew();
		Timer.buildCall(this.obj, i, arguments);
		Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
		return i;
	}
	
	// The clear functions should be called with
	// the return value from the equivalent set function.
	Timer.prototype.clearInterval = function(i){
		if(!Timer.set[i]) return;
		window.clearInterval(Timer.set[i].timer);
		Timer.set[i] = null;
	}
	Timer.prototype.clearTimeout = function(i){
		if(!Timer.set[i]) return;
		window.clearTimeout(Timer.set[i].timer);
		Timer.set[i] = null;
	}
	
	// Private data
	Timer.set = new Array();
	Timer.buildCall = function(obj, i, args){
		var t = "";
		Timer.set[i] = new Array();
		if(obj != window){
			Timer.set[i].obj = obj;
			t = "Timer.set["+i+"].obj.";
		}
		t += args[0]+"(";
		if(args.length > 2){
			Timer.set[i][0] = args[2];
			t += "Timer.set["+i+"][0]";
			for(var j=1; (j+2)<args.length; j++){
				Timer.set[i][j] = args[j+2];
				t += ", Timer.set["+i+"]["+j+"]";
			}
		}
		t += ");";
		Timer.set[i].call = t;
		return t;
	}
	Timer.callOnce = function(i){
		if(!Timer.set[i]) return;
		eval(Timer.set[i].call);
		Timer.set[i] = null;
	}
	Timer.getNew = function(){
		var i = 0;
		while(Timer.set[i]) i++;
		return i;
	}