if(document.getElementById("scollBtm")) {
	var oScrollBtm = document.getElementById("scollBtm");
	oScrollBtm.style.visibility = "hidden";
}

var searchBoxText = "";	// Text that will appear in the search box when it is blank
var searchBoxTextColor = "#999999";					// Colour of the text in the text box before the user types anything
var searchBoxTextColorOld = "";						// Used to store the colour of the text when a user types something in the box

/* URL to the PHP page called for receiving suggestions for a keyword*/
var getFunctionsUrl = "/mshop_search/suggest.php?keyword=";
/* URL for seeing the results for the selected suggestion */
var phpHelpUrl="http://www.php.net/manual/en/function.";
/* the keyword for which an HTTP request has been initiated */
var httpRequestKeyword = "";
/* the last keyword for which suggests have been requested */
var userKeyword = "";
/* number of suggestions received as results for the keyword */
var suggestions = 0;
/* the maximum number of characters to be displayed for a suggestion */
var suggestionMaxLength = 30;
/* flag that indicates if the up or down arrow keys were pressed
the last time a keyup event occurred  */
var isKeyUpDownPressed = false;
/* the last suggestion that has been used for autocompleting the keyword */
var autocompletedKeyword = "";
/* flag that indicates if there are results for the current requested keyword*/
var hasResults = false;
/* the identifier used to cancel the evaluation with the clearTimeout method. */
var timeoutId = -1;
/* the currently selected suggestion (by arrow keys or mouse)*/
var position = -1;
/* cache object containing the retrieved suggestions for different keywords */
var oCache = new Object();
/* the minimum and maximum position of the visible suggestions */
var minVisiblePosition = 0;
var maxVisiblePosition = 9;
// when set to true, display detailed error messages
var debugMode = true;
/* the XMLHttp object for communicating with the server */
var xmlHttpGetSuggestions = createXmlHttpRequestObject();

function search_init() {
   // This is to control the little cross in the text search field.
   if(document.getElementById('fieldImgsImg')) {
       document.getElementById('fieldImgsImg').style.display = "none";
   }

   search = document.getElementById('textSearchField');

   // prevent browser from starting the autofill function
   if(search) {
       search.setAttribute("autocomplete", "off");
   }else {
	   return false;
   }

   //attachEventListener(search, "blur", searchBoxBlur, false);
   //attachEventListener(search, "focus", searchBoxFocus, false);

   // Initialise the search box, grab the orignal text colour, assign the new colour and put the default text in.
   //searchBoxTextColorOld = search.style.color;
   //search.style.color = searchBoxTextColor;
   //search.value = searchBoxText;

   // This is to control the little cross in the text search field.
   if(document.getElementById('fieldImgsImg')) {
      cross = document.getElementById('fieldImgsImg');
      cross.style.display = "none";
      attachEventListener(cross, "click", closeSearchResults, false);
      attachEventListener(cross, "mouseover", searchCrossMouseOver, false);
      attachEventListener(cross, "mouseout", searchCrossMouseOut, false);

      // retrieve the input control for the keyword
   	  var oKeyword = search;

      if(document.getElementById("suggestContainer") != null) {
          suggestions = document.getElementById("suggestContainer");
          suggestions.style.visibility = "hidden";
      }else if(document.getElementById("suggestContainerInner") != null) {
          suggestions = document.getElementById("suggestContainerInner");
          suggestions.style.visibility = "hidden";
      }

       // set the timeout for checking updates in the keyword's value
       setTimeout("checkForChanges()", 500);
   }
}

function searchCrossMouseOver() {
   cross = document.getElementById('fieldImgsImg');
   cross.src = "/images/global/searchCross.gif";
}

function searchCrossMouseOut() {
   cross = document.getElementById('fieldImgsImg');
   cross.src = "/images/global/searchCrossUp.gif";
}

function closeSearchResults() {
   // This is to control the little cross in the text search field.
   document.getElementById('fieldImgsImg').style.display = "none";

   search = document.getElementById("textSearchField");
   search.value = "";
   search.value.length = 0;

   // If the user hasn't typed anything in the search box when focus is lost, put the default text back in
   if(search.value.length == 0) {
      search.value = searchBoxText;
      search.style.color = searchBoxTextColor;
   }
}

function searchBoxBlur() {
   // If the user hasn't typed anything in the search box when focus is lost, put the default text back in
   search = document.getElementById("textSearchField");
   if(search.value.length == 0) {
      search.value = searchBoxText;
      search.style.color = searchBoxTextColor;
   }

   // This is to control the little cross in the text search field.
   document.getElementById('fieldImgsImg').style.display = "none";
   hideSuggestions();
}

