/* ============================================================================
** Masterfoods Ajax Search
** Web Matrix, May 2006
** ----------------------------------------------------------------------------
*/

var searchResults;
var lastSearch;
var comment = '';
var searchValue;

var debugOutput;
var req;

var timer = null;
var timerRunning = false;

var popupLeft=0;
var popupTop=0;

/* ----------------------------------------------------------------------------
** AJAX
*/

function debugOut(str) {
  return;
  if(document.getElementById('debugOutputArea')) {
    document.getElementById('debugOutputArea').innerHTML += str;
  }
}

function getQuickResult(searchValue) {
  ret = new Array();
  if(searchResults && searchResults.length > 0) {
    for(var i = 0; i < searchResults.length; i++) {
      if(searchResults[i][1].toLowerCase().indexOf(searchValue.toLowerCase()) != -1) {
        idx = ret.length;
        ret[idx] = new Array();
        ret[idx][0] = searchResults[i][0];
        ret[idx][1] = searchResults[i][1];
        ret[idx][2] = searchResults[i][2];
        ret[idx][3] = searchResults[i][3];
      }
    }
  }
  return ret;
}

// Generate the search request
function submitSearch(from) {
  debugOut("Submit search from element: "+from+"<br/>");
  searchValue = document.getElementById(from).value;
  var blnSpices = "";
  
  if(document.getElementById('spices')) {
    blnSpices = document.getElementById('spices').value;
  }
  
//  if((searchResults && searchResults.length > 0) && searchValue.indexOf(lastSearch) != -1) {
    
//    debugOut("(Quick) Search value: "+searchValue+"<br/>");
//    quickResults = getQuickResult(searchValue);
//    searchOutput(quickResults.length,comment,quickResults);
//  } else {
  
    debugOut("(Full) Search value: "+searchValue+"<br/>");
    ajax_req(baseUrl+'/include/getSearchProducts.asp?strSearch='+searchValue+'&spice='+blnSpices);
//  }
}

// submit request
function ajax_req(url) {
  debugOut("Req URL: "+url+"<br/>");
  if(window.XMLHttpRequest) {
    
    req = new XMLHttpRequest();
    req.onreadystatechange = processReqChange;
    //req.overrideMimeType('text/xml');
    
    try {
      req.open("GET", url, true);
    } catch(e) {
      debugOut('Exception [' + e.message + '] occurred.<br/>');
    }
    req.send(null);
  } else if(window.ActiveXObject) {
  
    //req = new ActiveXObject("Microsoft.XMLHTTP");
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
      req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
      req = false;
      }
    }
    
    if(req) {
      
      req.onreadystatechange = processReqChange;
      
      try {
        req.open("GET", url, true);
      
      } catch(e) {
        alert('failed');
        if(debugOutput) {
          debugOut('Exception [' + e.message + '] occurred.');
        }
      }
       req.send();
    }
  } else {
    alert("Failed to initialise Ajax Object");
  }
}

// result callback
function processReqChange() {
  if(!req) {
    return;
  }
  
  if(req.readyState == 4) {
    
    if(req.status == 200) {
      xmlData = req.responseXML;
      
      var numElements = getNumElements(xmlData);
      
      comment = getComment(xmlData);
      debugOut("<br/>Num Results: " + numElements + "<br/>Comment: "+comment+"<br/>");
      searchResults = getElements(xmlData);
      searchOutput(numElements,comment,searchResults);
      req = null;
    } else {
      // Error output
      debugOut(req.status + " : " + req.responseText);
      req = null;
    }
  }
}

// parse result
function getComment(xml) {
  //if(xml.getElementsByTagName) {
  var comm;
  try {
    var elem = xml.getElementsByTagName('comment');
    if(elem && elem[0]) {
      try {
        comm = elem[0].firstChild.data;
      } catch(e) {}
    }
  } catch(e) { }
  return comm;
}

// get elements > array
function getElements(xml) {
  //if(xml.getElementsByTagName) {
  try {
    var nodes = xml.getElementsByTagName('element');
    var elements = new Array();
    for(var i = 0; i < nodes.length; i++) {
      if(nodes[i].childNodes) {
        var elem = new Array();
        elem[0] = nodes[i].getAttribute('id');
        debugOut("get: "+elem[0]+"<br/>");
        for(var j = 0; j < nodes[i].childNodes.length; j++) {
          child = nodes[i].childNodes.item(j);
          data = (child.firstChild) ? child.firstChild.data : "-";
          if(child.nodeName == 'title') {
            elem[1] = data;
          } else if(child.nodeName == 'location') {
            elem[2] = data;
          } else if(child.nodeName == 'category') {
            elem[3] = data;
          }
        }
        elements[elements.length] = elem;
      }
    }
    return elements;
  } catch(e) { }
  return false;
}

function getNumElements(xml) {
  var numElements = 0;
  //if(xml.getElementsByTagName) {
  try {
    var elem = xml.getElementsByTagName('result');
    if(elem[0]) {
      try {
        numElements = xml.getElementsByTagName('result')[0].getAttribute('elements');
      } catch(e) {}
    }
  } catch(e) {}
  
  return numElements;
}

/* ----------------------------------------------------------------------------
** Auto-complete popup
*/

var onclick_temp = false;
var popup_open = false;


function showPopup() {
  getPopupPosition('search');
  var obj = document.getElementById('popup_box');
  if(obj) {
    obj.style.display = 'block';
    obj.style.top = popupTop + 2;
    obj.style.left = popupLeft - obj.offsetWidth;
  }
  /*
  if(onclick_temp != window.showPopup) {
    onclick_temp = (window.onclick) ? window.onclick : false;
  }
  window.onclick = window.closePopup;
  */
  popup_open = true;
  return true;
}

