var lastid = -1;
var receiver_id = 0;
var sender_name = '';
var autodelay = 4;
var virpath = '';
var player = null;

function initChat(path,delay) {
    autodelay = delay;
    virpath = path;
    receiver_id = $("#receiver_id").val();
	sender_name = $('#sender_name').val();
	receiveChatText();
}

function receiveChatText() {
	$.post(virpath+'chat.php?p=update&id=' + receiver_id + '&lastid=' + lastid, {},
		function(response) {
		    var results = response.split("\n");
		    if (results.length > 2) {
			    for(i=0;i < (results.length-1);i=i+3) {
	    			insertNewContent(results[i+1],results[i+2]);
			    }
			    lastid = results[results.length-4];
			    playNotification();
		    }
		    setTimeout('receiveChatText();', (autodelay*1000));
		}
	);
}

function playerReady(thePlayer)
{
	player = window.document[thePlayer.id];
}

function playNotification()
{
	if ( donotify == true && $('#mpl').html() != '' ) {
		player.sendEvent("PLAY");
	}
}

function toggleSound()
{
	if ( donotify == true ) {
		donotify = false;
		$('#togglesound').html('<img src="/templates/novanilla/media/sound_off.png" border="0" align="absmiddle" /> ' + toggleString['off']);
	}
	else {
		donotify = true;
		$('#togglesound').html('<img src="/templates/novanilla/media/sound_on.png" border="0" align="absmiddle" /> ' + toggleString['on']);
	}
}

function insertNewContent(liName,liText) {
	$("#chat_messages").append('<li><span class="name">'+liName+'</span>'+liText+'</li>');
    chatD = document.getElementById("chat_messages_box");
    chatD.scrollTop = chatD.scrollHeight;
}

function sendComment() {
	var chat_message = $('#chat_message').val();
  	$('#chat_message').val('');
	if ( chat_message != '' ) {
		$.post(virpath+'chat.php?p=send&id=' + receiver_id, {'body':chat_message},
			function(response) {
			}
		);
		insertNewContent(sender_name,parse_smilies(chat_message.replace(/</g,"&lt;").replace(/>/g,"&gt;")));
	}
}

function parse_smilies(str)
{
	$(smilies).each(function(idx,smiley){
		str = str.replace(smiley['shortcut'],'<img src="'+virpicpath+smiley['filename']+'" align="absmiddle" border="0" class="smiley" />', "gi");
	});
	return str;
}

function blockMember(question) {
    receiver_id = $("#receiver_id").val();
	sender_name = $('#sender_name').val();
    var is_confirmed = confirm(question);
    if (is_confirmed) {
		$.post(virpath+'chat.php?p=block', {'id':receiver_id},
			function(response) {
  				setTimeout('refreshChat();',1000);
			}
		);
    }
}

function refreshChat() {
	window.location.href = virpath + 'index.php?m=account_chat&id=' + receiver_id;
}

