// text messaging system - (c) 2007 by www.koolcommunity.com
// programmed by www.orangeviewgames.com
// for internal use only please do not distribute

var txtmsgversion = "v1.12"; // url errors

var txtmsg_url = 'txtmsg.php?x=1&'; // always delete when done.
var TXTMSG_CACHE_URL = 'cache.php?f='; //'cache/';
var check_for_txtmsgs_poll_interval = 1000 * 15; // every 15 +0..3 seconds
var check_for_txtmsgs_poll_interval_extra_ms = 6000; // +/-
var txt_msg_clone_this = 'atxtmsg'; // what div to clone
var bottom_of_first_txtmsg = 78; // pixels from bottom
var cascade_each_txtmsg = 0; //0=overlapped. 32; // pixels higher each time?
var debugtxts = false;  // if true, create some fake data, no ajax

// url vars used:
// msgto,msgfrom,msgfromlook,msgbody,debug

// example check:
// http://www.koolcommunity/v4/txtmsg.php?debug=1&msgto=you

// example check and delete:
// http://www.koolcommunity/v4/txtmsg.php?debug=1&msgto=me&x=1

// example send:
// http://www.koolcommunity/v4/txtmsg.php?debug=1&msgfrom=me&msgfromlook=red&msgto=you&msgbody=Hello+world!

// txtmsg packet format:
// tm('msgfrom|msgfromlook|msgbody');

/*
'messages'
msgid,				integer
msgto,				string name
msgfrom,			string name
msgbody,			text with only html
msgsubj,			unused string
msgmode,			unused integer: sent, received, replied, etc.
msgsent,			timestamp integer
msgrecd,			timestamp integer
msgtoid,			duped lookup
msgtolook,			duped string
msgfromsgid,			duped lookup
msgfromlook			duped string
*/

var txts = Array();	// of txt_objects
var txtcount = 0;	// simple counter
function txt_object()	// data class constructor
{
	this.msgid = 0;
	this.msgto = '';
	this.msgfrom = '';
	this.msgbody = '';
	this.msgsubj = '';
	this.msgmode = 0;
	this.msgsent = 0;
	this.msgrecd = 0;
	this.msgtoid = 0;
	this.msgtolook = '';
	this.msgfromid = 0;
	this.msgfromlook = '';
	// pointer to a div
	this.htmlelement = null;
}

function txt_x_b_click(thisele) // poo
{
	var whichone = txtcount-1;
	//alert('txt_x_b_click: deleting text message: '+whichone);
	// fixme: assumes the only visible X button is the "LAST" seen one
	// they must overlap properly...
	if (txts[whichone])
	{
		if (window.game_sfxclick) game_sfxclick();
		// lowlevel:
		if (!document.body)
		{
			alert('ERROR: missing document.body in txt_x_b_click');
			txts[whichone].htmlelement.style.display='none';
		}
  		else
  		{
  			document.body.removeChild(txts[whichone].htmlelement);
  		}

  		//txts[whichone]=null;
		txts.splice(whichone,1); // delete from array
		txtcount--;
	}
}

function txt_x_b_over(thisele)
{
	if (window.game_sfxhover) game_sfxhover();
	//thisele.style.top = '-64px'; // v			// poo fixme: not this!
}
function txt_x_b_out(thisele)
{
	//if (window.game_sfxhover) game_sfxhover();
	//thisele.style.top = '0px';
}

var txt_look_up_look = Array(); // remember looks for af() function
function decode_txt(thedata)
{ // msgfrom|msgfromlook|msgbody
	if (!thedata) return;
	theparts = thedata.split('|');
	if (theparts.length > 2) // sanity
	{
		mytxt = new txt_object();
		// fixme: abstracti-ize the hardcodedness
		// extract available data since null is allowed
		if (theparts[0]) mytxt.msgfrom = ''+theparts[0];
		if (theparts[1]) mytxt.msgfromlook = ''+theparts[1];
		if (theparts[2]) mytxt.msgbody = ''+theparts[2];

		// remember the look for af() function
		txt_look_up_look[mytxt.msgfrom] = mytxt.msgfromlook;

		if (!document.body) alert('ERROR: no document.body');

		// spawn an html element and render the message once only
		cloneme = document.getElementById(txt_msg_clone_this);
		if (cloneme)
		{
			mytxt.htmlelement = cloneme.cloneNode(true);

			mydivs = mytxt.htmlelement.getElementsByTagName("div");
			if (mydivs[1]) // #0 is the face
			{
				mydivs[1].innerHTML = "From:&nbsp;<a title='Click here to view in the friendlist' id='txtfrom' href='javascript://' onclick='if (window.af) af(this.innerHTML)' onmouseover='if (window.fover) fover()'>"+mytxt.msgfrom+"</a>"+"<br>"+mytxt.msgbody;
			}
			else
			{
				alert('ERROR: unable to find a txtmsg div child');
			}
			myimgs = mytxt.htmlelement.getElementsByTagName("img");
			if (myimgs[1]) // #0 is the background #1 is the X button IF its an img...
			{
				myfacenum = body_to_state(mytxt.msgfromlook);
				myimgs[1].style.left = -1 * (myfacenum * AVATARW) + 'px';
			}
			else
			{
				alert('ERROR: unable to find a txtmsg img child');
			}

			// now put it on screen
			document.body.appendChild(mytxt.htmlelement);
			// and make it visible
			// fixme: if >1 they overlap.. cascade? but reset if read and deleted!
			// fixme otherwise it will go past top of screen soon
			mytxt.htmlelement.style.bottom=(bottom_of_first_txtmsg+(txtcount*cascade_each_txtmsg)) + 'px';
			//mytxt.htmlelement.style.right='0px';
			mytxt.htmlelement.style.display = 'block';
		}
		else
		{
			alert('ERROR: unable to clone ' + txt_msg_clone_this);
		}


		// now remember it for later
		txts[txtcount] = mytxt;
		// fixme: scan for empty array index - what about del then add
		txtcount++;
	}
}

