/**
 * Timer object definition.
 */
var timer = {
	interval : 5 * 1000,
	eventId : null,
	chatConversation : null,
	msgHandler : null,
	onlineUserHandler : null,
	status : 1,
	start : function(c) {
		chatConversation = c;
		msgHandler = chatConversation.msgHandler;
		onlineUserHandler = new OnlineUserHandler(chatConversation);
		eventId = setInterval("timer.polling()", timer.interval);
		this.polling();
		$("#chatOverlay").removeClass("hidden").addClass(chatConversation.isInstructor() ? "instructorCon" : "studentCon");
		$("#chatOverlay").draggable({ handle: '#titleBar' });
	},
	polling : function() {
		if(this.status==1) {
			if (chatConversation.isInstructor()){
				chatConversation.remind();
			}
			$.post(ctx + '/chat/polling.u', {
				"planId" : chatConversation.planId,
				"userId" : chatConversation.userId,
				"isInstructor" : chatConversation.isInstructor() ? "1" : "0",
				"username" : chatConversation.userName,
				"i" : Math.random()
			}, this.handling, 'json');		
			 //this.end();
		}
	},
	stop: function (){
		timer.status = 0;
		clearInterval(eventId);
		chatConversation.status = 'D';
	},
	end : function() {		
		this.stop();
		chatConversation.destroy();
	},
	handling : function(data) {
		msgHandler.recieveMessage(data.messages);
		onlineUserHandler.refreshTabs(data.onlineUsers);
		if (chatConversation.isInstructor()){
			chatConversation.updatePlan(data.plan);
		}
	}
};

/**
 * Conversation Class definition.
 */
function Conversation(creatorId, lessonId, planId, beginTime, endTime, status,timezone) {
	// instructor name (not 32-length id)
	this.creatorId = creatorId;
	// login user id
	this.userId = GetCookie("com_skta_ulearn_uid");
	// login user name
	this.userName = GetCookie("com_skta_ulearn_username");
	this.lessonId = lessonId;
	this.planId = planId;
	this.beginTime = beginTime;
	this.endTime = endTime;
	this.status = status;
	this.timezone = timezone;
	this.userRole = this.userName == this.creatorId ? "I" : "S";
	this.endReminder = 1;
	this.msgHandler = new MessageHandler(this);
	this.isInstructor = function(){
		return this.userRole == 'I';
	};
	
	this.destroy = function(){
		$("#mainPanel #userPanel").html('');
		$("#messageList").html('');
		$("#messageEditor textarea").val('');
		$('#closeBtn').addClass('hidden');
		$('#sendBtn').removeClass('hidden');
		$("#chatOverlay").addClass('hidden');
		$("#chatOverlay").css("top","10%").css("left","277px");
		$("#minimizeChatOverlay").addClass('hidden');
		$('#operationMenu').addClass('hidden');
		this.status = 'D';		
	};
	
	if (this.isInstructor()) {
		this.start = function() {
			if (this.status == 'S') {
				$.post(ctx + '/plan/start.u', {
					"planId" : this.planId,
					"i" : Math.random()
				}, this.afterStart);
			}
		}

		this.afterStart = function(data) {
			if (data == 'true') {
				timer.start(chatConversation);
			}
		}

		this.remind = function() {
			if (!isLogin() || this.status != 'P')
				return;
			// Minutes left.
			var timeLeft = diffWithEndTime(this.endTime,this.timezone.toString().substr(0,3));
			if (timeLeft >= 0) {
				this.end();
			} else if (chatConversation.endReminder == 1 && timeLeft >= (-10)) {
				confirmMsg(
						'This chat session is scheduled to end in '+(-1*timeLeft)+' minutes. Do you want to extend the chat session for an additional 30 minutes?',
						this.renew);
				chatConversation.endReminder = 0;
			}
		}

		this.end = function() {
			$.post(ctx + '/plan/end.u', {
				"planId" : chatConversation.planId,
				"i" : Math.random()
			}, chatConversation.afterEnd);
		}

		this.afterEnd = function() {			
			var tabs = $("#mainPanel #userPanel .tab");
			tabs.each(function (){
				chatConversation.msgHandler.appendMsg($(this).attr('id'), "System", "Chat session ended", true);
			});
			disableSendMsg();
			$("#sendBtn").addClass("hidden");
			$("#closeBtn").removeClass("hidden");
			timer.stop();
			document.getElementById("file_swf_room").refreshOfficeHour();
		}

		this.renew = function() {
			$.post(ctx + '/plan/renew.u', {
				"planId" : chatConversation.planId,
				"i" : Math.random()
			}, this.afterRenew);
		}

		this.afterRenew = function() {
			this.endReminder = 1;
		}
		
		this.updatePlan =  function(plan){
			if(typeof(plan)=='undefined'||plan=="null"||plan==null||plan==""){
				this.afterEnd();
			}else{
				this.endTime = plan.endTime;
				this.status = plan.status;
			}
		}
		disableSendMsg();
		$("#endConv span").text("End All Chat").click(function(){
			$('#operationMenu').addClass('hidden');
			confirmMsg(
					'This will end all your chat sessions with students. Are you sure you want to do this?',
					chatConversation.end);
			});
	} else {
		this.msgHandler.newEmptyTab(this.creatorId, this.userId);
		$("#endConv span").text("Close Window").click(function(){$('#operationMenu').addClass('hidden');timer.end();});
	}
	
	if (this.status == 'P') {
		timer.start(this);
	} 
}

