/* jslint white, browser, jquery, nomen, strict, maxlen: 100 */
/*global alert, confirm, jQuery, window, LANGUAGE_CODE, gettext, document */

if (typeof(WDL) == "undefined") {
    WDL = {};
}

WDL.ajaxRetry = function (options) {
    options.tries = 0;
    options.timeout = options.timeout || 15000;
    options.retryLimit = options.retryLimit || 3;
    options.error = function (xhr, textStatus, errorThrown) {
        if ((xhr.status >= 500 || textStatus == "timeout") && this.tries++ <= this.retryLimit) {
            $.ajax(this);
        }
    }

    return $.ajax(options);
};

jQuery(function ($) {
    "use strict";

    $("#language-selector form").submit(function (event) {
        var href = window.location.href;

        href = href.replace(/\/(ar|en|es|fr|pt|ru|zh)\//,
                            "/" + this.language.value + "/");

        window.location.href = href;

        return false;
    });

    $("#autosuggest").autocomplete({
        minLength: 2,
        source: function (request, response) {
            var term = request.term.toLowerCase(),
                highlight = function (text) {
                return text.replace(term, "<b>" + term + "</b>", "i");
            };

            $.ajax({
                url: "/" + LANGUAGE_CODE + "/search/suggest/",
                dataType: "json",
                data: {
                    q: term
                },
                success: function (data) {
                    response($.map(data, function (i) {
                        return {
                            label: highlight(i[0]),
                            count: i[1],
                            value: i[0]
                        };
                    }));
                },
                error: function (xhr, textStatus, err) {
                    response({});
                }
            });
        }
    }).each(function() {
        $(this).data("autocomplete")._renderItem = function ($ul, item) {
            var $li = $("<li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.label + ' <span class="count">(' + WDL.translateNumber(item.count) + ")</span></a>");

            if ($ul.children().length % 2) {
                $li.addClass("odd");
            }

            $li.appendTo($ul);
            return $li;
        };
    });

    /*
        This should simply be jQuery("ul.autocollapse:has(li:gt(9))") but that
        fails due to jQuery bug #6723: http://dev.jquery.com/ticket/6723

        Note also that :gt() uses zero-based indexing unlike the nth-child CSS
        selectors so we use 9 to include 10 elements above the fold
    */

    $("ul.autocollapse").each(function (i) {
        var $list = $(this),
            list_size = $list.data("collapse-size") || 10;

        if ($list.children("li").length > list_size) {
            var $button = $('<button></button>').click(function () {
                var $this = $(this);
                $list.children("li:not(.toggle):gt(" + (list_size - 1) + ")").toggle();

                if ($this.hasClass("toggled")) {
                    $this.removeClass("toggled");
                    $this.text(gettext("Less"));
                } else {
                    $this.addClass("toggled");
                    $this.text(gettext("More"));
                }
            });

            $('<li>').addClass("toggle").append($button).appendTo($list);

            $button.click();
        }
    });
});

/* Utility functions */
WDL.translateNumber = function (roman) {
    /* Given a string, translate numerals as appropriate for the current lang */
    if (LANGUAGE_CODE != "ar") {
        return roman;
    } else {
        /* convert a number to a string with arabic numerals */
        var arabic_map = new Array("٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩");
        var r = roman.toString();
        var arr = r.split('');

        for (var i = 0; i < arr.length; i++) {
            arr[i] = arabic_map[arr[i]];
        }

        return arr.join('');
    }
};
