var $j = jQuery.noConflict();

// Global variables that are used for result filtering
var searchResults;
var maxDate = new Date();
var minDate = new Date();
var currentDateVal = minDate.valueOf();
var selectedCycles = new Array();
var visibleItems = new Array();
var mapItems = new Array();
var selectedCategories = new Array();
var isMapReady = false;
var hasHypeData = false;
var categoryCount = {
	nightlife: 0,
	food: 0,
	style: 0,
	rock: 0,
	roll: 0,
	gear: 0,
	leisure: 0,
	destinations: 0,
	weekender: 0,
	profiles: 0,
	perks: 0
};

IASearchClass = function(){};
$j.extend( IASearchClass.prototype,
{
  tweening: false,
  sectionSlideSpeed: "slow",
  sections:
  {
    categories: 
    { 
        track_name: 'Categories',
        header:     'category_list_01',
        contents:   'category_list_holder',
        height:     218,
        variable:   false 
    },
    time_range: 
    { 
        track_name: 'Time Range', 
        header:     'time_range_01',
        contents:   'time_range',
        height:     55,
        variable:   false 
    },
    vicinity_map: 
    {  
        track_name: 'Map',
        header:     'vicinity_01',
        contents:   'vicinity_map',
        variable:   true 
    }   
  },

  initializeEventHandlers: function()
  {
    // add events to all the headers on the left hand side
    for( var i in IASearch.sections ) $j('#'+IASearch.sections[i].header).bind('click', IASearch.onSectionHeaderClick);
    
    // add events to clicking the category checkboxes
    $j('#category_list input').bind('click', IASearch.onFilterCategoryCheckboxClick);
    
    // default value and ENTER key binding for the search field
    $j('#search_field').defaultvalue('Search', 'Search');
    $j('#search_field').bind('keydown', IASearch.onSearchFieldKeydown);
    
    // overlay click-to-kill binding
    $j('#overlay').bind('click', IASearch.onOverlayClick)
  },
  
  onFilterCategoryCheckboxClick: function( evt )
  {
    if( this.id == 'check_all' && this.checked) $j("#category_list input[id!='check_all']").val([]);
    else $j('#check_all').val([]);
    
    if ($j('#extra_div:visible').length) filterResult();
  },
  
  onSearchFieldKeydown: function( evt )
  {
    // Gecko
    if(evt && evt.which)
    {
      evt = evt;
      characterCode = evt.which;
    }
    
    // IE
    else 
    {
      evt = event;
      characterCode = evt.keyCode;
    }
    
    // if we hit ENTER (code 13) then submit the form. this is done by eval-ing the code in the 
    // onsubmit handler - hacky but it works.
    if (characterCode == 13) 
    {
      eval($j('#interactive_search_form').attr('onsubmit').replace("return false;",""));
      return false;
    }
  },
  
  onOverlayClick: function( evt )
  {
    kill_ajax();
    GAEvent.track('IA Search', 'Click Off', GAEvent.currentPage);
  },
  
  /**
   * Initialize time range slider
   * @param {Object} min Number
   * @param {Object} max Number
   */ 
  initializeSlider: function(min, max){
    $j('#startYearLabel').text(minDate.getFullYear());
    $j('#endYearLabel').text(maxDate.getFullYear());
    
    $j("#time_range_slider").slider('destroy');
    $j("#time_range_slider").slider({
      min: min - 10,
      max: max,
      startValue: min,
      slide: function(e, ui){
        var date = new Date(ui.value);
        var dateStr = (date.getMonth()+1) + " '" + String(date.getFullYear()).substr(2);
        $j("#timerangeTooltip").css('left', parseInt(ui.handle.css('left'), 10) + 10).text(dateStr);
      },
      start: function(){
        $j("#timerangeTooltip").show();
      },
      stop: function(e, ui){
        $j("#timerangeTooltip").hide();
        $j("#time_range_handle").get(0).blur();
      },
      change: function(e, ui){
        $j("#timerangeTooltip").hide();
        currentDateVal = ui.value;
        filterResult();
      }
    });
    $j("#time_range_slider").slider('moveTo', min - 10);
  },
  
  /**
   * @function addVariableHeight
   *
   * Used when items open or close on the IASearch and this changes the height of the variable-height
   * items like the map.
   */
  addVariableHeight: function( h, exclude, tween )
  {
    var sections = [];
    if (typeof(tween)=='undefined') tween = true;
    for( var i in IASearch.sections ) 
    { 
      if (!IASearch.sections[i].variable) continue; // ignore non-variable sections
      if (i==exclude) continue; // don't do this to the section we're changing
      if ($j('#'+IASearch.sections[i].contents).height() < 1) continue; // don't do this if the section is hidden
      sections.push( String(i) );
    }
    if (sections.length < 1) return;
    var heightChangePerItem = Math.floor( h / sections.length );
    for( var i = 0; i < sections.length; i++ ) 
    {
      var contents = $j('#'+IASearch.sections[sections[i]].contents);
      if (tween) contents.animate({ height: contents.height()+heightChangePerItem }, IASearch.sectionSlideSpeed, 'swing');
      else contents.height( contents.height()+heightChangePerItem );
    }
  },
  
  showSectionContents: function( i, tween )
  {
    var section = IASearch.sections[i];
    if (typeof(tween)=='undefined') tween = true;
    
    // change header arrow placement
    $j('#'+section.header).css({backgroundPosition: 'left top'});
    
    if (section.variable)
    {
        var vSpace = $j('#resultsHolder').height() - $j('#search_category').height() + $j('#extended_search').height();
        if (tween) 
        {
          IASearch.onTweenStart();
          $j('#'+section.contents).animate({ height: vSpace }, IASearch.sectionSlideSpeed, 'linear', IASearch.onTweenEnd);
        }
        else $j('#'+section.contents).height( vSpace );
    }
    
    // otherwise it has a fixed height, so just slide it down.
    else 
    {
      if (tween) 
      {
        IASearch.onTweenStart();
        $j('#'+section.contents).slideDown(IASearch.sectionSlideSpeed, IASearch.onTweenEnd);
      }
      else $j('#'+section.contents).show();
      
      IASearch.addVariableHeight( - section.height, i, tween );
    }
  },
  
  hideSectionContents: function( i, tween )
  {
    var section = IASearch.sections[i];
    if (typeof(tween)=='undefined') tween = true;
    
    // change header arrow placement
    $j('#'+section.header).css({backgroundPosition: 'right top'});
    
    // open up any variable sections by the amount that this will free up
    IASearch.addVariableHeight( $j('#'+section.contents).height(), i, tween );
    
    // slide up the section contents.
    if (section.variable) 
    {
      if (tween) 
      {
        IASearch.onTweenStart();
        $j('#'+section.contents).animate({ height: 0 }, IASearch.sectionSlideSpeed, 'linear', IASearch.onTweenEnd);
      }
      else $j('#'+section.contents).height( 0 );
    }
    else 
    {
      if (tween) 
      {
        IASearch.onTweenStart();
        $j('#'+section.contents).slideUp(IASearch.sectionSlideSpeed, IASearch.onTweenEnd);
      }
      else $j('#'+section.contents).hide();
    }
  },
  
  onSectionHeaderClick: function( evt )
  {
    if (IASearch.tweening) return;
  
    // get the sections array item from the Event object
    for( var i in IASearch.sections ) { if (evt.target.id==IASearch.sections[i].header) break; }
    var section = IASearch.sections[i];
    
    GAEvent.track('IA Search', 'Click '+section.track_name, GAEvent.currentPage);
    var isVisible = !($j('#'+section.contents+':hidden').length > 0) && $j('#'+section.contents).height() > 0;
    
    if (isVisible) IASearch.hideSectionContents( i );
    else IASearch.showSectionContents( i );
    
    return false;
  },
  
  onTweenStart: function( evt ) { IASearch.tweening = true; },
  onTweenEnd: function( evt ) 
  { 
    IASearch.tweening = false; 
    filterChanged();
  },
  log:function ( s ) { Logger.log( "IASearch :: "+s ); }
});