// server ajax msg
function tm(txt)
{
	if (window.game_sfxlogin) game_sfxlogin();

	// fixme: add the party invitation magic detect and <a> for visitme()
	
	// special case: handle item gifts poo
	if (window.gift_msg_delim)
	{
		txta = txt.split(gift_msg_delim);
		if (txta.length==3)
		{
			theitem = txta[1];
			txt = '<br>'+txta[0]+'<b>'+txta[1]+'</b>'+txta[2];
			if (window.inventory)
			{
				// show the inventory gui if it is hidden
				inventory_gui_grow();
				inventory.pickup(theitem);
			}
			//alert('DEBUG: I just detected an item gift: '+theitem);
		}
	}

	if (window.visit_msg_delim)
	{
		addlog('You got an invitation!');
		txta = txt.split(visit_msg_delim);
		if (txta.length>1)
		{
			txt = '<br>'+txta[0]+'<br>'+"<a class='txtmsga' href='javascript://' onclick=\"visitfriendnow('"+txta[1]+"');\">CLICK TO VISIT NOW</a>";
		}
	}

	//alert('DEBUG: tm('+txt+')');
	decode_txt(txt);
	//render_txtmsg_html();
}

function check_for_txtmsgs() // again
{
	// uses global_user_name
	//alert('DEBUG: check_for_txtmsgs:\n'+txtmsg_url+'msgto='+global_user_name);
	if (window.ajax) txtmsg_ajax = new ajax('msgto='+global_user_name,txtmsg_url);
	// fixme: I don't like polling...
	// this could be incorporated into chat poll php
	// runs every 15-16 seconds
	// fake txt msg
	if (debugtxts) tm('Joe45|red|Hi there how are you?  The current timestamp is ' + game_timestamp() + ' which is awesome.');
	setTimeout(check_for_txtmsgs,check_for_txtmsgs_poll_interval+parseInt(Math.random()*check_for_txtmsgs_poll_interval_extra_ms));
}

function begin_checking_for_txtmsgs()
{
	//alert('DEBUG: begin_checking_for_txtmsgs');
	check_for_txtmsgs();
}

function send_txt(mfrom,mfromlook,mto,mbody,donotcounttxtstats)
{
	//alert('DEBUG: send_txt('+mfrom+','+mfromlook+','+mto+','+mbody+')');
	if ((!mfrom) ||
		(!mfromlook) ||
		(!mto) ||
		(!mbody))
	{
		alert('ERROR: bad params in send_txt');
		return;
	}

	if (window.ajax)
	{
		ajaxcmdline = 'msgto='+mto+'&msgfrom='+mfrom+'&msgfromlook='+mfromlook+'&msgbody='+mbody;
		//alert('DEBUG:send_txt is submitting this:\n'+txtmsg_url+ajaxcmdline);
		txtmsg_send_ajax = new ajax(ajaxcmdline,txtmsg_url);
	}

	if (!donotcounttxtstats)
	{
		// add to the friend stats: numtexts++
		if (window.everybody_find_by_name)
		{
			loopf = friend_name_to_index(mto);
			if (loopf!=-1)
			{
				// update stats locally
				friends[loopf].numtexts = parseInt(friends[loopf].numtexts)+1;
				// store number of visits in db
				cmdline = 'n='+chat_user_name+'&y='+mto+'&nt='+friends[loopf].numtexts;//+'&nv='+friends[loopf].numvisits;
				//alert('DEBUG: submitting text counter friend:\n'+cmdline);
				// fixme: this is not efficient for server: the txtmsg can add this counter!
				if (window.ajax) addajax = new ajax(cmdline,friendlist_url);
				render_friendlist_html(); // regen the html
			}
		}
	}
}