function searchBoxFocus() {
   // If there isn't anything in the search box or it contains the default text when focus is on the search box, blank the box;
   search = document.getElementById("textSearchField");
   if(search.value.length == 0 || search.value == searchBoxText) {
      search.value = "";
      // This is to control the little cross in the text search field.
      document.getElementById('fieldImgsImg').style.display = "";
   }
   search.style.color = searchBoxTextColorOld;
}

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
   // will store the reference to the XMLHttpRequest object
   var xmlHttp;
   // this should work for all browsers except IE6 and older
   try
   {
      // try to create XMLHttpRequest object
      xmlHttp = new XMLHttpRequest();
   }
   catch(e)
   {
      // assume IE6 or older
      var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
      "MSXML2.XMLHTTP.5.0",
      "MSXML2.XMLHTTP.4.0",
      "MSXML2.XMLHTTP.3.0",
      "MSXML2.XMLHTTP",
      "Microsoft.XMLHTTP");
      // try every prog id until one works
      for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
      {
         try

         {
            // try to create XMLHttpRequest object
            xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
         }
         catch (e) {}
      }
   }

   // return the created object or display an error message
   if (!xmlHttp)
   alert("Error creating the XMLHttpRequest object.");
   else
   return xmlHttp;
}


/* initiate HTTP request to retrieve suggestions for the current keyword */
function getSuggestions(keyword)
{
   /* continue if keyword isn't null and the last pressed key wasn't up or
   down */
   if(keyword != "" && !isKeyUpDownPressed)
   {
      /*
      // check to see if the keyword is in the cache
      isInCache = checkCache(keyword);
      isInCache = false;
      // if keyword is in cache...
      if(isInCache == true)
      {
      // retrieve the results from the cache
      httpRequestKeyword=keyword;
      userKeyword=keyword;
      // display the results in the cache
      displayResults(keyword, oCache[keyword]);
      }
      // if the keyword isn't in cache, make an HTTP request
      else
      {
      */
      if(xmlHttpGetSuggestions)
      {
         try
         {
            /* if the XMLHttpRequest object isn't busy with a previous
            request... */
            if (xmlHttpGetSuggestions.readyState == 4 ||
            xmlHttpGetSuggestions.readyState == 0)
            {
               httpRequestKeyword = keyword;
               userKeyword = keyword;
               xmlHttpGetSuggestions.open("GET",
               getFunctionsUrl + encode(keyword), true);
               xmlHttpGetSuggestions.onreadystatechange = handleGettingSuggestions;
               xmlHttpGetSuggestions.send(null);
            }
            // if the XMLHttpRequest object is busy...
            else
            {
               // retain the keyword the user wanted
               userKeyword = keyword;
               // clear any previous timeouts already set
               if(timeoutId != -1)
               clearTimeout(timeoutId);
               // try again in 0.5 seconds
               timeoutId = setTimeout("getSuggestions(userKeyword);", 500);
            }
         }
         catch(e)
         {
            displayError("Can't connect to server:\n" + e.toString());
         }
      }
      //  }
   }
}

/* transforms all the children of an xml node into an array */
function xmlToArray(resultsXml) {
   // initiate the resultsArray
   var resultsArray= new Array();
   // loop through all the xml nodes retrieving the content
   for(i=0;i<resultsXml.length;i++)
   resultsArray[i]=resultsXml.item(i).firstChild.data;
   // return the node's content as an array
   return resultsArray;
}

/* handles the server's response containing the suggestions
for the requested keyword  */
function handleGettingSuggestions() {
   //if the process is completed, decide what to do with the returned data
   if (xmlHttpGetSuggestions.readyState == 4) {
      // only if HTTP status is "OK"
      if (xmlHttpGetSuggestions.status == 200) {
         try {
            // process the server's response
            updateSuggestions();
         }
         
		 catch(e) {
            // display the error message
            displayError(e.toString());
         }
      }else {
         displayError("There was a problem retrieving the data:\n" +
         xmlHttpGetSuggestions.statusText);
      }
   }
}

