var sjakkMenuEngine = {
	init: function(){
		oldRankingList = "";
		oldOldGames = "";
		oldOtherGames = "";
		oldChallenges = "";
		document.cookie = "showActive=1";

		sjakkMenuVersion = "0.981";
		sjakkMenuEngine.checkForUpdates();

		sjakkMenuEngine.updateMyGames();
		sjakkMenuEngine.updateRankingList();
		sjakkMenuEngine.updateOldGames();
		sjakkMenuEngine.updateOtherGames();
		sjakkMenuEngine.updateChallenges();

		if ((sjakkMenuEngine.get_cookie("noSound") > 0) || ($('menuSound').checked == false)) sjakkMenuEngine.turnOffSound();

		myGamesUpdater = new PeriodicalExecuter(sjakkMenuEngine.updateMyGames,8);
		rankingListUpdater = new PeriodicalExecuter(sjakkMenuEngine.updateRankingList,63);
		oldGamesUpdater = new PeriodicalExecuter(sjakkMenuEngine.updateOldGames,30);
		otherGamesUpdater = new PeriodicalExecuter(sjakkMenuEngine.updateOtherGames, 55);
		challengesUpdater = new PeriodicalExecuter(sjakkMenuEngine.updateChallenges, 10);
		joomlaRefresher = new PeriodicalExecuter(Engine.joomlaRefresh,25000);
		// showscreenvars = new PeriodicalExecuter(sjakkMenuEngine.screenVars,1);	

		var challenge = Engine.getURLParam("challenge");
		if (challenge > 0) sjakkMenuEngine.userChallenge(challenge);
	
},

	checkForUpdates: function() {
		var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php", {
			method: 'post',
			parameters: "task=getVersion&sjakkMenuVersion=" + sjakkMenuVersion,
			onComplete: function(req){
				if (req.responseText) window.location.reload(true);
			}
		});
	},

		     
	screenVars: function(){
		if (typeof musX == "undefined") musX = 0;
		if (typeof musY == "undefined") musY = 0;
		if (typeof musXX == "undefined") musXX = 0;
		if (typeof musYY == "undefined") musYY = 0;
  	  if (!$('coords')) {
		  coords = document.createElement("div");
		  coords.id = "coords";
		  document.body.appendChild(coords);
		  $('coords').style.position = "absolute";
		  $('coords').style.left = "100px";
		  $('coords').style.top = "100px";
		  $('coords').style.background = "black";
		  $('coords').style.color = "white";
	  }
	  $('coords').innerHTML = "musXX: " + musXX + "<br>musYY: " + musYY + "<br>musX: " + musX + "<br>musY: " + musY;		
	},
	
	remainingTime: function(seconds){
     	var rt = seconds; 
     	var output = "";
     	var days = Math.floor (rt / 86400);
     	if (days > 0) {
     		rt = rt - (days * 86400);
     		output = days + " dag";
     		if (days > 1) output += "er";
     	}
     	var hours = Math.floor (rt / 3600);
     	if (hours > 0) {
     		if (days > 0) output += " og";
     		rt = rt - (hours * 3600);
     		output += " " + hours + " time";
     		if (hours > 1) output += "r";
     	}
     	var mins = Math.floor (rt / 60);
     	if ((mins > 0) && !days) {
     		if (hours > 0) output += " og";
     		rt = rt - (mins * 60);
     		output += " " + mins + " minutt";
     		if (mins > 1) output += "er";
		}
     	secs = rt; 
     	if ((secs > 0) && !days && !hours){
     	    if (mins > 0) output += " og";
     		output += " " + secs + " sekund";
     		if (secs > 1) output += "er";
     	}
     	return output;
     },
     
    updateChallenges: function(){
       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=updateChallenges",
      			onFailure: function(){
      			},
      			onSuccess: function(req){
      				if (oldChallenges != req.responseText) {
      					oldChallenges = req.responseText;
      					$('challengesContent').innerHTML = oldChallenges;
      					Behaviour.apply();
      				}
      			}
      		});
    },
    
    updateMyGames: function(){
    	if (typeof lastMoveMyGames == "undefined") lastMoveMyGames = 0;
    	if (typeof numberOfGames == "undefined") numberOfGames = 0;
    	if (typeof myGamesCounter == "undefined") myGamesCounter = 0;
    	if (myGamesCounter > 10) {
    		myGamesCounter = 0;
	       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
	      			method: 'post', 
					parameters: "task=updateMyGames&updateAnyways=1",
	      			onComplete: function(req){
	      					if (req.responseText){
	      						if ((lastMoveMyGames > 0) && (lastMoveMyGames != req.responseText.substring(3,12))) sjakkMenuEngine.playSound("futurebeep3");
	      						numberOfGames = req.responseText.substring(0,3);
	      						lastMoveMyGames = req.responseText.substring(3,12);
		      					$('myGamesContent').innerHTML = req.responseText.substring(12,req.responseText.length);
	    	  					Behaviour.apply();
	    	  				}
	      			}
	      		});
    	} else {
	    	myGamesCounter++;
	       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
	      			method: 'post', 
					parameters: "task=updateMyGames&lastMoveMyGames="+lastMoveMyGames + "&numberOfGames=" + numberOfGames,
	      			onComplete: function(req){
	      					if (req.responseText){
	      						if (lastMoveMyGames > 0) sjakkMenuEngine.playSound("futurebeep3");
	      						numberOfGames = req.responseText.substring(0,3);
	      						lastMoveMyGames = req.responseText.substring(3,12);
		      					$('myGamesContent').innerHTML = req.responseText.substring(12,req.responseText.length);
	    	  					Behaviour.apply();
	    	  				}
	      			}
	      		});
	    }
	   //  alert("lastMoveMyGames: " + lastMoveMyGames + " \nnumberOfGames: " + numberOfGames);
    },	
    
    updateRankingList: function(){
       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=updateRankingList",
      			onFailure: function(){
      			},
      			onSuccess: function(req){
      				if (oldRankingList != req.responseText) {
      					oldRankingList = req.responseText;
      					$('rankingList').innerHTML = oldRankingList;
      					Behaviour.apply();      					
      				}
      			}
      		});
    },
    
    updateOldGames: function(){
       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=updateOldGames",
      			onFailure: function(){
      			},
      			onSuccess: function(req){
      				if (oldOldGames != req.responseText) {
      					oldOldGames = req.responseText;
      					$('oldGamesContent').innerHTML = oldOldGames;
      					Behaviour.apply();      					
      				}
      			}
      		});
    },

    updateOtherGames: function(){
       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=updateOtherGames&showActive=" + sjakkMenuEngine.get_cookie("showActive"),
      			onSuccess: function(req){
      				if (oldOtherGames != req.responseText) {
      					oldOtherGames = req.responseText;
      					$('otherGamesContent').innerHTML = oldOtherGames;
      					Behaviour.apply();      					
      				}
      			}
      		});
    },
    
    registerChallenge: function(){
    	if ($('anybodyRadio').checked == true) {
    		var challenged = "0";
    		var challengedUsername = "";
    	} else if ($('emailUserRadio').checked == true) {
    	    if (!sjakkMenuEngine.validEmail($('inputEmail').value)) $('inputEmail').focus();
    	    var email = $('inputEmail').value;
    	} else {
    		var challenged = $F('manualInputOpponent_hidden');
    		var challengedUsername = $F('manualInputOpponent');
    	}
    	if ($('lynsjakk').checked == true) var gameMode = "lynsjakk";
    	if ($('panikksjakk').checked == true) var gameMode = "panikksjakk";
    	if ($('avslappa').checked == true) var gameMode = "avslappa";
    	if ($('episk').checked == true) var gameMode = "episk";
    	
    	if ($('blackRadio').checked == true) {
    		var challengerColor = "black";
    	} else {
    		var challengerColor = "white";
       	}
       	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=registerChallenge&challenged=" + challenged + "&gameMode=" + gameMode + "&challengerColor=" + challengerColor + "&gameTitle=" + escape($F('gameTitleInput')) + "&challengedUsername=" + challengedUsername + "&email=" + email,
      			onFailure: function(){
      			},
      			onSuccess: function(req){
      				sjakkMenuEngine.updateChallenges();
      				challengesUpdater.currentlyExecuting = false;
      			}
      		});
    },    
      
    remainingTime: function(seconds){
     	var rt = seconds; 
     	var output = "";
     	var days = Math.floor (rt / 86400);
     	if (days > 0) {
     		rt = rt - (days * 86400);
     		output = days + " dag";
     		if (days > 1) output += "er";
     	}
     	var hours = Math.floor (rt / 3600);
     	if (hours > 0) {
     		if (days > 0) output += " og";
     		rt = rt - (hours * 3600);
     		output += " " + hours + " time";
     		if (hours > 1) output += "r";
     	}
     	var mins = Math.floor (rt / 60);
     	if ((mins > 0) && !days) {
     		if (hours > 0) output += " og";
     		rt = rt - (mins * 60);
     		output += " " + mins + " minutt";
     		if (mins > 1) output += "er";
		}
     	secs = rt; 
     	if ((secs > 0) && !days && !hours){
     	    if (mins > 0) output += " og";
     		output += " " + secs + " sekund";
     		if (secs > 1) output += "er";
     	}
     	return output;
     },

     playSound: function(file, volume) {
		 if ($('menuSound').checked) {
			 file = "components/com_sjakk/sfx/" + file + ".wav";
			 if(!volume) volume = 100;
			 var soundcontainer = document.getElementById("soundcontainer");
			 if(!soundcontainer) {
				  soundcontainer = document.createElement("div");
				  soundcontainer.id = "soundcontainer";
				  soundcontainer.style.width = "1px"; //IE bugfix
				  soundcontainer.style.height = "0";
				  soundcontainer.style.overflow = "hidden";
				  document.body.appendChild(soundcontainer);
			 }
			 if(navigator.appName == "Microsoft Internet Explorer") { 
			 	soundcontainer.innerHTML = '<embed src="' + file + '" volume="' + volume + '" />';
			 } else {
			 	soundcontainer.innerHTML = '<object data="' + file + '" title=""><param name="volume" value="' + volume + '" /> <param name="autostart" value="true" /></object>';
			 }
		 }
	},
	
	turnOffSound: function() {
		document.cookie="noSound=1"; 
		$('menuSound').checked = false;
	},
	
	turnOnSound: function() {
		document.cookie="noSound=0"; 
		$('menuSound').checked = true;
	},
	
	//Get cookie routine by Shelley Powers 
	get_cookie: function(Name) {
	  var search = Name + "="
	  var returnvalue = "";
	  if (document.cookie.length > 0) {
	    offset = document.cookie.indexOf(search)
	    // if cookie exists
	    if (offset != -1) { 
	      offset += search.length
	      // set index of beginning of value
	      end = document.cookie.indexOf(";", offset);
	      // set index of end of cookie value
	      if (end == -1) end = document.cookie.length;
	      returnvalue=unescape(document.cookie.substring(offset, end))
	      }
	   }
	  return returnvalue;
	},
	
	userChallenge: function(userId) {
		setTimeout('sjakkMenuEngine.hideUserStats();',2000);
		var task = Engine.getURLParam("task");
		if (task == "archive") {
			top.location.href = "index.php?option=com_sjakk&Itemid=28&challenge=" + userId;
		} else {
			var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
	      			method: 'post', 
	      			parameters: "task=newGame&challengedPlayer=" + userId,
					onSuccess: function(req){
						$('challengesContent').innerHTML = req.responseText;
						$('challengesContent').style.display = "none";
						new Effect.BlindDown($('challengesContent')); 
						Element.scrollTo($('challenges'));
						Behaviour.apply();
	      			}
	      	});
	   }
	},

	hideUserStats: function() {
    	 	$('userStats').style.display = "none" ;	
    	 	statsOn = false;
    	      document.onmousemove = "";
	},
	
	showExpStats: function(chessUserId, rating, username){
		if (statsOn == chessUserId) {
		     	var myAjax = new Ajax.Request("components/com_sjakk/menuAction.php",{
      			method: 'post', 
				parameters: "task=getUserStats&userId=" + chessUserId,
      			onComplete: function(req, userDataJSON){
      				if (userDataJSON) {
      				  menuOutput = '<table width=82 cellspacing=1 cellpadding=0 bgcolor=lightgray ><tr><td><table width=140 cellspacing=0 cellpadding=0>';
					  menuOutput += '<tr><td style=\"background: gray; color: white;" onclick="sjakkMenuEngine.userChallenge(' + chessUserId + ')">' + username + ' (' + rating + ')</td></tr>';
					  menuOutput += '<tr><td bgcolor="#FFFFFF" width="140" height="16" onclick="sjakkMenuEngine.userChallenge(' + chessUserId + ')">vinn: ' + userDataJSON["wins"] + ' &nbsp;&nbsp; tap: ' + userDataJSON["losses"] + ' &nbsp;&nbsp; uavgj: ' + userDataJSON["draws"];
					  menuOutput += '<br><span style=\"color: red;\">Klikk for &aring; utfordre</span>';
					  if (userDataJSON["gameModes"])  menuOutput += '<br><span style=\"font-size: 10px; color: #666666;\">' + userDataJSON["gameModes"] + '</span>';
					  menuOutput += '</td></tr></table></td></tr></table>';
					  $('userStats').innerHTML = menuOutput;
      				}
      			}
      		});
		}
	},
	
	showUserStats: function(e, chessUserId, rating, username) {
		/*
  	  if (!$('userStats')) {
			  userStats = document.createElement("div");
			  userStats.id = "userStats";
			  document.body.appendChild(userStats);
			  $('userStats').style.position = "absolute";
	  }
	  if (typeof id2 == "undefined") id2 = 0;
	  musXX = Event.pointerX(e);
      musYY = Event.pointerY(e);
      statsOn = chessUserId;
	  if ((id2 != chessUserId) || ($('userStats').style.display = "none")) {
	  	  id2 = chessUserId;
		  if (!rating) rating = 0;		 
   		  menuOutput = '<table width=82 cellspacing=1 cellpadding=0 bgcolor=lightgray ><tr><td><table width=140 cellspacing=0 cellpadding=0>';
		  menuOutput += '<tr><td style=\"background: gray; color: white;" onclick="sjakkMenuEngine.userChallenge(' + chessUserId + ')">' + username + ' (' + rating + ')</td></tr>';
		  menuOutput += '<tr><td bgcolor="#FFFFFF" width="140" height="16" onMouseOver="this.style.backgroundColor=\'#EFEFEF\'" style="font-size: 10px;" onMouseOut="this.style.backgroundColor=\'#FFFFFF\'" onclick="sjakkMenuEngine.userChallenge(' + chessUserId + ')">henter statistikk...';
		  menuOutput += '<br><font color=red>Klikk for &aring; utfordre</font></td></tr>';
		  menuOutput += '</table></td></tr></table>';
		  $('userStats').innerHTML = menuOutput;
	
		  $('userStats').style.left = musXX+10 + "px";
		  $('userStats').style.top = musYY + "px";
		  $('userStats').style.display = "";
		  
		  setTimeout('sjakkMenuEngine.showExpStats("' + chessUserId + '", "' + rating + '", "' + username + '");',2000);
		  	   	  
		  document.onmousemove = function(ev){
				if(navigator.appName == "Microsoft Internet Explorer") {
					musX = Event.pointerX(event);
				    musY = Event.pointerY(event);				
				} else {
					musX = Event.pointerX(ev);
				    musY = Event.pointerY(ev);				
				}
				if ((musX > (musXX+10)) || (musY > (musYY+10)) || (musX < (musXX-10)) || (musY < (musYY-10))) 
					sjakkMenuEngine.hideUserStats();
		  }
		  
	   } 
	   */
	},
	
   validEmail: function (eAddr) { 
	  var chkDot = true;
      var usEmail = false;
      var lenSuffix = (usEmail) ? 4 : 3;
      var result = false;
      var ndxAt = ndxDot =  0;
          
      ndxAt  = eAddr.indexOf("@");
      ndxDot = eAddr.indexOf(".") ;
      ndxDot2 = eAddr.lastIndexOf(".") ;
          
      if ((ndxDot < 0) || (ndxAt < 0))
         alert("E-postadressen du har skrevet inn mangler '.' or '@'.\n\nKorrekt format er 'mostander@domene.no'"); 
      else if (chkDot && (ndxDot < ndxAt) )
         chkDot = !(confirm("Du har skrevet et punktum rett foran '@' i e-postadressen\nEr dette korrekt?") );
      else if ( (ndxDot2 - 3) <= ndxAt)
         alert("Domene mangler i e-postadressen du har skrevet inn. \n\n Korrekt format er 'motstander@domene.no'");
      else 
           result=true;           
      return result; 
   } 
};