var authorizationAlert = "You need to login to the site first \nto be able to participate in chat";
var chatLastMessageID = 0;
var chatLastInviteID = 0;
var chatAuthorized = false;
var chatReady = false;
var cp;
var chatLoadTimer = 1;
var chatBlinkMessage = "";
var chatBlinkTimer = 0;
var chatBlinkOriginalTitle;

chatInit();

function chatInit(){
	if( typeof( cpaint_loaded ) == 'undefined' ) {
		setTimeout('chatInit()', 1000 );
		return;
	}
	cp = new cpaint();
	cp.set_debug( -1 );
	cp.set_response_type( 'JSON' );
	if( cp.capable )
		chatAcknowledge();
	chatReady = true;
}

function chatNoResults( result ){
	
}

function chatActive(){
	var chatDiv = document.getElementById('chatDiv');
	return ( chatDiv && ( chatDiv.style.display != 'none' ) );
}

function chatAcknowledge(){
	if( !chatActive() )
		cp.call('/lib/chat/connector.php', 'Acknowledge', chatAcknowledgeResults, chatLastInviteID );
	else
		setTimeout('chatAcknowledge()', 5000);
}

function chatAcknowledgeResults( result ){
	if( ( !chatActive() ) && ( result.data != "" ) ) {
		var s = new String( result.data );
		//alert( s );
		arr = s.split( '|' );
		command = new String( arr[0] );
		if( command == 'wantChat' ){
			chatLastInviteID = arr[1];
			sender = arr[2];
			subject = arr[3];
			document.getElementById('chatWantSender').innerHTML = sender;
			if( subject != "" ){
				document.getElementById('chatWantSubject').innerHTML = subject;
				document.getElementById('chatWantSubjectDiv').style.display = 'block';
			}
			else
				document.getElementById('chatWantSubjectDiv').style.display = 'none';
			chatStartBlinking(sender + " wants to chat with you");
			chatDoScroll();
			var inviteDiv = document.getElementById('chatWantDiv');
			inviteDiv.style.display = "block";
			window.onscroll = chatDoScroll;
			window.onresize = chatDoScroll;
			chatAuthorized = true;
		}
		if( command == 'ok' ){
			chatAuthorized = true;
		}
	}
	setTimeout('chatAcknowledge()', 5000);
}

function chatDoScroll(){
	var inviteDiv = document.getElementById('chatWantDiv');
	var height;
	if (window.innerHeight) //if browser supports window.innerWidth
		height = window.innerHeight;
	else if (document.all) //else if browser supports document.all (IE 4+)
		height = document.body.clientHeight;
	var width;
	if (window.innerWidth) //if browser supports window.innerWidth
		width = window.innerWidth;
	else if (document.all) //else if browser supports document.all (IE 4+)
		width = document.body.clientWidth;
	var offset;
	if (document.all) 
		offset = document.body.scrollTop;
	else
		offset = pageYOffset;
	var s = new String( inviteDiv.style.height );
	s = s.substring( 0, 3 );
	var newY = offset + height - s - 12;
	s = new String( inviteDiv.style.width );
	s = s.substring( 0, 3 );
	var newX = width - s - 12 - 30;
	inviteDiv.style.top = newY;
	inviteDiv.style.left = newX;
}

function chatStart(){
	wantDiv = document.getElementById('chatWantDiv');
	if( wantDiv )
		wantDiv.style.display = "none";
	cp.call('/lib/chat/connector.php', 'Start', chatStartResults );
}

function chatStartResults( result ){
	var keyboard = document.getElementById('chatKeyboard');
	keyboard.disabled = false; 
	keyboard.focus();
	chatLoad();
}

function chatCancelInvite(){
	document.getElementById('chatWantDiv').style.display = "none";
	cp.call('/lib/chat/connector.php', 'CancelInvite', chatNoResults, chatLastInviteID );
}

function chatSend(){
	if( !chatAuthorized ){
		alert(authorizationAlert);
		return false;
	}
	var keyboard = document.getElementById('chatKeyboard');
	var text = trim( keyboard.value );
	if( text != "" ){
		cp.call('/lib/chat/connector.php', 'Send', chatSendResults, text );
		keyboard.value = "";
		keyboard.focus();
		//chatAdd( "<span class=chatMyText>me: " + text + "</span><br>" );
	}
}

function chatSendResults( result ){
	chatLoad();
}

