var messagesChannelPush;
var messagesPush; 
var scoresChannelPush; 
var scoresPush; 
var usersChannelPush; 
var usersPush; 
var trivialPush;  
var logStatusPush; 
var logPush;
var pushletsReady = false; 

function registerPushlets() {
	var registerObject = new ServiceObject(TRIVIAL_URL);
	registerObject.addParam("inPushletId", Pushlets.getSession());		
	var myBool = registerObject.call("register");
	if (myBool == "false") {
		alert("An unexpected error has occured loading the page, please reload. If this problem keeps happening, please contact us at trivity@icube.at."); 
	} else {
		pushletsReady = true; 
	}
}

function refreshPushlets() {
	var registerObject = new ServiceObject(TRIVIAL_URL);
	registerObject.addParam("inPushletId", Pushlets.getSession());		
	var myBool = registerObject.call("refreshPushlets");
	
	if (myBool == "false") {
		alert("[Error] Lost communication channel. Press F5 to reload page!");
	} else {
		alert("Restored"); 
	}
}

function subscribePushlets(inChannel) {
	if(typeof inChannel == "undefined") {
		inChannel = "system"; 
  }
  
  if(inChannel != "system") {		
		if(messagesChannelPush && messagesChannelPush.getActive()) {
			messagesChannelPush.change("/messages/" + inChannel); 
		} else {
			// register for system service
			messagesChannelPush = new PushObject("/messages/" + inChannel, onChannelEvent);
			messagesChannelPush.activate();
		}
		
		if(scoresChannelPush && scoresChannelPush.getActive()) {
			scoresChannelPush.change("/scores/" + inChannel); 
		} else {			
			scoresChannelPush = new PushObject("/scores/" + inChannel, onChannelEvent);
			scoresChannelPush.activate(); 
		}
		
		if(usersChannelPush && usersChannelPush.getActive()) {
			usersChannelPush.change("/users/" + inChannel); 
		} else {			
			usersChannelPush = new PushObject("/users/" + inChannel, onChannelEvent);
			usersChannelPush.activate(); 
		}
		
		if(trivialPush && trivialPush.getActive()) {
			trivialPush.change("/trivial/" + inChannel); 
		} else {
			// register for channel message service
			trivialPush = new PushObject("/trivial/" + inChannel, onTrivialEvent);
			trivialPush.activate(); 
		}	
	} else {
		messagesPush = new PushObject("/messages/" + inChannel, onSystemEvent);
		messagesPush.activate();
						
		scoresPush = new PushObject("/scores/" + inChannel, onSystemEvent);
		scoresPush.activate(); 
		
		usersPush = new PushObject("/users/" + inChannel, onSystemEvent);
		usersPush.activate(); 
				
		channelPush = new PushObject("/channels/" + inChannel, onSystemEvent);
		channelPush.activate(); 
				
		logStatusPush = new PushObject("/logstatus/system", onLogStatusEvent);
		logStatusPush.activate(); 
	}
}

function onSystemEvent(msg) {
	/* type ... 
				0 ... system message (global)
				1 ... private system message global) 
				2 ... normal message (global) (can only be done by admins) 
				3 ... private message (global)
				4 ... scoreList (global)
				5 ... channelList (global)
				6 ... userList (global)
	*/
	
	if (loaded && msg.type >= 0 && msg.type <=3) {
		message(msg); 
	} else if (msg.type == 4) {
		updateRanking(msg);
	} else if (msg.type == 5) {			
		updateChannelList(msg);
	} else if (msg.type == 6) {			
		updateUserList(msg); 
	} else if (msg.type == 10) {
		writeToLog(msg); 
	}
	
    if (doLogin)
    	tryRemoteLogin();
}

function onChannelEvent(msg) {
	/* type ... 
				0 ... system message (channel only)
				1 ... private system message (channel only) 
				2 ... normal message (channel only)
				3 ... private message (channel only)
				4 ... scoreList (channel only)
				6 ... userList (channel only)
	*/
	if (loaded && msg.type >= 0 && msg.type <=3) {
		message(msg); 
	} else if (msg.type == 4) {
		updateRanking(msg);
	} else if (msg.type == 6) {			
		updateUserList(msg); 
	} 
}