function delayPopChat(beginTime,offset) {
	//var startTime = new Date(Date.parse(beginTime.replace(/-/g,"/")));
	var startTime = new Date(beginTime.split(" ")[0].split("-")[0],
							beginTime.split(" ")[0].split("-")[1] - 1,
							beginTime.split(" ")[0].split("-")[2],
							beginTime.split(" ")[1].split(":")[0],
							beginTime.split(" ")[1].split(":")[1],
							beginTime.split(" ")[1].split(":")[2],
							0);
	var currDate = new Date();	 
	var localTime = currDate.getTime();
	var localOffset = startTime.getTimezoneOffset()*60*1000;
    //currentTime = localTime-localOffset - offset*60*60*1000;
    var interval = Math.round(((startTime.getTime() + localOffset + offset*60*60*1000) - localTime) / 1000);
	if(interval * 1000 >0){
		myInterval = setTimeout(popChat, interval * 1000);
	} else {
		popChat();
	}
}

function popChat(){
	chatConversation.start();
}

/**
 * MessageHandler Class definition.
 */
function MessageHandler(chatConversation) {
	this.chatConversation = chatConversation;
	this.recieveMessage = function(messages) {		
		for (key in messages) {
			msg = messages[key];
			if(this.handleEndingMsg(msg)) return;
			senderName = msg.senderName;
			if (!$("#userPanel #" + senderName).exists()) {
				this.newTab(msg);
			}
			if ($("#chatOverlay").is(".hidden") || !$("#userPanel #" + senderName).is(".current")) {
				this.blinkTab(senderName);
			}
			this.appendMsg(senderName, senderName, msg.message, false);
		}
	};

	this.blinkTab = function(tabId) {
		if ($("#chatOverlay").is(".hidden")) {
			$("#minimizeChatOverlay").addClass("blink");
		} else {
			$("#userPanel #" + tabId).not(".current").addClass("newMessage");
			for ( var i = 1; i < 7; i++) {
				setTimeout('$("#userPanel #' + tabId + '").not(".current").toggleClass("newMessage")', i * 300);
			}
		}
	};

	this.newTab = function(msg) {
		var tabObj = $("#tabTemplate .tab").clone();
		if (chatConversation.isInstructor()) 
			tabObj.find(".recieverName").text(msg.senderName.substring(0, 7));
		else
			tabObj.find(".recieverName").text(tabName);
		tabObj.find(".recieverName").attr("title",msg.senderName);
		tabObj.attr("id", msg.senderName);
		if (!$("#userPanel .current").exists()) {
			tabObj.addClass("current");
		}
		$("#mainPanel #userPanel").append(tabObj);		
		var msgObj = $("<div id='msg" + msg.senderName + "' class='userMessages'></div>");
		if ($("#messageList .userMessages").not(".hidden").exists()) {
			msgObj.addClass("hidden");
		}
		$("#messageList").append(msgObj);
		$("#mainPanel #userPanel .tab").eq("0").addClass("first");
	};

	this.newEmptyTab = function(tabName) {
		if($("#mainPanel #userPanel #"+tabName).exists()) return;
		var tabObj = $("#tabTemplate .tab").clone();
		if (chatConversation.isInstructor())
			tabObj.find(".recieverName").text(tabName.substring(0, 7));
		else
			tabObj.find(".recieverName").text(tabName);
		tabObj.find(".recieverName").attr("title",tabName);
		tabObj.attr("id", tabName);
		tabObj.addClass("current");
		$("#mainPanel #userPanel").append(tabObj);
		var msgObj = $("<div id='msg" + tabName + "' class='userMessages'></div>");
		$("#messageList").append(msgObj);
		$("#mainPanel #userPanel .tab").eq("0").addClass("first");
	};

	this.appendMsg = function(tabId, senderName, msgBody, isSystem) {
		var msgObj = $("#messageTemplate .message").clone();
		msgObj.find(".header").text("[" + senderName + " " + getCurrentHourMinute() + "]");
		msgObj.find(".content p").text(msgBody);
		if (isSystem)
			msgObj.addClass("system");
		$("#messageList #msg" + tabId).append(msgObj);
		$("#messageList").scrollTo($("#messageList").attr('scrollHeight'));
	};

	this.sendMsg = function() {
		if (!$("#userPanel .current").exists() || $.trim($("#messageEditor textarea").val()).length<1) {
			return;
		}
		var receiverId = $("#userPanel .current").attr("id");
		$.post(ctx + '/chat/send.u', {
			"planId" : this.chatConversation.planId,
			"message" : $("#messageEditor textarea").val(),
			"receiverId" : receiverId,
			"senderId" : this.chatConversation.userId,
			"senderName" : this.chatConversation.userName,
			"i" : Math.random()
		});
		this.appendMsg(receiverId, "Me", $("#messageEditor textarea").val(), false);
		$("#messageEditor textarea").val('');
	};
	
	this.handleEndingMsg = function(msg){
		if(!chatConversation.isInstructor()){
			if(msg.senderName=="-99" && msg.message=="-99" && msg.senderId=="-99"){
				//timer.end();
				var receiverId = $("#userPanel .current").attr("id");
				this.appendMsg(receiverId, "System", "Chat session ended", true);
				disableSendMsg();
				$("#sendBtn").addClass("hidden");
				$("#closeBtn").removeClass("hidden");
				timer.stop();
				return true;
			}
		}
		return false;
	}
}

