// Set these to control how results are returned
var slen = 4;                    // Number of chars to start search
var max_results = 15;            // The maximum number of results to display at one time

// Init additional vars
var results = new Array();       // Store the results from JSON in an array
var results_url = new Array();   // Store the urls for each result displayed; these will be created based on the type of result returned.
var sector_order = icon_order;   // List of sector image names in the order they should be displayed.
var dsp_total = 0;               // The total results; sum of array lengths in results
var displayed_results = 0;       // Number of results displayed for current term
var selected_result = -1;        // The id of the currently selected result using arrow keys
var last_result = -1;            // The id of the previously selected result
var curSearchTerm = "";          // Stores current 4-char search term for comparision
var search_results = "";         // Search results container div
var search_results_text = "";    // Search results text div

// Execute on keyup in search box or click on 'go' button
function doSearch(event,obj)
{
    if (typeof(ClickTaleExec) == 'function') {
        var serializedEvent = JSON.stringify(event); 
        ClickTaleExec("doSearch("+serializedEvent+", document.getElementById('"+obj.id+"'))"); // if clicktale exists
    }
    
    // There wasn't a key event, so we must have clicked 'go'. Get regular search results.
    // There is a bug in Mac Firefox that return 0 for certain characters - don't perform the search for 0 values.
    if ( event.type == 'click' && obj.value!="")
    {
        document.location.href = "/search-results/?s=" + obj.value;
        
    }

    // Decide how to handle the key that was pressed
    switch(event.keyCode){
        case 0: // Ignore null values - fix for Mac Firefox
            break;
        case 13: // Execute the search for the selected term
            if (selected_result==-1)
            {
                document.location.href = "/search-results/?s=" + obj.value;
            }
            else
            {
                document.location.href = results_url[selected_result];
            }
            break;
        case 38: // this is the arrow up
            selectUp();
            break;
        case 40: // this is the arrow down
            selectDown();
            break;
        default:
            // Some key other than 'enter', 'up', or 'down' was pressed. Start handling the result set.
            selected_result = -1;
            getSearchResults(obj);
            break;
    }
}

// Select the previous item in the results list
function selectUp()
{
    if (selected_result>=0)
    {
        last_result = selected_result;
        selected_result--;
    }

    if (selected_result>=-1 && selected_result<displayed_results)
    {
        if (selected_result>-1)
        {
            document.getElementById('item-'+selected_result).className = "item_div search_highlight_on";
        }
        document.getElementById('item-'+last_result).className = "item_div search_highlight_off";
    }
}

// Select the next item in the results list
function selectDown()
{
    if (selected_result<displayed_results-1)
    {
        last_result = selected_result;
        selected_result++;
    }

    if (selected_result>=0 && selected_result<displayed_results)
    {
        if (selected_result>0)
        {
            document.getElementById('item-'+last_result).className = "item_div search_highlight_off";
        }
        document.getElementById('item-'+selected_result).className = "item_div search_highlight_on";
    }
}

// Highlight the item moused over
function mouseoverResult(obj)
{
    last_result = selected_result;

    result_parts = obj.id.split("-");
    selected_result = result_parts[1];

    if (last_result>-1)
    {
        document.getElementById('item-'+last_result).className = "item_div search_highlight_off";
    }
    document.getElementById('item-'+selected_result).className = "item_div search_highlight_on";
}

// Go to the URL for the search result clicked
function mouseclickResult(obj)
{
    result_parts = obj.id.split("-");
    selected_result = result_parts[1];
    //alert(results_url[selected_result]);
    document.location.href = results_url[selected_result];
}

// Reset list highlighting if the search box is clicked
function mouseclickInput(obj)
{
    last_result = selected_result;
    selected_result = -1;

    if (obj.value.toLowerCase()=="search")
    {
        obj.value = "";
    }
    
    if (document.getElementById('search_results').style.display=="block")
    {
        document.getElementById('item-'+last_result).className = "item_div search_highlight_off";
    }
    
    last_result = -1;
}