// Initialize UI event handlers
var IASearch = new IASearchClass();
$j(document).bind('ready', IASearch.initializeEventHandlers );

/**
 * Shows or hides the images in result items.
 * @param {Object} event
 */ 
function show_images(event){
	
	//if( event.currentTarget.checked ){
	if( document.getElementById('showImages').checked ){
		$j('.resultBox > a > img').show();
	}else{
		$j('.resultBox > a > img').hide();
	}
}

/**
 * Filters the result by filter parameters.
 */ 
function filterResult()
{
	selectedCycles = [];
	
	try
	{
		if( document.getElementById('hype_selector') && document.getElementById('hype_selector').getHypeSelection ){
			selectedCycles = document.getElementById('hype_selector').getHypeSelection();
		}else{
			selectedCycles = [];
		}
	} catch (e) { }
	
	var hypeVisible = ($j('#hype_selector').height() > 0);
	
	selectedCategories = new Array();
	$j('#category_list input:checked').each(function(){
		if( this.id == 'check_all' ) return;
    	selectedCategories.push($j(this).val());
	});
	
	var vicinityMap = document.getElementById('vicinity_map');
	if( vicinityMap.getVisibleItems && $j('#vicinity_map').height() > 5 ){
		vicinityMap.filterByDate( new Date(currentDateVal));
		vicinityMap.filterByHype(selectedCycles, (hypeVisible && hasHypeData));
		vicinityMap.filterByCategory(selectedCategories);
		mapItems = vicinityMap.getVisibleItems();
	}else{
		mapItems = null;
	}
	
	var visibleItems = new Array();
	// Filter by date
	var resultArray = searchResults.articles;
	
	for (var i = 0; i < resultArray.size(); i++) {
		if (resultArray[i].dateObj.valueOf() > currentDateVal &&
		(!hasHypeData || !hypeVisible || (!selectedCycles.size() || (selectedCycles.indexOf(resultArray[i].hypecycle) != -1))) &&
		(mapItems == null || (mapItems.indexOf(resultArray[i].article_id) != -1)) &&
		(!selectedCategories.size() || (selectedCategories.indexOf(resultArray[i].category) != -1))) {
			visibleItems.push(resultArray[i].article_id);
		}
	}
	
	$j(".resultBox").each(function(){
		var art_id = parseInt($j(this).attr('articleId'), 10);
		
		if( visibleItems.indexOf(art_id) != -1 ){
			$j(this).show();
		}else{
			$j(this).hide();
		}
	});
	
	if(visibleItems.size()){
		$j('.noResultBox').hide();
	}else{
		$j('.noResultBox').show();
	}
}

