// GenoPro 2007 - This file can be copied, modify and distributed as you wish, it's plain and simple Ajax!
// Ajax service to search the GenoPro web site
// Create by JcMorin April 2007

var divSectionAnswer = null; // updated section
var searchBoxReference = null; // reference to the textbox (event sender)
var timerID = null; // callback timer
var hashAnswer = null; // global cache for search answer
var requestUrl = null; // the url of the AJAX server

// search filter parameters
var includeDeveloper = true;
var includeMainSite = true;
var includeHelpCenter = true;
var includeSupport = true;

// add the trim function to all string
String.prototype.trim = function() {
  return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}

// called from the textbox
function suggestQA(searchBox, url, idDivResult, event) {
  if (event.keyCode == 9) {
    // the user press the tab button... hide suggestion
    HideSuggestion();
    return;
  } else if (event.keyCode == 13) {
    // the user press the enter button... go to search page
    searchFor();
    event.cancelBubble = true;
    event.returnValue = false;
    return false;
  } else if (event.keyCode < 20) {
    // avoid flicker on control key such as alt, shift, ctrl
    return;
  }

  if (hashAnswer == null) {
    hashAnswer = new Object(); // hashtable to cache answers
    requestUrl = url;
    divSectionAnswer = document.getElementById(idDivResult);
    searchBox.onclick = performSuggestQA;
  }
  searchBoxReference = searchBox;
  
  if (searchBoxReference.value.length < 2) {
    // hide the suggestion since the text typped is too short.
    divSectionAnswer.style.visibility = 'hidden';
    if(timerID != null) {
      clearTimeout(timerID);
    }
  } else {
    if(timerID != null) {
      // clear the previous timer to avoid multiple refresh/ficker!
      clearTimeout(timerID);
    }
    timerID  = setTimeout("performSuggestQA()", 400);
  }
  return true;
}

// this function is call when the cursor leave the textbox 
function leavingQATextBox(e) {
  if (divSectionAnswer != null) {
    if (e != null && e.explicitOriginalTarget != undefined) {
      // firefox give the exact target hit so loop back until the top parent to see if we are inside the answer section
      var obj = e.explicitOriginalTarget;
      while (obj != null) {
        if (obj == divSectionAnswer) {
          // inside the answer section
          return;
        }
        obj = obj.parentNode; 
      }
      HideSuggestion();
    } else {
      // IE position fit
      var cursorPositionX = event.x;
      var cursorPositionY = event.y;
      var TopLimit = divSectionAnswer.offsetTop;
      var LeftLimit = divSectionAnswer.offsetLeft;
      var RightLimit = divSectionAnswer.offsetWidth + LeftLimit;
      var BottomLimit = divSectionAnswer.offsetHeight + TopLimit;

      // if the click is outside of the section, hide it
      if (TopLimit <= cursorPositionY && BottomLimit >= cursorPositionY && LeftLimit <= cursorPositionX && RightLimit >= cursorPositionX) {
        // inside the answer section
      } else {
        HideSuggestion();
      }
    }
  }
}

// create the context menu of the QA answer section and return the string
function BuildQAMenu() {
  var strMenu = '<div id=idDivMenu><table width=100%><tr><td>Search Result</td><td align=right>Filter ';
  
  strMenu += '<img src="http://www.genopro.com/images/help/Developer-16.gif" title="Search in the developer section" class="QAMenuImg"><input type="checkbox" name="chkDev" value="chkDev"  onclick="QAFilterChange(this);"';
  if (includeDeveloper) {
    strMenu += ' checked'; 
  }
  strMenu += '> <img src="http://www.genopro.com/images/help/Mainsite-16.gif" title="Search in the GenoPro main web site" class="QAMenuImg"><input type="checkbox" name="chkMainSite" value="chkMainSite"  onclick="QAFilterChange(this);" ';
  if (includeMainSite) {
    strMenu += ' checked'; 
  }
  strMenu += '> <img src="http://www.genopro.com/images/help/HelpCenter-16.gif" title="Search in the GenoPro Help Center" class="QAMenuImg"><input type="checkbox" name="chkHelpCenter" value="chkHelpCenter"  onclick="QAFilterChange(this);" ';
    if (includeHelpCenter) {
    strMenu += ' checked'; 
  }
  strMenu += '> <img src="http://www.genopro.com/images/help/Support-16.gif" title="Search in the GenoPro Support forum" class="QAMenuImg"><input type="checkbox" name="chkSupport" value="chkSupport"  onclick="QAFilterChange(this);" ';
    if (includeSupport) {
    strMenu += ' checked'; 
  }
  strMenu += '></td><td><img src="http://www.genopro.com/images/close-windows.gif" onclick="HideSuggestion();" style="float:right" title="Close Suggestions"></td></tr></table></div>';
  
  return strMenu;
}

