/*
 * Copyright 2006, Jeffrey Palm.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Form -> Void
 */ 
function doSearch(f) {
  //
  // the query and possible max price
  //
  var q = f.q.value;
  var maxPrice = parseInt(f.maxPrice.value);
  //
  // The original query, in case we replace it by one of the parts
  //
  var originalQ = q;

  function nonNull(s) {
    return s && s != 'null' && s != '';
  }

  function cnt(arr) {
    return arr ? arr.length : 0;
  }

  function findMatches(q) {
    var re = new RegExp(q,'ig');
    var result = new Array();
    for (type in TYPES2IDS) {
      var ids = getProductIDs(type);
      for (var i=0; i<ids.length; i++) {
        if (!ids[i] || typeof ids[i] == "undefined") continue;
        var p = getProduct(ids[i]);
        var c =  nonNull(p.getName().match(re)) 
          +      nonNull(p.getDescription().match(re)) 
          +      nonNull(p.getSubtitle().match(re));
        if (c>0) {
          if (maxPrice<0 || p.getPrice()<=maxPrice) {
            result.push(new Array(p,c));
          }
        }
      }
    }
    return result;
  }

  var replaceRE = new RegExp('(' + q + ')','ig');
  function rep(s) {
    return s.replace(replaceRE,"<em>$1</em>");
  }
				   
  function formatResult(img,name,desc,link,c) {
    var html = '';
    html += '<table class="searchResult">';
    html += '<tr><td>';
    html += '<a href="' + link + '" border=0>';
    html += '<img width="75"  valign=top src="' + img + '" border=0 />';
    html == '</a>';
    html += '</td><td>';
    html += '<b>' + rep(name) + '</b><br/>';
    //
    // Why is this undefined?
    //
    html += rep(desc);
    if (c) {
      html += '<br/>';
      html += c + ' match';
      if (c != 1) html += 'es';
      html += ' -';
    }
    html += ' ';
    html += '<a href="' + link + '">see more</a>';
    html += '</td></tr>';
    html += '</table>';
    return html;
  }
				     
  function formatHeading(len) {
    var s = '';
    if (!usedOriginalSearch) {
      s += 'There were no results for <b>' + originalQ + '</b><br/>but there';
    } else {
      s += 'There';
    }
    s +=   ' ' + (len != 1 ? 'were' : 'was') + ' ' 
      +    '<em>' + len + '</em>' + ' result' + (len != 1 ? 's' : '') 
      +    ' for <b>' + q + '</b>:<br/>';
    // Leave room for related results
    s += '<div id="relatedResults"></div>';
    s += '<br/>';

    return s;
  }
  //
  // the success array
  //
  var res = findMatches(q);
  //
  // construct the new html
  //
  var html;
  //
  // Whether we used the original search or not
  //
  var usedOriginalSearch = true;
  //
  // If there are no results, try to break the query and choose the
  // highest rated one
  //
  if (res.length == 0) {
    var parts = q.split(" ");
    if (parts && parts.length>1) {
      for (var i=0; i<parts.length; i++) {
        var matches = findMatches(parts[i]);
        if (matches.length > res.length) {
          res = matches;
          q = parts[i];
          usedOriginalSearch = false;
        }
      }
    }
  }
  //
  // Show results, if any
  //
  if (res.length!=0) {
    //
    // order them by price
    //
    res.sort(function (arr1,arr2) {
      var p1 = arr1[0];
      var p2 = arr2[0];
      return p2.getPrice()-p1.getPrice();
    });
    //
    // do the formatting
    //
    html = formatHeading(res.length);
    for (var i=0;i<res.length; i++) {
      var arr = res[i];			
      var p = arr[0];
      var c = arr[1];
      var img = getImageSmallThumb(p.getId());
      var desc = p.getDescription();
      var MAX = 80;
      if (desc.length > MAX)desc = desc.substring(0,MAX-3) + " ...";
      var link = 'javascript:showProduct(' + p.getId() + ')';
      var name = p.getName();
      html += formatResult(img,name,desc,link,c);
    }
    html += '</p>';	
  } else if (q == 'kermie' || q == 'kermit') {
    html = formatHeading(3);
    html += formatResult
      ("images/kermit.png",
       'Kermie!',
       'He\'s happy being green.',
       'http://en.wikipedia.org/wiki/Kermit_the_Frog');
  } else if (q == 'potato' || q == 'potatoes' || q == 'potatos' || q == 'tater') {
    html = formatHeading(3);
    html += formatResult
      ("http://www.jeffpalm.com/spudtrooper/images/spud-left.jpg",
       'Spud T',
       'The best tater of them all!!!!',
       'http://www.spudtrooper.org/');
    html += formatResult
      ("http://www.jeffpalm.com/darthtator/images/darthtator-small.jpg",
       'Darth T',
       'He\'ll take you to the carb side',
       'http://www.darthtater.org/');
    html += formatResult
      ("http://www.jeffpalm.com/princesspotato/images/spud-left.jpg",
       'Princess P',
       'This chick\'s got a nice pair or buns',
       'http://www.princesspotato.org/');
  } else if (q == 'turkey') {
    html = formatHeading(1);
    html += formatResult
      ("http://www.cnn.com/SPECIALS/1999/yearinreview/field.reports/politics/link.george.w.jpg",
       'George W',
       'The biggest turkey of them all',
       'http://www.whitehouse.gov/');
  } else if (q == 'maxwell') {
    html = formatHeading(1);
    html += formatResult("images/maxwell.gif",
			 'Maxilmillian',
			 'Yeah, that\'s him...',
			 'http://www.jeffpalm.com/maxwell');
  } else {
    html = 'Sorry, there were no results for <b>' + q + '</b>.';
  }
  //
  // now show it
  //
  $('searchPage').innerHTML = html;
  showPage('search');

  // Do a related search
  try {
    findRelatedSearches(q);
  } catch (e) {}

  // Record the actual search in an Ajax call
  // This records the date and search and that's all
  try {
    new Ajax.Request('/recordSearch.php?q=' + escape(originalQ) 
                     + "&n=" + escape(res.length)
                     + "&m=" + escape(maxPrice), {
      method: 'post'
          });  
  } catch (e) {}
								      
  return false;
}

function findRelatedSearches(q) {
  new Ajax.Request('/find_related_searches.php?q=' + escape(q), {
    method: 'get',
        onSuccess: function(transport){
        var response = transport.responseText || "no response text";
        //
        // This will be tab separated lines of query '\t' count
        //
        var lines = response.split("\n");
        if (lines && lines.length>0) {
          var el = $('relatedResults');
          var span = $n('span',el);
          span.innerHTML = 'People who search for <em>' + q + '</em> also searched for:';
          
          for (var i=0; i<lines.length && i<3; i++) {
            var line = lines[i];
            var parts = line.split("\t");
            var query = parts[0];
            $n('br',el);
            var a = $n('a',el);
            a.innerHTML = query;
            a.href = '#';
            a.addEventListener("click",doRelatedSearchListener(query),true);
          }
        }
      }
        
    });
}

function doRelatedSearchListener(query) {
  var _query = query;
  return function(e) {
    var f = $('searchForm');
    var input = $('searchFormInput');
    input.value = _query;
    doSearch(f);
  };
}