function updateSuggestions() {
   // retrieve the server's response
   var response = xmlHttpGetSuggestions.responseText;
   // server error?
   if (response.indexOf("ERRNO") >= 0
   || response.indexOf("error:") >= 0
   || response.length == 0)
   throw(response.length == 0 ? "Void server response." : response);
   // retrieve the document element
   response = xmlHttpGetSuggestions.responseXML.documentElement;
   // initialize the new array of functions' names
   nameArray = new Array();
   linkArray = new Array();
   nameArray2 = new Array();
   linkArray2 = new Array();
   nameArray3 = new Array();
   linkArray3 = new Array();
   nameArray4 = new Array();
   linkArray4 = new Array();

   // check to see if we have any results for the searched keyword
   if(response.childNodes.length) {
      /* we retrieve the predicted words and url's */
      nameArray = xmlToArray(response.getElementsByTagName("presult"));
      linkArray = xmlToArray(response.getElementsByTagName("purl"));
      /* we retreive actual searches people have performed */
      nameArray2 = xmlToArray(response.getElementsByTagName("qresult"));
      linkArray2 = xmlToArray(response.getElementsByTagName("qurl"));
      /* we retreive actual new stories */
      nameArray3 = xmlToArray(response.getElementsByTagName("nresult"));
      linkArray3 = xmlToArray(response.getElementsByTagName("nurl"));
      /* we retreive actual blog stories */
      nameArray4 = xmlToArray(response.getElementsByTagName("bresult"));
      linkArray4 = xmlToArray(response.getElementsByTagName("burl"));
   }
   else if(response.childNodes.length == 0) {
      // No results found
      html = '<table><tr><td><span class="noResults">No results found - Please click on the search button</span></td></tr></table>';
      /*
	  results = document.getElementById("scroll");
      results.innerHTML = html;
      results.style.visibility = 'visible';
      results.style.display = "";
	  */
	  results2 = document.getElementById("scroll");
      results2.innerHTML = html;
      results2.style.visibility = 'visible';
      results2.style.display = "";
      oScrollBtm = document.getElementById("scollBtm");
      oScrollBtm.style.visibility = "visible";
      // Display the X in the search field
      document.getElementById('fieldImgsImg').style.display = "";
      return;
   }

   /* contrcut the drop down list of suggestions */
   html = '<table id="tblsuggestions">';
   if(nameArray.length > 0) {
      html += "<thead><th>Featured Links</th></thead>";
      for(i = 0; i < nameArray.length; i++) {
         html += '<tr><td><a id="a' + i + '" href="' + linkArray[i] + '" onmouseover="handleOnMouseOver(this);" onmouseout="handleOnMouseOut(this);">' + nameArray[i] + '</a></td></tr>';
      }
   }

   if(nameArray2.length > 0) {
      html += "<thead><th>Top Searches</th></thead>";
      for(i = 0; i < nameArray2.length; i++) {
         html += '<tr><td><a href="' + linkArray2[i] + '" onmouseover="handleOnMouseOver(this);" onmouseout="handleOnMouseOut(this);">' + nameArray2[i] + '</a></td></tr>';
      }
   }

   if(nameArray3.length > 0) {
      html += "<thead><th>Latest News Story</th></thead>";
      for(i = 0; i < nameArray3.length; i++) {
         html += '<tr><td><a href="' + linkArray3[i] + '" onmouseover="handleOnMouseOver(this);" onmouseout="handleOnMouseOut(this);">' + nameArray3[i] + '</a></td></tr>';
      }
   }

   if(nameArray4.length > 0) {
      html += "<thead><th>Latest Blog Story</th></thead>";
      for(i = 0; i < nameArray4.length; i++) {
         html += '<tr><td><a href="' + linkArray4[i] + '" onmouseover="handleOnMouseOver(this);" onmouseout="handleOnMouseOut(this);">' + nameArray4[i] + '</a></td></tr>';
      }
   }

   html += "</table>";

   /* display the suggestions */
   results2 = document.getElementById("scroll");
   results2.innerHTML = html;
   results2.style.visibility = 'visible';
   results2.style.display = "";
   //results.innerHTML = 'SOME TROUSERS';


   var ie6 = false;
   if(identifyBrowser() == 'ie6') {
      ie6 = true;
   }

   if(ie6 == true) {
      if (newiframe = document.getElementById('dynamicPopupIFrame')) {
         newiframe.style.width    = parseInt(results2.clientWidth);
         newiframe.style.height   = parseInt(results2.clientHeight);
      } else {
         var newiframe = document.createElement('iframe');
         newiframe.setAttribute('scrolling', 'no');
         newiframe.setAttribute('frameBorder', '0');
         //newiframe.setAttribute('src', '/dynamicPopupIFrame.html');
         newiframe.setAttribute('src', 'javascript:\'<html><html>\';');
         newiframe.setAttribute('id', 'dynamicPopupIFrame');
         newiframe.style.position = 'absolute';
         newiframe.style.display  = 'block';
         newiframe.style.bgColor  = 'transparent';
         newiframe.style.zIndex   = -1;
         newiframe.style.width    = parseInt(results2.clientWidth);
         newiframe.style.height   = parseInt(results2.clientHeight);        
         newiframe.style.top      = 0;
         newiframe.style.left     = 4;
         document.getElementById('suggestContainer').insertBefore(newiframe,document.getElementById('scrolls'));
      }
   }

   oScrollBtm = document.getElementById("scollBtm");
   oScrollBtm.style.visibility = "visible";

   if(document.getElementById("suggestContainer") != null) {
      suggestions = document.getElementById("suggestContainer");
      suggestions.style.visibility = "visible";
   }else if(document.getElementById("suggestContainerInner") != null) {
      suggestions = document.getElementById("suggestContainerInner");
      suggestions.style.visibility = "visible";
   }

   // Display the X in the search field
   document.getElementById('fieldImgsImg').style.display = "";
}