/**
 * OnlineUserHandler Class definition.
 */
function OnlineUserHandler(chatConversation) {
	this.chatConversation = chatConversation;
	this.refreshTabs = function(onlineUsers) {
		if (chatConversation.isInstructor()){ 
			var tabs = $("#mainPanel #userPanel .tab");
			tabs.each(function (){
				var user;
				var isOffline = true;				
				for(var key in onlineUsers){
					user = onlineUsers[key];
					if(user.username == $(this).attr('id')){
						isOffline = false;
					}
				}
				if(isOffline) {
					if(!$(this).is('.offline')){
						chatConversation.msgHandler.appendMsg($(this).attr('id'), "System", $(this).attr('id')+" has left or disconnected from this chat session.", true);
						$(this).addClass('offline');
					}					
					if($(this).is('.current')){
						disableSendMsg();
					}										
				}else if($(this).is('.offline')){
					$(this).removeClass('offline');					
				}
				if($(this).is('.current') && !$(this).is('.offline')){
					enableSendMsg();
				}
			});
		}
	};
}

/**
 * Utility function list
 */

function diffWithEndTime(endTime,offset) {
	//var _endTime = new Date(Date.parse(endTime.replace(/-/g,"/")));
	var _endTime = new Date(endTime.split(" ")[0].split("-")[0],
							endTime.split(" ")[0].split("-")[1] - 1,
							endTime.split(" ")[0].split("-")[2],
							endTime.split(" ")[1].split(":")[0],
							endTime.split(" ")[1].split(":")[1],
							endTime.split(" ")[1].split(":")[2],
							0);
	var currDate = new Date();	 
	var localTime = currDate.getTime();
	var localOffset = _endTime.getTimezoneOffset()*60*1000;
	return Math.round((localTime -(_endTime.getTime() + localOffset + offset*60*60*1000))/1000/60);	
}