/**
 * @function reset_search_fields
 * 
 * Resets the innerHTML of the iasearch overlay if it has changed.
 */
function reset_search_fields()
{	
	// first run of this function, simply save the html.
	if (typeof(this.search_fields_html)=="undefined") 
	{
		this.search_fields_html = $j('#search_category').html();
		return;
	}
	
	// successive runs, replace it.
	$j('#search_category').html( this.search_fields_html );
	
	// re-attach events
	IASearch.initializeEventHandlers();
}

/**
 * @function iasearch_save_result
 *
 * Called by the IASearch result items when the SAVE button is clicked.
 */
var iasearchLoginHTML = "";
var iasearchFpFormHTML = "";
var iasearchFpConfirmHTML = "";
var iasearchProcessingHTML = "";
var iasearchSaveDiv = document.createElement( 'div' );
var iasearchProcessingDiv = document.createElement( 'div' );
function iasearch_save_result( saveUrl, articleId )
{
  GAEvent.track('IA Search', 'Click Save', articleId, GAEvent.currentPage);

	iasearch_cancel_save();
	
	iasearch_use_spinner( articleId );

	// save clean editions of the AJAX boxes
	iasearchSaveDiv = document.createElement( 'div' );
	iasearchProcessingDiv = document.createElement( 'div' );
	iasearchLoginHTML 		= $j('#ia_search_login_template').html();
	iasearchFpFormHTML 		= $j('#ia_search_password_reminder_template').html();
	iasearchFpConfirmHTML 	= $j('#ia_search_reminder_confirm_template').html();
	iasearchProcessingHTML 	= $j('#ia_search_processing_template').html();
	$j(iasearchSaveDiv).attr( "class", $j('#ia_search_login_template').attr("class") );
	$j(iasearchSaveDiv).attr( "style", "background-color:#fff;" );
	$j(iasearchSaveDiv).appendTo('#resultsHolder');
	$j(iasearchProcessingDiv).attr( "class", $j('#ia_search_login_template').attr("class") );
	$j(iasearchProcessingDiv).attr( "style", "background-color:#fff;" );
	$j(iasearchProcessingDiv).html( iasearchProcessingHTML );
	$j(iasearchProcessingDiv).appendTo('#resultsHolder');
	
	IASearch.log("Save Result");
	
	$j.get( saveUrl, '', function(data)
	{
	  IASearch.log("Save Result Response");
	  
		UDRefresh.refreshAds();
		iasearch_clear_spinner( articleId )
		
		switch( data )
		{
			case "RequiresLogin":
			  ajaxSignup.accountCreatedCallback = function() { iasearch_save_result( saveUrl, articleId ); };
			  ajaxSignup.signupCompletedCallback = function() {};
			  return ajaxSignup.launch("You must be a member to save an article to your My UD page.<br />Enter your email address below for a free membership.<br /><br /><a href=\"/myud#login\" onclick=\"ajaxSignup.close();scrollToIASearch();iasearch_goto_login("+articleId+");return false;\">Already a member? Click here to log in.</a>");
				break;
				
			case "Saved":
				iasearch_show_saved( articleId );
				break;
		}
	});
	
	return false;
}