/* function that periodically checks to see if the typed keyword has changed */
function checkForChanges()
{
   // retrieve the keyword object
   var keyword = document.getElementById("textSearchField").value;
   // check to see if the keyword is empty
   if(keyword == "")
   {
      // hide the suggestions
      hideSuggestions();
      // Hide cross
      cross = document.getElementById('fieldImgsImg');
      cross.style.display = "none";
      // reset the keywords
      userKeyword="";
      httpRequestKeyword="";
   }
   // set the timer for a new check
   setTimeout("checkForChanges()", 500);
   // check to see if there are any changes
   if((userKeyword != keyword) &&
   (autocompletedKeyword != keyword) &&
   (!isKeyUpDownPressed))
   // update the suggestions
   getSuggestions(keyword);
}

/* function that handles the keys that are pressed */
function handleKeyUp(e)
{
   // get the event
   e = (!e) ? window.event : e;
   // get the event's target
   target = (!e.target) ? e.srcElement : e.target;
   if (target.nodeType == 3)
   target = target.parentNode;
   // get the character code of the pressed button
   code = (e.charCode) ? e.charCode :
   ((e.keyCode) ? e.keyCode :
   ((e.which) ? e.which : 0));
   // check to see if the event was keyup
   if (e.type == "keyup")
   {
      isKeyUpDownPressed =false;
      // check to see we if are interested in the current character
      if ((code < 13 && code != 8) ||
      (code >=14 && code < 32) ||
      (code >= 33 && code <= 46 && code != 38 && code != 40) ||
      (code >= 112 && code <= 123))
      {
         // simply ignore non-interesting characters
      }
      else
      /* if Enter is pressed we jump to the PHP help page of the current
      function */
      if(code == 13)
      {
         // check to see if any function is currently selected
         if(position>=0)
         {
            location.href = document.getElementById("a" + position).href;
         }
      }
      else
      // if the down arrow is pressed we go to the next suggestion
      if(code == 40)
      {
         newTR=document.getElementById("tr"+(++position));
         oldTR=document.getElementById("tr"+(--position));
         // deselect the old selected suggestion
         if(position>=0 && position<suggestions-1)
         oldTR.className = "";

         // select the new suggestion and update the keyword
         if(position < suggestions - 1)
         {
            newTR.className = "highlightrow";
            updateKeywordValue(newTR);
            position++;
         }
         e.cancelBubble = true;
         e.returnValue = false;
         isKeyUpDownPressed = true;
         // scroll down if the current window is no longer valid
         if(position > maxVisiblePosition)
         {
            oScroll = document.getElementById("scroll");
            oScroll.scrollTop += 18;
            maxVisiblePosition += 1;
            minVisiblePosition += 1;
         }
      }
      else
      // if the up arrow is pressed we go to the previous suggestion
      if(code == 38)
      {
         newTR=document.getElementById("tr"+(--position));
         oldTR=document.getElementById("tr"+(++position));
         // deselect the old selected position
         if(position>=0 && position <= suggestions - 1)
         {
            oldTR.className = "";
         }
         // select the new suggestion and update the keyword
         if(position > 0)
         {
            newTR.className = "highlightrow";
            updateKeywordValue(newTR);
            position--;
            // scroll up if the current window is no longer valid
            if(position<minVisiblePosition)
            {
               oScroll = document.getElementById("scroll");
               oScroll.scrollTop -= 18;
               maxVisiblePosition -= 1;
               minVisiblePosition -= 1;
            }
         }
         else
         if(position == 0)
         position--;
         e.cancelBubble = true;
         e.returnValue = false;
         isKeyUpDownPressed = true;
      }
   }
}

