// 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


// 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
    hide(divSectionAnswer);
    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);
  }
  searchBoxReference = searchBox;
  
  if (searchBoxReference.value.length < 2) {
    // hide the suggestion since the text typped is too short.
    hide(divSectionAnswer);
    if(timerID != null) {
      clearTimeout(timerID);
    }
  } else {
    if(timerID != null) {
      // clear the previous timer to avoid multiple refresh/ficker!
      clearTimeout(timerID);
    }
    timerID  = setTimeout("performSuggestQA()", 500);
  }
  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) {
    hide(divSectionAnswer);
  } else {
    search = escape(search);

    if (hashAnswer[search] != null) {
      showResult(hashAnswer[search]);
    } else {
      ahah(requestUrl + "?q=" + search, search);
    }
  }
  timerID = null;
} 

// show the result
function showResult(results) {
  divSectionAnswer.innerHTML = results.replace('<a ', '<a target="blank" ');
  show(divSectionAnswer);
}

// 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; 
      }
      hide(divSectionAnswer);
    } else {
      // IE position fit
      var cursorPositionX = event.clientX;
      var cursorPositionY = event.clientY;
      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 {
        hide(divSectionAnswer);
      }
    }
  }
}

// AJAX request
function ahah(url,searchText) {
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = function() {ahahDone(searchText);};
    req.open("GET", url, true);
    req.send(null);
    // IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    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);
  }
}



function errorCallback(result, eventArgs) {
  alert(result._message);
}

// modal window util (TO BE REMOVED, not working in firefox), instead use CallFunctionOnEnter
function modal_onkeydown(panel) 
{
  if(event.keyCode==13 || event.keyCode==27) 
  {
      var _defaultButtonName= getDefautButtonName( event.keyCode==13 ?  "submitButton" : "cancelButton", panel);
      var button = document.getElementById(_defaultButtonName);
      if(button)
      {
          button.click();
      }
  }
}
function getDefautButtonName(className, panel) 
{
    var _defaultButtonName="";
    var children = panel.getElementsByTagName("input");
    for (var i = 0; i < children.length; i++) 
    {
        var child = children[i];
        var btnAction = child.buttonAction;
        if(btnAction == className)
        {
            _defaultButtonName = child.id;
            break;
        }
    }
    return _defaultButtonName;
}

// Util hide and show
function expandcontent(imgContainer, sectionId) {
  var section = document.getElementById(sectionId);
  if (section.style.display === 'none') {
    if (imgContainer != null && imgContainer.tagName == 'IMG') {
      imgContainer.src = 'img/icn/close.gif';
      imgContainer.alt = 'Close';
    }
    section.style.display = 'block';
  } else {
    if (imgContainer != null && imgContainer.tagName == 'IMG') {
      imgContainer.src = 'img/icn/open.gif';
      imgContainer.alt = 'Open';
    }
    section.style.display = 'none';
  }
}


// show/hide one of the 2 section
function flipSection(id1, id2) {
  var section1style = document.getElementById(id1).style;
  var section2style = document.getElementById(id2).style;
  if (section1style.display === 'none') {
    section1style.display = 'block';
    section2style.display = 'none';
  } else {
    section1style.display = 'none';
    section2style.display = 'block';
  }
}

function show(tohide) {
  var obj;
  if (typeof(tohide) === "string") {
    obj = document.getElementById(tohide);
  } else {
    obj = tohide;
  }
  if (obj !== null) {
    obj.style.display = 'block';
  }
}
function hide(tohide) {
  var obj;
  if (typeof(tohide) === "string") {
    obj = document.getElementById(tohide);
  } else {
    obj = tohide;
  }
  if (obj !== null) {
    obj.style.display = 'none';
  }
}


// activate the default button of the section when the user press the enter key
// event: the event (keypress most of the time
// target: the target to be activated when press enter
// cancel: optional the cancel button if the user press escape
function CallFunctionOnEnter(event, target, cancelaction) {
    if (event.keyCode == 13 || event.which == 13) {
      // user press Enter
      if (!(event.srcElement && (event.srcElement.tagName.toLowerCase() == 'textarea')))  {
        if (typeof target === "function") {
          target(); // call the function
          return StopEvent(event);
        } else {
          // invoke the button
          ActivateTarget(target);
          return StopEvent(event);
        }
      }
    } else if (event.keyCode == 27 || event.which == 27) {
      // user press Esc
      if (cancelaction !== 'undefined') {
        ActivateTarget(cancelaction);
        return StopEvent(event);
      }
    }
    return true;
}

// Activate a button or hyperlink
function ActivateTarget(target) {
  var defaultButton = document.getElementById(target);
  if (defaultButton === 'undefined') defaultButton = document.all[target]; 

  if (defaultButton && typeof(defaultButton.click) !== 'undefined') 
  {
    defaultButton.click();
  } else if (defaultButton && defaultButton.href) {
    // hyperlink with javascript
    __doPostBack(defaultButton.id,'')
  }
}

function StopEvent(event) {
  event.cancelBubble = true;
  if (event.stopPropagation) event.stopPropagation();
  return false;
}

function setGlobalMessage(message, wait) {
  if (wait) {
    show('globalMsgWait');
    hide('globalMsgOk');
    document.body.style.cursor = 'wait';
  } else {
    hide('globalMsgWait');
    show('globalMsgOk');
    document.body.style.cursor = 'default';
  }
  var msgElement = document.getElementById('globalMsgText');
  msgElement.innerHTML = message;
  show('globalMsg');
}

function clearGlobalMessage() {
  hide('globalMsg');
  document.body.style.cursor = 'default';
}