//fix the overall container fetching to use cssClass + 'Container' instead of favType


var Config=new Object()
var Err=new Object()
var Msg=new Object()


/////////////////////////////
//      config
/////////////////////////////
Config.MaxFavoritesPerPage=25
Config.maxFavorites=100						//number of favorites to show on the module
Config.MaxModuleRecent=6						//how many recent games to track/display
Config.MaxModuleFavorites=6					//how many favorites to show in the module
//Config.ImageUrl="http://agpublish.local.crantorland.com/images/"

/////////////////////////////
//      Error Messages
/////////////////////////////
Err.CookiesFull				=	"I'm sorry but you can only have a max of 100 favorite games"
Err.FailedToSaveFavorite	=	"Oops something went wrong.  I could not save the favorite"
Err.HtmlStatusNotOk			=	"Sorry there was a problem loading your favorite"
Err.NoHttpObj				=	"I'm sorry.  please enable javascript to use favorites"
Err.InvalidGameObject		=	"Oops. there has been an error"
Err.NoSuchPage				=	"yo that page of favorites dosn't exist" //bug message blank this later
////////////////////////////////////////
//      Informational Messages
////////////////////////////////////////
Msg.SavedFavorites			=	""
Msg.NoFavorites				=	"Add some favorites"
Msg.NoRecent				=	"The next time you play a game, it will be listed here for quick access."
Msg.RemovedFavorite			=	""
Msg.SavedRecent				=	""



////////end config
var curFavPageId=0

function initAddRemoveLink(gameId,background){
	var addRemoveLink=document.getElementById('addFavoriteLink')
	var addRemoveImg=document.getElementById('addFavoriteImg')
	var addRemoveText=document.getElementById('addFavoriteText')

	if( checkForGame( gameId ) ){
		addRemoveText.innerHTML="Remove from Favorites"
		addRemoveLink.title="Remove from Favorites"
		addRemoveLink.onclick=function (){ removeFavorite( gameId ); initAddRemoveLink( gameId, background ); return false;}
		addRemoveLink.className="btnTool btnRemoveFav"
		addRemoveImg.src="/images/btnRemoveFav" + background + ".png"
		addRemoveImg.className="btnTool btnRemoveFav"
	}else{
		addRemoveText.innerHTML="Add to Favorites"
		addRemoveLink.title="Add to Favorites"
		addRemoveLink.onclick=function (){ addFavorite( gameId ); initAddRemoveLink( gameId, background ); return false;}
		addRemoveLink.className="btnTool btnAddFav"
		addRemoveImg.src="/images/btnAddFav" + background + ".png"
		addRemoveImg.className="btnTool btnAddFav"
	}
}

function checkForGame(gameId){
	var allFavorites=getFavorites('fav')
	
	for( var i=0; i<allFavorites.length; i++ ){
		if( allFavorites[i] == gameId ){
			return true
		}
	}
	return false
}

function displayFavorites(pageId,favType,count,cssClass){
	
	if(!checkHTTP()){
		return false
	}
	
	
	
	//check how many pages we have
	var allFavorites=getFavorites(favType)
	if(!allFavorites){
		
		// var favoriteContainer	=document.getElementById(favType + 'ContainerDiv')
		// var favoriteLi=document.createElement('li')
		// favoriteLi.id=favType + "_empty" 
		// favoriteLi.className = cssClass
		// favoriteLi.innerHTML = Msg.NoRecent
		// favoriteContainer.appendChild(favoriteLi)
		 var containerDiv=document.getElementById(favType + 'ContainerDiv')
		 containerDiv.innerHTML= "<font color=#2E4B82 ><b>" + Msg.NoRecent + "</b></font>"
		//createNoFavorites(favType,cssClass)
		return false
	}
	
	initFavoriteContainer(favType,cssClass)
	
	var favoriteLength = allFavorites.length
	var favoritesPaged=splitFavorites(allFavorites,count)
	
	
	if(pageId>=favoritesPaged.length){  //length is a count but page id is an index starting from 0.  so if they were == it would be missing
		displayMessage(Err.NoSuchPage)
		return false
	}

	

		
	createFavoritesContainers(favType,favoriteLength,cssClass)

	displayGames(favType,favoritesPaged[pageId],count,cssClass)
	
	return favoritesPaged
}


function displayPage(pageId){
	var favorites=displayFavorites(pageId,'fav',Config.MaxFavoritesPerPage,'longFavorites')
	if(favorites){
		curFavPageId=pageId
		displayPagination(pageId,favorites.length)
	}
}

function reloadFavorites(){
	if(curFavPageId=='module'){
		displayFavorites(0,'fav',Config.MaxModuleFavorites,'shortFavorites')
	}else{	
		var favorites=displayFavorites(curFavPageId,'fav',Config.MaxFavoritesPerPage,'longFavorites')
		displayPagination(curFavPageId,favorites.length)
	}
}

