
$(document).ready(function() {
    SearchWidget.initialize();
});

var SearchWidget = {

    search_input: {},
    search_results: {},
    pop_topics: {},

    initialize: function () {

        //Attach google analytics logging
        $('.sw_banner a').click(function () {
            SearchWidget.tellGoogle($(this), 'Banner');
        });
        $('.sw_pop_topics a').click(function () {
            SearchWidget.tellGoogle($(this), 'Populære emner');
        });



        this.search_input = $("#searchWidget input.phrase");
        this.search_results = $("#searchWidget .sw_results");
        this.pop_topics = $("#searchWidget .sw_pop_topics");

        this.search_input.click(function () {
            $(this).unbind("click").css("color", "#000").val("");
        })

        if (this.search_results.children(":not(img)").size() > 0) {

            this.expandResults();
            this.hidePopularTopics();
            this.search_input.css("color", "#000");

            $("#searchWidget .search_tips li span").tipsy({ gravity: 's' });

            this.search_input.keyup(function (event) {
                SearchWidget.collapseResults();
                SearchWidget.showPopularTopics();
                $(this).unbind("keyup");
            });
        }

    },

    expandResults: function () {
        var _height = $("body").is(".vertical") ? "165px" : $("body").is(".vertical_small") ? "120px" : "140px";
        this.search_results.animate({ height: _height });
    },

    collapseResults: function () {
        this.search_results.animate({ height: "21px" });
        $(".sw_see_more").css("display", "none");
    },

    hidePopularTopics: function () {
        this.pop_topics.css("display", "none");
    },

    showPopularTopics: function () {
        this.pop_topics.css("display", "");
    },

    navigateTo: function (url, logId, title) {
        //register click
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/handlers/RegisterClick.ashx?url=" + url + "&logId=" + logId + "&title=" + title,
            dataType: "json",
            success: function (result) {
                return true;
            },
            error: function (result, ex) {
                return true;
            }
        });
    },

    tellGoogle: function ($a, type) {
        var url = $a.attr('href');
        pageTracker._trackEvent(type, 'Click', url);
    }


};