/**
 * Remote Control plugin
 *
 * Copyright (c) 2008 Lance Caraccioli
 *
 */

/**
 * @name $.remoteControl
 * @author Lance Caraccioli
 * @depends jQuery
 * @depends jquery.cookie [http://stilbuero.de/jquery/cookie/]
 * @depends jquery.json [http://code.google.com/p/jquery-json/]
 * @depends jquery.timer [http://plugins.jquery.com/project/Timer]
 */
if (jQuery.cookie == 'undefined') alert ('The Remote Control jQuery plugin depends on jQuery.Cookie... last found at this url http://stilbuero.de/jquery/cookie/');
if (jQuery.json == 'undefined') alert ('The Remote Control jQuery plugin depends on jQuery.json... last found at this url http://code.google.com/p/jquery-json/');
if (jQuery.timer == 'undefined') alert ('The Remote Control jQuery plugin depends on jQuery.timer... last found at this url http://plugins.jquery.com/project/Timer');

jQuery.remoteObject = {
	config: function(params){
		//output (sending) channel
		if (params.outputChannel !='undefined'){
			this.config.outputChannel=params.outputChannel;
		}
		//input (recieving) channel
		if (params.inputChannel !='undefined'){
			this.config.inputChannel=params.inputChannel;
		}
		//polling interval
		if (params.inputChannel !='undefined'){
			this.config.pollInterval=params.pollInterval;
		}
		if (typeof params.onUpdate =='function'){
			this.onUpdate=params.onUpdate;
		}
	},
	//START
	start:function(config_params){
		if (config_params == 'undefined'){
			config_params.outputChannel='output';
			config_params.inputChannel='input';
			config_params.pollInterval=200;//200 milliseconds
		}
		this.config(config_params);
		jQuery.timer(jQuery.remoteObject.pollInterval, function(timer){
			jQuery.remoteObject.recieve();
		});
	},
	//Notify User
	onUpdate:function(obj){
		//this funtion is given a handler by the user
		//alert("pass in a handler to handle the update event... i.e. config_params.update=function(){//do something... JSON:"+jQuery.toJSON(obj));
		//$('body').html($('body').html()+"JSON:"+jQuery.toJSON(obj)+"<br />");
	},
	//SEND 
	send:function(params){
		this.beforeSend(params);
		this.onSend(params);
		this.afterSend(params);		
	},
	onSend: function(params){
		sendThisString=jQuery.toJSON(params);
		jQuery.cookie(this.config.outputChannel,sendThisString, {path:'/'});
	},
	beforeSend: function(params){
	},
	afterSend: function(params){
	},
	//RECIEVE 
	recieve: function(params){
		this.beforeRecieve(params);
		obj=this.onRecieve(params);
		this.afterRecieve(params);
		this.onUpdate(obj);
	},
	onRecieve: function(params){
		jsonString=jQuery.cookie(this.config.inputChannel);
		returnObj=jQuery.evalJSON(jsonString);
		return (returnObj);
	},
	beforeRecieve: function(params){
	},
	afterRecieve: function(params){
		jQuery.cookie(this.config.inputChannel, '', {path:'/',expires:-1});
	}
};