var Engine = {
	init: function(){
		Engine.log("Initing Engine.");
		var contentId = Engine.getURLParam("id");
		if (contentId && $('comments')) Engine.autoRefrisk("start");
		if ($('freshComment')){
			commentFetcher = new PeriodicalExecuter(Engine.fetchFreshComment,120);
		}
		chatEngine.init();
	},
	debug: false,
	
	console: null,


	log: function(message){
		if(!Engine.debug)
			return;
		if(!Engine.console){
			// Log window does not exist, try to open it.
			consoleWnd = window.open('','Debug Information','width=600,height=150,menubar=0,toolbar=0,status=0,scrollbars=1,location=0,resizable=1');
			consoleWnd.document.writeln('<html><head><title>Console</title></head><body bgcolor=white></body></html>');
			Engine.console = consoleWnd.document.body;
		}
		Engine.console.innerHTML += (message + "<br/>\n");
	},
	
	autoRefrisk: function(command){
		if (command == "start") {
			oldComments = "";
			refrisk = new PeriodicalExecuter(Engine.doUpdateComments,300);	
		}
		if (command == "off") {	
			refrisk.currentlyExecuting = true;
		}
		if (command == "on") {
			oldComments = "";	
			refrisk.currentlyExecuting = false;
		}
	},

	doTest: function(){
		// alert("test...");
	},

	/************************************************************************
	 * Module handling
	 ************************************************************************/
	modules: new Array(),
	
	loadModule: function(module){
		if(Engine.modules[module])
			return;
		Engine.log("Module " + module + " not yet loaded. Loading now...");
		var myAjax = new Ajax.Request("javascript/" + module + ".module.js",{
			method: 'post', 
			parameters: "?nocache=" + new Date(), 
			onFailure: function(){
				Engine.log("Could not load module " + module);
			},
			onSuccess: function(req){
				eval(req.responseText);
				Engine.modules[module].execute(uri);
			}
		});
	},
    	uri: "/",

    	loadPage: function(url){
    		if(!url)
    			url = "" + document.location;
    		Engine.log("Loading " + url);
    		var hashIndex = url.indexOf('#');
    		if(hashIndex < 0 || hashIndex >= url.length-2)
    			return Engine.hideStatus;
    		uri = url.substring(hashIndex + 1);
    		document.location.hash = uri;
    		var moduleLength;
    		if(uri.indexOf('/') > 0)
    			moduleLength = uri.indexOf('/');
    		else
    			moduleLength = uri.length;
    		var module = uri.substring(0,moduleLength);
    		uri = uri.substring(uri.indexOf('/'));
    		if(Engine.modules[module]){
    			Engine.modules[module].execute(uri);
    		}else{
    			Engine.loadModule(module);
    		}
    	},
	

	setComments: function(comments){
		$('comments').innerHTML = comments;
	},	
	

	setFreshComment: function(content){
		var fader = new Effect.Fade2($('freshComment'), {duration: 1.0,
			afterFinish: function callback(obj) {
                $('freshComment').innerHTML = content; 
                new Effect.Appear($('freshComment'), {duration: 2.0 });
              }
		});		
	},


	setContent: function(content){
		$('content').innerHTML = content;
	},
	
	setCommentArea: function(area, content){
		$('commentArea' + area).innerHTML = content;
	},
	setUserCommentText: function(content){
		$('userComment').value="";
	},

	setError: function(element){
		element.style.background = '#ffeeee';
	},
	setOK: function(element){
		element.style.background = "#eeffee";
	},


      getURLParam: function(strParamName){
        var strReturn = "";
        var strHref = window.location.href;
	  if ( strHref.indexOf("?") > -1 ) {
          var strQueryString = strHref.substr(strHref.indexOf("?"));
          var aQueryString = strQueryString.split("&");
          for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
            if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
              var aParam = aQueryString[iParam].split("=");
			  if (aParam[0].length == strParamName.length) {
              	strReturn = aParam[1];
              	break;
			  }
            }
          }
        }
        return strReturn;
      },

	doUpdateComments: function(){
			var contentId = Engine.getURLParam("id");
			if (contentId && $('comments')) {
	      		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
	      			method: 'post', 
					parameters: "task=listComments&contentId=" + contentId,
	      			onFailure: function(){
	      				Engine.log("Could not load comments");
	      			},
	      			onSuccess: function(req){
	      				Engine.log("Loaded comments");
	      				if (oldComments != req.responseText) { 
	      					oldComments = req.responseText;
		      				$('comments').innerHTML = req.responseText;
							Behaviour.apply();
							Engine.autoRefrisk("on");
						} 
	      			}
	      		});
      		}
	},

	doSubmitComment: function(comment, replyToCommentId){
		Engine.log("Registrerer ny kommentar");
		var contentId = Engine.getURLParam("id");
		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
			method: 'post', 
			parameters: "task=submitComment&comment=" + comment + "&replyToCommentId=" + replyToCommentId + "&contentId=" + contentId, 
			onFailure: function(){
				Engine.log("Feil med registrering av kommentar");
			},
			onSuccess: function(){
				Engine.doUpdateComments();
				Engine.setUserCommentText("");
			}
		});
	},

	doDeleteComment: function(commentId){
		if (confirm("Virkelig slette denne kommentaren?")) {
      		Engine.log("Slett kommentar" + commentId);
      		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
      			method: 'post', 
      			parameters: "task=deleteComment&commentId=" + commentId,
      			onFailure: function(){
      				Engine.log("Feil med sletting av kommentar" + commentId);
      			},
      			onSuccess: function(){
      				Engine.doUpdateComments();
      			}
      		});
		}
	},

	doEditComment: function(commentId){
		Engine.log("Rediger kommentar" + commentId);
		Engine.autoRefrisk("off");
		if ($('editBox')) {
			commentId2 = $('editBox').getAttributeNode("commentId").value;
			new Effect.Fade($('editBox'), {duration: 1.0,
			afterFinish: function callback(obj) { Engine.doUpdateCommentArea(commentId2);}});
   		}
		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
			method: 'post', 
			parameters: "task=editComment&commentId=" + commentId,
			onFailure: function(){
				Engine.log("Feil med redigering av kommentar" + commentId);
			},
			onSuccess: function(req){
				Engine.setCommentArea(commentId,req.responseText);
				Behaviour.apply();
			}
		});
	},


	doReplyToComment: function(commentId){
		Engine.log("Svarer på kommentar" + commentId);
		Engine.autoRefrisk("off");
		if ($('editBox')) {
			commentId2 = $('editBox').getAttributeNode("commentId").value;
			new Effect.Fade($('editBox'), {duration: 1.0,
			afterFinish: function callback(obj) { Engine.doUpdateCommentArea(commentId2);}});
		}
		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
			method: 'post', 
			parameters: "task=replyToComment&commentId=" + commentId,
			onFailure: function(){
				Engine.log("Feil med innlegging av svar til " + commentId);
			},
			onSuccess: function(req){
				Engine.setCommentArea(commentId,req.responseText);
				Behaviour.apply();
			}
		});
	},


	doUpdateCommentArea: function(commentId){
		Engine.log("Oppdaterer kommentar" + commentId);
		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
			method: 'post', 
			parameters: "task=updateCommentArea&commentId=" + commentId,
			onFailure: function(){
				Engine.log("Feil med oppdatering av kommentarfelt " + commentId);
			},
			onSuccess: function(req){
				Engine.setCommentArea(commentId,req.responseText);
				Behaviour.apply();
			}
		});
	},


	doChangeComment: function(commentId,comment){
		Engine.log("Oppdater kommentar " + commentId);
		if ($('editBox')) {
			new Effect.Fade($('editBox'));
		}
		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
			method: 'post', 			
			parameters: "task=changeComment&commentId=" + commentId + "&comment=" + comment,
			onFailure: function(){
				Engine.log("Feil med oppdatering av kommentar " + commentId);
			},
			onSuccess: function(){
				Engine.doUpdateComments();
				Behaviour.apply();
			}
		});
	},
	
	fetchFreshComment: function(){
      		var myAjax = new Ajax.Request("components/com_comments/doAction.php",{
      			method: 'post', 
				parameters: "task=fetchFreshComment",
      			onFailure: function(){
      				Engine.log("Could not load comment");
      			},
      			onSuccess: function(req){
      				Engine.log("Loaded comment");
      				Engine.setFreshComment(req.responseText);
      			}
      		});
	},

	joomlaRefresh: function(){
    		var myAjax = new Ajax.Request("index.php",{
    			method: 'post' 
    		});
	}
};

