window.SiteSearch = function() {
  
  this.debug = false;
  this.debugOutput = function(txt) {
    alert(txt);
  };
  
  this.currentResultNum = 1;
  this.currentSearch = null;
  
  this.settings = {
    encoding :  "iso-8859-1",
    fe : "ajax",
    client : "rbs_com",
    host : "search.rbs.com",
    collections : [
      {
        label : "All",
        id   : "rbs_com"
      }
    ]
  };
  
  this.ui = {
    isInternetExplorer : document.all ? true:false,
    queryTextBox : null,
    contentPanel : null,
    heading1 : null,
    heading2 : null,
    createSearchNavigation : false,
    previousButtonText : "<< Previous",
    nextButtonText : "Next >>",
    loadingImageSource : "/images/interface/preloader.gif",
    nextInputImageSource : "/images/interface/next.jpg",
    previousInputImageSource : "/images/interface/previous.jpg",
    noQueryMessage : "Please enter your search terms above.",
    noResultsMessage : "No results found matching the query \"$a\".",
    spellingSuggestionMessage : "Did you mean : ",
    synonymSuggestionMessage : "You could also try : ",
    heading1Text : "Searching in $a",
    heading2Text : "Results matching $a searching in $b"
  };
  
  this.query = {

    setText : function(txt) {
      this.ui.queryTextBox.value = txt;
    },  
    
    getText : function() {
      var rawText = new String(this.ui.queryTextBox.value);
      return rawText.replace(/[{}"';]*/g, "");
    },
    
    currentCollection : null,
    
    getSearchCollectionName : function() {
      var name = "";
      for(var i = 0; i < this.settings.collections.length; i++) {
        if(this.settings.collections[i].id == this.currentCollection) {
          name = this.settings.collections[i].label;
        }
      }
      return name;
    } 
  };
  
  this.query.ui = this.ui;
  this.query.settings = this.settings;
  
  this.addScript = function(url) {  
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  };

  this.submit = function() {    
    return this.submit(null);
  };
  
  this.submit = function(start) {
    if(start == null) {start = 0;}
    var url = "http://" + this.settings.host + "/search?access=p&output=xml_no_dtd&getfields=description&client=";    
    url += this.settings.client + "&proxystylesheet=" + this.settings.fe + "&ie=" + this.settings.encoding + "&oe=" + this.settings.encoding;   
    url += "&start=" + start + "&q=" + this.query.getText() + "&site=" + this.query.currentCollection;
    if(this.debug){this.debugOutput("Debug on"); this.debugOutput("Contacting server via " + url);}
  
    this.clearAll();
    this.setHeadings();
    this.setLoadingStatus();
    this.currentResultNum = start;
    this.addScript(url);
    return false;
  };
  
  this.getNextResults = function() {
    var next = this.currentResultNum + 10;
    this.submit(next);    
  };
  
  this.getPreviousResults = function() {
    var previous = (this.currentResultNum >= 11) ?  this.currentResultNum - 10 : 0;
    this.submit(previous);
  };
  
  this.setHeadings = function() {
    
    if(this.debug){this.debugOutput("Setting headings");}
    
    var heading1 = this.ui.heading1;
    var heading2 = this.ui.heading2;
    
    if(heading1 != null) {
      var h1Text = this.ui.heading1Text.replace("\$a", this.query.getSearchCollectionName());   
      this.removeChildNodes(heading1);
      heading1.appendChild(document.createTextNode(h1Text));
    }
    
    if(heading2 != null) {
      this.removeChildNodes(heading2);
      if(this.query.getText() != ""){
        var h2text = this.ui.heading2Text.replace("\$a", this.query.getText());
        var h2text = h2text.replace("\$b", this.query.getSearchCollectionName());
        heading2.appendChild(document.createTextNode(h2text));
        heading2.style.display = "none";
      }
    }
  };
  
  this.setLoadingStatus = function() {
    if(this.debug){this.debugOutput("Setting loading icon");}
    this.loading = this.ui.contentPanel.appendChild(document.createElement("div"));
    this.loading.style.height = "540px";
    this.loading.style.listStyleImage = "none";
    this.loading.style.listStyleType = "none";
    this.loading.style.textAlign = "center";
    this.loading.style.paddingTop = "200px";
    var loadingImg = this.loading.appendChild(document.createElement("img"));
    loadingImg.setAttribute("src", this.ui.loadingImageSource);
  };

  this.removeChildNodes = function (element) {
    if(element.childNodes.length > 0) {
      var currentChild = element.childNodes.item(0);
      var nextChild;
      while(currentChild){
        nextChild = currentChild.nextSibling;
        element.removeChild(currentChild);
        currentChild = nextChild;
      }
    }
  };
  
  this.setStatusText = function(GSP) {
    
    if(this.debug){this.debugOutput("Setting status text");}
    
    this.ui.statusText = this.ui.contentPanel.appendChild(document.createElement("div"));
    this.ui.statusText.className = "statusText";
    
    var message;
    
    if(GSP.queryDetails.estimatedTotal > 0){
      message = "Results " + GSP.queryDetails.startRecordNum + " to " + GSP.queryDetails.endRecordNum;
      if(GSP.queryDetails.estimatedTotal > 10) message += " of about " + GSP.queryDetails.estimatedTotal;
      message += " matching the query \"" + this.query.getText() + "\".";
    }
    else {
      if(this.query.getText() == ""){
        message = this.ui.noQueryMessage;
      }
      else {
        message = this.ui.noResultsMessage.replace("\$a", this.query.getText());
      }
    } 
    
    this.ui.statusText.appendChild(document.createElement("p")).appendChild(document.createTextNode(message));
    this.loadSuggestions(GSP.spelling, this.ui.spellingSuggestionMessage);
    this.loadSuggestions(GSP.synonyms, this.ui.synonymSuggestionMessage);
  };
  
  this.loadSuggestions = function(ar, message) {
    
    if(this.debug){this.debugOutput("Loading " + ar.length + " suggestions");}
    
    if(ar.length > 0){  
      var cur_item;   
      var suggestion = this.ui.statusText.appendChild(document.createElement("p"));
      suggestion.appendChild(document.createTextNode(message));
      suggestion.id = "spelling";     
      for(var i = 0; i < ar.length; i++){
        cur_item = suggestion.appendChild(document.createElement("a"));
        cur_item.href = "#";
        cur_item.onclick = trySuggestion;
        cur_item.appendChild(document.createTextNode(ar[i].q));
      }
    }
  };
  
  this.createNavigation = function(GSP) {
    
    if(this.debug){this.debugOutput("Creating navigation bar");}
    
    var previousButton;
    var nextButton;
    var pageNum = ((GSP.queryDetails.startRecordNum - 1) / 10) + 1;
    var s = (Math.floor((pageNum-1)/10) * 10) + 1;
    var e = s + 9;
    var epc = GSP.queryDetails.estimatedTotal / 10;
    
    var navigator = this.ui.contentPanel.appendChild(document.createElement("div"));
    navigator.className = "searchNavigation";
    
    if(epc > 1) {
      
      if (GSP.queryDetails.hasPrevious) {
        previousButton = document.createElement("input");
        previousButton.setAttribute('src', this.ui.previousInputImageSource);
        previousButton.setAttribute('alt', this.ui.previousButtonText);
        previousButton.type = 'image';
        previousButton.className = "previous";
        previousButton.onclick = getPreviousResults;
        previousButton.onkeypress = getPreviousResults;
        navigator.appendChild(previousButton);
      }
/*
      if(this.ui.createSearchNavigation) {
        for(var i = s; i <= e && i <= epc; i++){
          anchor = navigator.appendChild(document.createElement("a"));
          anchor.href = "#" + i;
          anchor.title = "go to results page " + i;
          anchor.onclick = changePage;
          anchor.onkeypress = changePage;
          if(i == pageNum){
            anchor.style.fontWeight = "bold";
            anchor.style.textDecoration = "underline";
          }
          anchor.appendChild(document.createTextNode(i));
        }
      }
*/
      if (GSP.queryDetails.hasNext) {
        nextButton = document.createElement("input");
        nextButton.setAttribute('src', this.ui.nextInputImageSource);
        nextButton.setAttribute('alt', this.ui.nextButtonText);
        nextButton.type = 'image';
        nextButton.className = "next";
        nextButton.onclick = getNextResults;
        nextButton.onkeypress = getNextResults;
        navigator.appendChild(nextButton);
      }
    }
  };
  
  this.trackEvent = function(GSP) {
    try {
      var ev1 = _hbEvent("search");
      ev1.keywords = GSP.queryDetails.queryText;
      ev1.results = GSP.queryDetails.estimatedTotal;
      ev1.attr1 = GSP.queryDetails.site;
    }
    catch(e) {}
  };
  
  this.loadKeyMatches = function(GSP) {
    
    if(this.debug){this.debugOutput("Loading " + GSP.keyMatches.length + " key matches");}
    
    if(GSP.keyMatches.length > 0){
    
      var content;
      var item;
      var anchor;
      
      var keyMatches = this.ui.contentPanel.appendChild(document.createElement("div"));
      var top = keyMatches.appendChild(document.createElement("div"));
      top.className = "keyMatchTop";
      top.appendChild(document.createElement("hr"));
      var centre = keyMatches.appendChild(document.createElement("div"));
      centre.className = "keyMatchContent";
      content = centre.appendChild(document.createElement("ul"));
      content.className = "feed";
      content.setAttribute("id", "keyMatchResults");
      var base = keyMatches.appendChild(document.createElement("div"));
      base.className = "keyMatchBase";
      base.appendChild(document.createElement("hr"));
      keyMatches.appendChild(document.createElement("br")).className = "cb";
      
      for(var i = 0; i < GSP.keyMatches.length; i++) {
        item = content.appendChild(document.createElement("li"));
        anchor = item.appendChild(document.createElement("a"));
        anchor.setAttribute("href", GSP.keyMatches[i].url);
        anchor.appendChild(document.createTextNode(GSP.keyMatches[i].title));
        item.appendChild(document.createTextNode(" - (Key Match)"));
      }   
    } 
  };
  
  this.clearAll = function() {
    if(this.debug){this.debugOutput("Clearing all content");}
    this.removeChildNodes(this.ui.contentPanel);
  };

  this.loadResults = function(GSP) {
    var result;
    var listItem;
    var anchor;
    var para;
    var summaryText;
    
    if(this.debug){this.debugOutput("Loading results");}
    
    document.title = "Search";

    this.clearAll();
    this.setStatusText(GSP);
    
    if(GSP.queryDetails.estimatedTotal > 0){
      this.loadKeyMatches(GSP);
      
      if(this.debug){this.debugOutput(GSP.results.length + " results found");}
      
      this.resultsList = this.ui.contentPanel.appendChild(document.createElement("ol"));
      this.resultsList.className = "feed";
      
      for(var i = 0; i < GSP.results.length; i++) {
        result = GSP.results[i];
        if(result.title != "") {
          listItem = this.resultsList.appendChild(document.createElement("li"));
          anchor = listItem.appendChild(document.createElement("h4")).appendChild(document.createElement("a"));     
          anchor.href = result.url;
          anchor.title = result.title;
          if(anchor.innerHTML) {
            anchor.innerHTML = result.title;        
          }
          else {
            
            anchor.appendChild(document.createTextNode(this.cleanText(result.title)));
          }
          para = listItem.appendChild(document.createElement("p"));
          summaryText = (result.description == "") ? result.summary : result.description;
          if(para.innerHTML) {para.innerHTML = summaryText;}
          else{para.appendChild(document.createTextNode(this.cleanText(summaryText)));}
        }
      }
      
      this.createNavigation(GSP);
    }
    else {      
      if(this.debug){this.debugOutput("No results returned");}
    }
    
    if(typeof(this.onLoaded) == "function") this.onLoaded.call();
    
    this.currentSearch = GSP;
    this.trackEvent(GSP);
  };
  
  this.onLoaded = null;
  
  this.cleanText = function(txt) {
    var cleanTxt = txt;
    cleanTxt = cleanTxt.replace(/(<\/?b>)/g, "");
    cleanTxt = cleanTxt.replace(/&amp;/g, "&");
    cleanTxt = cleanTxt.replace(/&#39;/g, "'");
    return cleanTxt;
  };
}

function changePage() { 
  var a = (ie) ? window.event.srcElement : window.event.target;
  var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
  var start = ((parseInt(txt) - 1) * 10);
  search.submit(start);
}

function trySuggestion(e) {
  if(!e) {e = window.event}
  var a = (ie) ? e.srcElement : e.target;
  var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
  search.query.setText(txt);
  search.submit();
}

function getNextResults() {
  search.getNextResults()
}

function getPreviousResults() {
  search.getPreviousResults()
}

function loadSearch(GSP) {
  search.loadResults(GSP)
}