function iasearch_use_spinner( articleId )
{
	$j('#buttonSave_'+articleId).hide();
	$j('#resultSpinner_'+articleId).show();
}

function iasearch_clear_spinner( articleId )
{
	$j('#buttonSave_'+articleId).show();
	$j('#resultSpinner_'+articleId).hide();
}

function iasearch_use_saved( articleId )
{
	
}

function iasearch_goto_login( articleId )
{
  IASearch.log("Goto Login");

	var resultBox = $j('#resultBox_'+articleId );
	
	// format login box with relevant variables
	var newHtml = iasearchLoginHTML;
	newHtml = newHtml.replace( /__:name:/gi, resultBox.attr( 'articleName' ) );
	newHtml = newHtml.replace( /XXXXX/gi, resultBox.attr( 'articleId' ) );
	newHtml = newHtml.replace( /__:url:/gi, resultBox.attr( 'articleUrl' ) );
	$j(iasearchSaveDiv).html( newHtml );
	
	iasearch_position_div_on( articleId );
}
function iasearch_submit_login( articleId )
{
	GAEvent.track('IA Search', 'Click Login', articleId, GAEvent.currentPage);
	IASearch.log("Submit login");
	
	var resultBox = $j('#resultBox_'+articleId );
	
	var frmElement = iasearchSaveDiv.getElementsByTagName("form")[0];
	var formData = $j(frmElement).serialize();
	var submitURL = $j(frmElement).attr( "action" );
	var saveURL = String(frmElement.saveUrl.value).replace('XXXXX', articleId);
	
	IASearch.log("Sending '"+formData+"' to '"+submitURL+"'" );
	
	iasearch_show_processing( articleId );
	
	$j.post( submitURL, formData, function( data )
	{
		IASearch.log("Login Response: "+data );
		iasearch_hide_processing();
		switch( data )
		{
			case "SUCCESS":	
				// update the top links and badge
				new Ajax.Updater('restTopLinks', '/nav/loginNavbar', {asynchronous:true, evalScripts:true});
				new Ajax.Updater('headSignUpHolder', '/nav/myudBadgeHome', {asynchronous:true, evalScripts:true, method:'get'});
				
				// run back to SAVE
				iasearch_save_result( saveURL, articleId );
				break;
				
			default:
				// echo the ERROR
				$(iasearchSaveDiv).select('.inline_error')[0].innerHTML = data;
				break;
		}
	});
}

function iasearch_position_div_on( articleId )
{
	IASearch.log("Reposition On ( "+articleId+" )" );
	var resultBox = $j('#resultBox_'+articleId );
	
	var resultBoxPosition = resultBox.position();
	$j(iasearchSaveDiv).css( 'left', resultBoxPosition.left + resultBox.parent().scrollLeft() );
	$j(iasearchSaveDiv).css( 'top', resultBoxPosition.top + resultBox.parent().scrollTop() );
	$j(iasearchSaveDiv).fadeIn('normal', function() { 
		IASearch.log("Login div faded in" );
		if ($j.browser.msie) this.style.removeAttribute('filter'); 
	});
}

function iasearch_goto_fp( articleId )
{
	IASearch.log("Goto Forgot Password" );
	
	var resultBox = $j('#resultBox_'+articleId );
	
	// format login box with relevant variables
	var newHtml = iasearchFpFormHTML;
	newHtml = newHtml.replace( /__:name:/gi, resultBox.attr( 'articleName' ) );
	newHtml = newHtml.replace( /XXXXX/gi, resultBox.attr( 'articleId' ) );
	newHtml = newHtml.replace( /__:url:/gi, resultBox.attr( 'articleUrl' ) );
	$j(iasearchSaveDiv).html( newHtml );
	
	iasearch_position_div_on( articleId );
}

