
// add this to behavior...
function _parseargs( query, delimiter ) {
    var args = new Object(  );
    var pairs = query.split(delimiter);                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        args[argname] = unescape(value);          // Store as a property
        // In JavaScript 1.5, use decodeURIComponent(  ) instead of unescape(  )
    }
    return args;                                  // Return the object
}

function _checkKeyCode(e) {
   //alert(e.keyCode); 
   if (ss.data("open") == 1) {
      // are we trying to navigate the list?
      if (e.keyCode == 38 || e.keyCode == 40) { // jes...
         ci = ss.data("currentIndex");
         if (e.keyCode == 38) ci--;
         if (e.keyCode == 40) ci++;
         
         if (ci <= ss.children().length) {
            ss.children().removeClass("current");
            ss.children(":eq(" + ci + ")").addClass("current");
            ss.data("currentIndex", ci);
         }
         return false;
      }
      
      if (e.keyCode == 27) {
         ss.animate({ height: 'hide'}, 300);
         ss.height(0);
         
         // state ...
         ss.data("open", 0);
         
         return false;
      }								
      
      // we need to trap the enter key	
      if (e.keyCode == 13) {
         if (ss.data("currentIndex") > -1) {
            $("#searchBox").val($.trim(ss.children(":eq(" + ss.data("currentIndex") + ")").data("term")));									
            ss.data("currentIndex", $(this).data("index"));
            ss.animate({ height: 'hide'}, 300);
            ss.height(0);
            
            // state ...
            ss.data("open", 0);
            
            return false;
         } else if (ss.data("open") == 1) {
            // we need to close it and return tru
            ss.animate({ height: 'hide'}, 300);
            ss.height(0);
            
            // state ...
            ss.data("open", 0);                     
         }
      }
   }
   
   return true;   
}


$("document").ready(function() { 
        // set up the search box
        // first position the auto suggest box...
        
        sb = $('#searchBox');
        pos = sb.position();
        offs = sb.offset();
        
        pos.top = pos.top + sb.outerHeight();
        
        
        
        ss = $("#searchSuggestions");
        ss.offset(pos);
        //ss.position(pos);
        ss.width($(sb).outerWidth());
        
        ss.height(0);
        ss.data("open", 0);
        
        ss.data("currentIndex", -1);
        
        if ($.browser.msie) {
         $("#searchBox").keydown(_checkKeyCode);
        } else {
         $("#searchBox").keypress(_checkKeyCode);
        }
        
        $("#searchBox").keyup(function(e) {
                
                
                
                if ($(this).val().length >= 2) {
                        
                        if (!(((e.keyCode < 32) && (e.keyCode != 8)) ||
                            ((e.keyCode >= 33) && (e.keyCode <= 46)) ||
                            ((e.keyCode >= 112) && (e.keyCode <= 123)))) {
                              
                                // populate the suggs
                                getSearchData($(this).val(), ss);
                        } else {
                           return true;
                        }
        
                        if (ss.data("resultCount") > 0) {
                           
                           if (ss.data("open") == 0) {
                                 
                                 ss.css("display", "block");
                                 ss.height(0);
                                 ss.animate({ height: 100 }, 300);
                                 
                                 
                                 // save state
                                 ss.data("open", 1);                               
                           }
                        } else {
                           if (ss.data("open") == 1) {
                                ss.animate({ height: 'hide'}, 300);
                                ss.height(0);
                                
                                // save state
                                ss.data("open", 0);                              
                           }
                        }
                        
                } else {
                        if (ss.data("open") == 1) {
                        
                                ss.animate({ height: 'hide'}, 300);
                                ss.height(0);
                                
                                // save state
                                ss.data("open", 0);
                                
                        }
                }
                
                return true;
        });
        
        // if the search box looses focus ... close the suggs
        $("#searchBox").blur(function() {
                
                ss.animate({ height: 'hide'}, 300);
                ss.height(0);
                
                // state ...
                ss.data("open", 0);
                
                return true;
        });
        
      // we need to add some global code for checking if we are in a search
      // zone ...        
      var searchedon = GetCookie("searchedon");
      
      
      if (searchedon != null) {
         
         // parse the cookie ... the cookie looks like this
         // "location=*" + window.location.path + window.location.search + ";q=" + query + ";" + "start=" + start);
         var args = _parseargs(searchedon, "_$");
         currentLocation = window.location.pathname + window.location.search;
         
         if (args.location != null) if (args.location.charAt(0) == "*") {
            // we are fresh from some results so show the page but remove the *
            // so if we click Back we will still see the results ...
            SetCookie("searchedon", "location=" + args.location.substr(1) + "_$q=" + args.q + "_$" + "start=" + args.start, null, "/");

            // if not this case we are two pages from a result... 
            // We might be on the page we searched from or we might be on a new page. 
            // In the former case we should show the results we left here and reset the search 
            // If the latter case we should clear all memory of a search ...            
         } else if (args.location == currentLocation) { // show the results and reset
            SetCookie("searchedon", null, null, "/");
            DeleteCookie("searchedon");
            showSearchResults(args.q, Number(args.start));
         } else { // forget the search
            SetCookie("searchedon", null, null, "/");
            DeleteCookie("searchedon");
         }
         
      }        

});


