
var Explorer = {

  /**
   * Load
   */
  load: function()
  {
    this._autocomplete();
  },

  /**
   * Observe search box for auto complete
   */
  _autocomplete: function()
  {
    $("#searchTerm").autocomplete("/autocomplete.json", {
      selectFirst: true,
      dataType: "json",
      parse: function(data) {
        return $.map(data, function(row) {
          return {
            data: row,
            value: row.name,
            result: row.name
          };
        });
      },
      formatItem: function(item) {
        if(item.type == 'affiliate')
        {
          return item.name;
        }
        else if(item.type == 'link')
        {
          return item.name + ' - Go To Site';
        }
        else if(item.type == 'zone')
        {
          return item.name + ' - Go To Zone';
        }
      }
    });
    
    
    $("#searchTerm").result(function(event, data, formatted) {
      if(data)
      {
    	$.cookie('CakeCookie[searchTerm]', data.name, { expires:this.cookieExpire, domain:'.gemsta.com', path:'/' });
    	  
        if(data.type == 'zone')
        {
          document.location.href = '/exploremap/'+data.id;
        }
        else if(data.type == 'affiliate')
        {
          var slug = data.name;
          slug = slug.replace(/ \& /g,'_and_');
          slug = slug.replace(/\s/g,'+');
        
          document.location.href = '/search/'+slug;
        }
        else if(data.type == 'link')
        {
          document.location.href = data.url;
        }
      }
    });
  }
  
  
};


$(document).ready(function() {
  var searchdefault = 'What are you searching for?';
	
  Explorer.load();
  
  if ($('#searchTerm').val() == '') $('#searchTerm').val(searchdefault);
  
  $('#searchTerm').bind("focus", function(){
		if ($(this).val() == searchdefault)	$(this).val('');
	}).bind('blur', function(){
		if ($(this).val() == '')	$(this).val(searchdefault);
	});
  
  $('#searchSubmit').bind('click', function() { 
	  if ($('#searchTerm').val() == searchdefault) return false;
  });
  
  $('#resetSearch').bind('click', function() {
	  $('#searchTerm').val(searchdefault);
	  return false;
  });
});


