
rules['#x_gameType'] = initGame;
rules['.tabClick'] = addTabClick;
rules['#gameTrigger'] = updateGameHeader;
rules['#statsHead'] = updateStatsHeader;
rules['#userTopInfo'] = gameOverTopScoresRequest;
rules['#gameTeaserLink'] = initTeaserText;

function loadGame(iVal)
{
  var par = $('gameiframe');
  var gameId = getGameId(iVal);
  par.src = "/TIQGame?a=lg&gameid=" + gameId;
}

function displayResult(iVal)
{
  var par = $('gameiframe');
  var gameId = getGameId(iVal);
  score = iVal.className.match(/score\s(\w+)/);
  par.src = "/TIQGame?a=dr&escr=" + score[1];
  makeGOTopScoresRequest(gameId);
  
}

function updateGameHeader(elmt)
{
  if(elmt)
  {
  	var embedGId = elmt.className.match(/gid(\d+)/);
  	if(embedGId)
  	{
      if(parent.document.getElementById('x_gameType'))
  	  {
  		parent.document.getElementById('x_gameType').selectedIndex = embedGId[1];
  	  }
  	  if(parent.document.getElementById('leftColumn'))
  	  {
  		parent.makeGOTopScoresRequest(embedGId[1]);
  	  }
  	}
  }
  
  if($('x_gameType'))
  {
  	$('gameTitle').innerHTML=$('x_gameType').options[$('x_gameType').selectedIndex].innerHTML + JS_Challenge;
  }
  else if(parent.document.getElementById('x_gameType'))
  {
  	var dropdown = parent.document.getElementById('x_gameType');
  	var gameHead = parent.document.getElementById('gameTitle');
  	gameHead.innerHTML=dropdown.options[dropdown.selectedIndex].innerHTML + JS_Challenge;
  }
}

function loadGameFromLink(iVal)
{	
	var gId = getGameId(iVal);
	$('loadGameLink').href= $('loadGameLink').href + "&gameid=" + gId;	
}

function getGameId(dropDown){
  var gameId = 0;
  if(dropDown)
  {
  	var gameId = dropDown.options[dropDown.selectedIndex].value;
  }
   	
  return gameId;
}

function initGameOver(iVal, score){
	var par = $('gameiframe');
    par.src = "/TIQGame?a=ss&score=" + score + "&gameid=" + getGameId(iVal);
    //do single replacement ajax call
}

function initGame(iVal){
  if(iVal.className.match(/displayResult/)) displayResult(iVal);
  if(iVal.className.match(/loadGame/)) iVal.addEvent('change', function() {loadGame(iVal)});
  if(iVal.className.match(/initLoad/)) loadGame(iVal);
  
  if(iVal.className.match(/gameLink/)) initGameLink(iVal);
  
  if(iVal.className.match(/loadtop20/)) iVal.addEvent('change', function() {topScoresRequest(getGameId(iVal))});
  
  if(iVal.className.match(/updateHeader/)) iVal.addEvent('change', function() {updateStatsHeader()});
  
  if(score = iVal.className.match(/score\s(\w+)/))
  {
   	 initGameOver(iVal, score[1]);
  }
}

function initGameLink(iVal){
  $('loadGameLink').addEvent('click', function() {loadGameFromLink(iVal)});
}
 
function updateStatsHeader()
{
       if($('statsHead') && $('x_gameType'))
        {
               var newText = $('x_gameType').options[getGameId($('x_gameType'))].innerHTML;
                $('statsHead').innerHTML= newText + " (Top 20)";
        }
 }


function addTabClick(elmt) {
  elmt.addEvent('click', function() {appendGameId(elmt);});
}


function appendGameId(aTag)
{
  	if($('x_gameType'))
  	{
  		gameId = $('x_gameType').options[$('x_gameType').selectedIndex].value;
  	}
  	else
  	{
  		
  		if(gId = aTag.className.match(/gameid(\d+)/))
  		{
			gameId = gId[1];
  		}
  	}
  	
  	aTag.href.indexOf('?') != -1 ? aTag.href += "&" : aTag.href += "?";
  	aTag.href = aTag.href + "gameid=" + gameId;
}

function topScoresRequest(gameId)
{
	new Ajax('/TIQController', {
    	    data: {"a" : "ds", "gameid" : gameId},
         	onComplete: loadTopScores,
            onFailure: function(e) { alert(e.status + "\n" + e.responseText); }
        }).request();
	  return false;
}

function gameOverTopScoresRequest(elem)
{
	if(gameId = elem.className.match(/(\d+)/))
	{
		parent.makeGOTopScoresRequest(gameId[1]);
	}
}

function makeGOTopScoresRequest(gameId){
	new Ajax('/TIQController', {
    	    data: {"a" : "ds", "gameid" : gameId},
         	onComplete: loadGameOverTopScores,
            onFailure: function(e) { alert(e.status + "\n" + e.responseText); }
        }).request();
	  return false;
}

