//Setup a PlanetTagger namespace
var PT = PT || {};


//Setup the like event
PT.rsvp = function( e, options ){
	
	//show the user that this target is loading
	SDNA.loading(options.target);
	
	var $action = $j(options.target);
		
	$j.getJSON( options.url , 
		function(response){
			
			SDNA.loaded( options.target );
			
			//attach the target to the response
			$j.extend(response,options);
			
			if( response.success == true ){
				
				PT.rsvpd( response );
			
			//There was an error checking in	
			}else{
				
				Window.pop( response.message, {error:true} );
			
			}
		}
	);
	
}

PT.rsvpd = function( response ){
	
	PT.rsvp.syncDOM( response );
	
	//Now that the rsvp has occured,
	//Publish a rsvp event to all listeners with the response data attached
	SDNA.Event.publish('rsvp',response);	

}

PT.rsvp.syncDOM = function( response ){
	
	//Find all rsvp links on the page that are the
	//right entity (location, event, user)
	//and the right id
	$j("a." + response.action)
		.filter('.' + response.entity + '_' + response.id)
		.each(
			function(){
				var $this = $j(this);
				
				var $action = $j(response.html);				
				var sClass = $this.attr('class').replace(/yes|no/,'');
				$action.addClass( sClass );
				$this.replaceWith( $action );
			}
		);

}

//updates the form radio to be checked on the right response
PT.rsvp.updateForm = function(e, response){
	
	$j('form.rsvp :radio[value=' + response.rsvp + ']').attr('checked','checked');
	
}

//Handles a DOM click event on links with a class of rsvp
//and triggers the rsvp action with this link|radio as the target
PT.rsvp.click = function( e ){	              
	
	var $this = $j(this);
	var opts  = {};
	
	if( $this.is(':radio') ){
		
		var $form = $this.parents('form.rsvp');		
		opts.url = $form.attr('action') + $form.sdnaSerialize();
		opts.target = $form;
			
	}else{

		//keep this link from functioning
		e.preventDefault();
		
		opts.url = $j(this).attr('href');
		opts.target = this;
	}	

	//Trigger the global like action
	SDNA.Event.trigger(
		'rsvp',  
		opts
	);

};

//Binds any link or form with a class of "rsvp" to the dom handler
PT.rsvp.bind = function(){
	
	//bind rsvp links
	$j('a.rsvp').live('click.rsvp', PT.rsvp.click );
	
	//bind rsvp radio buttons
	$j('form.rsvp :radio')
		.unbind('change.rsvp')
		.bind('change.rsvp', PT.rsvp.click );
	
};

SDNA.Event.create('rsvp', 		PT.rsvp );
SDNA.Event.subscribe('rsvp', 	PT.rsvp.updateForm );