var RESULT_COLUMNS = 1;
var REQUEST_COUNTER = 0;


function dynamicSearch () {

  var el = document.getElementById( "namenumber" );
  var text = el.value;

  // where the status messages go
  var statusMonitor = document.getElementById( "statusMonitor" );

  // where the result table will go
  var container = document.getElementById( 'resultContent' );
  if ( container == undefined ) {
    return;
  }

  var monitor = document.getElementById( 'ajax_monitor' );

  if ( text.length < MIN_SEARCH_CHAR ) {
    // the search string is too short
    // hide the result panel and the product listing
    clear( monitor );
    clear( $(PROD_LISTING) );
    // hide the product list and display content 
    hideProductList();

    // ignore any ongoing request if any
    ++REQUEST_COUNTER;
    // reset the background color of the input
    el.style.backgroundColor='#ffffff';
    statusMonitor.innerHTML = '';
    return;

  } else {

    statusMonitor.innerHTML = DICTIONARY.s_searching_for +' <em>'+ text +'</em>, '+ DICTIONARY.s_please_wait +'...';
  }

  var thisCounter = ++REQUEST_COUNTER;
  var handler = function( hreq ) {

    if ( REQUEST_COUNTER != thisCounter ) {
      return;
    }

    hideProductList();
    var rt =  hreq.responseText.split( '__boundary__' );
    var data = eval("(" + rt[1] + ")"); 

    if ( data[0] == undefined ) {
      // nothing found
      el.style.backgroundColor='#ff9999';
      statusMonitor.innerHTML = DICTIONARY.s_search_for +' <em>'+ text +'</em> '+ DICTIONARY.s_got_no_products +'.';
      return;

    } else {

      el.style.backgroundColor='#ffffff';
      var colNumber = RESULT_COLUMNS;

      if ( colNumber > data.length ) {
        // don't make more columns that it is needed
        colNumber = data.length;
      }
      
      var res = getResultTable( text, data, colNumber );
     
      statusMonitor.innerHTML = res.hits +' '+ DICTIONARY.s_products_match +' <em>'+ text +'</em>';
    
      clear( monitor );
      clear( $(PROD_LISTING) );
      monitor.appendChild( res.table );

      displayCategoryMatches();
      pageTracker._trackPageview('/searchresult?search=' + text);

    }
  }

  var url = 
    URL_BASE + 'func=search.ajax_search&input='+ text;

  new Ajax.Request( url, { onSuccess: handler } );
}

function getResultTable ( text, data, columns ) {    
  // Build a table containing the search results
  var table = document.createElement( 'table' );
  //table.width = '100%';
  addHeaders( table, columns );

  var totalHits = 0;
  var tr;
  for ( var i=0; data[i] != undefined; ++i ) {
    var row = data[i];

    if ( i % columns == 0 ) {
      tr = table.insertRow(-1);
    }

    var a = document.createElement( 'a' );
    a.innerHTML = row.CATEGORY_NAME;
    a.href = '#';
    Event.observe( a, 'click', 
        function(txt, catnu, catname) {
        return function() {
        searchProducts(txt, catnu, catname)} 
        }(text, row.CATEGORYNU, row.CATEGORY_NAME) );

    var catCell = tr.insertCell(-1);
    catCell.className = 'category';
    catCell.appendChild( a );
    if ( i%2 == 0 ) {
      // stripy table !
      catCell.className = 'category zebra';
    }

    var numCell = tr.insertCell(-1);
    numCell.className = 'number';
    numCell.appendChild( document.createTextNode('('+ row.COUNT +')') );
    if ( i%2 == 0 ) {
      // stripy table !
      numCell.className = 'number zebra';
    }
    totalHits += parseInt(row.COUNT);
  }

  if ( (i % columns) != 0 ) {
    // we need to complete the last row with empty cells
    var emptyCells = columns - (i % columns);

    for ( var ii=0; ii < emptyCells; ++ii ) {

      var dummy1 = tr.insertCell(-1);
      dummy1.className = 'category';
      var dummy2 = tr.insertCell(-1);
      dummy2.className = 'number';
    }
  }

  return {table: table, hits: totalHits};
}


function addHeaders ( table, columns ) {
  // add the 'category' and 'hits' headers to the table
  var tr = table.insertRow(-1);

  for ( var i=0; i<columns; ++i ) {

    var h = tr.insertCell(-1);
    h.colSpan = 2;
    h.className = 'category_hits';

    var left = document.createElement( 'span' );
    left.className = 'stay_left';
    left.innerHTML = DICTIONARY.p_group;

    var right = document.createElement( 'span' );
    right.className = 'stay_right';
    right.innerHTML = DICTIONARY.s_hits;

    h.appendChild( left );
    h.appendChild( right );
  }
}


function searchProducts ( text, catNu, catName, page ) {

  var handler = function ( hreq ) {
    $(PROD_LISTING).innerHTML = hreq.responseText;
    $(PROD_LISTING).style.display = 'inline';
    document.body.style.cursor = 'auto';
    displayProducts();
  }
  var url = URL_SEARCH + '&productname='+ text +'&namenumber='+ text +'&productgroup='+ catNu
    +'&categoryname='+ catName;
  
  if ( undefined != page ) {
    url += '&page='+ page;
  }
  
  document.body.style.cursor = 'wait';
  new Ajax.Request( url, { onSuccess: handler } );
}


function displayProducts () {
  // display the product list div and hide the content div

  var prod = $(PROD_LISTING);
  var newProd = prod.cloneNode(true);
  var content = $('content');
  var newContent = content.cloneNode(true);

  prod.style.display = 'block';
  content.style.display = 'none';

  $$('.hideonsearch').each(function(ele){
    ele.style.display = 'none';
  });
}

function hideProductList () {
  // clear the product list and show the content div
  var prod = $(PROD_LISTING);
  var newProd = prod.cloneNode(true);
  var content = $('content');
  var newContent = content.cloneNode(true);

  prod.style.display = 'none';
  content.style.display = 'block';
  $$('.hideonsearch').each(function(ele){
    ele.style.display = 'block';
  });
}

function hideCategoryMatches() {
  // hide the category list and the ajax search result panels
  $('aUp').style.display='none'; 
  $('aDown').style.display='inline';
  $('ajax_monitor').style.display='none'; 
  $(PROD_LISTING).style.display='none'; 
  hideProductList();
}

function displayCategoryMatches() {
  // unhide the category list and the ajax search result panels
  $('aUp').style.display='inline';
  $('aDown').style.display='none';
  $('resultContent').style.display='inline';
  $('ajax_monitor').style.display='inline';
}

function clear ( element ) {
  // Remove all children of an element
  while ( element.firstChild != undefined ) {
    var e = element.removeChild( element.firstChild );
    clear( e );
  }
}

function db( message ) {

  var d = document.getElementById('debug');
  d.innerHTML += message + '<br>';
}



