<a href="#" name="modal">
<img id="chatgif2" src="{% nav public %}img/chatboxh.gif" style="display:scroll; position:absolute; right:100px;">
<img id="flashmsg2" title="" src="{% nav public %}img/newmsg.png" style="display:none;position:absolute;bottom:425px;right:70px;width:32px;height:32px;">

</a>
<br/>
<br/>
<br/>
<div id="titlechat">
	<span id="titlebuddy" class="sel"><b>Online Users (<span id="jmlonline"></span>)</b></span>
	<span id="titlemsg" class="sel" style="display:none"><b>Chat Window  <span id="closecontainer">x</span></b></span>
</div>
<br/>
<div id="viewchat" with="{{data.chat_with}}"></div>
<div id="viewbuddies"></div>

<script type="text/javascript">
    $(document).ready(function() {
		if ({{ data.chat_win }} == 1) {
			$('.window').slideToggle("fast");
		}
		if ({{ data.chat_with }} == 0) {
			$('#viewchat').hide();
		} else {
			showviewchat({{data.chat_with}});
		}
		$('#viewbuddies').load('{% nav view_buddies %}');

		$(window).unload(function() {
			saveState("");
		});
		
		$('#chatgif2').click(function (e) {
			e.preventDefault();
			bukaTutupChat();
		});
		$('#closecontainer').click(function() {
			hideviewchat();
		});
    });
	var refreshChat
	var refreshList

	function cekBuddies() {		/* check for new on/off buddies */
		$.ajax({
			type: "GET",
			url: "{% nav cek_buddies %}?id={{session.user.id}}" ,
			dataType: "json",
			async: true,
			cache: false,
			timeout:50000,
			success: function(data){
				if (data == "refresh") {
					refreshBuddies(data);
				}
			}
		});
	}

	function cekMessage() {		/* check for new message */
		$.ajax({
			type: "GET",
			url: "{% nav cek_message %}?id={{session.user.id}}&chatwith=" + $('#viewchat').attr('with'),
			dataType: "json",
			async: true,
			cache: false,
			timeout:50000,
			success: function(data){
				if (data['message'] != "") {
					startFlashMsg();
					refreshMessage(data['message']);
				} else {
					stopFlashMsg();
				}
				if (data['conversation'] != "") {
					refreshConversation(data['conversation']);
				}
			}
		});
	}

	function startrefresh()
	{
		stoprefresh();
		refreshChat = setInterval(function()
		{
			cekMessage();
		}, 2000);
		refreshList = setInterval(function()
		{
			cekBuddies();
		}, 5000);
	}
	
	function stoprefresh()
	{
		clearInterval(refreshChat);
		clearInterval(refreshList);
	}
	
	function refreshBuddies(data) { 	/* refresh buddies */
		saveState(data);
	}
	
	function refreshMessage(data) { 	/* refresh message */
		var i = 0;
		for (i = 0; i < data.length; i++) {
			if ($('.msg-' + data[i]['username']).is(':hidden')) {
				s = 1;
			}
			$('.msg-' + data[i]['username']).show();
			$('.num-' + data[i]['username']).text(data[i]['jml']);
		}
	}
	
	function refreshConversation(data) { 	/* refresh message */
		var i = 0;
		var nama = "";
		var scroll = 0;;

		if ($("#chatcontent").scrollTop() > $("#chatcontent").prop("scrollHeight") - $("#chatcontent").height() - 20) {
			scroll = 1;
		}
		for (i = 0; i < data.length; i++) {
			if (data[i]['username'] == {{session.user.id}}) {
				nama = "me";
			} else {
				nama = $('#buddyprofile').attr('nama');
			}
			$('#chatcontent').append('<div class="msg"><b><span class="sender">' + nama + '</span></b><span class="waktu">&nbsp;' + data[i]["waktu"] + '</span><br /><div class="txt">' + data[i]["message"] + '</div></div>');
		}
		if (scroll == 1) {
			$("#chatcontent").animate({ scrollTop: $("#chatcontent").prop("scrollHeight") - $("#chatcontent").height() }, 1000);
		}
	}
	
	function saveState(d) {		/* save chat state */
		var s = chatState();
		var c = $('#viewchat').attr('with');

		if (d == "refresh") {
			$('#viewbuddies').empty();
			$('#viewbuddies').load(		/* POST & GET */
				'{% nav save_state %}',
				{ state: s, chatwith: c, data: d, user: {{session.user.id}} },
				function() {
					if ($("#friend-" + $('#viewchat').attr('with')).attr('class') == "username online") {
						$('#profilestatus').attr('class','on');
						$('#profilestatus').text('online');
					} else {
						$('#profilestatus').attr('class','off');
						$('#profilestatus').text('offline');
					}
				}
			);
		} else {
			$.post(		//POST
				'{% nav save_state %}',
				{ state: s, chatwith: c, data: d, user: {{session.user.id}} }
			);
		}
	}
	
	function chatState() {		/* create state */
		var data = "";
		var ctr = 0;
		$('.list').each(function() {
			if (ctr != 0) {
				data = data + ";"
			}
			if ($(this).attr('roll') == 'open') {
				data = data + '1';
			} else {
				data = data + '0';
			}
			ctr++;
		});
		if ($('#checkoff').is(':checked')) {	/* show offline state */
			data = data + ';1';
		} else {
			data = data + ';0';
		}
		if ($('#chat').is(':hidden')) {			/* chat window state */
			data = data + ';0';
		} else {
			data = data + ';1';
		}
		return data;
	}
	function showviewchat(recipient) {			/* show viewchat */
		stoprefresh();
		$('#viewbuddies').hide();
		$('.msg-' + recipient).hide();
		$('.num-' + recipient).text('');
		$('#viewchat').attr('with',recipient)
		$('#viewchat').empty();
		$('#viewchat').show();
		$('#viewchat').html('<img src="{% nav public %}img/ajax-loader2.gif" width="24" height="24" style="position:absolute;left:110px;top:170px;" />');
		$('#titlebuddy').attr('class','unsel');
		$('#titlemsg').show();
		$('#viewchat').load(
			'{% nav view_chat %}',
			{chatwith: recipient},
			function(){
				startrefresh();
			}
		);
	}
	function hideviewchat() {			/* hide viewchat */
		//stoprefresh();
		$('#viewchat').hide();
		$('#viewchat').attr('with','0')
		$('#titlemsg').hide();
		$('#titlebuddy').attr('class','sel');
		$('#viewbuddies').show();
		$('#viewchat').empty();
	}
	function showoff() {
		if ($('#checkoff').is(':checked')) {
			$('.offline').show();
			$('#checkoff').attr('checked','true');
		} else {
			$('.offline').hide();
			$('#checkoff').removeAttr('checked');
		}
	}
	function expand(theDiv) {
		var theList = ".list-" + theDiv;
		var theImg = ".img-" + theDiv;
		if ($(theList).is(":visible")) {
			$(theImg).css({"transform": "rotate(-90deg)"});
			$(theList).attr('roll','close');
		} else {
			$(theImg).css({"transform": "rotate(0deg)"});
			$(theList).attr('roll','open');
		}
		$(theList).slideToggle();
	}
	var animateMsg
	function startFlashMsg() {
		if ($('#flashmsg').attr('title') == "") {
			var d = new Audio("{% nav index %}ding.ogg");
			d.play();
			$('#flashmsg').attr('title','new');
			animateMsg = setInterval(function()
			{
				if ($('#flashmsg').is(':hidden')) {
					$('#flashmsg').show();
					$('#flashmsg2').show();
				} else {
					$('#flashmsg').hide();
					$('#flashmsg2').hide();
				}
			}, 500);
		}
	}
	function stopFlashMsg() {
		clearInterval(animateMsg);
		$('#flashmsg').hide();
		$('#flashmsg2').hide();
		$('#flashmsg').attr('title','');
	}
</script>