var chatEngine = {
	init: function(){
		lastChatId = 0;
		chatEngine.doUpdateChat();
		gameId = Engine.getURLParam("game");
		if ($('chatOutput')){
			var chatUpdater = new PeriodicalExecuter(chatEngine.doUpdateChat,3);
			var onlineUsersUpdater = new PeriodicalExecuter(chatEngine.doUpdateOnlineUsers,30);
			chatEngine.doUpdateOnlineUsers();
		}
	},
	
	doUpdateChat: function(){
			if ($('chatOutput')){
				if (typeof gameId == "undefined") gameId = Engine.getURLParam("game");
	      		var myAjax = new Ajax.Request("components/com_sjakk/doAction.php",{
	      			method: 'post', 
					parameters: "task=updateChat&gameId=" + gameId + "&lastChatId=" + lastChatId,
					onSuccess: function(req) {
						if (req.responseText){						
							$('chatOutput').innerHTML = req.responseText.substring(9,req.responseText.length); 
							lastChatId = req.responseText.substring(0,9);
							if ($('hotChat')) setTimeout("$('hotChat').style.color='#000000'",40000);
							var height1 = $('chatOutputContainer').scrollHeight;
							var height2 = $('chatOutputContainer').offsetHeight;
							if (height1 > 0) {
								$('chatOutputContainer').scrollTop = height1;		
							} else {
								$('chatOutputContainer').scrollTop = height2;									
							}
						}
					}
	      		});
      		}
	},
	
	doSubmitChat: function(chatText){
		if (typeof gameId == "undefined") gameId = Engine.getURLParam("game");
		if (!gameId) gameId = "0";
		var myAjax = new Ajax.Request("components/com_sjakk/doAction.php",{
			method: 'post', 
			parameters: "task=submitChat&chatText=" + chatText + "&gameId=" + gameId, 
			onSuccess: function(){
				$('chatText').value = "";
				chatEngine.doUpdateChat();
			}
		});
	},

	doUpdateOnlineUsers: function(){
			if (typeof gameId == "undefined") gameId = Engine.getURLParam("game");
			if ($('onlineUsers')){
	      		var myAjax = new Ajax.Updater("onlineUsers","components/com_sjakk/doAction.php",{
	      			method: 'post', 
					parameters: "task=updateOnlineUsers&gameId=" + gameId
	      		});
      		}
	}
};
