var gomNs = {
    languageCode: 'fr'
}

function showResults(data) {
    $("#contentcount").html('<b>'+data.count+'</b> ' + ngettext('notice', 'notices', data.count));
    var contentdata = data.contents;
    if (contentdata && contentdata.length) {
        var _htmlCl = '<ul id="contentlist">'
            + contentdata.map(function(_d) {
                var _html = '<li class="content-item"><h3>'
                    + _d.title
                    + '</h3>'
                    + ( typeof _d.coords == "object" ?
                        '<div class="maplet"><img src="http://maps.googleapis.com/maps/api/staticmap?center=47,1.5&zoom=4&size=160x160&maptype=roadmap&markers=color:red%7C'
                        + _d.coords.latitude
                        + ','
                        + _d.coords.longitude
                        + '&sensor=false" /><h4>'
                        + gettext('Localisation&nbsp;:')
                        + ' '
                        + _d.coords.city_name
                        + '</h4></div>'
                        : '')
                    + '<h4><a href="'
                    + _d.url
                    + '" target="_blank">'
                    + _d.url.replace(/(^.{40}).+(.{30}$)/m,'$1 &hellip; $2')
                    + '</a></h4><p>'
                    + _d.description.replace(/(^.{0,160})([\s]|$)(.*)/,'$1&hellip;')
                    + '</p><ul class="content-tags">'
                    + _d.tags.map(function(_t) {
                        return '<li class="content-tag-item"><a href="#" onclick="getContents(this.textContent.trim()); return false;" original-label="'
                            + _t.label
                            + '"'
                            + (_t.match ? ' class="tagmatch"' : '')
                            + '>'
                            + _t.translated_label
                            + '</a></li>';
                    }).join('')
                    + '</ul>';
                _html += '</li>';
                return _html;
            }).join('')
            + '</ul>';
        $("#contents").html(_htmlCl).scrollTop(0);
    }
    else {
        $("#contents").html("");
    }
}

function getContents(label) {
    $.getJSON(
        gomNs.urls['contentsbytag'],
        {
            label: label
        },
        showResults
    );
}

function ellipse(_text, _length) {
    var _rgxp = new RegExp('(^.{0,' + _length + '})([\s]|$)(.*)')
    return _text.replace(/(\n|\r|\r\n)/mg,' ').trim().replace(_rgxp,'$1…')
}

function highlightText(_text, _search) {
    var _rgxp = new RegExp('(' + _search.replace(/(\W)/g, '\\$1') + ')','gi');
    return _text.replace(_rgxp, '<strong>$1</strong>');
}

function wikipediaUrl(_text) {
    return "http://" + gomNs.languageCode + ".wikipedia.org/wiki/" + encodeURI(_text.replace(/ /g,'_'))
}

wpTemplate = _.template(
    '<h4 class="wptitle"><% print(highlightText(item.label, inputvalue)); %></h4><% if (item.thumbnail) { %><img class="wpimg" src="<%-item.thumbnail%>" /><% };'
    + ' if (item.abstract) { %><p class="wpabstract"><% print(ellipse(item.abstract,250))%></p><p class="wpsource"><a href="<% print(wikipediaUrl(item.label)) %>" target="_blank"><% print(gettext("Source&nbsp;: Wikipédia")) %></a></p><% }; %><div class="clear"></div>'
);

acTemplate = _.template(
    '<a><span class="acnb"><%- item.nb %></span><h4 class="actitle"><% print(highlightText(item.label, inputvalue)); %></h4></a>'
)

$(document).ready(function() {
    $(" #tagform ").submit(function() {
        return false;
    });
    var cache = {}, /*CACHE => http://jqueryui.com/demos/autocomplete/#remote-with-cache */
        lastXhr;
    $( "#tagsearch" ).autocomplete({
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                $("#tagsearch").removeClass("waiting");
                response( cache[ term ] );
                return;
            }
            $("#tagsearch").addClass("waiting");
            lastXhr = $.getJSON( gomNs.urls['tag_search'], request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                    $("#tagsearch").removeClass("waiting");
                }
            });
        },
        minLength: ( gomNs.languageCode == 'ja' ? 1 : 2 ),
        focus: function( event, ui ) {
            $(".wpinfo").html(wpTemplate({
                item: ui.item,
                inputvalue: $("#tagsearch").val()
            }));
        },
        select: function( event, ui ) {
            getContents(ui.item.label);
        }
    })
    .data("autocomplete")._renderItem = function(ul, item) {
        var _contents = acTemplate({
            item: item,
            inputvalue: $("#tagsearch").val()
        });
        return $( "<li>" )
            .data( "item.autocomplete", item )
            .html( _contents )
            .appendTo( ul );
    };
});
