var SEARCH_BOX_DEFAULT_TEXT = 'Sök...';

var AJAX_PENDING_TIMER;
var CURRENT_PAGE = 1;
var CURRENT_LIMIT = 16;

var g_nItemsPerPage = 16;

function init( ) 
{

	var sTextBox = $( "#search_val");

	sTextBox.focus( function( ) 
	{
		if( this.value == SEARCH_BOX_DEFAULT_TEXT) 
		{
			this.value = '';
		}
	});
	
	sTextBox.blur( function( ) 
	{
		if( this.value == '') 
		{
			this.value = SEARCH_BOX_DEFAULT_TEXT;
		}
	});
	
	sTextBox.blur( );


	sTextBox.keyup( function( ) 
	{
		var q = $("#search_val").val( );
		if( q == SEARCH_BOX_DEFAULT_TEXT || q == '' || q == undefined || q.length<=3) 
		{
			HideLiveSearch( );
		}
		else 
		{
			clearTimeout( AJAX_PENDING_TIMER);
			CURRENT_PAGE = 1;
			AJAX_PENDING_TIMER = setTimeout( "PerformLiveSearch()",300);
		}
	});
	
	$("#livesearch_result_close_link").click(function() {
		HideLiveSearch();
	});

}

function ShowLoaders( ) 
{
	$( '#ajaxloader').fadeIn( 'fast');

	if( $( '#livesearch').css( 'display') == 'block') 
	{
		var h = $( '#livesearch').height() - 5;
		var w = $( '#livesearch').width() - 45;
		$( '#loader_div').width( w);
		$( '#loader_div').height( h);
		$( '#loader_div p').css( 'margin-top',( h / 2) + 20);
		$( '#loader_div').fadeIn( 'fast');
	}
}

function HideLoaders( ) 
{
	$( '#ajaxloader').fadeOut( 'fast');
	$( '#loader_div').hide();
}

var AJAX_IS_RUNNING = false;


function PerformLiveSearch( ) 
{

	if( AJAX_IS_RUNNING == true) 
	{
		return;
	}

	var query = $("#search_val");
	var q_val = (query.val() && query.val() != SEARCH_BOX_DEFAULT_TEXT) ? query.val() : '';	

	if( q_val == '') 
	{
		return;
	}
	
	AJAX_IS_RUNNING = true;

	$.ajax( {
	  type: 'POST',
		url: '/catalog/search',
		data: {
		  query: q_val,
			output: 'json',
			page: CURRENT_PAGE,
			limit: CURRENT_LIMIT
		},
		timeout:    '5000',
		dataType:   'json',
		beforeSend: function( ) 
		{
			// Before send request
			// Show the loader
			AJAX_IS_RUNNING = true;
			ShowLoaders();
		},
		complete: function( ) 
		{
			// When Sent request
			// Hide the loader
			AJAX_IS_RUNNING = false;
			HideLoaders();
		},
		success: function( data, textStatus) 
		{
			AJAX_IS_RUNNING = false;
			HideLoaders( );
			$( '#livesearch').slideDown( );

			// clear the results
			$( ".livesearch_results dd").remove( );

      // clean up items
      $( '#itemlist li').remove( );
      $( 'body #hiddenresult').remove( );
      $( 'body').append( '<div id="hiddenresult" style="display:none;"></div>');	
			$( '#paging_bottom').remove( );
			$( '#paging_top form').remove( );
			
			if( data['result'].length ) 
			{
				// add the new results (in reverse since the
				// append inserts right after the header and not
				// at the end of the result list
				
				var nResultCount = data[ 'result'].length;
				var nRest = nResultCount % g_nItemsPerPage;
				var nNumPages = (nResultCount - nRest) / g_nItemsPerPage;
				var i = 0;
				var nNextPage = 0;
				for( var page = 1; page <= nNumPages; page++)
				{
				  nNextPage = page * g_nItemsPerPage;
				  var str = "";
				  while( i < nNextPage)
				  {
				    str += DisplayResult( data[ 'result'][ i], data[ 'productpath'], data[ 'imgpath']);
				 
				    i++;
				  }
				  $( '#hiddenresult').append( '<div class="result">'+ str +'</div>');
				}
				
				str = "";
				var restStart = nNumPages * g_nItemsPerPage;
				for( var i = nNumPages * g_nItemsPerPage; i < nRest; i++)
				{
				  str += DisplayResult( data[ 'result'][ i], data[ 'productpath'], data[ 'imgpath']);
				}
				$( '#hiddenresult').append( '<div class="result">'+ str +'</div>');
				
			}
			
			// Pagination at the bottom of LiveSearch panel
			initPagination();
		},
		
		// We're gonna hide everything when get error
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			AJAX_IS_RUNNING = false;
			HideLoaders();
			HideLiveSearch();
		}
	});

}

function DisplayResult( row, productPath, imgPath) 
{

  var output = "<li>";
  
  output += "<div class=\"items-image\">";
  output += "<a id=\"item-link\" href=\""+ productPath + "/"+ row[ 'id'] +"\">";
  output += "<img src=\""+ imgPath + "/" + row[ 'imgPath']+"/"+ row[ 'imgURL'] +"\" class=\"thumb\" alt=\""+ row[ 'name']+"\" />";
  output += "</a>";
  output += "</div>"
  output += row[ 'name'];
  output += "<div class=\"price\">"+ row[ 'price'] + " kr</div>";
  output += "</li>";
  
  return output;
}

/**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the container with the pagination links as a jQuery object
 */
function pageselectCallback(page_index, jq)
{
  var new_content = $( '#hiddenresult div.result:eq('+ page_index  +')').clone();
  
  $( '#itemlist').empty().append( new_content);
  
  $("a#item-link").fancybox({
    'width'       : '75%',
    'height'      : '75%',
    'autoScale'     : false,
    'overlayColor'    : '#FFFFFF',
    'overlayOpacity'  : 0.6,
    'type'        : 'iframe'
  });
  
  return false;
}
           
/** 
 * Callback function for the AJAX content loader.
 */
function initPagination() 
{
  var num_entries = $('#hiddenresult div.result').length;
    
  // Create pagination element
  $("#pagination-clean").pagination( num_entries,   
    {
      num_edge_entries: 2,
      num_display_entries: 8,
      callback: pageselectCallback,
      items_per_page:1,
      prev_text:'«',
      next_text: '»'
    });
}

function HideLiveSearch( ) 
{
	$( '#livesearch').slideUp( );
	$( '#ajaxloader').fadeOut( 'fast');
}

$( document).ready( function( ) 
{
	init( );
});

