function sortNew(){
	//doSort("DESC");
	window.location.href = strURL;
}
function sortToday(){
	//doSort("TODAY");
	window.location.href = strURL+"?view=TODAY";
}
function sortWeek(){
	//doSort("WEEK");
	window.location.href = strURL+"?view=WEEK";
}
function sortAllTime(){
	//doSort("ALLTIME");
	window.location.href = strURL+"?view=ALLTIME";
}

function doSort(inSort){
  
  var strLoading = "<table width=500 border=0 cellpadding=2>";
  strLoading += "<tr><td height=2 class='colorHead'></td></tr>";
  strLoading += "<tr><td align=center valign=center>";
  strLoading += "<font size=2 color=#666666><b>gathering...</b></font>";
  strLoading += "</td></tr>";
  strLoading += "<tr><td height=2 class='colorHead'></td></tr>";
  strLoading += "</table>";
  
  document.getElementById("listarea").innerHTML = strLoading;

  var xmlhttp;

  if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("Your browser does not support XMLHTTP!");
  }
  
  xmlhttp.onreadystatechange=function(){

    //alert("readystate = "+xmlhttp.readyState);

    if(xmlhttp.readyState==4){
      if (xmlhttp.status==200) {
        // 200 = OK
        
        document.getElementById("listarea").innerHTML = doListing(inSort, xmlhttp.responseXML);

      } else {
        alert("Problem retrieving XML data");
      }
    }
  }

  var d = new Date();
  var strURL = "src/getHaikus.php"+"?ts="+d.getMilliseconds();
  var params = "";
  params += "sort="+inSort;

  xmlhttp.open("POST",strURL,true);
  
  //Send the proper header information along with the request
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.setRequestHeader("Content-length", params.length);
  xmlhttp.setRequestHeader("Connection", "close");
  
  xmlhttp.send(params);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Initializing sequence
var strURL = "http://www.drunkenhaiku.com";

var view = "";
if( getQueryStringVar("view") != "" ){
  view = getQueryStringVar("view");
} else {
  view = "DESC";
}

var selectedIndex = 1; // default value
var perPage = 10; // default value

if( getQueryStringVar("page") != "" ){
  selectedIndex = Number( getQueryStringVar("page") );
}

if( getCookie('perpage') != null && getCookie('perpage') != ""){
  perPage = Number( getCookie('perpage') );
} else {
  // set a new perPage cookie
  setCookie('perpage',String(perPage),365);
}

function selectIndex(index){
	selectedIndex = index;
	//sortNew();
	// change from an AJAX call and reload page, instead
	window.location.href = strURL+"?page="+selectedIndex;
}
function setPerPage(num){
	perPage = num;
	//sortNew();
	// 1) set perPage as a cookie
	setCookie('perpage',String(perPage),365);
	// 2) reload current page
	window.location.href = strURL;
}

