// status ticker functions for RP

// No more editinplace - bloated for what we need
Event.observe(window, 'load',status_ticker_init);

var el_ticker = null; // ticker pointer
var status_msg_arr = Array(); // hold message data
var status_msg_orig = null;
var status_pos = 0; // array index, min is 1
var status_hash = null; // hash for the updating
var show_ticker = true; //hide during edit/update states
var status_timer_update = null;
var status_timer_rotate = null;
var status_timer_START_TIME = null;     // when we loaded
var status_timer_MAX_TIME = 30*60*1000; // die after 30min
var status_rotatate_interval_ms = 7000;
var status_update_interval_ms_DEFAULT = 60000;
var status_update_interval_ms = status_update_interval_ms_DEFAULT;

// initialize_ticker
function status_ticker_init() { // bootstrap
	el_ticker = $('status_ticker');
	if(el_ticker != undefined)
	{
		Event.observe('edit_status_ticker','keydown',function(e) {
			   	// Validate form on enter press
				if(Event.KEY_RETURN==e.keyCode) {	save_status_ticker();	}
		});
        var now = new Date();
        status_ticker_START_TIME = now.getTime(); // in ms since epoch
		rotate_status_ticker(); // start automatic updating events
		update_status_ticker();
	}
}

// die now? - bool - whether timeout reached
function status_ticker_check_timeout()  {
    var now = new Date();
    var uptime = now.getTime()-status_ticker_START_TIME; // in ms
    return (uptime>status_timer_MAX_TIME);
}

function rotate_status_ticker()
{
	//format and display the messages recieved from the server
	// cycle through messages
	if(status_msg_arr.length>1 && show_ticker)
	{
		if(status_pos+1
		<status_msg_arr.length) {
			status_pos++;
			show_status_message(status_pos);
		}
		else {
			status_pos=0;
			show_status_message(status_pos);
		}
	}
	// refresh view every Xs
    if(status_timer_rotate)     {clearTimeout(status_timer_rotate);}
	status_timer_rotate = setTimeout('rotate_status_ticker()',status_rotatate_interval_ms);
}



function show_status_message_next()
{
	clearTimeout(status_timer_rotate); // stop timers
	if(status_pos+1<status_msg_arr.length) {
		status_pos++;
		show_status_message(status_pos);
	}
	else {
		status_pos=0;
		show_status_message(status_pos);
	}
	status_timer_rotate = setTimeout('rotate_status_ticker()',status_rotatate_interval_ms); //restart
}

function show_status_message_prev()
{
	clearTimeout(status_timer_rotate); // stop timers
	if(status_pos-1>-1) {
		status_pos--;
		show_status_message(status_pos);
	}
	else {
		status_pos=status_msg_arr.length-1;
		show_status_message(status_pos);
	}
	status_timer_rotate = setTimeout('rotate_status_ticker()',status_rotatate_interval_ms); //restart
}

function show_status_message(n)
{
	// place message on screen
	$(el_ticker).hide();
	$(el_ticker).innerHTML = status_msg_arr[n];
	$(el_ticker).appear();
}

function update_status_ticker()
{
    clearTimeout(status_timer_update); // unset old timer
        
    if(status_ticker_check_timeout()) {return false;} // if timeout, die
    
	// check server for updated statuses
	new Ajax.Request('ajax/status_ticker.php', {
		method: 'post',
		parameters: {hash: status_hash, verb : 'update_hash'},
		onFailure: function() {
			// Failure in server communications
			// TO DO : just keep rotating, try again later
			//alert("Sorry, cannot contact server. Try again.");		
		},
		onSuccess: function(transport) {
			// Convert JSON to variable object
			var response = transport.responseText.evalJSON(true); // w/ injection prevention
			if(response.status=='ok') {
				if(response.data.hash!=status_hash && response.data.hash!=null)
				{
					status_hash = response.data.hash; // update hash
					status_msg_arr = response.data.msg_arr; // update messages
                    status_update_interval_ms = status_update_interval_ms_DEFAULT; // min wait time
				} 
				else    {
				    status_update_interval_ms *= 2; // increase wait time;
				}
			}
			else {
				// TO DO : again, fail graceful, do nothing
			}
		}});
	
	// refresh every 30s
	status_timer_update = setTimeout('update_status_ticker()',status_update_interval_ms);
}

function cancel_status_ticker()
{
	// cancel edit, renew rotate
	$('edit_status_ticker_container').hide();
	$('status_ticker').appear();

	// restart updates
	rotate_status_ticker();
	update_status_ticker();
}

function edit_status_ticker()
{
	// allow editing of status message (if it is owner's) on clicking
	if(status_msg_orig!=null) {$('edit_status_ticker').value=status_msg_orig;}
	else {status_msg_orig=$('edit_status_ticker').value;}

	// hide/show status options
	$('status_ticker').hide();
	$('edit_status_ticker_container').appear();	

	// stop updates
	clearTimeout(status_timer_update);
	clearTimeout(status_timer_rotate);
}

function save_status_ticker()
{
	// Save the new status message
	msg = $('edit_status_ticker').value;
	
	if(msg.length>255 || msg==null || msg=='' || msg==status_msg_orig) {cancel_status_ticker(); return;} // nothing new
	
	// send message to server, save
	new Ajax.Request('ajax/status_ticker.php', {
		method: 'post',
		parameters: {user_status: msg, verb : 'save'},
		onFailure: function() {
			// Failure in server communications
			// TO DO : just keep rotating, try again later
			cancel_status_ticker();
			//alert("Sorry, cannot contact server. Try again.");		
		},
		onSuccess: function(transport) {
			// Convert JSON to variable object
			var response = transport.responseText.evalJSON(true); // w/ injection prevention
			if(response.status=='ok') {
				if(response.data.hash)
				{
					status_hash = response.data.hash; // update hash
					status_msg_arr = response.data.msg_arr; // update messages
				} 
				// otherwise do nothing
				status_msg_orig=$('edit_status_ticker').value; // store new msg
				cancel_status_ticker(); // reset the view
			}
			else {
				// TO DO : again, fail graceful, do nothing
				cancel_status_ticker();  // reset the view
				//alert("Sorry, cannot contact server. Try again.");	
			}
		}});	
	// update the hash and message strings
}