function displayFavoritesModule(){
	curFavPageId='module'
	displayFavorites(0,'fav',Config.MaxModuleFavorites,'boxed')
	var favContainer=document.getElementById('favContainerUl')
	
		var viewAllLi=document.createElement('li')
		viewAllLi.className="on viewAll"
		
			var viewAllAnchor=document.createElement('a')
			viewAllAnchor.innerHTML="&#187;View all favorites"
			viewAllAnchor.className="l1"
			viewAllAnchor.href="/favorites.html"
			
		viewAllLi.appendChild(viewAllAnchor)
	
	favContainer.appendChild(viewAllLi)
		
}

function displayRecentModule(){
	displayFavorites(0,'recent',Config.MaxModuleRecent,'boxed')
}

function getFavorites(favType){
	var favoriteCookies=getCookiesLike(favType)
	
	if(!favoriteCookies){
		return false
	}
	
	var favorites=new Array()
	
	for(var i=0; i<favoriteCookies.length; i++){
		favorites.push(favoriteCookies[i].value)
	}
	
	favorites=favorites.join(",").split(",")	//since each of the elements of favorites is a comma seperated string 
												//it combines them into one string and then splits them into alot of pieces
	
	return favorites
}

function createFavoritesContainers(favType,count,cssClass){
	var favoriteContainer=document.getElementById(favType + "ContainerUl")
	
	favoriteContainer.innerHTML=""
	if (count > Config.MaxModuleRecent)
	{
		count = Config.MaxModuleRecent;
	}
		
	for(var i=0; i<count; i++){
		var favoriteLi=document.createElement('li')
		favoriteLi.id=favType + "GameLi" + i
		favoriteLi.className=cssClass + "_loading"
		favoriteLi.innerHTML="Loading..."
		
		favoriteContainer.appendChild(favoriteLi)
	}
}

function createNoFavorites(favType,cssClass){
 	
	var favoriteContainer=document.getElementById(favType + "ContainerDiv")
 	
 
	favoriteContainer.innerHTML=""
	
	
	var emptyDiv=document.createElement('div')

	emptyDiv.id=favType + "EmptyDiv"
	
	emptyDiv.className=cssClass + "_empty"
		
	if(favType=="recent"){
		emptyDiv.innerHTML=Msg.NoRecent
	}else{
		emptyDiv.innerHTML=Msg.NoFavorites
	}
		
	favoriteContainer.appendChild(emptyDiv)

}

function displayPagination(curPageId,pageCount){
	var paginationDivs = getDivsByClass('paginationDiv')
	
	for( var i=0; i < paginationDivs.length; i++ ){
		setPagination( curPageId, pageCount, paginationDivs[i])
	}
}

function setPagination(curPageId, pageCount, paginationDiv){
	var prevPageId = curPageId - 1
	var nextPageId = curPageId + 1
	
	if(curPageId==0){
		var pageString = 'prev '
	}else{
		var pageString = '<a href="" onClick="displayPage(' + prevPageId + '); return false;">prev</a> '
	}
	
	for( var i=0; i<pageCount; i++ ){
	    var displayPageNumber= i + 1
		if( curPageId == i ){
			pageString= pageString + '<span class="selectedPage">' + displayPageNumber + '</span> '
		}else{
			pageString=pageString + '<a href="" onClick="displayPage(' + i + '); return false;">' + displayPageNumber + '</a> '
		}
	}
	
	if( curPageId==pageCount-1 ){
		var pageString = pageString + 'next'
	}else{
		var pageString = pageString + '<a href="" onClick="displayPage(' + nextPageId + '); return false;">next</a>'
	}
	
	paginationDiv.innerHTML = pageString
}

var DISABLED=false


function displayGames(favType,favorites,favNumber,cssClass){

	if(favorites.length > 0){
		var containerUl=document.getElementById(favType + "ContainerUl")
		
		var i=0;
		while ( (i < favorites.length ) && ( i < Config.MaxModuleRecent) )
		{
			ajaxDisplayFavorite(favorites[i],i,favType,containerUl,cssClass)
			i++
		}
		
		//for( var i=0; i<favorites.length; i++ ){
	//		ajaxDisplayFavorite(favorites[i],i,favType,containerUl,cssClass)
//		}
		
		
		
		for( i; i<favNumber; i++){
			createBlankFavorite(i,favType,cssClass)
		}
	}
	
	return false
}