function loadGameOverTopScores(txt)
{
	var leftCol = $('leftColumn');
	leftCol.innerHTML = "";
	var rightCol = $('rightColumn');
	rightCol.innerHTML = "";
		
	if(txt.indexOf("(") == -1 && txt.indexOf(")") == -1)
	{
		var topScorers = eval("(" + txt + ")");
		
		var scoreDiv = topScorers.length+1 > 10 ? 11 : topScorers.length+1;
		if(topScorers && topScorers[1])
		{
			var i;
			for(i = 1; i < scoreDiv && i < 11; i++)
			{
				var topScorer = topScorers[i];
				if(topScorer)
				{
					var col = i < scoreDiv/2 ? leftCol : rightCol;
					
					var topScoreBlock = createTopScorer(topScorer, i);
					if(topScoreBlock)
					{
						topScoreBlock.injectInside(col);
						scaleImage2(topScorer.username, 50);
					}
				}
				else
				{
					break;
				}
			}
		}
	}
}

function loadTopScores(txt)
{
	var leftCol = $('leftColumn');
	leftCol.innerHTML = "";
	var rightCol = $('rightColumn');
	rightCol.innerHTML = "";
		
	if(txt.indexOf("(") == -1 && txt.indexOf(")") == -1)
	{
		var topScorers = eval("(" + txt + ")");
		
		if(topScorers && topScorers[0] && $('memberResults'))
		{
			if(topScorers[0].score != -1)
			{
				$('memberResults').style.display = 'block';
				$('myPoints').innerHTML = topScorers[0].score;
				$('myRank').innerHTML = topScorers[0].rank;
				$('myIQ').innerHTML = topScorers[0].iq;
				$('myLevel').innerHTML = topScorers[0].level;
				$('teaserText').style.display = 'none';
			}
			else
			{
				$('memberResults').style.display = 'none';
				$('teaserText').style.display = 'block';
				changeTeaserText($('gameTeaserLink'), getGameId($('x_gameType')));
			}
		}
		
		var scoreDiv = topScorers.length+1;
		if(topScorers && topScorers[1])
		{
			var i;
			for(i = 1; i < scoreDiv && i < 21; i++)
			{
				var topScorer = topScorers[i];
				if(topScorer)
				{
					var col = i < scoreDiv/2 ? leftCol : rightCol;
					
					var topScoreBlock = createTopScorer(topScorer, i);
					if(topScoreBlock)
					{
						topScoreBlock.injectInside(col);
						scaleImage2(topScorer.username, 50);
						
					}
				}
				else
				{
					break;
				}
			}
		}
	}
}

function createTopScorer(topScorer, rank)
{
  	var tsd = new Element('div', {'class': 'box'});
  	var aTag = new Element('a', {'href': '/members/' + topScorer.username, 'rel' : 'nofollow'}).injectInside(tsd);
    var imgTag = new Element('img', {'src': topScorer.avatarurl, 'alt' : '', 'id' : topScorer.username, 'width' : '50', 'height' : '50'}).injectInside(aTag);

	new Element('span', {'class': 'rank'}).setHTML(rank +'.').injectInside(tsd).injectBefore(aTag);
	
	var outerUl = new Element('ul').injectInside(tsd);
	var outerLi = new Element('li').injectInside(outerUl);
	
	
	var innerUl = new Element('ul').injectInside(outerLi);
	new Element('a', {'href': '/members/' + topScorer.username, 'rel' : 'nofollow'}).setHTML(topScorer.username).injectInside(innerUl);
	new Element('li', {'class' : 'points'}).setHTML(topScorer.score + '&nbsp;' + JS_TIQ_Pts ).injectInside(innerUl);
	new Element('li', {'class' : 'level'}).setHTML(JS_TIQ_Level + ':&nbsp;' + topScorer.level).injectInside(innerUl);
	new Element('li', {'class' : 'iq'}).setHTML(JS_TIQ + ':&nbsp;' + topScorer.iq).injectInside(innerUl);
	
	return tsd;		
}


function initTeaserText(elmt) {
	elmt.addEvent('click', function() {appendGameId(elmt);});
	if(gameId = elmt.className.match(/(\d+)/))
	{
		changeTeaserText(elmt, gameId[1]);
	}
	elmt.className = "";
}

function changeTeaserText(elmt, gameId) {
	var gameText = $('x_gameType').options[gameId].innerHTML + " Challenge";
    elmt.innerHTML = gameText;
}


// The following two functions; scaleImage2 andscaleImageDims are from tripadvisor.js which is not available on redesign pages.
// scaleImage2(imageID, maxSize) with helper function scaleImageDims(...)
// to use: pass in a document id as the imageID and a maxSize that the image
// should be scaled to preserving aspect ratio
function scaleImage2(imageID, maxSize) {
  if (typeof imageID != "undefined" && $(imageID)) {
    $(imageID).style.visibility = "hidden";
  	var tempImage = new Image();
  	tempImage.onload = function() { scaleImageDims(tempImage, imageID, maxSize); }
  	tempImage.src = $(imageID).src;
  }
}

function scaleImageDims(tempImage, imageID, maxSize) {
  if(tempImage.width > tempImage.height) {
    var width = maxSize;
    var height = width * tempImage.height / tempImage.width;
  } else {
    var height = maxSize;
    var width  = height * tempImage.width / tempImage.height;
  }
  $(imageID).style.height = height + "px";
  $(imageID).style.width = width + "px";
  $(imageID).style.visibility = "visible";
}
