/*
 * @projectDescription NE Bubblan
 *
 * @author Hellsing & Hellsing
 * @version 0.1
 *
 * @param {Boolean} useOverlay Lägger en svag overlay över sidan och bubblan blir
 * vit ovanför. False går att bubblan blir grå istället utan overlay.
 *
 * @param {Integer} mouseOutDelay Antal millisekunder som bubblan ska vänta innan
 * den stängs vid mouseout.
 *
 * @param {String} getExplanationUrl URL till förklarings förfrågan via ajax.
 *
 **/
var contextRoot = 'http://widgets.ne.se';

// Does not work, this has to be included before we use any jQuery functions, so it has to be included in the file using this one
//document.write('<script src="' + contextRoot + '/js/jquery-current.js" type="text/javascript"></scr'+'ipt>');

function replaceAllSpecialCharacters(targetString) {
    var retval = targetString;

    retval = retval.replace(/\\\\/g, "\\");
    retval = retval.replace(/\\\"/g, "\"");
    retval = retval.replace(/\\{/g, "{");
    retval = retval.replace(/\\}/g, "}");
    retval = retval.replace(/\\]/g, "]");

    //An extra backslash on theese 2 for some reason.
    retval = retval.replace(/\\\[/g, "[");
    retval = retval.replace(/\\\//g, "/");

    retval = retval.replace(/\\:/g, ":");
    retval = retval.replace(/\\,/g, ",");
    retval = retval.replace(/\\=/g, "=");
    retval = retval.replace(/\\;/g, ";");
    retval = retval.replace(/\\#/g, "#");

    return retval;
}

document.write('<link rel="stylesheet" type="text/css" href="' + contextRoot + '/bubbla/css/nebubbla-min.css" media="all">');

var NEBubbla = {
    mouseOutDelay: 400, // delatrinity: hiding the bubble
    getExplanationUrl: 'http://www.ne.se/ArticleExplanation', // JSON request URL
    showSearch: false, // toggles the search field
    cache: {}, // global cache

    init: function() {

        // create bubble structure
        var _nd = $(document.createElement('div')).addClass('d1');
        NEBubbla.container = $(document.createElement('div')).attr('id','neBubble');
        NEBubbla.arrow = $(document.createElement('div')).attr('id','neArrow');
        NEBubbla.content = $(document.createElement('div')).attr('id','neContent');

        // append the bubble to body
        NEBubbla.container.append(_nd.append(NEBubbla.content).append(NEBubbla.arrow));
        $('body').append(NEBubbla.container);

        // find, fetch, cache and listen
        $('a[href^=http://ne.se],a[href^=http://www.ne.se]').each(function() {
            $(this).attr('href',$(this).attr('href').replace(/http:\/\/ne\./gi,'http://www.ne.'));

            //Contains the articleReference as it is on the web page. The value
            //is used when the JSON callback comes and it is also the key that
            //is used when caching the callback object.
            var articleReference = $(this).attr('href').toString().replace(/http:\/\/(www\.)?ne\.se/gi,'');

            //Decoding the article reference in order to handle encoded charachters.
            //The article reference is encoded after that in order to make sure
            //that the characters is sent correctly to the server.
            var hrefDecoder = articleReference;
            hrefDecoder = decodeURIComponent(hrefDecoder);
            var href = encodeURIComponent(hrefDecoder);

            var request = NEBubbla.getExplanationUrl + '?url=' + href + '&callback=?';
            $.getJSON(request, function(data){
                data.title = replaceAllSpecialCharacters(data.title);
                data.explanation = replaceAllSpecialCharacters(data.explanation);

                NEBubbla.cache[articleReference] = data;

                $('a[href=http://www.ne.se'+articleReference+']').addClass('ne_markup').hover(
                function() {
                    $('a.ne_bubbleup').each(function(){
                        NEBubbla.hide(this);
                    });
                    $(this).addClass('ne_active');
                    NEBubbla.show(this);
                },
                function() {
                    $(this).removeClass('ne_active');
                }
            );
            });
        });
    },
    show: function(el) {
        $(document).mouseover(
        function(e) {
            var target = $(e.target);
            if (!(target.parents('#neBubble').length || target.is('#neBubble') || target.is('.ne_markup'))){
                $(document).unbind('mouseover');
                NEBubbla.timer = window.setTimeout("NEBubbla.hide()", NEBubbla.mouseOutDelay)
            }
        }
    );
        $(el).addClass('ne_bubbleup');
        NEBubbla.doShow($(el), $(el).attr('href').toString().replace(/http:\/\/www\.ne\.se/gi,''));
    },
    doShow: function(neLink, returnURL){
        var today = new Date();
        var currentYear = today.getFullYear();
        var title = NEBubbla.cache[returnURL].title;

        var explanation = NEBubbla.cache[returnURL].explanation;
        var formTag = '';
        if (NEBubbla.showSearch) {
            formTag = '<form id="neSearch" method="get">'+
                '<fieldset>'+
                '<legend>S\u00F6k i Encyklopedin</legend>'+
                '<div>'+
                '<span class="neSearchField"><input type="text" name="query" autocomplete="off" value="S\u00F6k p\u00E5 fria NE"><span></span></span>'+
                '<span class="neSearchBtn"><a class="submit_anchor" target="_blank" href="#">s\u00F6k</a></span>'+
                '</div>'+
                '</fieldset>'+
                '</form>';
        }

        NEBubbla.content.html(explanation +
            '<p class="readfull"><a target="_blank" href="' + neLink.attr('href') + '">L\u00E4s hela artikeln p\u00E5 NE</a></p>'+
            formTag +
            '<p class="footer">\u00A9 ' + currentYear + ' Nationalencyklopedin <span class="sep">|</span> <a target="_blank" href="http://www.ne.se/static/tools/bubbla.jsp">OM NE:S FAKTABUBBLA</a></p>');

        // prepend the title
        NEBubbla.content.prepend('<h2>' + title + '</h2>');

        // create the ne.se logo link
        NEBubbla.content.prepend('<div class="neLink"><a target="_blank" href="http://www.ne.se">NE</a></div>');

        // calculate positions
        var linkOffset = neLink.offset();
        var viewport = NEBubbla.viewport();
        var topPos = linkOffset.top - NEBubbla.container.height() - 28;
        var leftPos = linkOffset.left + neLink.width() / 2 - NEBubbla.container.width() / 3;
        var leftPosStrict = leftPos;
        if (leftPos + NEBubbla.container.width() > viewport.cx) {
            leftPos = viewport.cx - NEBubbla.container.width() - 8;
        }
        if (leftPos < 8) {
            leftPos = 8;
            NEBubbla.container.addClass('noleft');
        }
        if (topPos < viewport.y) {
            topPos = linkOffset.top + neLink.height();
            NEBubbla.container.addClass('viewbottom');
            NEBubbla.arrow.addClass('bottom');
        }
        var arrowPos = NEBubbla.container.width() / 3 - 11 + (leftPosStrict - leftPos);
        NEBubbla.arrow.css('margin-left',arrowPos + 'px');

        // show the bubble and add events
        NEBubbla.container.css({
            left: leftPos + 'px',
            top: topPos + 'px',
            display: 'block'
        });

        // add events to search input
        var inputField = $('#neSearch .neSearchField input');
        var default_q = inputField.attr('value');
        inputField.focus(function() {
            $(this).addClass('focus').attr('value','');
        }).blur(function() {
            $(this).removeClass('focus');
            if($(this).attr('value') == '') {
                $(this).attr('value',default_q);
            }
        });
        // search button event
        $('#neSearch .neSearchBtn a').click(function() {
            var q = inputField.attr('value');
            if (q != default_q && q) {
                $(this).attr('href', 'http://www.ne.se/sok/' + encodeURIComponent(q));
            }
        });
        jQuery("#neSearch").submit( function() {
            var q = inputField.attr('value');

            window.open('http://www.ne.se/sok/' + encodeURIComponent(q), '_blank');
            return false; //don't do the actual submit
        });
    },
    hide: function(el) {
        window.clearTimeout(NEBubbla.timer);
        $('a.ne_bubbleup').removeClass('ne_bubbleup');
        NEBubbla.container.removeClass('noleft').removeClass('viewbottom');
        NEBubbla.arrow.removeClass('bottom');
        NEBubbla.container.css('display','none');
        $(NEBubbla.content).empty();
    },

    // utility methods
    viewport: function() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }
};

jQuery(function() { NEBubbla.init(); });

