var LoopDelay = 300;
var submitted = false;
var searchTimer = null;
var LastSeenValue = null;
var sr = -1;
var CurVal = null;
var ClickedInside = false;
var ResultsCacheArray = new Array();
ResultsCacheArray['q'] = new Array();

function getXmlObj() {
	var xmlhttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function trimString(str) {  
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

String.prototype.trim = trimString;

/**
 * Throughout, whitespace is defined as one of the characters
 *  "\t" TAB \u0009
 *  "\n" LF  \u000A
 *  "\r" CR  \u000D
 *  " "  SPC \u0020
 *
 * This does not use Javascript's "\s" because that includes non-breaking
 * spaces (and also some other characters).
 */

/**
 * Determine whether a node's text content is entirely whitespace.
 *
 * @param nod  A node implementing the |CharacterData| interface (i.e.,
 *             a |Text|, |Comment|, or |CDATASection| node
 * @return     True if all of the text content of |nod| is whitespace,
 *             otherwise false.
 */
function is_all_ws(nod) {
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.data));
}


/**
 * Determine if a node should be ignored by the iterator functions.
 *
 * @param nod  An object implementing the DOM1 |Node| interface.
 * @return     true if the node is:
 *                1) A |Text| node that is all whitespace
 *                2) A |Comment| node
 *             and otherwise false.
 */

function is_ignorable(nod) {
  return (nod.nodeType == 8) || // A comment node
         ((nod.nodeType == 3) && is_all_ws(nod)); // a text node, all ws
}

/**
 * Version of |previousSibling| that skips nodes that are entirely
 * whitespace or comments.  (Normally |previousSibling| is a property
 * of all DOM nodes that gives the sibling node, the node that is
 * a child of the same parent, that occurs immediately before the
 * reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest previous sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_before(sib) {
  while((sib = sib.previousSibling))
    if(!is_ignorable(sib)) 
      return sib;
  return null;
}

/**
 * Version of |nextSibling| that skips nodes that are entirely
 * whitespace or comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest next sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_after(sib) {
  while((sib = sib.nextSibling))
    if(!is_ignorable(sib)) 
      return sib;
  return null;
}

/**
 * Version of |lastChild| that skips nodes that are entirely
 * whitespace or comments.  (Normally |lastChild| is a property
 * of all DOM nodes that gives the last of the nodes contained
 * directly in the reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The last child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function last_child(par) {
  var res = par.lastChild;
  while(res) {
    if(!is_ignorable(res)) 
      return res;
    res = res.previousSibling;
  }
  return null;
}

/**
 * Version of |firstChild| that skips nodes that are entirely
 * whitespace and comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The first child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function first_child(par) {
  var res = par.firstChild;
  while(res) {
    if(!is_ignorable(res)) 
      return res;
    res = res.nextSibling;
  }
  return null;
}

/**
 * Version of |data| that doesn't include whitespace at the beginning
 * and end and normalizes all whitespace to a single space.  (Normally
 * |data| is a property of text nodes that gives the text of the node.)
 *
 * @param txt  The text node whose data should be returned
 * @return     A string giving the contents of the text node with
 *             whitespace collapsed.
 */
function data_of(txt) {
  var data = txt.data;
  // Use ECMA-262 Edition 3 String and RegExp features
  data = data.replace(/[\t\n\r ]+/g, " ");
  if(data.charAt(0) == " ")
    data = data.substring(1, data.length);
  if(data.charAt(data.length - 1) == " ")
    data = data.substring(0, data.length - 1);
  return data;
}

function hiliterow(linkObj) {
  linkObj.parentNode.parentNode.className = 'over';
  linkObj.className = 'over';
}

function faderow(linkObj) {
  linkObj.parentNode.parentNode.className = '';
  linkObj.className = '';
}

function setAutoCompleteOff() {
  if(document.getElementById('q'))
    document.getElementById('q').setAttribute('autocomplete', 'off');
  else
    document.getElementById('q-safari').setAttribute('autocomplete', 'off');
}

function handleBlur() {
  if(ClickedInside)
    return false;
  ClickedInside = false;
  destroyResultsDiv();
  LastSeenValue = null;
  clearTimeout(searchTimer);
  return true;
}

function handleFormSubmit() {
  if(!submitted) {
    q = document.getElementById('q');
    myRD = document.getElementById('resultsDiv');
    if(myRD != null) {
      myList = myRD.childNodes[1];
      if(sr != -1) {
        q.value = myList.childNodes[sr].childNodes[0].data;
        LastSeenValue = q.value;
      }
    destroyResultsDiv();
    }
    q.focus();
    q.select();
    getSearchResults();
  }  
  return submitted;
}

searchLoop = function() {
  q = document.getElementById('q');
  if(q.value.trim() == '')
    destroyResultsDiv();
  else if(q.value != LastSeenValue)
    getSearchResults();
  LastSeenValue = q.value;
  searchTimer = setTimeout('searchLoop()', LoopDelay);
  return true;
}

function getSearchResults() {
  q = document.getElementById('q');
  cc1 = ResultsCacheArray['q'][q.value];
  if(cc1 == null || cc1.length == 0) {
    ResultsCacheArray['q'][q.value] = new Array();
    ResultsCacheArray['q'][q.value]['mejor'] = new Array();
    ResultsCacheArray['q'][q.value]['productos'] = new Array();
    ResultsCacheArray['q'][q.value]['categorias'] = new Array();
    ResultsCacheArray['q'][q.value]['preguntas'] = new Array();
    myXml = getXmlObj();
    myXml.open('POST', '/_sr.php', true);
    myXml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    myXml.send('op=getSearchResults&q=' + encodeURI(q.value.trim()));
    myXml.onreadystatechange = function() {
      if(myXml.readyState == 4)
        eval(myXml.responseText);
    }
  } else
    displaySearchResults(ResultsCacheArray['q'][q.value]);
}