function chatLoad(){
	if( chatLoadTimer != 0 ){
		clearTimeout( chatLoadTimer );
		chatLoadTimer = 0;
		cp.call('/lib/chat/connector.php', 'Load', chatLoadResults, chatLastMessageID );
	}
}

function chatAdd( messages ){
	if( !chatActive() )
		return;
	var chatFrame = document.getElementById('chatContentFrame');
	var chatDocument = chatFrame.contentWindow.document;
	var chatContentTable = chatDocument.getElementById('chatContentDiv');
	var newMessages = false;
	for(  var i = 0; i < messages.length; i++ ){
		var row = chatContentTable.insertRow(-1);
		var cell1 = row.insertCell(-1);
		if( messages[i].Sender == "" )
			messages[i].Sender = "&nbsp;";
		else
			messages[i].Sender = "<nobr>" + messages[i].Sender + "</nobr>";
		cell1.className = 'chatNameCell';
		cell1.innerHTML = messages[i].Sender;
		var cell2 = row.insertCell(-1);
		cell2.className = 'chatTextCell';
		cell2.innerHTML = messages[i].Text;
		newMessages = true;
	}
/*	if( ( messages.length > 0 )	&& ( typeof( windowBlurred ) != 'undefined' ) && ( windowBlurred == true ) ) {
		chatStartBlinking( "New message" );
	}*/
	if(newMessages)
		setTimeout('chatScroll()',100);
}

function chatScroll(){
	if( !chatActive() )
		return;
	var chatFrame = document.getElementById('chatContentFrame');
	var chatDocument = chatFrame.contentWindow.document;
	var chatContentDiv = chatDocument.getElementById('chatContentDiv');
	chatFrame.contentWindow.scrollBy( 0, 6000 );
}

function chatLoadResults( result ){
	if( !chatActive() )
		return;
	var s = new String( result );
	var arr = s.split( '|' );
	chatLastMessageID = result.data.LastMessageID;
	var refreshUsers = result.data.RefreshUsers;
	chatAdd( result.data.Messages );
	if( refreshUsers == '1' ){
		parent.frames['chatUsersFrame'].document.location.href = '/chat/usersFrame.php';
	}
	chatLoadTimer = setTimeout('chatLoad()', 2000 );
}

function chatClose(){
	document.getElementById('chatDiv').style.display = "none";
	return false;
}

function chatKeyboardKeyPress( event ){
	if( !event )
		var event = window.event;
	if( event.keyCode == 13 )
		chatSend();
}

function chatSayTo( recipient ){
	if( !chatAuthorized ){
		alert(authorizationAlert);
		return false;
	}
	var keyboard = document.getElementById('chatKeyboard');
	keyboard.value = 'message to ' + recipient + ': ';
	keyboard.focus();
}

function chatInvite( userId, subject ){
	if( !chatAuthorized ){
		alert(authorizationAlert);
		return false;
	}
	cp.call('/lib/chat/connector.php', 'Invite', chatNoResults, userId, '' );
}

function chatInviteStart( userId, subject ){
	if( chatAuthorized )
		cp.call('/lib/chat/connector.php', 'Invite', chatInviteStartResults, userId, subject );
	else
		alert( authorizationAlert );
}

function chatInviteOffline( userId, subject ){
	if( chatAuthorized )
		cp.call('/lib/chat/connector.php', 'InviteOffline', chatInviteOfflineResults, userId, subject );
	else
		alert( authorizationAlert );
}

function chatInviteOfflineResults( result ) {
	alert( result.data );
	document.location.href = '/chat/chat.php';
}

function chatAcceptInvite(){
	document.location.href = '/chat/chat.php';
}

function chatInviteStartResults( result ) {
	document.location.href = '/chat/chat.php';
}

function chatStartBlinking( subject ){
	chatBlinkOriginalTitle = document.title;
	chatBlinkMessage = subject;
	chatBlinkOn();
}

function chatStopBlinking(){
	if( chatBlinkTimer != 0 ){
		chatBlinkOff();
		clearTimeout( chatBlinkTimer );
		chatBlinkTimer = 0;
	}
}

function chatBlinkOn(){
	document.title = chatBlinkMessage;
	clearTimeout( chatBlinkTimer );
	chatBlinkTimer = setTimeout( 'chatBlinkOff()', 1000 );
}

function chatBlinkOff(){
	document.title = chatBlinkOriginalTitle;
	clearTimeout( chatBlinkTimer );
	chatBlinkTimer = setTimeout( 'chatBlinkOn()', 1000 );
}