function getCurrentHourMinute() {
	var cur = new Date();
	var hour = cur.getHours();
	var temp = "AM";
	if (hour > 12) {
		hour -= 12;
		temp = "PM";
	}
	return ((hour < 10 ? "0" : "") + hour) + ":" + ((cur.getMinutes() < 10 ? "0" : "") + cur.getMinutes()) +" "+ temp;
}

function hideConversation() {
	$('#chatOverlay').addClass('hidden');
	$('#minimizeChatOverlay').removeClass('hidden');
}

function showConversation() {
	$('#chatOverlay').removeClass('hidden');
	$('#minimizeChatOverlay').addClass('hidden').removeClass("blink");
	$('#operationMenu').addClass('hidden');
}

function disableSendMsg(){
	disableButton($("#sendBtn"));
}

function enableSendMsg(){
	enableButton($("#sendBtn"));
}

$("#userPanel .tab").live("click", function() {
	if (!$(this).is(".current")) {
		$("#userPanel .current").removeClass("current");
		$(this).addClass("current");
		$(this).removeClass("newMessage");
		$("#messageList .userMessages").not(".hidden").addClass("hidden");
		$("#messageList #msg" + $(this).attr("id")).removeClass("hidden");
		$("#messageList").scrollTo($("#messageList").attr('scrollHeight'));
	}
	
	if ($(this).is(".offline")) {
		disableSendMsg();
	}else{
		enableSendMsg();
	}
});

$("#userPanel .tab .closeIcon").live("click", function() {
	var tab = $(this).parent();
	if(!chatConversation.isInstructor() || !tab.is(".current")) return;
	confirmMsg(
			'Are you sure you want to end the chat session with '+tab.attr("id")+'?',
			function(){
				var nextTab;
				if(tab.next().exists()){
					nextTab = tab.next();
				}else if(tab.prev().exists()){
					nextTab = tab.prev();
				}
				if(typeof(nextTab)!='undefined' && tab.is('.first')){
					nextTab.addClass('first');
				}
				if(typeof(nextTab)!='undefined') {
					nextTab.trigger('click');
				}else{
					disableSendMsg();
				}
				$("#messageList #msg" + tab.attr("id")).remove();
				tab.remove();
				return false;
			});	
});

function initConversation(lessonId){
	$.getJSON(ctx + '/plan/load.u', {"lessonId" : lessonId,"i" : Math.random()}, function (data){
		if(typeof(data)!='undefined' && data != null && data!='null' && (typeof(chatConversation)=='undefined' || chatConversation.status!='P')){
			timer.status = 1;
			if(typeof(chatConversation)=='undefined' || chatConversation.status=='D'){
				$("#mainPanel #userPanel").html('');
				$("#messageList").html('');
				$("#messageEditor textarea").val('');
				$('#closeBtn').addClass('hidden');
				$('#sendBtn').removeClass('hidden');
				$("#chatOverlay").addClass('hidden');
				$("#chatOverlay").css("top","10%").css("left","277px");
				$("#minimizeChatOverlay").addClass('hidden');
				$('#operationMenu').addClass('hidden');
				chatConversation = new Conversation(data.creatorId,data.lessonId,data.id,data.startTime,data.endTime,data.status,data.timeZone.toString().substr(0,3));
				if(!chatConversation.isInstructor()) enableSendMsg();
			} else {
				chatConversation.beginTime = data.startTime;
				chatConversation.endTime = data.endTime;
				chatConversation.timezone = data.timeZone.toString().substr(0,3);
				chatConversation.status = data.status;
				if(chatConversation.status == 'P') {
					timer.start(chatConversation);
				}
			}
			if(data.status=='S') {
				delayPopChat(data.startTime,data.timeZone.toString().substr(0,3));
			}
			
		}

	});
}

function padNum(number) {
    return (number < 10 ? '0' : '') + number;
}
