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


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

PT.rated = function( response ){
	
	PT.rate.syncDOM( response );
	
	//Now that the like has occured,
	//Publish a like event to all listeners
	SDNA.Event.publish('rate',response);	

}

PT.rate.syncDOM = function( response ){
	
	//Find all (dis)like links (or spans) on the page that are the
	//right entity (location, event, user)
	//and the right id
	$j(".rating")
		.filter('.' + response.entity + '_' + response.id)
		.replaceWith( response.html );
}

//Handles a DOM click event on links with a class of like
//and publishes the like action with this link as the target
PT.rate.click = function( e ){	              
	
	//keep this link from functioning
	if( e ){
		e.preventDefault();
	}
	//Trigger the global like action
	SDNA.Event.trigger(
		'rate',  
		{ 
			url: $j(this).attr('href'), 
			target: this 
		}
	);
	
	return false;

};

//Binds any link with a class of "like" to the dom handler
PT.rate.bind = function( $dom ){
	if( $dom ){
		$dom.find('a.rate').bind('click.rate', PT.rate.click );
	}else{	
		$j('a.rate').live('click.rate', PT.rate.click );
	}
};