function iasearch_submit_fp( articleId )
{
	GAEvent.track('IA Search', 'Click Password Reminder', articleId, GAEvent.currentPage);
	IASearch.log("Submit Forgot Pass" );
	
	var resultBox = $j('#resultBox_'+articleId );
	
	var frmElement = iasearchSaveDiv.getElementsByTagName("form")[0];
	var formData = $j(frmElement).serialize();
	var submitURL = $j(frmElement).attr( "action" );
	var saveURL = String(frmElement.saveUrl.value).replace('XXXXX', articleId);
	
	IASearch.log("Forgot Pass: Sending '"+formData+"' to '"+submitURL+"'" );
	
	iasearch_show_processing( articleId );
	
	$j.post( submitURL, formData, function( data )
	{
		IASearch.log("Forgot Pass Response: "+data );
		iasearch_hide_processing();
		switch( data )
		{
			case "SUCCESS":	
				// run back to SAVE
				iasearch_goto_confirm_fp( saveURL, articleId );
				break;
				
			default:
				// echo the ERROR
				iasearchSaveDiv.getElementsByClassName('inline_error')[0].innerHTML = data;
				break;
		}
	});
}

function iasearch_goto_confirm_fp( saveURL, articleId )
{
	IASearch.log("Confirming Forgot Pass sent for ('"+saveURL+"', "+articleId+")" );
	
	var resultBox = $j('#resultBox_'+articleId );
	
	// format login box with relevant variables
	var newHtml = iasearchFpConfirmHTML;
	newHtml = newHtml.replace( /__:name:/gi, resultBox.attr( 'articleName' ) );
	newHtml = newHtml.replace( /XXXXX/gi, resultBox.attr( 'articleId' ) );
	newHtml = newHtml.replace( /__:url:/gi, resultBox.attr( 'articleUrl' ) );
	$j(iasearchSaveDiv).html( newHtml );
}

function iasearch_show_saved( articleId )
{
	IASearch.log("Save Complete ("+articleId+")" );
	$j('#buttonSave_'+articleId).hide(); 
	Effect.Appear('buttonSaved_'+articleId, {}); 
	// Effect.Highlight('buttonSaved_'+articleId, {});
}

function iasearch_show_processing( articleId )
{
	var resultBox = $j('#resultBox_'+articleId );
	var resultBoxPosition = resultBox.position();
	$j(iasearchProcessingDiv).css( 'left', resultBoxPosition.left + resultBox.parent().scrollLeft() );
	$j(iasearchProcessingDiv).css( 'top', resultBoxPosition.top + resultBox.parent().scrollTop() );
	$j(iasearchProcessingDiv).fadeIn('normal', function() { if ($j.browser.msie) this.style.removeAttribute('filter'); } );
}

function iasearch_hide_processing()
{
	$j(iasearchProcessingDiv).hide();
}

function iasearch_cancel_save()
{
	$j(iasearchSaveDiv).hide();
	return false;
}

/**
 * Send the search query to the server and creates result from the returned JSON string.
 */ 
function do_search(s_url, ccount)
{
	//ticket #660 don't do anything if the search is empty or defaulted to 'Search'
	if( $j('#search_field').val().toLowerCase() == 'search' || $j('#search_field').val() == '' ){
		return false;
	}
	
	GAEvent.track('IA Search', 'Search for \''+$j('#search_field').val()+'\'', GAEvent.currentPage);
	
	// show the "in progress" image
	HideExtra();
	$j('#interactive_search_processing').show();
	
	// replace s_url with real service address
	$j.post(s_url, $j('#interactive_search_form').serialize(), processSearchResults, 'json' );
	
	// Close hype and map
	$j('#vicinity_map').height(0).css('');
	$j('#vicinity_01').css({backgroundPosition: 'right top'});
	$j('#hype_selector').height(0);
	$j('#sector_selector_01').css({backgroundPosition: 'right top'});
	
	return false;
}