function ajaxDisplayFavorite(gameId,favNumber,favType,containerUl,cssClass){
	if(!checkHTTP()){
		return false
	}
	
	//do ajaxy stuff here to populate game info
	try {
		var HTTP = new XMLHttpRequest();
	}catch (e) {
		var HTTP = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	HTTP.open("get","/gameData/" + gameId,true)
	
	HTTP.onreadystatechange=function(){
		// if HTTP shows "loaded"
		if (HTTP.readyState==4){
			// if "OK"
			if (HTTP.status==200){
				//dbg("game id: " + gameId + " returned")
				createFavorite(favType,favNumber,HTTP,cssClass)
			}else{
				displayMessage(Err.HtmlStatusNotOk)
			}
		}
	}
	
	HTTP.send(null)
}

//function dbg(message){
//	var debugDiv=document.getElementById("debugDiv")
//	debugDiv.innerHTML=debugDiv.innerHTML + message + '\n'
//}

function createBlankFavorite(favNumber,favType,cssClass){
	
	var gameLi=document.getElementById(favType + 'GameLi' + favNumber)
	
	//gameLi.innerHTML="" //blank it first so its done loading
	
	//gameLi.className=cssClass + "_blank"
//alert(favType + favNumber +" "+cssClass)
}

function initFavoriteContainer(favType,cssClass){
	var containerDiv=document.getElementById(favType + 'ContainerDiv')
	
	containerDiv.innerHTML=""
	
	var containerUl=document.createElement('Ul')
	containerUl.id=favType + 'ContainerUl'
	containerUl.className=cssClass
	containerDiv.appendChild(containerUl)
	
	
	return true
}

function createFavorite(favType,favNumber,HTTP,cssClass){

	var game=new gameObj(HTTP.responseText)	
	
	if( favNumber % 2 ){
		var evenOdd=""
	}else{
		var evenOdd="on"
	}
	
	cssClass = cssClass + " " + evenOdd
	
	if(!game){
		displayMessage(Err.InvalidGameObject)
	}
	
	var gameLi=document.getElementById(favType + 'GameLi' + favNumber)
	gameLi.innerHTML="" //blank it first so its done loading
	gameLi.className=evenOdd
	
		var gameAnchor=document.createElement('a')
		gameAnchor.href=game.url
		gameAnchor.className="l1"
	
			var gameImage=document.createElement('img')
			gameImage.src=game.picture
			gameImage.className="IB"
			
			
		gameAnchor.appendChild(gameImage)

	gameLi.appendChild(gameAnchor)
	
	var div = document.createElement('div')
	div.className="title"
	
	var gameName=document.createElement('a')
	if(game.name.length>20){
		gameName.innerHTML=game.name.substr(0,17) + '...'
	}else{
		gameName.innerHTML=game.name
	}
	
	
	
	gameName.href=game.url
	gameName.className="l1"
	
	div.appendChild(gameName)
	gameLi.appendChild(div)
	//gameLi.appendChild(gameName)

	var gameRemove=document.createElement('a')
	gameRemove.href="#"
	gameRemove.onclick=function () { removeFavorite(game.id); reloadFavorites(); return false; }
	gameRemove.className="btnRemove"
	
	gameLi.appendChild(gameRemove)
}

function gameObj(gameData){
	if(gameData!=""){
		var itemData=gameData.split('\n')
	
		this.id=itemData[0]
		this.name=itemData[1]
		this.url=itemData[2]
		this.picture=itemData[3]
	}else{
		return false
	}
}
function getDivsByClass(toFind){
	var divs=document.getElementsByTagName('div')
	var ret=new Array()
	
	for( var i=0; i<divs.length; i++){
		if( divs[i].className == toFind ){
			ret.push(divs[i])
		}
	}
	
	return ret
}


function checkHTTP(){
	if(DISABLED==1){
		//silently fail we already alerted
		return false
	}else if(DISABLED==2){
		//we already checked and all is good
		return true
	}else{
	
		try {
			var HTTP = new XMLHttpRequest();
		}catch (e) {
			var HTTP = new ActiveXObject("Microsoft.XMLHTTP");
		}
	
		if(!HTTP){
			//broken
			displayMessage(Err.NoHttpObj)
		
			DISABLED=1
			return false
		}else{
			//all good
			HTTP=null
			DISABLED=2
			return true
		}	
	}
	return false
}

function setCookie(cName,value,expireDays){
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expireDays)
	return document.cookie=cName+ "=" +escape(value)+((expireDays==null) ? "" : ";expires="+exdate.toGMTString() + ";path=/")
}
function clearCookie(cName){
	var exdate=new Date()
	exdate.setDate(exdate.getDate()-20)
	return document.cookie=cName+ "="+ ";expires="+exdate.toGMTString() + ";path=/"
}