function onTrivialEvent(msg) {
	/* type ... 
				0 ... question as image 
				1 ... banner
				2 ... question as text
	*/
	if(msg.type == 0) {
		showImage(msg.URL, false);
		resetVote(msg.Vote); 
	} else if (msg.type == 1) {
		showImage(msg.URL, true);
	} else if (msg.type == 2) {
		askQuestion(msg.question); 
	}
}

function onLogStatusEvent(msg) {
	if (msg.status == "true") {
		startLog(); 
	} else {
		stopLog(); 
	} 
}

/**
 *	Prints a received message to the DIV containing all chat messages.
 */
function message(msg) {
	// decide on style
	var weight = "normal";
	var color = null;
	var style = "normal";  
	if (msg.type == 0 || msg.type == 1) weight = "bold";
	if (msg.type == 0 || msg.type == 1) color = "#999999";
	if (msg.type == 1 || msg.type == 3) style = "italic";
	
	// handle special system messages
	if (msg.type == 1 && msg.text == "logout") {
		callback_logout();
		return;
	}
	if (msg.type == 1 && msg.text == "ping") {
		var sendObject = new ServiceObject(TRIVIAL_URL);
		var json = {"msg":"/pong"};
		var myMessage = JSON.stringify(json);
		sendObject.addParam("inMessage", myMessage); 		
		var myBool = sendObject.call("sendMessage");	
		return;
	}
	
	/*
	// DEBUG prepare message
	msg = prepareMessage(msg);
	// DEBUG decide on banner effects
	if (msg.text.indexOf("/banner-on") == 0) {
		startBanner();
		return false;
	}
	if (msg.text.indexOf("/banner-off") == 0) {
		endBanner();
		return false;
	}*/
		
	// prepare string	
	var line = document.createElement("span");
	line.style.color = (color) ? color : msg.color;
	line.style.fontWeight = weight;
	line.style.fontStyle = style;
	line.innerHTML = "<b>" + msg.nick + "</b>: " + msg.text;
	var crlf = document.createElement("br");
	// decide on channel
	var target = msg.target;
	if (!target) target = TAB_DEFAULT;
	// initialize channel
	var chat;
	chat = document.getElementById("chat.channel." + target);
	if (!chat) {
		var def = document.getElementById("chat.channel." + TAB_DEFAULT);
		chat = def.cloneNode(false);
		chat.id = "chat.channel." + target;
		chat.style.visibility = "hidden";
		tabs.push(new Tab(target));
		def.parentNode.appendChild(chat);
		updateTabList();
	}
	// get tab associated with current channel
	var tab = tabs[tabs.indexOf(target)];
	// manage unseen state and alert color
	if (chat.style.visibility == "hidden") {
		document.getElementById("tabcontrol.channel." + target).style.color = TAB_ALERT_COLOR;
		tab.unseen = true;
	}
	// remove first if cache capacity has been reached
	if (tab.messageCount >= MESSAGE_CACHE) {
		chat.removeChild(chat.firstChild);
		chat.removeChild(chat.firstChild);
	} else tab.messageCount = tab.messageCount + 1;
	// write message and crlf
	chat.appendChild(line);
	chat.appendChild(crlf);
	// scroll to bottom
	chat.scrollTop = chat.scrollHeight;
}

/**
 *	Sends the message typed in the text input field to the server by calling
 *	the respective service.
 */
function send() {
	var tx = document.getElementById("txt");
	var myText = tx.value; 
	var json = {"msg":myText, "target":currentTab, "color":currentColor};
	var myMessage = JSON.stringify(json);
	
	var sendObject = new ServiceObject(TRIVIAL_URL);
	sendObject.addParam("inMessage", myMessage); 		
	var myBool = sendObject.call("sendMessage");	
	if (myBool == "false") {
		alert("An unexpected error has occured sending your message. If this keeps happening, please reload the page."); 
	}
	tx.value = "";
	tx.focus();
	
	return false;
}

function writeToLog(msg) {
	var json = {"type":10, "target":"log", "color":"#000000", "nick": "system", "text": msg.text};
	message(json); 
}	