function processSearchResults( data )
{
  searchResults = data;
  //categoryCount = ccount;
  categoryCount = {
    nightlife: 0,
    food: 0,
    rock: 0,
    roll: 0,
    style: 0,
    gear: 0,
    leisure: 0,
    destinations: 0,
    weekender: 0,
    profiles: 0,
    perks: 0
  };
  $j('#resultsHolder').empty();
  
  // hide the processing div
  $j('#interactive_search_processing').hide();
  ShowExtra();
  
  // Create item template
  var itemTpl = new Template('<div class="resultBox" id="resultBox_#{article_id}" articleName="#{name}" articleUrl="#{url}" articleId="#{article_id}"><h3>#{category}</h3><a href="#{url}" target="_blank" onclick="GAEvent.track(\'IA Search\', \'Click Thumbnail\', #{article_id}, GAEvent.currentPage);"><img src="#{image}" alt="#{name}" /></a><p class="resultText"><a href="#{url}" target="_blank" onclick="GAEvent.track(\'IA Search\', \'Click Business Name\', #{article_id}, GAEvent.currentPage);">#{name}</a><br />#{teaser}</p><p id="saveholder_#{article_id}" class="saveSearchHolder">#{button}</p></div>');
  
  var noResultTpl = new Template('<div class="noResultBox"><p><i>#{search_word}</i><br />No results found.</p></div>');
  
  if (!data || !data.size) {
    /*$j('#resultsHolder').append(noResultTpl.evaluate({
      search_word: $j('#search_field').val()
    }));*/
    $j('#sector_selector, .sector_selector').hide();
  }else {
    // Create result items and add missing data to search result
    hasHypeData = false;
    $j.each(data.articles, function(){
      
      if( this.hypecycle != null ) hasHypeData = true;
      
      // Add category
      this.category = this.category_name;
      
      // Increment category counter
      if (categoryCount[this.category]) {
        categoryCount[this.category]++;
      }
      else {
        categoryCount[this.category] = 1;
      }
      
      // Convert to Date object
      this.dateObj = Date.parseDate(this.date, 'm/d/y H:i:s');
      
      if (this.dateObj < minDate) {
        minDate = this.dateObj;
      }
      
      // Append item
      $j('#resultsHolder').append(itemTpl.evaluate(this));
    });
    
    // don't change map size on the 'hasHypeData' param, because this will cause
    // result filtering before the user sees anything.
    if( !hasHypeData ){
      $j('#sector_selector, .sector_selector').hide();
      // $j('#vicinity_map').height(173);
    }
    else{
      $j('#sector_selector, .sector_selector').show();
      $j('#sector_selector').height(0);
      // $j('#vicinity_map').height(0);
    }
  }
  
  // console.debug(data);
  currentDateVal = minDate.valueOf();
  IASearch.initializeSlider( minDate.valueOf(), maxDate.valueOf());
  
  if( document.getElementById('vicinity_map').resultReady ){
    document.getElementById('vicinity_map').resultReady();
  }
  
  // Enable and disable categories in category filter
  var catTemplate = new Template('(<b><a href="#">#{count}</a></b>)');
  $j.each(categoryCount, function(i, v){
    if( v ){
      $j('#'+i+'_count').html(catTemplate.evaluate({count:v}));
      $j('#check_'+i).removeAttr('disabled').removeClass('disabled');
    }else{
      $j('#'+i+'_count').html('(<b>0</b>)');
      $j('#check_'+i).addClass('disabled').attr({
        disabled: 'disabled'
      });
    }
  });
  $j('#all_count').html(catTemplate.evaluate({count:searchResults.size}));
  $j('#check_all').val(['all']);
  
  $j('#show_result').show();
  $j('#filter_categories').show();
  
  // calibrate heights, these will differ per-browser
  IASearch.sections.categories.height = $j('#'+IASearch.sections.categories.contents).height();
  IASearch.sections.time_range.height = $j('#'+IASearch.sections.time_range.contents).height();
  
  IASearch.hideSectionContents( 'categories', false );
  IASearch.showSectionContents( 'vicinity_map', false );
  
  $j('#resultsHolder').append(noResultTpl.evaluate({
    search_word: $j('#search_field').val()
  }));
  
  if (!data || !data.size) {
    $j('.noResultBox').show();
  }else{
    $j('.noResultBox').hide();
  }
}

/** 
 * This function is called from flash. 
 * It triggers the filter with delay.
 */
function filterChanged(){
	setTimeout(filterResult, 100);
}

/**
 * Returns unfiltered list of search result.
 * It's called by flash.
 */
