﻿var GoogleSearch = {

    ready: false,
    searches: null,
    translate: null,
    filenames: null,
    more: null,
    groupCount: 0,
    groupHits: 0,
    groupRender: 0,

    init: function() {
        google.setOnLoadCallback(function() {
            GSearch.getBranding($('#googleBranding')[0], google.search.Search.HORIZONTAL_BRANDING);
            $(GoogleSearch.searches.websearch).each(function(i, item) {
                $("#searchResults").append('<div id="searchresult_' + item.id + '">0</div>');
            });

            GoogleSearch.ready = true;
        });
    },

    execute: function(q) {

        GoogleSearch.groupCount = 0;
        GoogleSearch.groupRender = 0;
        GoogleSearch.groupHits = 0;

        $("#searchDropDown").hide();
        $("#searchInfoOverLay").hide();
        $("#googleSearchHeading").hide();
        $("#googleSearchLoader").show();

        $(GoogleSearch.searches.websearch).each(function(i, item) {
            var search = new google.search.WebSearch();
            search.setResultSetSize(GSearch.LARGE_RESULTSET);
            search.setNoHtmlGeneration();
            search.setSearchCompleteCallback({
                target: $("#searchresult_" + item.id),
                search: search,
                searchid: item.id,
                timer: GoogleSearch.timer,
                title: item.title,
                titlecount: item.titlecount,
                text: item.text,
                type: item.type,
                maxhits: item.maxhits,
                urls: item.urls,
                query: q
            }, GoogleSearch.render);

            search.execute(item.url + " " + q);

            GoogleSearch.groupCount++;
        });

        return false;
    },

    render: function() {
        var q = this.query;
        var r = this.search.results;
        var sid = this.searchid;
        var tot = 0;
        var t = this.target;
        var mh = parseInt(this.maxhits);
        var tc = parseInt(this.titlecount);
        var n = false;

        var u = this.urls;
        var uth = this.thumb;
        var ute = this.text;
        var type = this.type;
        var sh = r.length > mh && mh > 0 ? mh : r.length;

        if (type == "calendar") {
            r = $.grep(r, function(n, i) {

                var url = n.unescapedUrl.substring(7);

                if (url.indexOf("?") > -1)
                    url = url.substring(0, url.indexOf("?"));

                var isf = true;

                $.each(u, function() {
                    if (url.toLowerCase() == this.toLowerCase())
                        isf = false;
                });

                return isf;
            });
        }

        t.empty();

        GoogleSearch.groupRender++;

        if (r.length > 0) {

            tot = this.search.cursor.estimatedResultCount;

            t.show();

            GoogleSearch.groupHits++;

            var h = '<dl class="' + this.searchid + ' ' + type + (type == "text" && !ute ? ' bullet' : '') + '"><dt><span>' + this.title + '</span>';

            if (tot > sh)
                h += '<a href="' + GoogleSearch.more + '?t=' + sid + '&q=' + escape(q) + '">' + GoogleSearch.translate.show_all + '</a><em>' + GoogleSearch.translate.showing + sh + GoogleSearch.translate.of + tot + '</em>'
            else
                h += '<em>' + GoogleSearch.translate.showing_all + '</em>';

            h += '<br class="clr" /></dt>';

            $.each(r, function(i, m) {
                var url = m.unescapedUrl;
                var cl = "";

                if (mh == 0 || (mh > 0 && i < mh)) {
                    var id = url.replace(/[^a-z]/g, "") + i;
                    h += '<dd id="' + id + '">';

                    if (type == "documents") {
                        if (url.indexOf('.') > -1)
                            cl = ' class="filelink ' + url.substring(url.lastIndexOf('.') + 1) + '"';
                    } else if (type == "calendar") {

                        cl = ' class="calendar"';

                        var jsonUrl = m.url + "?format=jsonsearch";

                        jsonUrl = jsonUrl.replace("http://www.liko.se/", baseUrl);

                        $.getJSON(jsonUrl, { pid: id }, function(json) {
                            var dd = $("#" + json.id);
                            if (json.date != null) dd.append('<p>' + json.date + '</p>');
                        });

                    }

                    var title = "";
                    var tao;
                    var ta = new Array();

                    if (type == "documents") {
                        tao = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.')).split('_');

                        for (var j = 0; j < tao.length; j++) {
                            if (GoogleSearch.filenames[tao[j]] != null)
                                ta.push(GoogleSearch.filenames[tao[j]]);
                            else
                                ta.push(tao[j]);
                        }

                        title = ta.join(' ');
                    } else {
                        tao = m.title.split(' › ');

                        for (var i = 0; i < tc && i < tao.length; i++) {
                            ta.push(tao[i]);
                        }
                        title = ta.reverse().join(" › ");
                    }

                    h += '<a href="' + url + '"' + cl + '>' + title + '<em>&nbsp;›</em></a>';

                    if (ute)
                        h += '<p>' + m.content + '</p>';

                    h += '</dd>';
                }
            });

            if (tot > sh)
                h += '<dd class="all-results"><a href="' + GoogleSearch.more + '?t=' + sid + '&q=' + escape(q) + '">' + GoogleSearch.translate.show_all_of + tot + GoogleSearch.translate.show_all_of_results + '</a></dd>';

            t.append(h + "</dl>");

        }
        else
            t.hide();


        $("dd:not(.all-results) a:not(.filelink)", t).mouseenter(function() {

            var pos = $(this).offset();
            var jsonUrl = this.href + "?format=jsonsearch";
            jsonUrl = jsonUrl.replace("http://www.liko.se/", baseUrl);

            $.getJSON(jsonUrl, function(json) {
                var html = "";

                if (json.image != null || json.text != null) {
                    html += "<div class='content'>";

                    if (json.image != null)
                        html += "<div class='text-content'>";

                    html += "<h1>" + json.title;

                    if (json.byline != null)
                        html += "<em>" + json.byline + "</em>";

                    html += "</h1>";
                }

                if (json.text != null)
                    html += json.text + ((json.image != null) ? '</div>' : "");

                if (json.image != null)
                    html += "<img src='" + json.image + "' /><br class='clr' />";

                if (html.length > 0) {
                    html += "</div><div class='overlay-footer-shadow'></div>";

                    $("#searchInfoOverLay")
                        .css({ "position": "absolute", "left": (pos.left) + "px", "top": (pos.top + 20) + "px" })
                        .html(html)
                        .show();
                }

            });
        }).mouseleave(function() {
            $("#searchInfoOverLay").hide();
        });

        if (GoogleSearch.groupRender == GoogleSearch.groupCount) {

            var c = t.parent().parent();

            if (GoogleSearch.groupHits == 0) {               
                $('h4.no-hits', c).remove(); // remove previous                    
                c.prepend('<h4 class="no-hits">' + GoogleSearch.translate.no_results + '</h4>');                
                //t.show();
            }
            else
                $("h4.no-hits", c).remove()
            
            // add search query...
            $("#googleSearchHeading .query").html(q);
            
            // delay
            setTimeout(function()
            {            
                $("#searchDropDown").show();
                $("#googleSearchLoader").hide();                                
                
                if (GoogleSearch.groupHits != 0) {
                    $("#googleSearchHeading").fadeIn("slow");                        
                }
            }, 1000);                                                            

        }
    },

    delay: function(c, m) {
        clearTimeout(this.timer);
        this.timer = setTimeout(c, m);
    }
};

GoogleSearch.init();