/* function that updates the keyword value with the value
of the currently selected suggestion */
function updateKeywordValue(oTr)
{
   // retrieve the keyword object
   var oKeyword = document.getElementById("textSearchField");
   // retrieve the link for the current function
   var crtLink = document.getElementById("a" +
   oTr.id.substring(2,oTr.id.length)).toString();
   // replace - with _ and leave out the .php extension

   crtLink = crtLink.replace("-", "_");
   crtLink = crtLink.substring(0, crtLink.length - 4);
   // update the keyword's value
   // oKeyword.value = unescape(crtLink.substring(phpHelpUrl.length, crtLink.length));
}

/* function that removes the style from all suggestions*/
function deselectAll()
{
   for(i=0; i<suggestions; i++)
   {
      var oCrtTr = document.getElementById("tr" + i);
      oCrtTr.className = "";
   }
}

/* function that handles the mouse entering over a suggestion's area
event */
function handleOnMouseOver(oTr)
{
   deselectAll();
   oTr.className = "highlightrow";
   position = oTr.id.substring(2, oTr.id.length);
}

/* function that handles the mouse exiting a suggestion's area event */
function handleOnMouseOut(oTr)
{
   oTr.className = "";
   position = -1;
}

/* function that escapes a string */
function encode(uri)
{
   if (encodeURIComponent)
   {
      return encodeURIComponent(uri);
   }

   if (escape)
   {
      return escape(uri);
   }
}

/* function that hides the layer containing the suggestions */
function hideSuggestions()
{
   var oScroll = document.getElementById("scroll");
   oScroll.style.visibility = "hidden";

   oScrollBtm = document.getElementById("scollBtm");
   oScrollBtm.style.visibility = "hidden";

   if(document.getElementById("suggestContainer") != null) {
      suggestions = document.getElementById("suggestContainer");
      suggestions.style.visibility = "hidden";
   }else if(document.getElementById("suggestContainerInner") != null) {
      suggestions = document.getElementById("suggestContainerInner");
      suggestions.style.visibility = "hidden";
   }
}

/* function that selects a range in the text object passed as parameter */
function selectRange(oText, start, length)
{
   // check to see if in IE or FF
   if (oText.createTextRange)
   {
      //IE
      var oRange = oText.createTextRange();
      oRange.moveStart("character", start);
      oRange.moveEnd("character", length - oText.value.length);
      oRange.select();

   }
   else
   // FF
   if (oText.setSelectionRange)
   {
      oText.setSelectionRange(start, length);
   }
   oText.focus();
}

/* function that autocompletes the typed keyword*/
function autocompleteKeyword()
{
   //retrieve the keyword object
   var oKeyword = document.getElementById("textSearchField");
   // reset the position of the selected suggestion
   position=0;
   // deselect all suggestions
   deselectAll();
   // highlight the selected suggestion
   document.getElementById("tr0").className="highlightrow";
   // update the keyword's value with the suggestion
   updateKeywordValue(document.getElementById("tr0"));
   // apply the type-ahead style
   selectRange(oKeyword,httpRequestKeyword.length,oKeyword.value.length);
   // set the autocompleted word to the keyword's value
   autocompletedKeyword=oKeyword.value;
}

/* function that displays an error message */
function displayError(message) {
   // display error message, with more technical details if debugMode is true
   alert("Error accessing the server! "+
   (debugMode ? "\n" + message : ""));
}

// This is to hide the search text in a normal search bar.
function hideSearchText() {
	var searchBarText = document.getElementById('textSearchField');
	if(searchBarText.value == 'Search') {
		searchBarText.value = '';
	}
}

// This is to show the search text in a normal search bar.
function showSearchText() {
	var searchBarText = document.getElementById('textSearchField');
	if(searchBarText.value == '') {
		searchBarText.value = 'Search';
	}
}

// This is to display more info on the Effective monthly cost.
function showEMCInfo() {
	globalPopUp('moreInfoEffectiveMonthlyCost', 300, 300);
}

function emc_init() {
	var moreInfoEMC = document.getElementById('moreInfoEMC');
	attachEventListener(moreInfoEMC, "click", showEMCInfo, false);
}

// hide/show text in normal search bar (without predictive search).
function normalSearch_field() {
	var searchBar = document.getElementById('textSearchField');
	attachEventListener(searchBar, "click", hideSearchText, false);
	attachEventListener(searchBar, "blur", showSearchText, false);
}

addLoadListener(search_init);
if(document.getElementById('moreInfoEffectiveMonthlyCost')) {
	addLoadListener(emc_init);
}

// hide/show text in normal search bar (without predictive search).
if(document.getElementById('normalSearch')) {
	document.getElementById('textSearchField').value = 'Search';
	addLoadListener(normalSearch_field);
}