function getSearchResult(){
	//console.debug( searchResults.articles );
	return searchResults.articles;
}

function mapReady(){
	setTimeout(function(){
		if( searchResults ){
			document.getElementById('vicinity_map').resultReady();
		}
	}, 100);
}

//function fire ajax search
function ajax_search(animatePage)
{
	reset_search_fields();
	
	// show overlay
	$j('#overlay').css('display', 'block').height($j(document).height());
	$j('#overlay').fadeTo('slow', .5);
	
	scrollToIASearch();
	setSearchFieldPosition();
	$j(window).bind('resize', setSearchFieldPosition);
  	
	// show the search box
	$j('#filter_categories').hide();
	$j('#search_category').show();
	$j('#search_field').focus();
}

function searchInProgress()
{
  // we'll check for both the holder div AND the filter_categories div, because only the combo of
  // bother determines search results being up.  
  var answer = ($j("#search_category").css("display")!="block" || $j("#filter_categories").css("display")!="block") ? false : true;
  return answer;
}

function scrollToIASearch()
{
  var topElement = $j('#mainHeadContent');
	if (typeof(topElement.position())=='undefined') topElement = $j('#articleHeadHolder');
	var topOfIASearch = parseInt( topElement.position().top, 10 );
	if (topOfIASearch > -1) scrollWindowTo( 0, topOfIASearch );
}

function setSearchFieldPosition()
{
  var topElement = $j('#mainHeadContent');
	if (typeof(topElement.position())=='undefined') topElement = $j('#articleHeadHolder');
	var leftOfIASearch = parseInt( topElement.position().left, 10 );
	var topOfIASearch = parseInt( topElement.position().top, 10 );
	if (topOfIASearch > -1)
	{
	  $j('#search_category').css( "top", topOfIASearch+"px" );
	  $j('#search_category').css( "left", leftOfIASearch+"px" );
	  $j('#search_category').css( "margin-left", "0" );
	}
}

function scrollWindowTo( x, y )
{
  $j('html').animate({scrollTop: y}, 'normal');

  // scrollTo( x, y );
}

//function shutdown search
function kill_ajax()
{
  Logger.log( "IASearch :: removing assets." );

	$j('#overlay').hide();
	$j('#hidden_all').hide();
	$j('#extra_div').hide();
	$j('#search_category').hide();
	$j('#category_list input').unbind('select');
	
	searchResults = null;
}

function close_ajax()
{
  kill_ajax();
  GAEvent.track('IA Search', 'Click Close', GAEvent.currentPage);
}

function HideExtra()
{
	$j('#extra_div').hide();
	$j('#hidden_all').hide();
	$j('#filter_categories').hide();
}

function ShowExtra()
{
	$j('#extra_div').show();
	//$j('#filter_categories').hide();
	$j('#hidden_all').show();
	$('search_category').style.border='none';
	//$j('#category_list_01').css({backgroundPosition: 'right top'});
}

/* Google Analytics tracking wrapper. */
GAEventObject = function(){};
$j.extend( GAEventObject.prototype,
{
  // disabledSources will permit us to switch tracking on and off for specific components.
  disabledSources: {},
  currentPage: window.location.pathname,
  
  init: function(e)
  {
    GAEvent.log( "init" );
  },
  
  getCurrentPage: function() { return this.currentPage; },
  
  track: function( source, category, action, optional_label, optional_value )
  {
    if (typeof(GAEvent.disabledSources[source])!='undefined') return; 
    GAEvent.log( "track( "+source+", "+category+", "+action+", "+optional_label+", "+optional_value+" )" );
    pageTracker._trackEvent(category, action, optional_label, optional_value);
  },
  
  enableSource: function( source )
  {
    GAEvent.disabledSources[source] = void 0; // generates 'undefined'
  },
  
  disableSource: function( source )
  {
    GAEvent.disabledSources[source] = "1";
  },
  
  log: function( s )
  {
    Logger.log( "GAEvent: " + s );
  }
});
var GAEvent = new GAEventObject();
$j(document).bind('ready', GAEvent.init);

// ensure that the debug console exists
if (window['loadFirebugConsole']) window.loadFirebugConsole(); 
else if (!window['console']) window.console = { info:function(s){}, log:function(s){}, warn:function(s){}, error:function(s){} }

var Logger = 
{
  log: function( s )
	{
		console.log( s );
	}
}