﻿var fxSearchCookie = "360portal_fxSearch";
var suggestScrollInit = true;
var makeSuggestion = false;

// we need to remove any characters that will interfere
// with the search or suggest feature. Puncuation and 
// the like can all be eliminated
var article_search_char_hash = {
    '<' : '&lt;'
    ,'>' : '&gt;'
    ,'…' : '&hellip;'
    ,'“' : '&ldquo;'
    ,'”' : '&rdquo;'
    ,'‘' : '&lsquo;' 
    ,'’' : '&rsquo;' 
    ,'—' : '&mdash;' 
    ,'–' : '&mdash;' 
    ,'"' : '&quot;'
    ,'!' : ''
    ,';' : ''
    ,':' : ''
    ,'~' : ''
    ,'\\+' : ''
    ,'\\.' : ''
    ,'\\(' : ''
    ,'\\)' : ''
    ,'\\,' : ''
};

/* use jQuery to make autosuggestions as the user types */
$j(document).ready(function(){
   
    //fix IE CSS issues
    var classBrowser = "";
    if ( $j.browser.msie )
    {
        classBrowser = "-IE";
        
        //$j("#SearchResultsContainer div.pager").height(2500);
    }
    
    $j("#SearchAutoSuggestContainer").addClass("SearchAutoSuggestContainerMargin"+classBrowser);    
    
    
    // when the suggest box gets the focus show it
    $j("#SearchAutoSuggest").focus(function() {  
        $j("#SearchAutoSuggestContainer").show('slow');
    });
    
    // when we press ESC hide the suggest box
    $j(document).keydown(function(e) {
        if(e.keyCode == 27)
        {
            $j("#SearchAutoSuggestContainer").hide('fast');            
        }
        
        //IE won't detect the enter key on a keyup
        if ($j.browser.msie && e.keyCode == 13)
        {            
            searchArticles();
        }        
    });
      
  
    //give a small delay after the user finishes typing before we suggest words
    //this will prevent us from shooting past a match since and let's the keyup
    //event keep up with user typing
    $j("#SearchAutoSuggest").typeWatch({ highlight: true, wait: 100, captureLength: 1, callback: autoSuggest });
    
    
    /***************************************************************
     * add a keyup event that will make an ajax call to the server
     * to find the best match based on what you type
     ***************************************************************/  
    $j("#SearchAutoSuggest").live("keyup", function(e)
    {
        makeSuggestion = false;

        //ignore some keys
        switch(e.keyCode)
        {
            case 27: //escape
                return;
                break;
        
            case 13: //enter
                searchArticles();
                return;
                break;
                    
            case 40: //arrow down
                setSuggestToCurrentItem();
                return;
                break;
            
            case 38://arrow up
                setSuggestToCurrentItem();           
                return;
                break;
                
            default:
                makeSuggestion = true;
                break;                          
        }
     
    });
    
    $j("#btnArticleSearch").live("click", function(e)
    {        
        searchArticles();
    });
    
    $j("#SearchAutoSuggestContainer").live("mouseover", function(e)
    {        
        var api = $j("#SearchAutoSuggestResults").scrollable();
        var indx = api.getIndex();
        
        $j(api.getItems()[indx]).removeClass("highlight");
    });

    setSuggestion();
       
});

var autoSuggest = function(SearchAutoSuggest)
{
    if (makeSuggestion)
    {
        $j("#SearchAutoSuggestContainer").show('slow');
                   
        if (hasValue(SearchAutoSuggest))
        {
            suggestWords(SearchAutoSuggest);
        }
    }
}

//take the text of the highlighted suggestion and put it in
//the search box
function setSuggestToCurrentItem()
{
    var api = $j("#SearchAutoSuggestResults").scrollable();
    var indx = api.getIndex();
    $j(api.getItems()[indx]).addClass("highlight");
    $j("#SearchAutoSuggest").attr("value", $j(api.getItems()[indx]).text());
    $j("#SearchAutoSuggestContainer").show('slow');
}
                
/* set the client side suggestion input value */
function setSuggestion(item)
{   
    var doSearch = true;
    
    //if we don't find a value then use our cookie value and search automagically
    if (!hasValue(item))
    {        
        item = getCookieValue(fxSearchCookie);
        if ( $j("#SearchResultsContainer").length == 0 )
        {
            doSearch = false;
        }
    }

    $j("#SearchAutoSuggest").attr("value", item);
      
    if ( doSearch )
    {
        searchArticles();  
    }
}