function destroyResultsDiv() {
  if(document.getElementById('resultsDiv') != null) {
    myParent = document.getElementById('resultsDiv').parentNode;
    myParent.removeChild(document.getElementById('resultsDiv'));
  }
  CurVal = null;
  sr = -1;
}

function doClickInside() {
  ClickedInside = true;
}

function displaySearchResults(myArray) {
  myForm = document.getElementById('searchform');
  destroyResultsDiv();
  q = document.getElementById('q');
  if(q.value.trim() != '' && myArray != null && myArray['total'] > 0) {
    CurVal = q.value;
    myRD = document.createElement('div');
    myRD.id = 'resultsDiv';
    if(myRD.attachEvent)
      myRD.attachEvent('onmousedown', doClickInside);
    else
      myRD.addEventListener('mousedown', doClickInside, false);
//    myRD.setAttribute('onmousedown', 'ClickedInside = true;');
    myShadowDiv = document.createElement('div');
    myShadowDiv.id = 'searchshadow';
    myShadowTop = document.createElement('img');
    myShadowMiddle = document.createElement('img');
    myShadowBottom = document.createElement('img');
    myShadowTop.src = '/img/searchresults-shadow-top.png';
    myShadowMiddle.src = '/img/searchresults-shadow.png';
    myShadowMiddle.width = 407;
    myShadowMiddle.height = myArray['height'];
    myShadowMiddle.id = 'shadowmiddle';
    myShadowBottom.src = '/img/searchresults-shadow-bottom.png';
    myShadowBottom.id = 'shadowbottom';
    myShadowDiv.appendChild(myShadowTop);
    myShadowDiv.appendChild(myShadowMiddle);
    myShadowDiv.appendChild(myShadowBottom);
    myRD.appendChild(myShadowDiv);

    myList = document.createElement('ul');
    myList.id = 'searchresults';

    myListItem = document.createElement('li');
//    mySpan = document.createElement('span');
//    mySpan.setAttribute('onmouseover', 'hiliterow(first_child(node_after(this)));');
//    mySpan.setAttribute('onmouseout', 'faderow(first_child(node_after(this)));');

    myText = document.createTextNode('\u00a0');
//    mySpan.appendChild(myText);
    myListItem.appendChild(myText);
    mySublist = document.createElement('ul');
//    mySublist.className = 'todo';
    mySublistItem = document.createElement('li');
//    mySublistItem.setAttribute('onmouseover', 'hiliterow(this);');
//    mySublistItem.setAttribute('onmouseout', 'faderow(this);');

    mySublistItemLink = document.createElement('a');
    mySublistItemLink.href = '/search.php?q=' + encodeURI(q.value);
    mySublistItemLinkImage = document.createElement('img');
    mySublistItemLinkImage.src = '/img/searchresults-todo.gif';
    mySublistItemLinkLabel = document.createTextNode('Mostrar Todo (' + myArray['total'] + ')');
    mySublistItemLink.appendChild(mySublistItemLinkImage);
    mySublistItemLink.appendChild(mySublistItemLinkLabel);
    mySublistItem.appendChild(mySublistItemLink);
    mySublist.appendChild(mySublistItem);
    myListItem.appendChild(mySublist);
    myList.appendChild(myListItem);
    
    myResultsets = new Array({'nombre':'mejor', 'label':'Mejor Resultado'}, {'nombre':'productos', 'label':'Productos'}, {'nombre':'categorias', 'label':'Categorias'}, {'nombre':'preguntas', 'label':'Preguntas Frecuentes'});
    for(j = 0; j < myResultsets.length; j++) {
      if(myArray[myResultsets[j]['nombre']].length > 0) {
        myListItem = document.createElement('li');
//        mySpan = document.createElement('span');
//        mySpan.setAttribute('onmouseover', 'hiliterow(first_child(node_after(this)));');
//        mySpan.setAttribute('onmouseout', 'faderow(first_child(node_after(this)));');
        myText = document.createTextNode('\u00a0');
//        mySpan.appendChild(myText);
        myListItem.appendChild(myText);
        myListItem.className = myResultsets[j]['nombre'];
        mySublist = document.createElement('ul');
        for(i = 0; i < myArray[myResultsets[j]['nombre']].length; i++) {
          mySublistItem = document.createElement('li');
          if(i == 0)
	    mySublistItem.className = 'first';
//            mySublistItem.setAttribute('onmouseover', 'hiliterow(this);');
//            mySublistItem.setAttribute('onmouseout', 'faderow(this);');
          mySublistItemLink = document.createElement('a');
          mySublistItemLink.href = myArray[myResultsets[j]['nombre']][i]['url'];
	  mySublistItemLink.title = myArray[myResultsets[j]['nombre']][i]['nombre'];
          mySublistItemLinkImage = document.createElement('img');
          mySublistItemLinkImage.src = '/img/blank.gif';
          mySublistItemLinkLabel = document.createTextNode(myArray[myResultsets[j]['nombre']][i]['nombre']);
          mySublistItemLink.appendChild(mySublistItemLinkImage);
          mySublistItemLink.appendChild(mySublistItemLinkLabel);
          mySublistItem.appendChild(mySublistItemLink);
          mySublist.appendChild(mySublistItem);
        }
        myListItem.appendChild(mySublist);
        myList.appendChild(myListItem);
      }
    }

    myRD.appendChild(myList);
    myForm.appendChild(myRD);
  }
}  