function getSearchData(startStr, ss) {

// send the json request ...

$.getJSON("/search/terms?terms.fl=autoSuggest&wt=json&omitHeader=true&terms.prefix=" + startStr.toLowerCase(),
                function(data) {
                        
                        // get the new suggs
                        // clear out the terms -- add the new suggs
                        ss.empty();
                        
                        ss.data("resultCount", 0);
                        ss.data("resultCount", data.terms[1].length);
                        
                        for (i=0; i < data.terms[1].length; i++) {
                                
                                nd = $('<div>');
                                nd.data("term", data.terms[1][i]);
                                nd.data("index", i);
                                suggStr = $('<b>');
                                suggStr.html(data.terms[1][i].substr(startStr.length)); // + "(" + data.terms[1][i+1] + ")")
                                nd.html(startStr).append(suggStr);
                                nd.click(function() {							
                                        // we selected a term!
                                        
                                        $("#searchBox").val($.trim($(this).data("term")));
                                        
                                        ss = $('#searchSuggestions');
                                        ss.data("currentIndex", $(this).data("index"));
                                        ss.animate({ height: 'hide'}, 300);
                                        ss.height(0);
                                        ss.data("open", 0);
                                        
                                });
                                
                                nd.hover(function() {
                                        // mouseover
                                        $(this).addClass("current");
                                }, function() {
                                        // mouseout
                                        $(this).removeClass("current");
                                });
                                
                                ss.append(nd);
                                i++; // skip the count
                        }

                });
}


function showSearchResults(query, start, track) {
   
   if (start == null) { start = 0; }
   if (track == null) { track = false; }
   
   
   
   // get the results from solr
   $.getJSON("/search/select?version=2.2&start=" + start + "&rows=10&fl=*,score&omitHeader=true&qt=standard&wt=json&q=" + query,
      function(data) {
         
         // okay we have some results ...
         term = $("#searchResults h2 span.term");
         term.empty();
         term.html(query);
           
         resultsx = $("#searchResults #results");
         resultsx.empty();
         
         maxScore = data.response.maxScore;
         
         
         resultCount = $("#searchResults div.resultRange span.resultCount");
         resultCount.empty();
         
         resultCount.html(data.response.numFound);
         
         if (start != 0) {
            
            rangeString = $("#searchResults .resultRange span.currentRange");
            rangeString.empty();
            
            rangeString.html((start+1) + "-" + (start+11));
         }
         
      for (i=0; i<data.response.docs.length; i++) {
         doc = data.response.docs[i];
         addResult(resultsx, doc.title_exact, doc.url, doc.description, doc.score, maxScore, start + i + 1);
      }
      
      // we want to intercept the click and set a cookie to allow for
      // state management of the search results window
      // we will save the state for one page away. if the user navigates to
      // more then one page then the results history is lost.
      SetCookie("searchedon", "location=*" + window.location.pathname + window.location.search + "_$q=" + query + "_$" + "start=" + start, null, "/");         

      
      addPager(data.response.numFound, start, 10, query); // resultCount, current start, page size
      
   });
                  
   // show the results on the page
   $("#screen").height($("body").height() + 160);
   $("#screen").css("visibility", "visible");
   
   $("#searchResults").show(200);
   
   if (track) {
       // track the search with a google analytics virtual page view
      _gaq.push(['_trackPageView', '/search?query=' + query]);
   }
}

function closeSearchResults() {

   $("#searchResults").hide();
   $("#screen").css("visibility", "hidden");
   SetCookie("searchedon", null, null, "/");
   DeleteCookie("searchedon");
}


function addResult(results, title, url, description, score, maxScore, index) {
   
   result = $("<div>");
   result.addClass("result");
   urla = $("<a>");
   urla.addClass("arrowLinkGlobal");
   urla.attr("href", url);
   titlediv = $("<div>");
   titlediv.addClass("title");
   scorediv = $("<div>");
   scorediv.addClass("score");
   descdiv = $("<div>");
   descdiv.addClass("description");
   
   stars = "Score: "
   
   starValue = maxScore / 5;
   starCount = Math.round(score / starValue);
   
    stars += starCount + " of 5";
   
   urla.html(title);
   scorediv.html(stars);
   descdiv.html(description);
   
   titlediv.append(index + ". ");
   titlediv.append(urla);
   titlediv.append(scorediv);
   
   result.append(titlediv);  result.append(descdiv);
   
   results.append(result);
}

function addPager(resultCount, start, pageSize, query) {
   
   resultPagerx = $("#resultPager");
   
   numPages = Math.floor(resultCount / pageSize);
   
   if ( ( resultCount % pageSize ) > 0 ) {
      numPages++;
   }
   
   if ( numPages > 10 ) numPages = 10;
   
   
   resultPagerx.empty();
   resultPagerx.append("Pages: ");
   
   for (i=0; i<(numPages); i++) {
      
      aLink = $("<a>");
      aLink.append(i+1);
      
      if ((start >= (i*pageSize))&&((start < ((i+1)*pageSize)))) {
         // this is the page we are on so handler appropo...
         aLink.addClass("current");
         resultPagerx.append(aLink);
      } else {
         aLink.attr("href", "#");
         aLink.data("start", i*pageSize);
         aLink.click(function() {
            showSearchResults(query, $(this).data("start"));
            return false;
         });
      }
      
      resultPagerx.append(aLink);
   }
   
   if (numPages > 1) {
      
      nxtBtn = $("<a>");
      nxtBtn.attr("href", "#");
      nxtBtn.addClass("next");
      
      nxtBtn.click(function() {
         showSearchResults(query, start+pageSize);
         return false;            
      });
      
      resultPagerx.append(nxtBtn);
   }
}


// -->