// hide the suggestion
function HideSuggestion() {
  divSectionAnswer.style.visibility = 'hidden';
}

// trigger when the user change the filter status of the search
function QAFilterChange(chk) {
  if (chk.name == 'chkDev') {
    includeDeveloper = chk.checked;
  } else if (chk.name == 'chkMainSite') {
    includeMainSite = chk.checked;
  } else if (chk.name == 'chkHelpCenter') {
    includeHelpCenter = chk.checked;
  } else if (chk.name == 'chkSupport') {
    includeSupport = chk.checked;
  }
  
  // special, if user exclude ALL type... select them all.
  if (!includeDeveloper && !includeMainSite && !includeHelpCenter && !includeSupport) {
    includeDeveloper = true;
    includeMainSite = true;
    includeHelpCenter = true;
    includeSupport = true;
  } 
  performSuggestQA();
  return true;
}

// perform the search for a question and answer
function performSuggestQA() {
  performSuggestQA2(searchBoxReference.value.trim(), divSectionAnswer);
} 

// perform the search for a question and answer
function performSuggestQA2(search, answer) {
  divSectionAnswer = answer;
  // check in the hashtable
  if (search.length <= 2) {
    divSectionAnswer.style.visibility = "hidden";
  } else {
    search = encodeURI(search);
    if (includeDeveloper && includeMainSite && includeHelpCenter && includeSupport) {
      // no filter, send request as is
    } else {
      // create some filter
      var filter = 0;
      if (!includeDeveloper) {
        filter += 1;
      }
      if (!includeMainSite) {
        filter += 2;
      }
      if (!includeHelpCenter) {
        filter += 4;
      }
      if (!includeSupport) {
        filter += 8;
      }
      search += "&f=" + filter;
    }
    
    if (hashAnswer == null) {
      hashAnswer = new Object(); // hashtable to cache answers
      requestUrl = '/QA.ashx';
    }

    if (hashAnswer[search] != null) {
      showResult(hashAnswer[search]);
    } else {
      ahah(requestUrl + "?q=" + search, search);
    }
  }
  timerID = null;
} 

// show the result
function showResult(results) {
  divSectionAnswer.innerHTML = BuildQAMenu() + results;
  divSectionAnswer.style.visibility = "visible";
}

// AJAX request
function ahah(url,searchText) {
  // native XMLHttpRequest object
  
  if (window.XMLHttpRequest) {
    divSectionAnswer.innerHTML = 'Sending search request...';
    req = new XMLHttpRequest();
    req.onreadystatechange = function() {ahahDone(searchText);};
    req.open("GET", url, true);
    req.send(null);
    // IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    divSectionAnswer.innerHTML = 'Sending search request...';
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = function() {ahahDone(searchText);};
      req.open("GET", url, true);
      req.send();
    }
  }
} 

// AJAX request callback
function ahahDone(searchText) {
  // only if req is "loaded"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      results = req.responseText;
      showResult(results);
      
      // add to the cash
      if (hashAnswer[searchText] == null) {
        hashAnswer[searchText] = results;  
      }
    } else {
      divSectionAnswer.innerHTML="Error: " + req.statusText;
    }
  }
} 

// redirect to the search page for a specific string
function searchFor() {
  if (searchBoxReference != null) {
    document.location.href = 'http://www.genopro.com/search/?q=' + encodeURI(searchBoxReference.value);
  }
}


// other usefull javascript
function toggleDisplay(me){
		if (me.style.display=="none"){
				me.style.display="block";
		}
		else {
			me.style.display="none";
		}
}


