﻿/**
 * The Google Search Appliance Auto Complete.
 * @constructor
 * @param {String} searchBoxId
 * @param {String} autoCompleteUrl
 * @param {String} searchPageUrl
 * @param {Boolean} showSalesPitch
 */
function GsaAutoComplete(websiteSection, searchBoxId, searchButtonId, autoCompleteUrl, searchPageUrl, showSalesPitch) {
    this.WebsiteSection = websiteSection;
    this.SearchBox;
    this.SearchBoxId = searchBoxId;
    this.SearchButton;
    this.SearchButtonId = searchButtonId;
    this.AutoCompleteUrl = autoCompleteUrl;
    this.SearchPageUrl = searchPageUrl;
    this.ShowSalesPitch = showSalesPitch;

    return this;
}

/**
 * Initializes the Google Search Appliance Auto Complete.
 */
GsaAutoComplete.prototype.Initialize = function() {
    var instance = this;

    // Enable auto complete functionality for the given textbox.
    instance.SearchBox = $("#" + instance.SearchBoxId).autocomplete(instance.AutoCompleteUrl, {
        autoFill: false,
        cacheLength: 0,
        dataType: "json",
        delay: 400,
        minChars: 2,
        resultsClass: "autocomplete-result",
        selectFirst: false,
        scrollHeight: 237,
        width: instance.GetAutoCompleteWidth(),
        extraParams: {
            "ShowSalesPitch": instance.ShowSalesPitch,
            "WebsiteSection": instance.WebsiteSection
        },
        parse: function(data) {
            var parsed = [];
            // General Suggestions
            if (data.QuerySuggestions !== null) {
                var suggestions = data.QuerySuggestions;
                for (var i = 0; i < suggestions.length; i++) {
                    parsed[parsed.length] = {
                        data: {
                            "Suggestion": suggestions[i],
                            "Type": "QuerySuggestions"
                        },
                        value: suggestions[i],
                        obj: suggestions[i],
                        result: suggestions[i]
                    };
                }
            }

            // Sales Pitch
            if (data.SalesPitchTitle !== null &&
                data.SalesPitchText !== null &&
                data.SalesPitchLinkUrl !== null &&
                data.SalesPitchImageUrl !== null) {
                parsed[parsed.length] = {
                    data: {
                        "SalesPitchTitle": data.SalesPitchTitle,
                        "SalesPitchText": data.SalesPitchText,
                        "SalesPitchLinkUrl": data.SalesPitchLinkUrl,
                        "SalesPitchImageUrl": applicationPath + data.SalesPitchImageUrl,
                        "Type": "SalesPitch"
                    },
                    value: data.SalesPitchLinkUrl,
                    result: data.SalesPitchTitle
                };
            }

            // Link To All Results
            if (data.LinkToAllResults !== null) {
                parsed[parsed.length] = {
                    data: {
                        "LinkToAllResults": data.LinkToAllResults,
                        "Type": "LinkToAllResults",
                        "Query": data.Query
                    },
                    value: data.LinkToAllResults,
                    result: data.Query
                };
            }

            return parsed;
        },
        formatItem: function(data, i, max, term) {
            if (data.Type === "SalesPitch") {
                var html = "<div class=\"autocomplete-item sales-pitch\">";
                html += "<img class=\"float-right\" src=\"" + data.SalesPitchImageUrl + "\">";
                html += "<a href=\"" + data.SalesPitchLinkUrl + "\">" + data.SalesPitchTitle + "</a>";
                html += "<p>" + data.SalesPitchText + "</p>";
                html += "</div>";
                return html;
            } else if (data.Type === "QuerySuggestions") {
                return "<div class=\"autocomplete-item\">" + data.Suggestion + "</div>";
            } else if (data.Type === "LinkToAllResults") {
                return "<div class=\"autocomplete-item link-all-results\"><a href=\"#\" class=\"action-link-next\">" + data.LinkToAllResults + "</a></div>";
            }
        },
        formatResult: function(data) {
            return null;
        }
    });

    // Load search button.
    instance.SearchButton = $("#" + instance.SearchButtonId);

    // Bind auto complete result function.
    instance.SearchBox.result(function(event, data, formatted) {
        if (data.Type === "SalesPitch") {
            instance.SearchBox.unbind("keyup");
            window.location = data.SalesPitchLinkUrl;
        } else if (data.Type === "QuerySuggestions") {
            instance.SearchBox.unbind("keyup");
            window.location = instance.SearchPageUrl + data.Suggestion;
        } else if (data.Type === "LinkToAllResults") {
            instance.SearchBox.unbind("keyup");
            window.location = instance.SearchPageUrl + data.Query;
        }
    });

    // Bind search function on keyup event for SearchBox must be executed after 
    // the auto complete result function. Which is executed on keydown.
    instance.SearchBox.keyup(function(event) {
        instance.Search(event, instance.SearchBox.val());
    });

    // Bind button click function.
    instance.SearchButton.click(function(event) {
        instance.Search(event, instance.SearchBox.val());
    });
}

/**
* Get the auto complete witdh.
* @return {int} The auto complete width
*/
GsaAutoComplete.prototype.GetAutoCompleteWidth = function() {
    var instance = this;
    var autocompleteWidth = $("#" + instance.SearchBoxId).outerWidth();

    // Border left and right.
    var borderLeftWidth = parseInt($("#" + instance.SearchBoxId).css("borderRightWidth"), 10);
    var borderRightWidth = parseInt($("#" + instance.SearchBoxId).css("borderRightWidth"), 10);

    // Calculate the auto complete width.
    autocompleteWidth = autocompleteWidth - borderLeftWidth - borderRightWidth;

    return autocompleteWidth;
}


/**
* Redirects the user to the search engine result page with the search query
* @param {Event} The event
* @param {String} The search query
*/
GsaAutoComplete.prototype.Search = function(event, searchquery) {
    var instance = this;
    var blockSubmit = false;
    switch (event.type) {
        case "click":
            blockSubmit = true;
            window.location = instance.SearchPageUrl + searchquery;
            break;
        case "keydown":
        case "keyup":
            var code = (event.keyCode ? event.keyCode : event.which);
            if (code == 13) {
                blockSubmit = true;
                window.location = instance.SearchPageUrl + searchquery;
            }
            break;
    }

    // Since we trigger a window location change,
    // we must prevent a submit from being triggered.
    $("form").submit(function() {
        if (blockSubmit) {
            return false;
        }
    });
}
