/*

Copyright 2008 TheGamesWeCrave

*/

window.dhtmlHistory.create();

forwardTo = "";

function historyChange(newLocation, historyData) {

  if(newLocation.indexOf("/") == -1) {
    newLocation = "/featured";
  }

  ajaxFetch(newLocation, false);
}

function historyAdded(newLocation) {

    if(forwardTo != "") {
      window.location = forwardTo;
      forwardTo = "";
    } else {
      updateTitle(newLocation, true);
    }
}

window.onload = function() {
  // initialize the DHTML History framework
  dhtmlHistory.initialize();
  
  // subscribe to DHTML history change events
  dhtmlHistory.addListener(historyChange);
  dhtmlHistory.addInsertListener(historyAdded);

  var hash = "" + window.location.hash;
  if(hash.length > 0 && hash != '#/blank.html') {
    var hash = hash.substring(1, hash.length);
    ajaxFetch(hash, false);
  } else if(window.location.pathname.length <= 1) {
    ajaxFetch("/featured", false);
  } else if(window.location.href.indexOf('blank') == -1) {
    ajaxFetch(window.location.pathname, false);
  }
}


function fadeOut(id, op) {

  var div = document.getElementById(id);
  div.className = "op" + op;
  op -= 10;
  if(op >= 0)
    window.setTimeout("fadeOut('" + id + "', " + op + ")", 20);
  else
    window.setTimeout("fadeIn('" + id + "', 0)", 20);
}

function fadeIn(id, op) {

  var div = document.getElementById(id);
  div.className = "op" + op;
  op += 10;
  if(op <= 100)
    window.setTimeout("fadeIn('" + id + "', " + op + ")", 20);
}

function urldecode(url) 
{
  url = url.replace(/\+/g, " ");
  url = decodeURI(url);
  return url;
}

function updateTitle(newLocation, reloadHash)
{ 
  var args = new Array();
  var title = "";
  args = newLocation.split("/");
  
  if(args[1] == 'about')
    title = args[2];
  else if(args[1] == 'featured')
    title = "Featured games";
  else if(args[1] == 'playing')
    title = "Now playing";
  else if(args[1] == 'played')
    title = "Games you've played";
  else if(args[1] == 'popular')
    title = "The most popular games";
  else if(args[1] == 'hot')
    title = "Today's hottest games";
  else if(args[1] == 'new')
    title = "New additions";
  else if(args[1] == 'favorites')
    title = "Your Favorites";
  else if(args[1] == 'tagged')
    title = args[2] + " games";
  else
    title = args[1] + " games";

  title = title.replace(/%20/, " ");
  title = title.replace(/games games/, "games");

  if(title)
    title = urldecode(title) + " on The Games We Crave";
  else
    title = "The Games We Crave";

  document.title = title;
  if (dhtmlHistory.isIE) {
    dhtmlHistory.iframe.contentWindow.document.title = title;
  }

  /* reload the hash so the new title "sticks" in the browser history object*/
  if (!dhtmlHistory.isIE && !dhtmlHistory.isOpera) {
    if(document.location.hash.length > 1) {
      document.location.hash = newLocation;
    } else {
//      document.location.hash = "";
    }
  }
}

/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com

    http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
*/

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function rate(id, rating)
{
  ajaxFetch("/rate/" + id + "/" + rating, false, false);
  var divs = getElementsByClassName(document.getElementById("ratings"), "*", "activeRating");
  for(i = 0; i < divs.length; i++)
    divs[i].className = 'inactiveRating';

  var div=document.getElementById('rating' + rating);
  if(div)
    div.className = 'activeRating';
  return false;
}

function play(title)
{
  dhtmlHistory.add("/about/" + title);  
  var div=document.getElementById('body');
  div.innerHTML = "";

  if (dhtmlHistory.isSafari) {
    window.location = "http://" + window.location.hostname + "/visit/" + title;  
  } else {
    forwardTo = "http://" + window.location.hostname + "/visit/" + title;  
  }
  return false;
}

function getXmlHttp() {
  var xmlHttp;
  try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }
  catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }
  return xmlHttp;
}



function ajaxFetch(args, record, display)
{
  var xmlHttp = getXmlHttp();

  if(!xmlHttp) return false;

  record  = typeof(record)  != 'undefined' ? record  : true;
  display = typeof(display) != 'undefined' ? display : true;
 
  if(args == "" || args == "/")
    args = "/featured";
 
  // If the browser supports JavaScript, but started from a non-AJAX link, forward them to
  // the correct AJAX link.
  if(window.location.pathname.length > 1 && record) {
    window.location = "http://" + window.location.hostname + "/#" + args;
    return true;
  } 

  if(display) {

    var div = document.getElementById("gamelist");
    div.innerHTML="";
    var timeout = window.setTimeout("document.getElementById('gamelist').innerHTML=\"<img src='/images/activityanimation.gif' alt='searching' style='margin-top: 50px;'/>\";", 250);

    div = document.getElementById('validate');
    div.innerHTML = "<a href='http://validator.w3.org/check?uri=http://" + window.location.hostname + args + "'>Valid HTML 4.01</a> <a href='http://validator.w3.org/check?uri=http://" + window.location.hostname + "/xhtml" + args + "'>Valid XHTML 1.1</a>";


    var splitArgs = new Array();
    splitArgs = args.split("/");
    var menu = splitArgs[1];
    if(splitArgs[1] == 'tagged')
      menu = "tagged" + splitArgs[2];

    menu = menu.replace(/ /g, "");
    menu = menu.replace(/%20/g, "");
    switchMenu(menu);

    xmlHttp.onreadystatechange=function()
    {
      if(xmlHttp.readyState==4)
      {
        clearTimeout(timeout);
        var div = document.getElementById("gamelist");
        div.innerHTML=xmlHttp.responseText;
	if(!record)
          updateTitle(args);
      }
    }
  }

  if(args.charAt(0) == "#")
    args = "/" + args.substring(1, args.length);

  xmlHttp.open("GET","/gwc.php/ajax" + args,true);
  xmlHttp.send(null);

  if(record) {
    dhtmlHistory.add(args);
  }
}

function switchMenu(to)
{
  var div = document.getElementById("menu"+activeMenu);
  if(div) 
    div.className = "inactive";
  div = document.getElementById("menu"+to);
  if(div)
    div.className = "active";
  activeMenu = to;
}

function savfav(id) {
  xmlHttp = getXmlHttp();

  if(!xmlHttp) return false;

  xmlHttp.onreadystatechange=function() {
      if(xmlHttp.readyState==4) {
//       location.reload();
//        document.getElementById('save'+id).innerHTML = xmlHttp.responseText;
        document.getElementById('savFav').innerHTML = xmlHttp.responseText;
      }
  }
  xmlHttp.open("GET","/savfav/"+id,true);
  xmlHttp.send(null);

  return false;
}


function delfav(id) {
  xmlHttp = getXmlHttp();

  if(!xmlHttp) return false;

  xmlHttp.onreadystatechange=function() {
      if(xmlHttp.readyState==4) {
        document.getElementById('savFav').innerHTML = xmlHttp.responseText;
//       location.reload();
//        document.getElementById('save'+id).innerHTML = xmlHttp.responseText;
      }
  }
  xmlHttp.open("GET","/delfav/"+id,true);
  xmlHttp.send(null);

  return false;
}


