var _search = {};

jQuery('#cnnContentColumn').ready(function(){
	
	_search = {
		input:[$('input#searchInputTop'), $('input#searchInputBot'), $('input#searchInputFooter')],
		term:jQuery.urlParam('text'),

		url:(location.href.indexOf('.turner.com') > 0) ? 'http://srchp1devws1.turner.com/si-search/query.jsp' : 'http://searchapp.sportsillustrated.cnn.com/si-search/query.jsp',
		args:{
			page:	1,
			npp:	10,
			start: 	1,
			text:	jQuery.urlParam('text'),
			type: 	'mixed',
			bucket:	true,
			sort: 'date'
		},
		filtered:false,
		filteredBy:[],
		firstLoad:true,
		scrollTop:300,
		emptyQuery:false,
		metrics:function( o ){
		
			//ADBP Tracking
			cnn_metadata.search = cnn_metadata.search || {};				
			cnn_metadata.search.term = o.criteria[0].queries[0];
			cnn_metadata.search.results = o.metaResults.mixed;
			cnn_metadata.search.type = function(){
				var type = 'all';
				jQuery.each(callObj.args.split('&'), function(i){
					var pair = callObj.args.split('&')[i].split('=');
					jQuery.each(pair, function(){
						if( pair[0] === 'content_type'){
							type = pair[1].toLowerCase();
						}
					});
				});
				return type;
			}();
			
			try {
				jsmd.trackMetrics("search-results",cnn_metadata);
			} catch(e){
				siLog.error( 'jsmd search error: ', e );
			}
			
		}
	};				
	
	_search.query = (typeof jQuery.urlParam('text') !== 'undefined') ? unescape(_search.term.replace(/\+/g,' ')) : '';
				
	//Omniture for Search
	//omnitureForSearch( _search.query );			
		
	function clearSearchFilters( from_suggested_results ){
		
			jQuery.each(_search.filteredBy, function(i){
				var theFilter = _search.filteredBy[i];
				delete _search.args[theFilter];
			});
			
			delete _search.args.startDate;
			delete _search.args.endDate;
			
			_search.filteredBy = [];
			_search.filtered = false;
			
			if( from_suggested_results ){
				window.location.href = '/search/?text=' + _search.term;
			} else {
				callObj.args = setSearchParams();					
				CSIManager.getInstance().callObject(callObj);					
			}
	}
	
	function setSearchParams(){
		_args = '';
		jQuery.each(_search.args, function(k,v){
			_args += (k==='page') ? k+'='+v+'&' : 
					 (k==='sport') ? '&section='+v+'&' : 
					(k !== 'dredate') ? '&'+k+'='+v : '';
		});
		return _args;
	}

	//results config
	var callObj = {
		url: _search.url, 
		args:'',
		domId: 'cnnSearchSummaryResults', 
		funcObj: handle_search_results
	};
	
	//topics config
	var callObj_topics = {
		url: _search.url, 
		args:'text='+jQuery.urlParam('text')+'&topics=true',
		domId: '', 
		funcObj: handle_topics_results
	};

	//set the search parameters, fetch the results
	
	if( _search.query.length > 0 ){
		$('#cnnSearchLoader').show('fast');
						
		//fetch the results
		callObj.args = setSearchParams();
		CSIManager.getInstance().callObject(callObj);

		
		//fetch the topics
		CSIManager.getInstance().callObject(callObj_topics);
					
		//Drop the search term into each input box
		jQuery.each(_search.input, function(){
			$(this).val( _search.query );
			$(this).blur(function(){
				$(this).val( $(this).val().toLowerCase() );
			});
		});
	} else {
		
		$(_search.input[0]).focus();
		
		_search.emptyQuery = true;
		_search.args.text = _search.query = ' ';
		_search.dateSort = 'Last 7 days';
		_search.filtered = true;
		_search.filteredBy.push('dredate');
		
		var dates = get_dates( 'Last 7 days' );
		if(dates.start !== ''){
			_search.args.startDate = dates.start;
		}
		
		if(dates.end !== ''){
			_search.args.endDate = dates.end;
		}

		callObj.args = setSearchParams();
		CSIManager.getInstance().callObject(callObj);
		
		$('#cnnSearchLoader').show('fast');
		
	}
	
	function handle_topics_results(o, i, c, e){				
		display_topics( o.topics );				
	}
	
	function handle_search_results(o, i, c, e){

		//check query against section spotlights in top IF, then sub sections in ELSE
		if ( (typeof section_spotlight_model[_search.query.toUpperCase()] !== 'undefined') ||
		     (typeof section_spotlight_model[_search.query.toTitleCase()] !== 'undefined')){
			if ( typeof o.spotlights !== 'undefined'){
				o.spotlights.push(
					{
						type: 'Section',
						name: _search.query.toUpperCase(),
						links: section_spotlight_model[_search.query.toUpperCase()] || section_spotlight_model[_search.query.toTitleCase()]
					}
				)
			}
		} else if ( (typeof sub_section_model[_search.query.toUpperCase()] !== 'undefined') ||
		     (typeof sub_section_model[_search.query.toTitleCase()] !== 'undefined')){
			if ( typeof o.spotlights !== 'undefined'){
				var main_section = sub_section_model[_search.query.toUpperCase()];
				o.spotlights.push(
					{
						type: 'Section',
						name: main_section,
						links: section_spotlight_model[main_section] || section_spotlight_model[main_section.toTitleCase()]
					}
				)
			}
		} 
		
		//ADBP tracking
		_search.metrics( o );
		
		$('#cnnSearchLoader').hide('fast');
		$('#cnnContentColumn').show('fast');

		jQuery('#cnnSearchSummary a').click(function(){
			var sort = $(this).text();
			var other = (sort === 'date') ? 'relevance' : 'date';
			var html = '<div><strong>Sort by: </strong>';
			html += (sort === 'date') ? '<span>date</span>' : '<a>date</a>';
			html += ' | ';
			html += (sort === 'date') ? '<a>relevance</a>' : '<span>relevance</span>';
			html += '</div>';
			
			jQuery('#cnnSearchSummary>div').html(html);
			_search.args.sort = sort;

			callObj.args = setSearchParams();

			//fetch the results
			$('#cnnSearchLoader').show('fast');
			CSIManager.getInstance().callObject(callObj);
		});
					
		_search.results = {
			count: o.metaResults.mixed,
			player:{count: o.metaResults.player},
			content:o.results[0],
			start:o.criteria[0].startAt,
			spotlights:o.spotlights,
			buckets:o.buckets,
			dym:o.didYouMean
		};
			
		if( _search.results.buckets.length >= 0 ){
		/* begin: author cleanup */
					
			try{
			
			
			var authors = _search.results.buckets[0].countByValues || [];
			_search.results.authors = {};
			jQuery.each( authors, function(i){
				var author = authors[i].fieldvalue;
				var count = authors[i].count;
				var note = '';
				if( authors[i].fieldvalue.indexOf(',') > -1 ){
					author = jQuery.trim(authors[i].fieldvalue.split(',')[0]);
					note = 'comma';
				} else if ( authors[i].fieldvalue.indexOf('EDITED') > -1 ){
					author = jQuery.trim(authors[i].fieldvalue.split('EDITED')[1]);
					note = 'edited';
				} else if ( authors[i].fieldvalue.indexOf('AS TOLD TO') > -1 ) {
					author = jQuery.trim(authors[i].fieldvalue.split('AS TOLD TO')[1]);
					note = 'told';
				}
				
				if( typeof _search.results.authors[author] === 'undefined'){
					_search.results.authors[author] = {
						'fieldvalue':author,
						'count':count,
						'note':note
					};
				} else {
					_search.results.authors[author].count += count;
					_search.results.authors[author].note += ',' + note;
				}
			});
			
			//clear the authors bucket array and re-write it
			_search.results.buckets[0].countByValues = [];
							
			jQuery.each(_search.results.authors, function(){
				_search.results.buckets[0].countByValues.push( this );
			});
		/* end: author cleanup */
		
		/* begin: source cleanup */
			var sources = _search.results.buckets[1].countByValues;
			_search.results.sources = {};
			jQuery.each( sources, function(i){
				var source = sources[i].fieldvalue;
				var count = sources[i].count;
				var note = '';
				if( source == 'SI' || source == 'RB' || source == 'ST' || 
					source == 'CNNSI.COM' || source == 'SI.COM' || source == 'SPORTSILLUSTRATED' || 
					source == 'SI/AP' || source == 'SI/RB' || source == 'AC' ||
					source == 'REUT' || source == 'SA' || source == 'LA' || 
					source == 'SOCCER AMERICA' || source == 'SPORTSILLUSTRATED'){
					note = source;
					source = 'SI';
				} else if( source == 'AP' || source == 'AP CONTRIB' || source == 'AP/RB' || source == 'AP/REUT' ){
					note = source;
					source = 'AP';
				}
				
				if( typeof _search.results.sources[source] === 'undefined'){
					_search.results.sources[source] = {
						'fieldvalue':source,
						'count':count,
						'note':note
					};
				} else {
					_search.results.sources[source].count += count;
					_search.results.sources[source].note += '|' + note;
				}
			});
			
			//clear the sources bucket array and re-write it
			_search.results.buckets[1].countByValues = [];
							
			jQuery.each(_search.results.sources, function(){
				_search.results.buckets[1].countByValues.push( this );
			});
		/* end: source cleanup */
		
		/* begin: section cleanup */
			var sections = _search.results.buckets[4].countByValues;
			_search.results.sports = {total:0};
			_search.results.sections = {total:0};
			
			jQuery.each( sections, function(i){
				var section = sections[i].fieldvalue;
				var count = sections[i].count;
				var note = '';
				var type = '';
				
				//sports
				if( section === 'BASEBALL' || section === 'MLB' ){							
					note = section;
					section = 'BASEBALL';
					type = 'sport';
				} else if( section === 'BASKETBALL' || section === 'NBA' || section === 'NCAAB.VIDEO' ){							
					note = section;
					section = 'BASKETBALL';
					type = 'sport';
				} else if( section === 'HOCKEY' || section === 'NHL' ){
					note = section;
					section = 'HOCKEY';
					type = 'sport';
				} else if( section === 'FOOTBALL' || section === 'NFL' || section === 'NCAAF_VIDEO' ){
					note = section;
					section = 'FOOTBALL';
					type = 'sport';
				} else if( section === 'TENNIS' ){
					note = section;
					section = 'TENNIS';
					type = 'sport';
				} else if( section === 'SOCCER' ){
					note = section;
					section = 'SOCCER';
					type = 'sport';
				} else if( section === 'OLYMPICS' || section === 'OLYMPICS_WINTER' ){
					note = section;
					section = 'OLYMPICS';
					type = 'sport';
				} else if( section === 'MMA' ){
					note = section;
					section = 'MMA';
					type = 'sport';
				} else if( section === 'HIGHSCHOOL' ){
					note = section;
					section = 'HIGH SCHOOL';
					type = 'sport';
				} else if( section === 'RACING' || section === 'NASCAR' ){
					note = section;
					section = 'RACING';
					type = 'sport';
				} else if( section === 'GOLF' || section === 'GOLF.COM' ){
					note = section;
					section = 'GOLF';
					type = 'sport';
				}
				
				//sections
				else if( section === 'EXTRAMUSTARD'){
					note = section;
					section = 'EXTRA MUSTARD';
					type = 'section';
				} else if( section === 'FANTASY'){
					note = section;
					section = section;
					type = 'section';
				} else if( section === 'MAGAZINE'){
					note = section;
					section = section;
					type = 'section';
				} else if( section === 'MORNING_JOLT'){
					note = section;
					section = 'MORNING JOLT';
					type = 'section';
				} else if( section === 'SCOREBOARD'){
					note = section;
					section = 'SCOREBOARD';
					type = 'section';
				} else if( section === 'SIONCAMPUS'){
					note = section;
					section = 'SIONCAMPUS';
					type = 'section';
				} else if( section === 'SPECIALS'){
					note = section;
					section = 'SPECIALS';
					type = 'section';
				} else if( section === 'STATITUDES'){
					note = section;
					section = 'STATITUDES';
					type = 'section';
				} else if( section === 'TRUTH_AND_RUMORS' || section === 'TRUTH &AMP; RUMORS'){
					note = section;
					section = 'TRUTH &AMP; RUMORS';
					type = 'section';
				} else if( section === 'WRITERS' || section === 'PETER_KING'){
					note = section;
					section = 'WRITERS';
					type = 'section';
				}
									
				//drop it into the corresponding object
				if( type === 'sport' ){
					if( typeof _search.results.sports[section] === 'undefined'){
						_search.results.sports[section] = {
							'fieldvalue':section,
							'count':count,
							'note':note
						};								
						_search.results.sports.total += count;
					} else {								
						_search.results.sports[section].count += count;
						_search.results.sports[section].note += '|' + note;
						_search.results.sports.total += count;
					}
				} else if( type === 'section' ){							
					if( typeof _search.results.sections[section] === 'undefined'){
						_search.results.sections[section] = {
							'fieldvalue':section,
							'count':count,
							'note':note
						};								
						_search.results.sections.total += count;
					} else {
						_search.results.sections[section].count += count;
						_search.results.sections[section].note += '|' + note;
						_search.results.sections.total += count;
					}
					
				}
				
			});
			
			//clear the sections bucket array and re-write it
			_search.results.buckets[4].countByValues = [];
			_search.results.buckets[4].fieldname = 'section';
			_search.results.buckets[4].total = _search.results.sections.total;

			jQuery.each(_search.results.sections, function(){
				if( typeof this.note !== 'undefined' )
					_search.results.buckets[4].countByValues.push( this );
			});
			
			//create the sport bucket array and re-write it					
			_search.results.buckets.push({countByValues:[], fieldname:'sport',total:_search.results.sports.total});
			
			jQuery.each(_search.results.sports, function(){
				if( typeof this.note !== 'undefined' )
					_search.results.buckets[5].countByValues.push( this );
			});
		/* end: section cleanup */
		
			
			} catch( e ){
				siLog.info( 'error: ', e );
			}
		}
		//if there is a prompt and there are no regular results, dym is true
		var didYouMean = (_search.results.dym.prompt != '' && _search.results.count < 1) ? true : false;
		
		_search.spotlights = _search.results.spotlights;
		
	//fetch sponsored links
	SponsoredLinks.getInstance().initialize(o.criteria[0]);
		
	if( _search.firstLoad ){				
		display_spotlights();				
		_search.firstLoad = false;				
	}
	
	
	if(didYouMean){
		var didYouMeanMsg = 'Your search for <strong>'+ unescape(_search.term.replace(/\+/g,' ')) +'</strong> did not match any documents';
		var sResults = _search.results.dym.correctedResults;
		
			jQuery('#cnnSearchRefine').hide();
			jQuery('#cnnSearchPagination').hide();
			jQuery('#cnnSearchTips').show();
			jQuery('#cnnSearchResults').removeClass('cnnSearchResults').addClass('cnnSearchSuggestSpelling');
			
			if( jQuery('div#cnnSearchSuggest').length < 1 ){
				var html = '<div id="cnnSearchSuggest">';
					html +=	'Did you mean: <a href="/search/?text='+_search.results.dym.prompt+'">'+_search.results.dym.prompt+'</a>?';
				if(sResults.length > 0){
					html +=  '<span>Top	'+sResults.length+' results shown</span>'
				}
					html += '</div>';
				if(sResults.length > 0){
					html += '<h6>Example of found results</h6>'
				}			
				$(html).insertAfter('div#cnnSearchSummary');
			}
			
		display_suggested_results();
		
		//clear all filters functionality
		jQuery('a#cnnSearchRefineClearAll').click( function(){
			clearSearchFilters( true );
		});
	} else {
		//display the content
		display_results();
		
		//display the buckets
		display_buckets();
		
		//display the pagination
		display_pagination();
		
	}
		var msg = (didYouMean) ? didYouMeanMsg : _search.results.count + ' Results';
		
		return msg;
		
	} //end: handle_search_results
	
	function translate_stat(stat){
		var keys = {
			'rushing-yards':'YDS',
			'passing-yards':'YDS',
			'receiving-yards':'YDS',
			'receptions':'REC',
			'tackles':'Tk',
			'fumbles-recovered':'FR',
			'int':'Int',
			'touchdowns':'TD',
			'rushes':'Rush',
			'winloss':'W-L',
			'saves':'Sv',
			'strikeouts':'K',
			'fgPct':'FG%',
			'battingAvg': 'AVG',
			'homeruns': 'HR',
			'stolenBases':'SB'
		};
		return (typeof keys[stat] !== 'undefined') ? keys[stat] : stat.toUpperCase();
	}
	
	function translate_bucket( bucket, plural ){
		var keys = {
			'source': 'Source',
			'content_type': 'Type',
			'dredate': 'Date',
			'author':'Columnist',
			'section':'Section',
			'sport':'Sport',
			'PAST YEAR':'Last 365 days',
			'PAST BEYOND':'Past years',
			'PAST WEEK':'Last 7 days',
			'PAST MONTH':'Last 30 days',
			//convert dates back, if needed
			'Last 365 days':'PAST YEAR',
			'Past years':'PAST BEYOND',
			'Last 7 days':'PAST WEEK',
			'Last 30 days':'PAST MONTH'
		};				
		var newname = (typeof keys[bucket] !== 'undefined') ? keys[bucket] : bucket;				
		return ( plural ) ? newname + 's' : newname;
	}
	
	function get_datestring(val){
		var datestring =	(get_dates('Last 7 days').start === val) ? 'Last 7 days' :
							(get_dates('Last 30 days').start === val) ? 'Last 30 days' :
							(get_dates('Last 365 days').start === val) ? 'Last 365 days' :
							(get_dates('Past years').end === val) ? 'Past years' : val;					
		return datestring;
	}
	
	function get_dates(val){
		var date = new Date();
		var time = date.getTime();
		
		var _ayearago = new Date(time - (3600 * 24 * 365 * 1000));
		var _amonthago = new Date(time - (3600 * 24 * 30 * 1000));
		var _aweekago = new Date(time - (3600 * 24 * 7 * 1000));
		
		var today = {
			yyyy: date.getFullYear(),
			mm: ( (date.getMonth() + 1) < 10) ? '0'+(date.getMonth() + 1) : date.getMonth()+1,
			dd: ( date.getDate() < 10) ? '0' + date.getDate() : date.getDate()					
		};
		
		var ayearago = {
			yyyy: _ayearago.getFullYear(),
			mm: ( (_ayearago.getMonth() + 1) < 10) ? '0'+ (_ayearago.getMonth() + 1) : _ayearago.getMonth()+1,
			dd: ( _ayearago.getDate() < 10) ? '0' + _ayearago.getDate() : _ayearago.getDate()
		};
		
		var aweekago = {
			yyyy: _aweekago.getFullYear(),
			mm: ( (_aweekago.getMonth() + 1) < 10) ? '0'+ (_aweekago.getMonth() + 1) : _aweekago.getMonth()+1,
			dd: ( _aweekago.getDate() < 10) ? '0' + _aweekago.getDate() : _aweekago.getDate()
		};
		
		var amonthago = {
			yyyy: _amonthago.getFullYear(),
			mm: ( (_amonthago.getMonth() + 1) < 10) ? '0'+ (_amonthago.getMonth() + 1) : _amonthago.getMonth()+1,
			dd: ( _amonthago.getDate() < 10) ? '0' + _amonthago.getDate() : _amonthago.getDate()
		};
		
		var start = (val === 'Last 365 days' ) ? ayearago.yyyy + '-' + ayearago.mm + '-' + ayearago.dd :
					(val === 'Last 30 days' ) ? amonthago.yyyy + '-' + amonthago.mm + '-' + amonthago.dd :
					(val === 'Last 7 days' ) ? aweekago.yyyy + '-' + aweekago.mm + '-' + aweekago.dd : '';
					
		var end = (val === 'Past years') ? (today.yyyy - 1) + '-' + today.mm + '-' +today.dd : '';
		
		var polars = {
			start:start,
			end:end
		};
		
		return polars;
	}
	
	function get_type( spotlight ){
		var typed = '';
		switch( spotlight.type ){
			case 'swim':
				typed = 'Model';
				break;
			case 'player':
				typed = (spotlight.careerUrl.match('/mlb/')) ? 'MLB' : 
						(spotlight.careerUrl.match('/nfl/')) ? 'NFL' : 
						(spotlight.careerUrl.match('/nhl/')) ? 'NHL' : 
						(spotlight.careerUrl.match('/nba/')) ? 'NBA' : spotlight.type;
				break;
			case 'team':
				typed = (spotlight.url.match('/mlb/')) ? 'MLB' : 
						(spotlight.url.match('/nfll/')) ? 'NFL' : 
						(spotlight.url.match('/nhl/')) ? 'NHL' : 
						(spotlight.url.match('/nba/')) ? 'NBA' : spotlight.type;
				break;
			case 'writer':
				typed = 'Writer';
				break;
			case 'Section':
				typed = 'Section';
				break;
			default:
				typed = spotlight.type.toTitleCase();
				break;
		}
		return typed;
	}
	
	function display_spotlights(){
		
		var names = [];
		jQuery.each(_search.spotlights, function(i){
			var spotlight = _search.spotlights[i];
			
			if(typeof spotlight !== 'undefined'){
			
			var _spotlight = '';
			
			//team spotlight
			if(spotlight.type === 'team'){
				spotlight.transactions = spotlight.url.replace(/index\.html/, 'transactions.html');
				spotlight.injuries = spotlight.url.replace(/index\.html/, 'injuries.html');
				spotlight.sport = 	(spotlight.url.indexOf('football/nfl') > -1) ? 'football/nfl'  :
									(spotlight.url.indexOf('baseball/mlb') > -1) ? 'baseball/mlb'  :
									(spotlight.url.indexOf('basketball/nba') > -1) ? 'basketball/nba'  :
									(spotlight.url.indexOf('hockey/nhl') > -1) ? 'hockey/nhl'  : '';
				spotlight.logo = spotlight.logo.replace('65.gif', '60.png');
				spotlight.logo = spotlight.logo.replace('60.gif', '60.png');
				
_spotlight +=	'<div class="cnnSearchATeam cnnSearchSpotlight">';
_spotlight +=			'<div class="cnnLeft" style="border:none; margin-right:12px;">';
_spotlight +=				'<a href="'+spotlight.url+'">';
_spotlight +=					'<img src="'+spotlight.logo+'" />';
_spotlight +=				'</a>';
_spotlight +=			'</div>';
_spotlight +=			'<div class="cnnLine0">';
_spotlight +=				'<a href="'+spotlight.url+'">';
_spotlight +=					spotlight.name
_spotlight +=				'</a>';
_spotlight +=			'</div>';
_spotlight +=			'<div class="cnnLine2">';
_spotlight +=				'<div>';
_spotlight +=					'<a href="' + spotlight.stats + '" class="cnnFirst">Stats</a>';
_spotlight +=					'<a href="' + spotlight.schedule + '">Schedule</a>';
_spotlight +=					'<a href="' + spotlight.roster + '">Roster</a>';
_spotlight +=					'<a href="' + spotlight.transactions + '">Transactions</a>';
_spotlight +=					'<a href="' + spotlight.injuries + '">Injuries</a>';
_spotlight +=					'<a href="http://sportsillustrated.cnn.com/"' + spotlight.sport + '/index.html">News</a>';
_spotlight +=					'<a href="http://sportsillustrated.cnn.com/alerts/"' + spotlight.sport + '/index.html">Alerts</a>';
_spotlight +=					'<a href="' + spotlight.tickets + '">Tickets</a>';
_spotlight +=					'<a href="' + spotlight.photos + '">Photos</a>';
_spotlight +=					'<a href="' + spotlight.videos + '">Videos</a>';
_spotlight +=				'</div>';
_spotlight +=			'</div>';
_spotlight +=		'</div>';						
			
			}
			
			//writer spotlight
			if(spotlight.type === 'writer'){
				var writer_id = spotlight.name.toLowerCase().replace(/\s/g,'_');
				var columns = spotlight.latestArticles; 
				var hasColumns = (columns.length > 0) ? true : false;
				var writer_include = '/.element/ssi/story/4.1/writers/'+writer_id+'/.branding/default/subBanner_search.html';
				var writer_info_container = 'cnnSearchWriterInfo_'+writer_id;

_spotlight +=		'<div id="cnnSearchWriter" class="cnnSearchSpotlight cnnSearchAWriter">';
_spotlight +=			'<span id="'+writer_info_container+'"> </span>';
_spotlight +=			'<div class="cnnLine2"><ul>';
				 if( hasColumns ){
_spotlight +=				'<div>Latest Columns: </div>';
					jQuery.each(columns, function(i){
_spotlight +=					'<li><a href="'+columns[i].url+'">'+columns[i].title.replace(spotlight.name+':','')+'</a> (' + columns[i].articleDate + ') </li>';
					});
_spotlight +=			'</ul></div>';
				}
_spotlight +=		'</div>';
				jQuery.ajax({
					url: writer_include,
					success: function(data) {
						jQuery('span#'+writer_info_container).html(data);
						tb_init('a.thickbox'); //init thickbox
					}
				});
			}
			
			//player spotlight
			if(spotlight.type === 'player'){
				
				//check to see if there is a duplicate
				if( typeof _search.spotlights[i+1] !== 'undefined'){							
					if( _search.spotlights[i+1].homeUrl === spotlight.homeUrl ){
						_search.spotlights.splice(i+1, 1);
					}						
				}
				var tokens = spotlight.careerUrl.split('/');
				var sport_path = tokens[3] + '/' + tokens[4];
				var sportID = tokens[4];
				var playerID = tokens[6];
				var teamtokens = spotlight.teamUrl.split('-');
				var teamID = teamtokens[teamtokens.length - 1].split('/')[0];
				teamID = (teamID === 'wings') ? 'red_wings' : 
						 (teamID === 'blazers') ? 'trail_blazers' : 
						 (teamID === 'leafs') ? 'maple_leafs' : teamID;
				
				spotlight.position = (spotlight.position === 'Left Wing') ? 'LW' :
									 (spotlight.position === 'Right Wing') ? 'RW' :
									 (spotlight.position === 'Defense') ? 'D' :
									 (spotlight.position === 'Center') ? 'C' :
									 (spotlight.position === 'Goaltender') ? 'G' : spotlight.position;
									 
				
				var stats = spotlight.stats; 
				spotlight.age = (typeof spotlight.age === 'undefined') ? false : spotlight.age;
_spotlight +=	'<div class="cnnSearchAPlayer cnnSearchSpotlight">';
_spotlight +=			'<div class="cnnLeft">';
_spotlight +=				'<img src="http://i.cdn.turner.com/si/.e1d/img/4.0/global/'+sport_path+'/players/'+playerID+'.jpg" />';
_spotlight +=			'</div>';
_spotlight +=			'<div class="cnnLine0">';
_spotlight +=				'<span>';
_spotlight +=					'<a href="'+spotlight.teamUrl+'">';
_spotlight +=						'<img src="http://i.cdn.turner.com/si/.e1d/img/4.0/global/'+sport_path+'/logos/'+teamID+'_30.png" />';
_spotlight +=					'</a>';
_spotlight +=				'</span>'+spotlight.name+' <strong>'+spotlight.position+' #'+spotlight.number+'</strong>';
_spotlight +=			'</div>';
_spotlight +=			'<div class="cnnRight">';
_spotlight +=				'<table border="0" cellpadding="0" cellspacing="0">';
			for(stat in stats){
_spotlight +=					'<td>'
_spotlight +=						'<div>'+translate_stat(stat)+'</div>'+stats[stat];
_spotlight +=					'</td>'
			};
_spotlight +=				'</table>';
_spotlight +=				'<div><a href="'+spotlight.homeUrl+'">Player Page</a> | <a href="'+spotlight.careerUrl+'">Career Stats</a> | <a href="'+spotlight.teamUrl+'">Team Page</a></div>';
_spotlight +=			'</div>';
_spotlight +=			'<div class="cnnLine2">';
_spotlight +=				'<ul>';
_spotlight += (spotlight.age) ?	'<li><strong>Age:</strong> ' + spotlight.age +'</li>' : '';
_spotlight +=					'<li><strong>Born:</strong> ' + spotlight.birthDate.replace('District of Columbia', 'D.C.') + '</li>';
_spotlight +=					'<li><strong>Height:</strong> ' + spotlight.height + '</li>';
_spotlight +=					'<li><strong>Weight:</strong> ' + spotlight.weight + '</li>';
//_spotlight +=					'<li><strong>Rookie Year:</strong> ' + spotlight.rookieYear + '</li>';
_spotlight +=					'<li><strong>'+sportID.toUpperCase()+' Experience:</strong> ' + spotlight.yearsPro + ' years</li>';
_spotlight +=				'</ul>';
_spotlight +=			'</div>';
_spotlight +=		'</div>';
			}

		if(spotlight.type === 'swim'){					
		
		var model_id = spotlight.modelKey;
		var model_nm = spotlight.modelName;
		var model_img = spotlight.modelThumbnail;
		var img_json = ( typeof swimsuit_img_map !== "undefined" ) ? swimsuit_img_map : {}; //swimsuit_img_map defined externally, called in htmlHead.html
		var img_base = 'http://i.cdn.turner.com/sivault/swimsuit/image/';
		var img_src = 	( typeof model_img !== "undefined") ?  img_base + model_img :
						( img_json !== "" &&  typeof img_json[model_id] !== "undefined" ) ? img_base + img_json[model_id] : "http://i.cdn.turner.com/si/.element/img/4.1/global/1.gif";
		var img_used = 	( typeof model_img !== "undefined") ?  'model image from srch json' :
						( img_json !== "" &&  typeof img_json[model_id] !== "undefined" ) ? 'model image from EMBEDDED json' : "there's no model image";
_spotlight +=	'<div class="cnnSearchSwimsuitModel cnnSearchSpotlight">';
_spotlight +=		'<div class="cnnLeft">';
_spotlight +=			'<a href="http://sportsillustrated.cnn.com/vault/swimsuit/model/'+model_id+'/index.htm">';
_spotlight +=				'<img src="' + img_src + '" id="cnnSearchModelImg_'+model_id+'"/>';
_spotlight +=			'</a>';
_spotlight +=		'</div>';
_spotlight +=		'<div class="cnnLine0">';
_spotlight +=			'<a href="http://sportsillustrated.cnn.com/vault/swimsuit/model/'+model_id+'/index.htm">' + model_nm + '</a>';
_spotlight +=		'</div>';
_spotlight +=		'<div class="cnnLine2">';
_spotlight +=			'<a href="http://sportsillustrated.cnn.com/vault/swimsuit/model/'+model_id+'/index.htm" class="cnnFirst">Swimsuit Collection: ' + model_nm + ' Photos & Video</a>';
_spotlight +=		'</div>';
_spotlight +=	'</div>';

		}
		
		if(spotlight.type === 'Section'){
						
		var name = spotlight.name;
		var links = spotlight.links;
		var link = ( typeof links === 'string' ) ? links : links.link ;
		var linkcount = 0;
		
		
_spotlight +=	'<div class="cnnSearchATeam cnnSearchASection cnnSearchSpotlight" style="display: block; height:69px; width:877px !important;">';
_spotlight +=		'<div class="cnnLine0">';
_spotlight +=			'<a href="'+link+'/index.htm">';
_spotlight +=				name
_spotlight +=			'</a>';
_spotlight +=		'</div>';
			
_spotlight +=		'<div class="cnnLine2">';
_spotlight +=			'<div style="margin-left:20px;">';
			if( typeof links === 'object'){
				for( linkname in links){
					if ( linkname !== 'link'){
_spotlight +=						'<a href="'+links[linkname]+'"'+((linkcount===0)?' class="cnnFirst"':'')+'>';
_spotlight += 							linkname;
_spotlight += 						'</a>';							
					}
					linkcount++;
				}
			} else if ( typeof links === 'string' ){
_spotlight +=					'<a href="'+link+'" class="cnnFirst">';
_spotlight += 						name.toTitleCase() + ' Home';
_spotlight += 					'</a>';
			}
			
_spotlight +=			'</div>';
_spotlight +=		'</div>';
_spotlight +=	'</div>';					
		}
			jQuery('div#cnnSearchPlayer').append(_spotlight).show();
			
			
			//building list for 'others'
			var name = spotlight.name || spotlight.modelName;
			var type = get_type( spotlight );
			
			if ( type !== 'Section' ){
				
				if( name !== 'Venus Williams' && name !== 'Serena Williams'){
					names.push( name + ' (' + type +')');
				} else{
					names.push( name );  
				}
			
			}
			}
		});
		
		
		
	var players = jQuery('div.cnnSearchAPlayer')[0];
	var teams = jQuery('div.cnnSearchATeam');
	var writers  = jQuery('div.cnnSearchAWriter');
	var models = jQuery('div.cnnSearchSwimsuitModel');
	
	//display teams and writers before players
	if( teams.length > 0 ){
		teams.insertBefore(players);
		jQuery('div.cnnSearchAPlayer').remove();
	}
	
	if( writers.length > 0 ){
		writers.insertBefore(players);
		jQuery('div.cnnSearchAPlayer').remove();
	}
	
	var spotlight_containers = jQuery('div.cnnSearchSpotlight');
	
	if(spotlight_containers.length > 0){
		_search.scrollTop = 500;
		var curr = 0;
		var total = spotlight_containers.length;
		var newitem = 0;
		var prev = jQuery('div#cnnSearchSpotlightNav>ul>li:first')[0];
		var next = jQuery('div#cnnSearchSpotlightNav>ul>li:last')[0];

		//show the first
		jQuery(spotlight_containers[0]).show('slow');
		//jQuery('div#cnnSearchCM').show('slow');
	
		prev.onclick = function(){
			newitem = (curr == 0) ? (total - 1) : curr - 1;
			jQuery(spotlight_containers[curr]).hide();
			jQuery(spotlight_containers[newitem]).show('slow');
			curr = newitem;
		};
		
		next.onclick = function(){	
			newitem = (curr == (total-1)) ? 0 : curr + 1;
			jQuery(spotlight_containers[curr]).hide();
			jQuery(spotlight_containers[newitem]).show('slow');
			curr = newitem;
		};
		
		//s/*
		if(spotlight_containers.length > 1){
			jQuery('div#cnnSearchSpotlightNav').show('slow');				
		}

		if( names.length > 1){
			var spotlight_nav = jQuery('div#cnnSearchSpotlightNames');
			spotlight_nav.html(function(){
					var html = [];
					html.push('<ul id="extra_spotlights">');
				jQuery.each(names, function(i){
					html.push('<li>');
					html.push('	<a href="/search/?text=' + names[i].substring(0, names[i].indexOf(' (')).replace(/ /g, '+') +'">');
					html.push('		<span>');
					html.push( 			names[i] );
					html.push('		</span>');
					html.push('	</a>');
					if( i < names.length - 1){
					html.push('	|');
					}
					html.push('</li>');
				});
					
					html.push('<ul>');
					html = html.join('');
					
					html = '<p>More results: </p>' + html;
					return html;
					
			}).show('slow');
		}
		
	}
	
	}//end:display_spotlights
	
	function display_results(){
		var _content = '<ul>';
		
		jQuery.each(_search.results.content, function(i){
			var rslt = _search.results.content[i];
			var type = rslt.mediaType.toLowerCase();
			
			var date = rslt.mediaDateUts.replace(/\//g, '.');
			var date_a = date.split('.');
			//date = (true) ? date_a[1] + '.' + date_a[0] + '.' + date_a[2] : date;
			
			if(/^COM/.test(rslt.id)){
				rslt.url = 'http://sportsillustrated.cnn.com/vault' + rslt.url + '/index.htm';
			}
			
			if(/^MAG/.test(rslt.id)){
				rslt.url = 'http://sportsillustrated.cnn.com/vault' + rslt.url + '/index.htm';
			}
			
			if(/^GAL/.test(rslt.id)){
				rslt.url = 'http://sportsillustrated.cnn.com/vault' + rslt.url + '/1/index.htm';
			}
								
			if(type === 'cover'){
				rslt.url = 'http://sportsillustrated.cnn.com/vault' + rslt.url + '/index.htm';					
			}
			
			if(type === 'audio') rslt.url = 'javascript:CNN_DPAudio("'+rslt.url+'")';
			
			
			if(rslt.metadata.media.excerpt.length >= 480){
				rslt.metadata.media.excerpt = rslt.metadata.media.excerpt.substring(0, 480) + '...';
			}
_content +=	'<li>';
		//START: thumbnail
		if( type === 'gallery' || type === 'video' || type === 'cover' || type === 'photo'){

			if( typeof rslt.metadata.media.thumbnail !== 'undefined' ){
			
				var img_url = rslt.metadata.media.thumbnail.url;
									
				var img_w = parseInt(rslt.metadata.media.thumbnail.width, 10);
				var img_h = parseInt(rslt.metadata.media.thumbnail.height, 10);
				var ratio = 0;
				
				if( img_w > 130 && img_w > img_h ){
					ratio = 130 / img_w;
					img_w = 130;
					img_h = Math.ceil( img_h * ratio );
				} else if ( img_h > 130 && img_h > img_w ) {
					ratio = 130 / img_h;
					img_h = 130;
					img_w = Math.ceil( img_w * ratio );
				} else if ( img_h === img_w && img_h > 130){
					ratio = 1;
					img_h = 100;
					img_w = 100;
				}else {
					img_h = img_w = '';
				}
				
				if(type === 'cover'){
					img_url = 'http://i.cdn.turner.com/sivault' + rslt.metadata.media.thumbnail.url + 'thumb.jpg';
					img_w = 100;
					img_h = 132;
				} 
				
				if( /IMG/.test(rslt.url) ){
					img_url = 'http://i.cdn.turner.com/sivault' + rslt.metadata.media.thumbnail.url + '.thumbnail.jpg';
				}
				
				if( img_url.indexOf('130x100.gif/') > -1 ){
					img_url = img_url.split('.gif')[0] + '.gif';
				}
				
				if( img_url.indexOf('124x70.jpg/') > -1 ){
					img_url = img_url.split('.jpg')[0] + '.jpg';
				}
													
_content +=		'<div>';
_content +=			'<a href='+ rslt.url +'>';			
_content +=				'<span class="image">';
_content +=					'<img title="' + rslt.title + '" alt="' + rslt.title + '" src="' + img_url + '" width="'+img_w+'" height="'+img_h+'"/>';
_content +=				'</span>';
_content +=			'</a>';			
_content +=		'</div>';

			}
		}
		//END: thumbnails
		//START: title and desc
_content +=		"<div>";
_content +=			"<a href=\""+ rslt.url +"\">";			
_content +=				"<span class=\"title\">" + rslt.title  + "</span>";
_content +=				"<span class=\"date\">(" + date + ")</span>"; 
_content +=			"</a>";			
_content +=		"</div>";					
_content +=		"<div>";
//	_content +=			"<a href="+ rslt.url +">";			
_content +=				"<span class=\"desc\">" + rslt.metadata.media.excerpt  + "</span>";
//	_content +=			"</a>";			
_content +=		"</div>";

	//	}
		//END: title and desc
_content +=	"</li>";	
			
		});
		_content += "</ul>";
		jQuery('div#textResultsContainer').html(_content);
	}
	
	function display_suggested_results(){
	
		$('<li><a href="/search/?text='+_search.term+'" id="cnnSearchRefineClearAll">Clear Any Search Filters</a></li>').insertBefore('div#cnnSearchTips ul li:first');
			
		var _content = '<ul>';
		
		jQuery.each(_search.results.dym.correctedResults, function(i){
			var rslt = _search.results.dym.correctedResults[i];
			var type = rslt.mediaType;
			
			var date = rslt.mediaDateUts.replace(/\//g, '.');
			var date_a = date.split('.');					
			
			if(type === 'article') rslt.url = 'http://sportsillustrated.cnn.com/vault/article/magazine/' + rslt.url + '/index.htm';
			
_content +=	'<li>';
		//START: gallery
		if( type === 'gallery' ){
			var img_url = (rslt.metadata.media.thumbnail.url) ? rslt.metadata.media.thumbnail.url : 'http://i.cdn.turner.com/si/.element/img/4.1/global/si_logo-124x70.jpg';
_content +=		'<div>';
_content +=			'<a href="'+ rslt.url +'">';			
_content +=				'<span class="image">';
_content +=					'<img title="' + rslt.title + '" alt="' + rslt.title + '" src="' + img_url + '"/>';
_content +=				'</span>';
_content +=			'</a>';			
_content +=		'</div>';
		}
		//END: gallery
		
_content +=		'<div>';
_content +=			'<a href="'+ rslt.url +'">';			
_content +=				'<span class="title">' + rslt.title  + '</span>';
_content +=				'<span class="date"> (' + date + ')</span>'; 
_content +=			'</a>';			
_content +=		'</div>';					
_content +=		'<div>';
_content +=			'<a href="'+ rslt.url +'">';			
_content +=				'<span class="desc">' + rslt.metadata.media.excerpt  + '</span>';
_content +=			'</a>';			
_content +=		'</div>';

		//END: article
_content +=	'</li>';	
			
		});
		_content += '</ul>';
		jQuery('div#textResultsContainer').html(_content);
	}
	
	function display_buckets(){
		var buckets = _search.results.buckets;
		var _buckets = '<h6>Refine Search Options</h6>';
		var cap = (name !== 'content_type') ? 4: 6;
		
		if( _search.filtered ){
_buckets +=		'<div id="cnnSearchRefineClearAll" class="cnnSearchRefineGroup cnnSearchRefineMinimized"><ul><li class="cnnAlt"><a>CLEAR ALL FILTERS</a><span id="source"></span></li></ul></div>';
		}
		
		jQuery.each(buckets, function(i){
			
			var bucket = buckets[i];
			var name = bucket.fieldname;
			var counts = bucket.countByValues;
			if( _search.filtered ){
				var bucketString = jQuery.objectToString(counts); 
				
				// if( jQuery.inArray(name, _search.filteredBy) >= 0 || (name === 'dredate' && (typeof _search.args.startDate !== "undefined" || typeof _search.args.endDate !== "undefined"))){
					// if( name !== 'dredate' && bucketString.indexOf( translate_bucket(_search.args[name]) ) < 0 ){	
							// counts.push({'fieldvalue':translate_bucket(_search.args[name]), 'count':0});
					// } else if( bucketString.indexOf( translate_bucket(_search.dateSort) ) < 0) {
							// counts.push({'fieldvalue':translate_bucket(translate_bucket(_search.dateSort)), 'count':0});									
					// }
				// }
			}

			counts.sort(function(a,b){
				return b.count - a.count;
			});
			
_buckets +=		'<div id="cnnSearchRefineGroup'+i+'" class="';
_buckets +=	(_search.filtered && (typeof _search.args[name] !== 'undefined' || (name === 'dredate' && typeof _search.dateSort !== 'undefined') ) ) ? 'cnnSearchRefineGroup cnnSearchRefineMinimized' : 'cnnSearchRefineGroup';
_buckets +=		'">';
_buckets +=			'<div>BY ' + translate_bucket( name, false ).toUpperCase() + '</div>';
_buckets +=			'<ul>';

	//if the search is unfiltered, or this bucket isn't the one filtered, or if sorted by date highlight "All X"
	if( !_search.filtered || ( (name !== 'dredate' && typeof _search.args[name] === 'undefined') || (name === 'dredate' && typeof _search.dateSort === 'undefined') ) ){
_buckets += 			'<li class="cnnAlt"><a> All ' + translate_bucket( name, true ) + ' (' + bucket.total + ') </a><span></span></li>';
	}
	jQuery.each(counts, function(j){
		var value = counts[j].fieldvalue;
		var title = value;
		var note = (typeof counts[j].note !== 'undefined') ? counts[j].note : false;
		
		if( name === 'author' && note !== false ){ //if the author has been consolidated, the title should account for that
			title = ( note.indexOf('comma') > -1 ) ? title + '|' + title + '*' : title;	//PETER KING|PETER KING*
			title = ( note.indexOf('edited') > -1 ) ? title + '|*' + title : title;		//PETER KING|*PETER KING
			title = ( note.indexOf('told') > -1 ) ? title + '|*' + title : title;		//PETER KING|*PETER KING
		}
		if( (name === 'source' || name === 'section' || name === 'sport')  && note !== false ){
			title = (note !== '') ? note : title;	
		} 
			
				
	//if the search is filtered by this bucket, highlight it, 
	//otherwise if it's not one of the first five, hide it
	if(	_search.filtered && 
		( (typeof _search.args[name] !== 'undefined') && ((_search.args[name] === title) || _search.args[name].indexOf(title) > -1 || _search.args[name].indexOf(value) > -1) ) ||
		( (typeof _search.dateSort !== 'undefined') && (_search.dateSort === translate_bucket(value)) )
	){
				
_buckets +=				'<li class="cnnAlt">';
	} else if ( j > cap ) {
_buckets +=				'<li style="display:none;">';
	} else {
_buckets +=				'<li>';
	}	

_buckets +=					'<a title="'+translate_bucket(title)+'" name="'+name+'" >';			
_buckets +=						translate_bucket(value) + ' (' + counts[j].count + ')';
_buckets +=					'</a>'; 

	//if search is filtered by this bucket, show a red x (span tags)
	if(	_search.filtered && 
		( (typeof _search.args[name] !== 'undefined') && ((_search.args[name] === title) || _search.args[name].indexOf(title) > -1 || _search.args[name].indexOf(value) > -1) ) ||
		( (typeof _search.dateSort !== 'undefined') && (_search.dateSort === translate_bucket(value)) )
	){
_buckets +=					'<span id="'+name+'"></span>';
	}
_buckets +=				'</li>';
	
	
	});
	
	//if there are more than 5 filter options returned, show a more link
_buckets +=	( counts.length > 5 ) ? '<li id="cnnSearchRefineGroup'+i+'MoreLink" class="cnnSearchRefineGroupMoreLink"><a>More ...</a></li>' : '';

_buckets +=			'</ul>';
_buckets +=		'</div>';
		});
		
		jQuery('div#cnnSearchRefine').html(_buckets);
		
		//clear all filters functionality
		jQuery('div#cnnSearchRefineClearAll').click( function(){
			clearSearchFilters();
		});
		
		//clicking a refine group will filter the results
		jQuery('div.cnnSearchRefineGroup a').each(function(i){
			if ( $(this).attr('title') ){
				
				$(this).click(function(){
					var rel = $(this).attr('name');
					//if( rel === 'sport' ) rel = 'section';
					
					var val = $(this).attr('title')
					_search.filtered = true;
					_search.filteredBy.push( rel );
					
					//set the proper params
					if(rel === 'dredate'){
						var dates = get_dates( val );
						_search.dateSort = val;
						if(dates.start !== ''){
							_search.args.startDate = dates.start;

						}
						
						if(dates.end !== ''){
							_search.args.endDate = dates.end;

						}
					}
						_search.args[rel] = val;
						_search.args.page = 1;
						_search.args.start = 1;
					callObj.args = setSearchParams();
					
					//fetch the results
					$('#cnnSearchLoader').show('fast');
					CSIManager.getInstance().callObject(callObj);
				});
			}
		});
		
		//if the refine box is minimized, clicking a span (red X) will unfilter the results
		jQuery('div.cnnSearchRefineGroup li.cnnAlt span').click(function(){
		
			var filter = $(this).attr('id');
			var index = jQuery.inArray( filter, _search.filteredBy );
			
			if( index > -1){
				
				delete _search.args[filter];
				_search.filteredBy.splice(index, 1);
				
				if(_search.filteredBy.length < 1){
					_search.filtered = false;
					_search.filteredBy = [];


				}
				
				if( filter === 'dredate'){
					delete _search.dateSort;

					if( typeof _search.args.startDate !== 'undefined' ) delete _search.args.startDate;



					if( typeof _search.args.endDate !== 'undefined' ) delete _search.args.endDate;


				}


				callObj.args = setSearchParams();	
				
				//fetch the results
				$('#cnnSearchLoader').show('fast');
				CSIManager.getInstance().callObject(callObj);
			}
		});
		
		register_events('more links');
		register_events('less links');
						
	}
	
	function display_pagination(){
		
		var pagesToDisplay = _search.args.npp;
		var start = parseInt(_search.args.page, 10);
		var curr = start;
		var end =  curr + 5;
		var _pagination = '';
		var totalPages = Math.ceil(parseInt(_search.results.count, 10) / pagesToDisplay);
		
		if( curr <= 5 ){
			start = 1;
			end = (end >= totalPages) ? totalPages : 10;
		} else {
			start = curr - 4;
		}
		if( end >= totalPages) {
			start = (totalPages <= 10) ? 1 : end - 4;
			end = totalPages;
		} 				
		if( start > 1){
			_pagination	+=	'<span>';
			_pagination	+=		'<a class="cnnSearchPageLink" name="cnnSearchPage'+ (start-1) +'">BACK</a>';
			_pagination	+=	'</span>';
		}
		
		for(var page=start; page <= end; page++){
			_pagination	+=	(page === curr) ? '<a class="cnnSearchPageLink cnnAlt"' : '<a class="cnnSearchPageLink"';
			_pagination +=	'name="cnnSearchPage'+page+'">'+page+'</a>';
			_pagination	+=	(page < end ) ? '|' : '';
		}

		if( end < totalPages ){
			_pagination	+=	'<span>';
			_pagination	+=		'<a class="cnnSearchPageLink" name="cnnSearchPage'+ (curr + 1) +'">NEXT</a>';
			_pagination	+=	'</span>';
		}
		jQuery('div#cnnSearchPagination').html( _pagination );
		
		jQuery('a.cnnSearchPageLink').each(function(){
			var _page = jQuery(this).attr('name').substring(13); //'cnnSearchPage123'.substring(13) = 12
			jQuery(this).click(function(){
				_search.args.page = _page;
				_search.args.start = (_page*_search.args.npp) - 9;
				
				callObj.args = setSearchParams();

				$('#cnnSearchLoader').show('fast');
				CSIManager.getInstance().callObject(callObj);
				
				$('html, body').animate({scrollTop:_search.scrollTop}, 'slow');
			});
			
		});

	}
	
	function display_topics( topics ){	
		
		topics.sort(function(a,b){
			return b.topicValue - a.topicValue;
		});
		
		var _topics = '';
		
		if(topics.length > 0){
_topics +=	'<div class="cnnTopicsHeader">Related Topics</div>\n';
_topics +=	'<div class="cnnTopicsContent">';
_topics +=		'<ol>'	
		
		jQuery.each(topics, function(i){
			var nm = topics[i].topicName;
			var val = topics[i].topicValue;
			
			if( nm.toLowerCase() !== unescape(_search.term.replace(/\+/g,' ')).toLowerCase() ){
_topics +=	'<li>';
_topics +=		'<a title="'+nm+'('+val+')" href="/search/?text='+nm.toTitleCase()+'">';
_topics +=			nm.replace(/\./g,' ').toTitleCase();
_topics +=		'</a>';
_topics +=	'</li>';	
			}
		});

_topics += 		'</ol>';
_topics += 	'</div>';

		jQuery('div#cnnTopicsbox').html(_topics).show();
						
		}
		
		delete _search.args.topics;
	} //end: display_topics
	
	function register_events(where){
	
		if(where === 'more links'){
			jQuery('div.cnnSearchRefineGroup li.cnnSearchRefineGroupMoreLink').click(function(){
				var siblings = $(this).siblings();
				var id = jQuery(this).attr('id');
				var max = 5;
				var counter = 0;
				var total = siblings.size();
				var totalReached = false;
				
				jQuery.each(siblings, function( i ){					
					if( jQuery(this).css('display') === 'none' && counter < max){
						jQuery(this).show('fast');
						counter++;
						
						if ( jQuery(this).css('display') !== 'none' && i === (total-1) ){
							totalReached = true;
							jQuery('#'+id).html('<a>Less...</a>').removeClass('cnnSearchRefineGroupMoreLink').addClass('cnnSearchRefineGroupLessLink');
							
							register_events('less links');
						}
					}
					
				});
			});
		}
		if(where === 'less links'){
			jQuery('div.cnnSearchRefineGroup li.cnnSearchRefineGroupLessLink').click(function(){
				var siblings = $(this).siblings();
				var max = 5;
				
				jQuery(this).html('<a>More ...</a>').removeClass('cnnSearchRefineGroupLessLink').addClass('cnnSearchRefineGroupMoreLink');
				register_events('more links');
									
				jQuery.each(siblings, function( i ){					
					if( i > max ){
						jQuery(this).hide();						
					};						
				});
			});
		}
	}

});