function setCookie(c_name,value,expiredays){
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name){
  if (document.cookie.length>0)
    {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1)
      {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
      }
    }else{
    return "";
  }
}
function getQueryStringVar(ji) {
  var hu = window.location.search.substring(1);
  var gy = hu.split("&");
  var strReturn = "";
  for (i=0; i < gy.length; i++) {
    var ft = gy[i].split("=");
    if ( ft[0] == ji ) {
      strReturn = ft[1];
    }
  }
  return strReturn;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
function checkCookies(inID){
  bool = false;
  myRatings = getCookie('ratings');
  if (myRatings != null && myRatings != ""){
    arr = myRatings.split(',');
    for(k=0; k<arr.length; k++){
      if( arr[k] == inID ){
        bool = true;
        break;
      }
    }
  }
  return bool;
}

function doListing(inSort, inXML){

  var numColumns = 4;
  var numColWidth1 = 350;
  var numColWidth2 = 75;
  var numDivWidth = 1;

  var strHTML = "";
  
  // Nav Table
  strHTML += "<table width=500 border=0 cellpadding=2>";
  strHTML += "<tr><td align=center><font size=2><b>";

  if( inSort != "DESC" ){
  strHTML += "<a href='javascript: sortNew()' class='nav'>current live feed</a>";
  } else {
    strHTML += "current live feed";
  }
  strHTML += " | ";
  if( inSort != "TODAY" ){
    strHTML += "<a href='javascript: sortToday()' class='nav'>today's favorites</a>";
  } else {
    strHTML += "today's favorites";
  }
  strHTML += " | ";
  if( inSort != "WEEK" ){
    strHTML += "<a href='javascript: sortWeek()' class='nav'>favorites of the week</a>";
  } else {
    strHTML += "favorites of the week";
  }
  strHTML += " | ";
  if( inSort != "ALLTIME" ){
    strHTML += "<a href='javascript: sortAllTime()' class='nav'>all-time favorites</a>";
  } else {
    strHTML += "all-time favorites";
  }
  strHTML += "</td></tr>";
  strHTML += "<tr><td height=2 class='colorHead' bgcolor=#000000 ></td></tr>";
  strHTML += "<tr><td height=5 ></td></tr>";
  strHTML += "</table>";

  // List Table
  strHTML += "<table width=500 border=0 cellpadding=2>";
  
  var index = 0;
  var maxIndex;
  var minIndex = 0;
  //var selectedIndex = 1;
  //var perPage = 10;
  switch( inSort ){
    case "DESC":
    maxIndex = (selectedIndex*perPage);
    minIndex = (selectedIndex*perPage)-perPage;
    break;
    case "TODAY":
    maxIndex = 20;
    selectedIndex = 1;
    perPage = 20;
    break;
    case "WEEK":
    maxIndex = 20;
    selectedIndex = 1;
    perPage = 20;
    break;
    case "ALLTIME":
    maxIndex = 20;
    selectedIndex = 1;
    perPage = 20;
    break;
    default:
    //
    break;
  }
  
  var arrHaikus = inXML.getElementsByTagName('h'); 

  for(r=0; r<arrHaikus.length; r++){
    index++;
    if( index > minIndex ){ 
      if( index < (maxIndex+1) ){
        
        strHTML +="<tr>";
        strHTML +="<td rowspan=2 width=numColWidth2 ></td>";
        strHTML +="<td width=numColWidth1 align=center valign=top>";
        strHTML +="<b><font size=3 color='#003366'>";
        strHTML +="<a href='haiku.php?id="+arrHaikus[r].getAttribute('ID')+"' class='haiku'>";
        strHTML +=washString(unescape(arrHaikus[r].getElementsByTagName('line1')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'))+"<br />";
        strHTML +=washString(unescape(arrHaikus[r].getElementsByTagName('line2')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'))+"<br />";
        strHTML +=washString(unescape(arrHaikus[r].getElementsByTagName('line3')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'));
        strHTML +="</a></font></b>";
        
        if( arrHaikus[r].getAttribute('profane') == 1 ){ 
          strHTML += writeProfaneWarning();
        }
        
        strHTML +="</td>";
        
        strHTML +="<td rowspan=2 width=numDivWidth ></td>";
        
        strHTML +="<td width=numColWidth2 align=center valign=center>";
        strHTML +="</td>";
        
        strHTML +="</tr><tr>";
        
        strHTML +="<td width=numColWidth1 align=center valign=bottom><font size=1 color=#666666>";
        //strHTML +=arrHaikus[r]['month']."-".arrHaikus[r]['day']."-".arrHaikus[r]['year'];
        strHTML +=arrHaikus[r].getAttribute('dayofweek')+", "+ arrHaikus[r].getAttribute('month')+" "+arrHaikus[r].getAttribute('day')+", "+arrHaikus[r].getAttribute('year');
        
        strHTML +="<font color=#006666 size=1> | </font>";
        strHTML +="URL <input type=text id='url"+arrHaikus[r].getAttribute('ID')+"' value='http://www.drunkenhaiku.com/haiku.php?id="+arrHaikus[r].getAttribute('ID')+"' size=30 readonly='readonly' class='urlLink' onclick='javascript:document.getElementById(this.id).select()' />";
        strHTML +="</font>";
        
        strHTML +="<br>";
        
        strHTML +="<font size=1 color=#666666>";
        strHTML +="<span id='txtCount"+arrHaikus[r].getAttribute('ID')+"'>";
        strHTML +=arrHaikus[r].getAttribute('rating');
        strHTML +="</span>";
        strHTML +=" votes";
        strHTML +="</font>";
        strHTML +="<font color=#006666 size=1> | </font>";
        strHTML +="<span id='txtRate"+arrHaikus[r].getAttribute('ID')+"'>";
        if( checkCookies(arrHaikus[r].getAttribute('ID')) ){
          strHTML +="<font size=2><b>You like it!</b></font>";
        } else {
          strHTML +="<font size=2><b><a href='javascript: doRate(\""+arrHaikus[r].getAttribute('ID')+"\")' class='like'>I Like It!</a></b></font>";
        }
        strHTML +="</span>";
        
        strHTML +="</td>";
        
        strHTML +="<td width=numColWidth2 align=center valign=bottom></td>";
        
        strHTML +="</tr>";
        
        strHTML +="<tr><td colspan="+numColumns+" height="+numDivWidth+" class='divColor1' bgcolor=#000000 ></td></tr>";
        
      }
    }
  }
  
  if( inSort == "DESC" ){

    strHTML += "<tr><td colspan="+numColumns+" align=center><font size=2><b>";

    if( selectedIndex != 1 ){
      strHTML += "<a href='javascript: selectIndex("+ (selectedIndex-1) +")' class='nav'>&#60; prev</a>";
      strHTML += " | ";
    }

    for( i=0; i<Math.ceil(index/perPage); i++ ){
      var num = i+1;
      
      if( selectedIndex != num ){
        strHTML += "<a href='javascript: selectIndex("+num+")' class='nav'>"+ num +"</a>";
      } else {
        strHTML += num;
      }
      
      if( i < Math.ceil(index/perPage)-1 ){
        strHTML += ", ";
      }
    }

    if( selectedIndex != Math.ceil(index/perPage) ){
      strHTML += " | ";
      strHTML += "<a href='javascript: selectIndex("+ (selectedIndex+1) +")' class='nav'>next &#62;</a>";
    }

    strHTML += "</b></td></tr>";
    strHTML += "<tr><td colspan="+numColumns+" align=center><font size=1>";
    strHTML += "view per page: ";

    for(p=10; p<101; p = p+10){
      if( perPage == p ){
        strHTML += p;
      } else {
        strHTML += "<a href='javascript: setPerPage("+ p +")' class='nav'>";
        strHTML += p;
        strHTML += "</a>";
      }
      strHTML += " | ";
    }
    strHTML += "</font></td></tr>";
    strHTML += "<tr><td colspan="+numColumns+" height="+numDivWidth+" class='divColor1'></td></tr>";
  }
  
  strHTML += "<tr><td colspan="+numColumns+" align=center>";
  strHTML += "<font size=1 color='#006666'>";
  strHTML += "profanity ";
  if( getProfanityCookie() == 'FALSE' ){
    strHTML += "<a href='javascript: setProfanityDisplay(\"ON\")' class='nav'>";
    strHTML += "on";
    strHTML += "</a>";
  } else {
    strHTML += "on";
  }
  strHTML += " | ";
  if( getProfanityCookie() == 'TRUE' ){
    strHTML += "<a href='javascript: setProfanityDisplay(\"OFF\")' class='nav'>";
    strHTML += "off";
    strHTML += "</a>";
  } else {
    strHTML += "off";
  }
  strHTML += "</font>";
  strHTML += "</td></tr>";
  
  strHTML += "</table>";
  
  return strHTML;
}

function sortID(inID){
  
  var strLoading = "<table width=500 border=0 cellpadding=2>";
  strLoading += "<tr><td height=2 class='colorHead'></td></tr>";
  strLoading += "<tr><td align=center valign=center>";
  strLoading += "<font size=2 color=#666666><b>gathering...</b></font>";
  strLoading += "</td></tr>";
  strLoading += "<tr><td height=2 class='colorHead'></td></tr>";
  strLoading += "</table>";
  
  document.getElementById("displayarea").innerHTML = strLoading;

  var xmlhttp;

  if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("Your browser does not support XMLHTTP!");
  }
  
  xmlhttp.onreadystatechange=function(){

    //alert("readystate = "+xmlhttp.readyState);

    if(xmlhttp.readyState==4){
      if (xmlhttp.status==200) {
        // 200 = OK
        
        document.getElementById("displayarea").innerHTML = doDisplayHaiku(xmlhttp.responseXML);

      } else {
        alert("Problem retrieving XML data");
      }
    }
  }

  var d = new Date();
  var strURL = "src/getHaikuByID.php"+"?id="+inID+"&ts="+d.getMilliseconds();

  xmlhttp.open("GET",strURL,true);
  
  xmlhttp.send(null);
}

function doDisplayHaiku(inXML){
  var arrHaikus = inXML.getElementsByTagName('h'); 
  var r = 0; // should be only one
  
  var strHTML = "<table width=550 height=400 border=0 cellpadding=0 background='img/bg-fade.png'>";
  strHTML += "<tr>";
  strHTML += "<td width=550 height=250 align=center valign=bottom>";
  
  if( arrHaikus[r].getAttribute('approved') == 1 ){
    // this is an approved haiku, so display it 
    
    strHTML += "<b><font size=4 color='#003366'>";
    strHTML += washString(unescape(arrHaikus[r].getElementsByTagName('line1')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'))+"<br />";
    strHTML += washString(unescape(arrHaikus[r].getElementsByTagName('line2')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'))+"<br />";
    strHTML += washString(unescape(arrHaikus[r].getElementsByTagName('line3')[0].childNodes[0].nodeValue), arrHaikus[r].getAttribute('profane'))+"<br />";
    strHTML += "</font></b>";
    
    if( arrHaikus[r].getAttribute('profane') == 1 ){ 
      strHTML += writeProfaneWarning();
    }
    
    strHTML += "<br />";
    strHTML += "</td>";        
    strHTML += "</tr>";
    
    strHTML += "<tr><td height=150 align=center valign=top><font size=1 color=#666666>";
    strHTML +=arrHaikus[r].getAttribute('dayofweek')+", "+ arrHaikus[r].getAttribute('month')+" "+arrHaikus[r].getAttribute('day')+", "+arrHaikus[r].getAttribute('year');
    strHTML += "</font>";
          
    strHTML += "<br>";

    strHTML += "<font size=1 color=#666666>";
    strHTML += arrHaikus[r].getAttribute('rating');
    strHTML += " votes";
    strHTML += "</font>";
          
    strHTML += "<font color=#006666 size=1> | </font>";
    strHTML += "<font size=1 color=#666666>";
    strHTML +="<span id='txtRate"+arrHaikus[r].getAttribute('ID')+"'>";
    if( checkCookies(arrHaikus[r].getAttribute('ID')) ){
      strHTML +="<font size=2><b>You like it!</b></font>";
    } else {
      strHTML +="<font size=2><b><a href='javascript: doRate(\""+arrHaikus[r].getAttribute('ID')+"\")' class='like'>I Like It!</a></b></font>";
    }
    strHTML +="</span>";
  
  } else {
    // this is NOT an approved haiku, so display error
    
    strHTML += "<b><font size=4 color='#003366'>";
    strHTML += "The haiku you're looking for was improperly formatted,"; 
    strHTML += "<br>";
    strHTML += "but you may access hundreds more at the link below!";
    strHTML += "</font>";
  }

  strHTML += "</td>";
  strHTML += "</tr>";
  strHTML += "</table>";
  
  strHTML += "<table width=550 height=50 border=0 cellpadding=0 >";
  
  strHTML += "<tr><td height=2 bgcolor=#00CCCC></td></tr>";
  
  strHTML += "<tr>";
  strHTML += "<td height=48 align=center valign=bottom>";
  strHTML += "<font size=3><b><a href='http://www.drunkenhaiku.com' class='nav'>See more or submit your own Drunken Haiku!</a></b></font>";
  strHTML += "</td>";
  strHTML += "</tr>";
  
  strHTML += "</table>";
  
  return strHTML;
}
function writeProfaneWarning(){
  var strHTML = "";
  //if( inProfane == 1 ){ // inProfane, 1 == yes, this is profane
    var bool = getProfanityCookie(); // display profanity? FALSE = "no, don't show profanity"
    strHTML += "<br>";
    strHTML += "<font size=1 color='#006666'>";
    strHTML += "turn ";
    if( bool == 'FALSE' ){
      strHTML += "<a href='javascript: setProfanityDisplay(\"ON\")' class='nav'>";
      strHTML += "on";
      strHTML += "</a>";
      strHTML += " profanity to view";
    } else {
      strHTML += "<a href='javascript: setProfanityDisplay(\"OFF\")' class='nav'>";
      strHTML += "off";
      strHTML += "</a>";
      strHTML += " profanity to hide";
    }
    strHTML += "</font>";
    strHTML += "<br>";
  //}
  return strHTML;
}

function washString(inStr, inProfane){
  var bool = getProfanityCookie(); // display profanity? FALSE = "no, don't show profanity"
  if( bool == 'FALSE' ){
    if( inProfane == 1 ){ // inProfane, 1 == yes, this is profane
      var arr = inStr.split(" ");
      for(a=0; a<arr.length; a++){
        arr[a] = hashOutString(arr[a]);
      }
      inStr = arr.join(" ");
    }
  }
  return inStr;
}

function hashOutString(inStr){
  var arrWord = inStr.split("");
  for(y=0; y<arrWord.length; y++){
    arrWord[y] = "#";
  }
  return arrWord.join("");
}

function setProfanityDisplay(inType){
  switch(inType){
  case "ON":
  setProfanityCookie('TRUE');
  break;
  case "OFF":
  setProfanityCookie('FALSE');
  break;
  default:
  break;
  }
  // reload page
  window.location.href=window.location.href;
}
function getProfanityCookie(){
  var boolReturn;
  // cookie should be a boolean
  var myProfanity = getCookie('profanity');
  if (myProfanity != null && myProfanity != ""){
    // return cookie value
    boolReturn = myProfanity;
  } else {
    // create default cookie value, FALSE = "no, don't show profanity"
    boolReturn = 'FALSE';
    setProfanityCookie(boolReturn);
  }
  return boolReturn;
}
function setProfanityCookie(inBool){
  // cookie should be a boolean
  myProfanity = inBool;
  setCookie('profanity',myProfanity,365);
}