// Get the result set for the current search term
function getSearchResults(obj)
{
    search_results = document.getElementById('search_results');
    search_results_text = document.getElementById('search_results_text');

    if (obj.value.length==slen)
    {
        // Ask for database results only if the term searched is different than the current, stored term. Otherwise, call showResults to use the result set already stored.
        if (dsp_total>0 && obj.value==curSearchTerm)
        {
            showResults(curSearchTerm);
        }
        else
        {
            // create ajax call with search box value
            var url = '/script/ajax/search-bar/search-bar.php';
            var params = 't='+obj.value;
            curSearchTerm = obj.value;
            var mfRequest = new Ajax.Request(url, {method:'post', parameters:params, onComplete:searchResults});
        }
    }
    // The search term is longer than our trigger length, so filter the current result set
    else if (obj.value.length>slen)
    {
        showResults(obj.value);
    }
    // There aren't enough characters to trigger a search, so hide the results
    else if (obj.value.length<slen)
    {
        hideResults();
    }
}

// Handle the JSON data returned through our AJAX call
function searchResults(my_results)
{
    // Assign JSON to the 'results' array
    results = eval("(" + my_results.responseText + ")");

    if(!results['artists']){
        results['artists'] ='';
    }
    
    // Get the total length of all results by adding up the sub-arrays
    dsp_total = results['artists'].length + results['songs'].length + results['games_apps'].length;
    
    // Show the results now that all of the data is ready
    showResults(curSearchTerm);
}

// Write the icon code representing the sector for a song
function outputSector(sector_img,sector_url)
{
    return '<a href="' + sector_url + '"><img class="result_type" src="/template/shared/images/global/' + sector_img + '" /></a>';
}

// Highlight the search term within the result
function highlightVal(val,result_text)
{
    // Trim the text if it's too long before highlighting the term
    if (result_text.length>27)
    {
        rtext = result_text.substring(0,24) + "...";
    }
    else
    {
        rtext = result_text;
    }

    val = result_text.substr(result_text.toLowerCase().indexOf(val.toLowerCase()), val.length);
    var re = new RegExp(val, 'i');

    // Return the result with the term highlighted
    return rtext.replace(re, '<span class="term_highlight">' + val + '</span>');
}

