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

PT.search = function( options ){
	
	//extend the defaults
	options = $j.extend({}, PT.search.options, options);
	
	//format the url
	var url = '/ajax/Search/Search.' + (options.format == 'json_html'? 'jsnhtm' : options.format=='json'? 'jsn' : 'htm');
	
	//now create a url
	if( options.query || options.filter ){
		var oVars = {
			q: options.query
		};
		$j.extend( oVars, options.filter );

		//Object.prototype.toString() is in prototype.extensions.js
		url += SDNA.utils.json2String(oVars,'/','/').replace(/'|"/g,'');

	}else if( options.vars &&  options.vars.constructor == String){
		url += options.vars;
	}	
	
	//check to see if results are cached
	var cache = PT.search.cache( url );
	if( options.cache == true && cache ){

		options.callback( cache );

	}else{
	
		//get the search results
		$j.ajax({
			url: url,
			success: function( data ){
				
				if( PT.search.options.cache == true){
					//cache it
					PT.search.cache( url, data );
				}
				//call the callback passing it the data
				options.callback.call( this, data );
			},
			dataType: options.format!='html'? 'json':'html'
		});
	}

}

PT.search.options = {
	cache: false,
	query: '',
	filter: null,
	pgsz: '',
	format: 'json_html', //or html
	callback: function(){}	
};

//Define a cache variable
PT.search.cache = function( name, data ){
	if(!this._cache){ 
		this._cache = {}; 
	}
	if( data ){
		this._cache[name] = data;	
	}else if( name ){
   	return this._cache[name];
   }
};

PT.search.filter = function(){
	
}

//Handles a DOM click event on search filter links
//and triggers the search action with this link as the target
PT.search.filter.click = function( e ){	              
	
	//ref filters and results
	var $results = e.data.results;
	var $filters = e.data.filters;

	//ref this link
	var $link = $j(this);
	
	//ref the filter link
	if( $link.attr('rel') ){
		
		var $filterLink = $filters.find('a.search_filter').filter( '.' + $link.attr('rel') );		
		if( $filterLink.length > 0 ){
			var $link = $filterLink;
		}
	}
	
	//get url vars outta this link
	var filterVars = SDNA.utils.get( $link.get(0).hash.replace('#','') );
	
	//setup a search object
	var searchOptions = {
		query: SDNA.utils.get('q'),
		filter: filterVars,
		callback: function( jsn ){
			
			//replace the item list with this one
			$results.empty().append( jsn.html );
			
			//bind new results
			PT.search.bind( $results, $filters );

			//trigger the filtering event
			SDNA.Event.trigger('search_filtered', { target: $link, options: searchOptions, results: $results, filters:$filters });	
			
		}
		
	};	
	
	//trigger the filtering event
	SDNA.Event.trigger('search_filtering', { target: $link, options: searchOptions, results: $results, filters:$filters });	
		
	//get the search results
	PT.search( searchOptions );

};

//this function runs when a filter has been clicked to remove all other areas
PT.search.filtering = function( e, data ){
	
	//get a ref to the target that was clicked
	var $filterLink = $j(data.target);	
	
	var $filters = $j(data.filters);
	
	//find all other filters and remove class of current
	$filters.find('a.search_filter').removeClass('selected');
	
	//indicate that it is loading
	SDNA.loading( $filterLink.addClass('selected') );
	
	//publish the filtering event
	SDNA.Event.publish('search_filtering', data);	
		
}

//this function runs after a filter is complete
PT.search.filtered = function(e, data){
	
	//get a ref to the target that was clicked
	var $filterLink = $j(data.target);	

	var $filters = $j(data.filters);
	
	//indicate that it is loading
	SDNA.loaded( $filterLink );
	
	//publish the filtered event
	SDNA.Event.publish('search_filtered', data);			
	
}

PT.search.page = {};

//Handles a DOM click event on search filter links
//and triggers the search action with this link as the target
PT.search.page.click = function( e ){
	
	//ref this link
	var $link = $j(this);
	
	if( !$link.hasClass('disabled') ){
	
		//get a ref to the target that was clicked
		var $results = $j(e.data.results);	
	
		var $filters = $j(e.data.filters);
			
		//get url vars outta this link
		var pageVars = SDNA.utils.get( this.hash.replace(/^#/,'') );
		
		//setup a search object
		var searchOptions = {
			query: SDNA.utils.get(this.hash.replace(/^#/,'')).q,
			filter: pageVars,
			callback: function( jsn ){
				
				//indicate to the user that this filter is done loading
				SDNA.loaded( $link );
	
				//replace the item list with this one
				$results.empty().append( jsn.html );
				
				//bind new results
				PT.search.bind( $results, $filters );
	
				//trigger the filtering event
				SDNA.Event.trigger('search_paged', { target: $link, options: searchOptions, results: $results, filters:$filters, response: jsn });	
				
			}
			
		};	
		
		//trigger the filtering event
		SDNA.Event.trigger('search_paging', { target: this, options: searchOptions, results: $results, filters:$filters });	
		
		//select this item
		SDNA.loading( $link );
			
		//get the search results
		PT.search( searchOptions );	
	}
}

PT.search.updateCache = function(e, response){

	//console.log(response);
	
}

//Binds any form with a class of "search" to the dom handler
PT.search.bind = function( results, filters ){
	
	var $results = $j(results);
	var $filters = $j(filters || '');
	
	//bind the filters
	$results.add($filters).find('a.search_filter')
		.unbind('click.search_filter')
		.bind('click.search_filter', 
			{results: $results, filters: $filters }, 
			PT.search.filter.click 
	);
	
	//bind pagination
	$results
		.find('a.pagination_next,a.pagination_previous')
		.unbind('click.search_page')
		.bind('click.search_page',
			{results: $results, filters: $filters },
			PT.search.page.click			
		);		
};

SDNA.Event.create('search_filtering', PT.search.filtering );
SDNA.Event.create('search');
SDNA.Event.create('search_paged');
SDNA.Event.create('search_paging');
SDNA.Event.create('search_filtered', PT.search.filtered );

SDNA.Event.subscribe('search_paging', PT.search.updateCache );