/*global trans, jQuery*/
(function (trans, jQuery, body) {

    //private
    var yql = {
        address: "http://query.yahooapis.com/v1/public/yql?callback=trans.yqlGet&format=json&q=",
        perPage: 10,

        queryPattern: "select title, abstract, url from search.web({{current}}, {{perPage}}) " +
                "where query = 'site:www.transplantation-verstehen.de {{term}}' and appid = 'www.transplantation-verstehen.de'",

        parentNode: jQuery("#content"),

        templates: {
            count: 'Angezeigt werden die Ergebnisse {{start}} bis {{end}}.',
            page:
                    '<div class="tab-navigation"><ul><li class="active">' +
                    '<a class="cursor-default"><span>Transplantation verstehen | Suchergebnisse' +
                    '</span></a></li></ul></div><div class="content-container">' +
                    '<table class="text-content"><tr><td class="text-content-left">' +
                    '<div class="text"><p class="content">Ihre Suche nach ' +
                    '<strong>"{{term}}"</strong> {{process}}<br/><br/>{{count}}</p>' +
                    '<ul class="search-results">{{results}}</ul></div></td>' +
                    '<td class="text-content-right"><div class="teaser"><h1>Neue Suche</h1>' +
                    '<div class="border-top"><form class="search" id="fakesearch"><div>' +
                    '<input name="search_query" class="text" type="text"value="{{term}}"/>' +
                    '<a class="button more"><span>Suche</span></a></div></form></div></div></td>' +
                    '</tr><tr><td colspan="2"><div class="info search-nav">{{prev}}{{next}}</div>' +
                    '</td></tr></table></div>',
            prev: '<a class="button back"><span>Zur&uuml;ck</span></a>',
            processDone: 'wurde geladen.',
            processLoading: 'wird geladen...',
            processNoResults: 'ergab keine Ergebnisse.',
            next: '<a class="button more"><span>Weiter</span></a>',
            result: '<li><a href="{{url}}" class="double-arrow">{{title}}</a><br />' +
                    '<p>{{abstract}}</p></li>'
        },

        //if !data then isLoading === true
        process: function (data) {
            var count, item, resultHTML, resultList;

            resultHTML = [];

            if (!data) {    //is loading
                return yql.templates.page
                        .replace(/\{\{term\}\}/g, yql.term)
                        .replace(/\{\{count\}\}/g, "")
                        .replace(/\{\{results\}\}/g, "")
                        .replace(/\{\{prev\}\}/g, "")
                        .replace(/\{\{next\}\}/g, "")
                        .replace(/\{\{process\}\}/g, yql.templates.processLoading);
            }

            count = parseInt(data.query.count, 10);
            if (!count) {   //no result
                return yql.templates.page
                        .replace(/\{\{term\}\}/g, yql.term)
                        .replace(/\{\{count\}\}/g, "")
                        .replace(/\{\{results\}\}/g, "")
                        .replace(/\{\{prev\}\}/g, "")
                        .replace(/\{\{next\}\}/g, "")
                        .replace(/\{\{process\}\}/g, yql.templates.processNoResults);
            }

            //from now on: all is loaded and we have results

            resultList = data.query.results.result;

            if (!jQuery.isArray(resultList)) {
                //exactly one result means no array
                resultList = [resultList];
            }

            if (count === yql.perPage) {
                item = resultList.pop();
            }

            while (resultList.length) {
                item = resultList.shift();
                resultHTML.push(
                    yql.templates.result
                            .replace(/\{\{url\}\}/g, item.url)
                            .replace(/\{\{title\}\}/g, item.title)
                            .replace(/\{\{abstract\}\}/g, item.abstract)
                );
            }

            return yql.templates.page
                    .replace(/\{\{term\}\}/g, yql.term)

                    .replace(/\{\{count\}\}/g, 
                        yql.templates.count
                                .replace(/\{\{start\}\}/g, yql.start + 1)
                                .replace(/\{\{end\}\}/g, yql.start + count -
                                        (count === yql.perPage ?  1 : 0))
                    )

                    .replace(/\{\{results\}\}/g, resultHTML.join(""))

                    .replace(/\{\{prev\}\}/g, !yql.start ? "" : yql.templates.prev)
                    .replace(/\{\{next\}\}/g, count < yql.perPage ? "" : yql.templates.next)

                    .replace(/\{\{process\}\}/g, yql.templates.processDone);
        }
    };

    // getting one more than needed, to know, if I have to show next button
    yql.perPage += 1;

    //public
    trans.yqlSend = function (term, start) {
        var query, uri;

        start = yql.start = start || 0;
        term = yql.term = term.replace(/'/g, "\\'");

        query = yql.queryPattern
                .replace(/\{\{current\}\}/, start)

                .replace(/\{\{perPage\}\}/, yql.perPage)
                .replace(/\{\{term\}\}/, term);

        uri = yql.address + encodeURIComponent(query);

        //fix for home page
        jQuery(".home-teasers").addClass("hidden");

        yql.parentNode.html(yql.process());
        jQuery.getScript(uri);
    };

    trans.yqlGet = function (data) {
        yql.parentNode.html(yql.process(data));
        jQuery("#fakesearch").submit(function (event) {
            event.preventDefault();
            trans.yqlSend(jQuery(this).find(".text").val(), 0);
        });
    };

    jQuery(".more", yql.parentNode).live("click", function () {
        trans.yqlSend(yql.term, yql.start + 10);
    });

    jQuery(".back", yql.parentNode).live("click", function () {
        trans.yqlSend(yql.term, yql.start > 10 ? yql.start - 10 : 0);
    });

    jQuery("form[name=searchForm]").submit(function () {
        trans.yqlSend(jQuery(this).find(".text").val(), 0);
        return false;
    });

    jQuery("#head .search .button")
            .removeAttr("onclick")  //TODO: this line can be remove, when the attribute disappears
            .removeAttr("href")     //TODO: this line can be remove, when the attribute disappears
            .click(function () {
                trans.yqlSend(jQuery(this).prev().val(), 0);
                return false;
            });

    jQuery("form.search").submit(function (event) {
        event.preventDefault();
        trans.yqlSend(jQuery(this).find(".text").val(), 0);
    });

    jQuery(".search .button", yql.parentNode).live("click", function () {
        trans.yqlSend(jQuery(this).prev().val(), 0);
        return false;
    });

}(trans, jQuery, document.body));