// Output the code for the list of results
function showResults(val)
{
    val = val.toLowerCase();
    results_shown = 0;
    results_url.length = 0; // Reset the url array

    if(!results['artists']){
        results['artists'] ='';
    }

    if(!results['songs']){
        results['songs'] ='';
    }
    
    
    if(!results['games_apps']){
        results['games_apps'] ='';
    }
    
    // Only show the list if the results array is not empty
    if ((results['artists'].length + results['songs'].length + results['games_apps'].length)>0)
    {
        displayed_results = 0;

        var html_output = "";
        var cur_item_name = "";

        // Output artists
        items = results['artists'];
        
        if (items.length>0)
        {
            // Only show the label if there are items to display
            val_found = false;
            for (var i=0; i<items.length; i++)
            {
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].result_text.toLowerCase().indexOf(val)!=-1 || items[i].result_text.toLowerCase().indexOf(val)>0)))
                    {
                        val_found = true;
                    }
                }
            }

            if (val_found) {
                html_output += '<div class="search_results_label">' +
                '<div class="search_results_label_bg"></div>' +
                '<div class="search_results_label_text">' + artists_label + '</div>' +
                '</div>';
            }

            // 
            for (var i=0; i<items.length; i++)
            {
                // Only show up to the max_results limit
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].result_text.toLowerCase().indexOf(val)!=-1 || items[i].result_text.toLowerCase().indexOf(val)>0)))
                    {
                        html_output += '<div class="item_div" id="item-' + displayed_results + '" onmouseover="mouseoverResult(this)" onclick="mouseclickResult(this)">';
                        html_output += highlightVal(val,items[i].result_text);
                        html_output += "</div>\n";
                        results_url[displayed_results] = items[i].result_url;
                        displayed_results++;
                    }
                }
            }
        }

        // Output songs
        items = results['songs'];
        
        if (items.length>0)
        {
            // Only show the label if there are items to display
            val_found = false;
            for (var i=0; i<items.length; i++)
            {
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].title.toLowerCase().indexOf(val)!=-1 || items[i].title.toLowerCase().indexOf(val)>0)))
                    {
                        val_found = true;
                    }
                }
            }
            
            if (val_found) {
                html_output += '<div class="search_results_label">' +
                '<div class="search_results_label_bg"></div>' +
                '<div class="search_results_label_text">' + ringtones_label + '</div>' +
                '</div>';
            }
            
            for (var i=0; i<items.length; i++)
            {
                // Only show up to the max_results limit
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].title.toLowerCase().indexOf(val)!=-1 || items[i].title.toLowerCase().indexOf(val)>0)))
                    {
                        html_output += '<div alt="' + items[i].title + '" title="' + items[i].title + '" class="item_div" id="item-' + displayed_results + '" onmouseover="mouseoverResult(this)" onclick="mouseclickResult(this)"><div class="item_text">';
                        highlight_result = highlightVal(val,items[i].title);
                        html_output += highlight_result;
                        html_output += '</div>';

                        // Output the icons for each sector for this song, limit of two
                        pub_count = 0;
                        if (items[i].publications && pub_count<2)
                        {
                            html_output += '<div class="ringtone_types">';

                            for (sector in sector_order)
                            {
                                var pubs = items[i].publications;
                                for(pub in pubs)
                                {
                                    if (pubs[pub].sector_id == sector) 
                                    {
                                        // Pass the key/val pair (image filename/song URL) to outputSector
                                        html_output += outputSector(pubs[pub].legend_icon,pubs[pub].url);
                                        if (!results_url[displayed_results])
                                        {
                                            results_url[displayed_results] = pubs[pub].url;
                                        }
                                    }
                                }
                            }

                            html_output += '</div>';
                            
                            pub_count++;
                        }

                        html_output += "</div>\n";
                        displayed_results++;
                    }
                }
            }
        }

        
        // Output games and apps
        items = results['games_apps'];

        if (items.length>0)
        {
            // Only show the label if there are items to display
            val_found = false;
            for (var i=0; i<items.length; i++)
            {
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].result_text.toLowerCase().indexOf(val)!=-1 || items[i].result_text.toLowerCase().indexOf(val)>0)))
                    {
                        val_found = true;
                    }
                }
            }
            if (val_found) {
                html_output += '<div class="search_results_label">' +
                '<div class="search_results_label_bg"></div>' +
                '<div class="search_results_label_text">' + games_apps_label + '</div>' +
                '</div>';
            }

            for (var i=0; i<items.length; i++)
            {
                // Only show up to the max_results limit
                if (displayed_results < max_results)
                {
                    if (!val || (val && val.length>=slen && (items[i].result_text.toLowerCase().indexOf(val)!=-1 || items[i].result_text.toLowerCase().indexOf(val)>0)))
                    {
                        html_output += '<div class="item_div" id="item-' + displayed_results + '" onmouseover="mouseoverResult(this)" onclick="mouseclickResult(this)">';
                        html_output += highlightVal(val,items[i].result_text);
                        html_output += "</div>\n";
                        results_url[displayed_results] = items[i].result_url;
                        displayed_results++;
                    }
                }
            }
        }

        html_output += "</div>\n";
          search_results_text.innerHTML = html_output;
    }

    // Display the results div if there are results to show, or hide it if there are none.
    if (dsp_total>0 && displayed_results>0)
    {
        if (search_results.style.display=="none")
        {
            //Effect.SlideDown(search_results,1);
	        search_results.style.display = "block";
        }
    }
    else
    {
        hideResults();
    }
}

// Hide the results div
function hideResults()
{
    if (search_results.style.display!="none")
    {
        //Effect.SlideUp(search_results,1);
	    search_results.style.display = "none";
        search_results_text.innerHTML = "";
    }
}