function getCookies(){
	//return an array of objects: cookies.name cookies.value
	
	var cookieChunks=document.cookie.split('; ')
	
	var cookies=new Array()
	
	function cookie(cookieString){
		var cookieParts=cookieString.split("=")
		this.name=cookieParts[0]
		this.value=unescape(cookieParts[1])
	}

	for(var i=0; i<cookieChunks.length; i++){
		cookies.push(new cookie(cookieChunks[i]))
	}
	
	return cookies
}

function getCookie(cName){
	var cookies=getCookies()
	
	for(var i=0; i<cookies.length; i++){
		if(cookies[i].name==cName){
			return cookies[i]
		}
	}
	
	return false
}

function getCookiesLike(startsWith){
	var cookies=getCookies()
	
	var matchedCookies=new Array()

	for(var i=0; i<cookies.length; i++){
		if(cookies[i].name.indexOf(startsWith)==0){
			matchedCookies.push(cookies[i])
		}
	}

	if(matchedCookies.length){
		return matchedCookies
	}else{
		return false
	}
}

function clearCookies(type){
	var cookies=getCookiesLike(type)
	for( var i=0; i<cookies.length; i++ ){
		clearCookie(cookies[i].name)
	}
	return true
}
		
	

function depricated__getCookie(cName){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(cName + "=")
		if (c_start!=-1){
			c_start=c_start + cName.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))
		}
	}
	return ""
}

function saveFavorites(favorites,favType,pageLength){

	favorites=splitFavorites(favorites,pageLength)
	//clear cookies first
	clearCookies(favType)
	for( var i=0; i < favorites.length; i++ ){
		if(!setCookie(favType + i, favorites[i].join(","), 730)){
			return false
		}
	}
	return true
}
	
	
function splitFavorites(favorites,pageLength){
	var cookieGroup=0
	var retFavorites=new Array()
	retFavorites[0]=new Array()

	while(favorites.length>0){
		if(retFavorites[cookieGroup].length>=pageLength){
			cookieGroup++
			retFavorites[cookieGroup]=new Array()
		}
		retFavorites[cookieGroup].push(favorites.shift())
	}
	return retFavorites
}

function displayMessage( message ){
	if( message ){
		alert( message )
	}
}

function addFavorite(gameId){
	var allFavorites=getFavorites('fav')
	if(!allFavorites){
		allFavorites=new Array()
	}
	
	if(inFavorites(gameId,allFavorites)){
		//didn't fail we just didn't add it.  this indicates a bug any way
		return true
	}
	
	allFavorites.unshift(gameId)
	if(saveFavorites(allFavorites,'fav',Config.MaxFavoritesPerPage)){
		displayMessage( Msg.SavedFavorites )
		return true
	}else{
		displayMessage( Err.FailedToSaveFavorites )
		return false
	}
}

function inFavorites(needle,haystack){
	
	var length;
	if ( haystack.length < Config.MaxModuleRecent)
	{
		length = haystack.length 
	}
	else
	{
		length = Config.MaxModuleRecent
	}
	
	for(var i=0; i< length; i++){
		if(haystack[i]==needle){
			return true
		}
	}
	return false
}

function addRecent(gameId){
	var recentGames=getFavorites('recent')
	if(!recentGames){
		recentGames=new Array()
	}
	
	if(inFavorites(gameId,recentGames)){
		//didn't fail just didn't add it
		return true
	}
	
	recentGames.unshift(gameId)
	for(var i=Config.MaxRecentModule;i<=recentGames.length; i++){
		recentGames.pop()
	}
	
	if(saveFavorites(recentGames,'recent',Config.MaxFavoritesPerPage)){
		displayMessage( Msg.SavedRecent )
		return true
	}else{
		displayMessage( Err.FailedToSaveFavorites )
		return false
	}
}

function removeFavorite(gameId){
	var allFavorites=getFavorites('fav')
	for(var i=0; i<allFavorites.length; i++ ){
		if( allFavorites[i] == gameId){
			allFavorites.splice(i,1)
			
			if(saveFavorites(allFavorites,'fav',Config.MaxFavoritesPerPage)){
				displayMessage( Msg.RemovedFavorite )
				return true
			}else{
				displayMessage( Err.FailedToSaveFavorites )
				return false
			}
		}
	}
	return false
}
	

function doTest(){
	var favorites=new Array()
	for(i=0; i<30; i++ ){
		favorites.push(i+1000)
	}
	
	saveFavorites(favorites,'fav',Config.MaxFavoritesPerPage)
}	

function doTestold(){
	var testDiv=document.getElementById('testDiv')
	var fooDiv=document.createElement('div')
	
	fooDiv.id="fooDiv"
	testDiv.appendChild(fooDiv)
	
	if(checkTest(testDiv)){
		alert("found foo div")
	}else{
		alert("failed to find foo div")
	}
}

function checkTest(testDiv){
	return document.getElementById('fooDiv')
}
