// Autocompleting search box for CIS preview pages
// needs: jquery, jquery-ui, preview-search-box.css
//        and this html structure somewhere in the document
//       <div id="searchbox-container">
//          <form id="preview-form" action="/cis/preview/">
//             <input id="searchbox" type="text" />
//             <input id="searchbox-id" type="hidden" />
//          </form>
//       </div>

// search box 
$(function() {
   var $searchbox = $('#searchbox2').autocomplete({
      source: function(req, respond) {
         $.ajax({
            url: '/cis/autocomplete/',
            dataType: 'json',
            data: { query: req.term, rm: 'Chemical' },
            success: function(response) { respond(response.data) }
         });
      },
      minLength: 4,
      focus: function( event, ui ) {
         $('#searchbox2').val( ui.item.primary );
         return false;
      },
      select: function( event, ui ) {
		  $.fancybox({
			  			'width' : '70%',
						'height' : '80%',
						'href' : '/cis/preview/' + ui.item.id ,
						'type': 'iframe',
						'onComplete' : function(){ $("iframe").focus();},
						'onClosed' : function() { $("#searchbox2").val('').focus(); 
						}

					});
         //$('#preview-form2')
         //   .attr( 'action', '/cis/preview/' + ui.item.id )
          //  .submit();
         return false;
      }
   });

	if ($('#searchbox2').length > 0){
	$('#searchbox2').data( "autocomplete" )._renderItem = function( ul, item ) {
      return $('<li></li>')
         .data('item.autocomplete', item)
         .append('<a><span class="primary">' + item.primary 
            + '</span><br><span class="secondary">' + item.secondary + "</span></a>")
         .appendTo( ul )
   		};
	}
});

