/*
Hey i knew you will be here, need some help? Contact Julius at tivolaj@yahoo.com!! info@hellouganda.com

*/

//	Setting constants ... +256782477875
var
MAX_MSG_LEN = 140;

//	obj is the object, reg is the regular expression to filter out what you (don't) want to see.
function dir(obj, reg)
{
	var rez = '';
	if(! reg) reg = /^/;
	for(var mem in obj) if(reg.test(mem)) rez += mem + ' ' + obj[mem] + '\n';
	return rez;
}

if(! [].map)
{
	//	In-place map. Array#map! in Ruby.
	//	Give it a func as arg 1, and an alternative arg 2 predicate (default returns true always).
	//	It maps the effects of what accross the array. See:
	//	var a = [1, 2, 3]; function dbl(x){return x * 2;}; a.map(double); alert(a); This shows: [2, 4, 6]
	Array.prototype.map = function(what, selector)
	{
		if(! selector) selector = function(){return true;};
		for(var notI = 0; notI < this.length; ++notI) if(selector(this[notI])) this[notI] = what(this[notI]);
	}
}

function setCounter(ev)
{
	var left = 0,
		elem = document.forms['jns']['to_send'];
	ev = (ev ? ev : event);
	counter = document.getElementById('compteur');
	if(! counter) return;
	if(! counter.innerHTML) counter.innerHTML = '0';
	left = MAX_MSG_LEN - (elem.value.length);
	counter.innerHTML = left;
	if(left < 0 && ev.keyCode != 8)
	{
		if(! ev) event.returnVal = false;
		else ev.preventDefault(true);
		elem.value = elem.value.slice(0, MAX_MSG_LEN);
		showCount();
	}
}

function showCount()
{
	document.getElementById('compteur').innerHTML = MAX_MSG_LEN - (document.forms['jns']['to_send'].value.length);
}

function showChatMsg(who, what)
{
	var elem = document.getElementById('conversation');
	if(! elem.innerHTML) elem.innerHTML = '<b class="conv">Message Sent:</b><br />', (window['applyStyle'] ? applyStyle(elem, 'display:block') : elem.setAttribute('style', 'display:block'));
	elem.innerHTML += '<b class="sender_me">' + who + '</b>: ' + what + '<br />';
}

function validate_form(form)
{
	var els = form.elements,
		valid_phone = function(num)
		{
			var sev = 0;
			if(! num.indexOf('256')) num = '+' + num;	//	First normalise ...
			sev = num.indexOf('7');
			if(! sev) num = '0' + num;
			if(! num.indexOf('07')) num = '+256' + num.substr(1);
			return num.length == 13;	//	... then deal with the normal.
		},
		go_on = true,
		err_msgs = [];
	document.getElementById('err_msg').innerHTML = '';
	for(var notI = 0; notI < els.length; ++notI)
	{
		if(els[notI].type != 'text') continue;
		if(/^\+?\d+$/.test(els[notI].value) && valid_phone(els[notI].value)) alertInvalidity(els[notI], false), els[notI].title = '';	//	Unix!
		else alertInvalidity(els[notI]), els[notI].focus(), go_on = false, err_msgs[0] = els[notI].title = 'Phone number is invalid.';
	}
	if(/^\s*$/.test(form['to_send'].value)) go_on = false, err_msgs[1] = 'No message Entered?';
	return [go_on, err_msgs.join('<br />')];	//	It's (Python/Haskell) tuples that we need, but the gods think otherwise.
}

function submit_data(ev)
{
	var elem = document.forms['jns']['to_send'];
	var msg  = elem.value,
		rez  = validate_form(document.forms['jns']);
	if(! rez[0])
	{
		document.getElementById('err_msg').innerHTML = rez[1];
		return;
	}
	showChatMsg('Said', msg.replace(/\n/gi, '<br />'));
	with(elem.form)
	{
		try
		{
			unidirectionalAjax('http://www.hellouganda.com/jns/send.php?fm=' + numfrom.value + '&tm=' + numto.value + '&dt=' + to_send.value, true);
		}
		catch(e){/*	In IE, him puke ev'y now and den.*/}
	}
	elem.value = '';
	elem.form.this_num = elem.form['numfrom'].value;
}

function insert_reply(json)
{
	//	TODO:	Called by the JSON-fetcher. Inserts into the chat nankani.
}

function get_num()
{
	var num = document.forms['jns'];
	if(! num || ! num.this_num) return false;
	return num.this_num;
}

function get_reply()
{
	var num = get_num();
	if(! num) return;
	getJSONFrom('http://www.hellouganda.com/jns/validate.php?recipient=' + encodeURIComponent(num) + '&' +  generate_random_param(), 
	function(json)
	{
		var rez = eval(json);
		if(! rez.length || !rez[0].length) return;
		for(var notI = 0; notI < rez.length; ++notI) showChatMsg(rez[notI][0], rez[notI][1]);
	});
}

function log_out(ev)
{
	var num = get_num(),
		frm = null,
		cnv = document.getElementById('conversation');
	if(! num) return;
	unidirectionalAjax('http://www.hellouganda.com/jns/validate.php?number=' + num, true);
	frm = document.forms['jns'];
	if(! frm) return;
	frm.this_num = null;
	frm.numto.value = frm.numfrom.value = '';
	if(cnv) cnv.innerHTML = '';
}

//	Referred to by some code that runs on start.
function logOffer()		//	As in: put-outter.
{
	log_out();
}

//	Should purify the lib version of this here guy. He gets all links that have `jshack' as the protocol, and
//	assigns them to some action, on click.
//	The action is specified by the text after the protocol.
//	So, a link like: <a href="jshack:alert"></a> in the page would result in an alert at the opening.
function collectHacks()
{
	var ls  = document.getElementsByTagName('a'),
		lks = [];
	arrcpy(lks, ls);	//	So my prototypes, like Array.map, can work.
	lks.map(function(lk)
	{
		addEvent(lk, 'click', window[lk.href.split(':', 2)[1]]);
		lk.href = 'javascript:;';
		return lk;
	}, function(lk)
	{
		return !lk.href.indexOf('jshack');
	});
}
function run()
{
	var UPDATE_INTERVAL = 5000;
	handleDefaultText();
	showCount();
	collectHacks();
	addEvent(document.forms['jns']['to_send'], 'onkeydown', setCounter);
	addEvent(document.forms['jns']['to_send'], 'blur', setCounter);
	addEvent(document.forms['jns']['mailman'], 'click', submit_data);
	addEvent(window, 'unload', log_out);
	get_reply();
	window.setInterval('get_reply()', UPDATE_INTERVAL);
}

addEvent(window, 'load', run);
window.onunload = function(){log_out();}
