$(window).load(function() {
  var searchbox = $('#main_search');
  function fake_liquid_input_width() {
  //  alert("I'm done resizing for the moment");
    var desired_width = $('div.func_fields').width() - $('img.browse').outerWidth() - $('div.or').outerWidth() - $('#filtered_content').outerWidth() - $('input.go').outerWidth() - 40 - 16 -10;
    //alert(desired_width * .9 );
    searchbox.width(desired_width);
  };
  fake_liquid_input_width();
});

$(document).ready(function() {
  var searchbox = $('#main_search');
  function fake_liquid_input_width() {
  //  alert("I'm done resizing for the moment");
    var desired_width = $('div.func_fields').width() - $('img.browse').outerWidth() - $('div.or').outerWidth() - $('#filtered_content').outerWidth() - $('input.go').outerWidth() - 40 - 16 -10;
    //alert(desired_width * .9 );
    searchbox.width(desired_width);
  };

  var resizeTimer;
  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(fake_liquid_input_width, 100);
  });
  

  $('#search_book').focus(function()  {
    if ( $(this).val() == "Search Inside This Book" ) {
      $(this).val('');
    }
  });

  searchbox.focus(function()  {
 	if ( $(this).val() == "Search" ) {
  	  $(this).val('');
	}
  });
  $('#search').live('submit', function() {
     $.ajax.abort();
     $('#searchProgress').show();
  });
  searchbox.autocomplete({ minLength: 3,
                           open: function(event, ui) { 
			     $(this).autocomplete('widget').css('z-index', 10);
			     $(".ui-tooltip").css("z-index", -1); 
			   },
                           close: function(event, ui) { $(".ui-tooltip").css("z-index", 2); },
			   source: function( request, response ) {
								$.ajax({
									url: "http://msr02mw.muse.jhu.edu/suggest?format=json",
									dataType: "jsonp",
									data: { term: request.term },
									success: function(data) {
								                    response($.map(data, function(item) {
       											var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi");
								                        return {
								                            label: (item.label).replace(regex, "<strong>$1</strong>"),
								                            value: item.value
                        								}
										    })) 
									} 
								});
								 } 
	            })
  .data('autocomplete')._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( '<a>' + item.label + '</a>' )
            .appendTo( ul );
  };
  fake_liquid_input_width();
});