function closePopup() {
  var obj = document.getElementById('popup_box');
  if(obj) {
    obj.style.display = 'none';
    obj.style.left = "-300px";
    obj.style.top = 0;
    document.getElementById('search').value='';
    lastSearch='';
  }
  /*
  if(onclick_temp != false) {
    window.onclick = onclick_temp;
  }
  */
  popup_open = false;
}

function timerAdjust() {
  if(timerRunning) {
    timerStop();
    timerStart();
  } else {
    timerStart();
  }
}
function timerStop() {
  if(timerRunning) {
    clearTimeout(timer);
  }
  timerRunning = false;
}
function timerStart() {
  if(popup_open) {
    doSearch();
    return;
  }
  timerRunning = true;
  timer = self.setTimeout('doSearch()', 500);
}

function doSearch() {
  timerStop();
  
  if(lastSearch != document.getElementById('search').value && document.getElementById('search').value.length != 0) {
  
    submitSearch('search');
  
    lastSearch = document.getElementById('search').value;
  } else {
    if(document.getElementById('search').value.length == 0) {
      document.getElementById('output_container').innerHTML = '';
      closePopup();
    }
  }
}

function testPopup() {
  if(lastSearch != document.getElementById('search').value) {
    timerStop();
    doSearch();
  } else {
    //window.onclick=false;
    showPopup();
  }
}

function togglePopup() {
  if(popup_open) {
    closePopup();
  } else {
    showPopup();
  }
}

function getPopupPosition(id) {
  obj = document.getElementById(id);
  if(obj) {
    var p;
    var top = 0;
    var left = 0;
    top += obj.offsetHeight;
    left += obj.offsetWidth;
    if(obj.offsetParent) {
      while(obj.offsetParent) {
        left += obj.offsetLeft;
        top  += obj.offsetTop;
        obj = obj.offsetParent;
      }
    } else {
      top = obj.y;
      left = obj.x;
    }
  }

  
  popupTop = top;
  popupLeft = left;
}

function spOn(obj) {
        if(obj) { obj.className = "light"; }
      }
      function spOff(obj, cls) {
        if(obj) { obj.className = cls; }
      }
      
      function searchGo(id, name, location, cat) {
       document.getElementById('search').value = name;
       searchResults = null;
       lastSearch = null;
       //document.location = location + "#"+id;
       document.location = baseUrl + "/products/catalogue/?prodPK=" + id + "&ProdCat=" + cat + "";
        
     }
     
     function HerbsGo() {
       document.getElementById('search').value = searchValue;
       searchResults = null;
       lastSearch = null;
       //document.location = location + "#"+id;
       document.location = baseUrl + "/products/herbs.asp";
        
     }
      
      function searchOutput(num, comment, itemArray) {
        var outputContainer = document.getElementById('output_container');
        // itemArray = (0='id' 1='title' 2='location')
        if(outputContainer) {
          // add rows
          out = '';
          //out = "<b>"+comment+"</b><br/>";
          out += "<table cellpadding='2' cellspacing='1' border='0' class='searchResults' width='100%'>";
          if(num > 0) {
            var cls = '';
            var limit = (num > outputLimit) ? outputLimit : num;
            
            out += "<tr class='odd' onclick='javascript: closePopup();'>";
            out += "<td valign='top' width='12'><img src='/products/images/arrow.gif' alt='' border='0' height='12' width='14'></a></td>";
            out += "<td class='foundText' valign='top' style='color:#D37C50'>Clear Search list</td>";
            out += "</tr>";
            
            if((searchValue=="spice")||(searchValue=="spices")||(searchValue=="herb")||(searchValue=="herbs")){
              ///products/herbs.asp
              cls = (cls == 'even') ? 'odd' : 'even';
              out += "<tr style='cursor:pointer;cursor:hand;' title='Herbs & Spices' class='"+cls+"' onclick='javascript:HerbsGo();' onmouseover='javascript: spOn(this);' onmouseout='javascript:spOff(this,\""+cls+"\");'>";
              out += "<td valign='top' width='12' align='right'><img src='/products/images/arrow.gif' width='14' height='12' alt='' border='0'/></td>";
              out += "<td valign='top' class='foundText'>View Herbs & Spices</td>";
              out += "</tr>";
            }
            
            for(i = 0; i < limit; i++) {
              if(itemArray[i][1].substr(0,25) != itemArray[i][1]) {
                dispText = itemArray[i][1].substr(0,25) + "...";
              } else {
                dispText = itemArray[i][1];
              }
              cls = (cls == 'even') ? 'odd' : 'even';
              out += "<tr style='cursor:pointer;cursor:hand;' title='"+itemArray[i][1]+"' class='"+cls+"' onclick='javascript:searchGo("+itemArray[i][0]+",\""+itemArray[i][1]+"\",\""+itemArray[i][2]+"\",\""+itemArray[i][3]+"\");' onmouseover='javascript: spOn(this);' onmouseout='javascript:spOff(this,\""+cls+"\");'>";
              out += "<td valign='top' width='12' align='right'><img src='/products/images/arrow.gif' width='14' height='12' alt='' border='0'/></td>";
              out += "<td valign='top' class='foundText'>"+dispText+"</td>";
              out += "</tr>";
            }
          } else {
		    out += "<tr class='odd'>";
			out += "<td valign='top' width='12'><img src='/products/images/arrow.gif' alt='' border='0' height='12' width='14'></a></td>";
            out += "<td class='foundText' valign='top' style='color:#D37C50'>0 Matches Found</td>";
			out += "</tr>";
          }
          out += "</table>";
          outputContainer.innerHTML = out;
        }
        
        showPopup();
      }