/* make an ajax request to the server to suggest words to search for */
function suggestWords(srch)
{
    var dt = new Date();
    var match = escape(srch.multiReplace(article_search_char_hash)).singleSpacesOnly().trim();    
    $j.ajax( 
    { 
        type: "POST", 
        url: "/search/Search.aspx", 
        data: "action=suggest" +
                "&match=" + match +
                "&numitems=30" + 
                "&dt=" + dt.getTime(),                
        success: function(message) 
        {            
            if (message.length > 0) 
            {
                // pad some items to make the Arrow Keys work properly.
                // add (Size - 1) items to the end so when we get to
                // the last page we can use the keyboard to reach the very
                // last item.
                message += "<div></div><div></div><div></div><div></div>";
            
                if (suggestScrollInit)
                {
                    $j("#SearchAutoSuggestResults").html("<div class=\"items\">" + message + "</div>");
                    
                    /**************************************************
                     * make the suggestion box scrollable
                     **************************************************/
                    $j("#SearchAutoSuggestResults").scrollable({
                        vertical:true,
                        size: 5,
                        next: 'div.prev',
                        prev: 'div.next',
                        hoverClass: 'highlight',
                        alert: false,
                        onBeforeSeek: function() {
                            var api = $j("#SearchAutoSuggestResults").scrollable();
                            var indx = api.getIndex();
                            if ( $j("#SearchAutoSuggestResults div.items div.highlight").length == 0 )
                            {
                                var api = $j("#SearchAutoSuggestResults").scrollable();
                                $j(api.getItems()[indx]).addClass("highlight");                                
                                return false;
                            }
                        },
                        onSeek: function() {
                            // if we don't have any items selected yet select the first item
                            // otherwise it will always get skipped and they'll have to go                            
                            var api = $j("#SearchAutoSuggestResults").scrollable();
                            var indx = api.getIndex();

                            $j(api.getItems()[indx]).addClass("highlight");
                            //we're moving 1 item at a time, so make sure the items
                            //on either side of the this item are not highlighted
                            $j(api.getItems()[indx-1]).removeClass("highlight");
                            $j(api.getItems()[indx+1]).removeClass("highlight");                           
                        }                        
                    });

                    suggestScrollInit = false;
                }
                else
                {
                    var api = $j("#SearchAutoSuggestResults").scrollable();
                    api.move(api.getIndex()*-1);
                    api.getItemWrap().html(message);
                    api.reload();                    
                }                              
                
                /******************************************************
                 * when we click on a suggested item send its value to
                 * the search box
                 ******************************************************/
                $j("#SearchAutoSuggestResults div.items div").click(function() {                    
                    var stext = $j(this).text();
                    //$j(this).fadeOut().fadeIn();
                    setSuggestion(stext);
                });
            }
        },
        error: function(message, d)
        {
            alert(message + ":" + d);
        }
    });
}

// check to see if we're on the search page first, if not, then go to the search
// page, otherwise run the search
function cbWrapper(url, data, funct)
{
    if( $j("#SearchResultsContainer").length == 0 )
    {
        top.location.href= url;//redirection
    }
    else
    {
        funct(data);
    }
}

/* format the search results and add the paging elements */
function formatSearchResults(message)
{    
    if (message.length > 0)
    {        
        $j("#SearchResults.pager").empty().append(message);
        
        // add pagination to our results
        $j("#SearchResults.pager").pager("div.group", 
        { 
           navAttach: "prepend",
           height: "1000"
        });
    } 
}

/* make an ajax request to the server to suggest words to search for */
function searchArticles()
{    
    var dt = new Date();
    var srch = $j("#SearchAutoSuggest").val().multiReplace(article_search_char_hash).singleSpacesOnly().trim();        
    if (hasValue(srch))
    {
        bakeCookie(fxSearchCookie, srch);
            
        $j("#SearchAutoSuggestContainer").hide('fast');
      
        $j.ajax( 
        { 
            type: "POST", 
            url: "/search/Search.aspx", 
            data: "action=search" + 
                  "&match=" + srch +
                  "&itemsperpage=10" + 
                  "&numpages=5" + 
                  "&dt=" + dt.getTime(),
            success: function(message) 
            {                
                cbWrapper($(this).url, message, formatSearchResults);
            },
            error: function(message, d)
            {
                alert(message + ":" + d);
            }
        });
    }
}

