// @@require jms/lib/browser.js
// @@require jms/lib/tree.js
// @@require jms/lib/difi.js
// @@require jms/lib/station.js
// @@require jms/lib/pager.js
// @@require jms/lib/zzlegacy.js
// @@require cssms/pages/news.css
// @@require jms/lib/menutraffic.js

if (!window.Browser) {
    Browser = browser;
}
Page = {};
News = {
     patch: function ()
    {
        if (window.deviantART) {
            Page = deviantART.pageData;
            Page.deviant = deviantART.deviant || {};
        }
        else {
            DRE.notice('deviantART.pageData unavailable');
        }
    }
    ,ready: false
    ,current: {}
    ,go: function ()
    {
        var pager, node, height, links, i;
    
        if (News.ready) {
            return;
        }

        if (!(Tree.get('#news') || Tree.get('#news-submit'))) {
            return false;
        }

        // code patches
        News.patch();

        if (Tree.get('#news-submit')) {
            News.submitGo();
            News.ready = true;
            return;
        }

        // main page is still invisible here
        News.current = Page.news_state;

        // category list (expected preloaded)
        MenuTraffic.news_hack = true; // don't fetch to levels deep. TODO: remove
        Pager.overrides.push(News.pagerOverride);
        pager = Pager.create(
            {
                 href_base: 'http://news.deviantart.com/browse%s?type=' + Page.news_state.type
                 //href_base: '#'
                ,more_links: false
                ,master_links: true // brrrroken if turned off :/
                ,class_name: 'side-pager'
                ,paned: true
                ,selection: Page.news_state.section ? 'news/' + Page.news_state.section : 'news'
                //,disable_clicks: true
                //,callback_immediately: true
                ,callback: function (value, pager)
                {
                    //pager.selection = '';
                    //News.load('newspie', value.split('/').slice(1).join('/'), 0);
                    //BackForward.load(News.current.type + '-' + (value).split('/').slice(1).join('/') + '-0')
                    //window.location = 'http://news.deviantart.com/browse/' + value;
                    return true;
                    //return false;
                }
                ,callback_object: pager
            }
        );

        document.getElementById('newscats').appendChild(pager.node);
        Pager.loadPage(pager, 'news');
            
        // ligg sprinkler (also preloaded)
        //Sprinkler.supply();

        // go!
        DiFi.send();
        var link = Tree.get(pager.node, 'a');
        if (link) link.innerHTML = 'All Topics';

        links = Tree.gets(pager.node, 'a');
        if (pager.selection != 'news') {
            for (i = 0; links[i]; i++) {
                if (i > 0 && pager.selection.indexOf(links[i].getAttribute('menuri')) == 0) {
                    Pager.clickBack(links[i]);
                    break;
                }
            }
            node = Tree.gets(pager.node, 'div.page2')[1];
            if (node) {
                Tree.addClass(node, 'page2-alt');
                node = Tree.get(node, 'a');
                node.style.display = 'none';
                if (!Tree.hasClass(node, 'selected')) {
                    Tree.addClass(Tree.get(pager.node, 'a.more-selected'), 'alt-selected');
                }
            }
        }

        News.loaded();
        _forcePageLayout();

        if (Page.news_article && Tree.get('#jsid-news')) {
            height = Tree.get(Tree.get('#jsid-news'), 'div.report').offsetHeight + 170;
            node = Tree.get('#news-side-top');
            if (Browser.isIE) {
                node.style.height = height + 'px';
            }
            else {
                node.style.minHeight = height + 'px';
            }
        }

        News.ready = true;
    }
    ,submitGo: function ()
    {
        var links, i, chooser;
        chooser = Pager.create(
            {
                 //href_base: 'http://news.deviantart.com/browse%s'
                 //href_base: '#'
                 more_links: false
                ,master_links: false
                ,callback_immediately: false
                ,theme: 'light'
                ,paned: true
                ,selection: Page.news_state && Page.news_state.section ? 'news/' + Page.news_state.section : ''
                ,callback: function (value, pager)
                {
                    var input;
                    input = Tree.get(Tree.ancestor(pager.node, 'form'), 'input.section');
                    input.value = value.split('/').slice(1).join('/');
                }
            }
        );
        document.getElementById('news-submit-categories').appendChild(chooser.node);
        Pager.loadPage(chooser, 'news');
        DiFi.send();
        links = Tree.gets(chooser.node, 'a');
        for (i = 0; links[i]; i++) {
            if (!Page.admin && links[i].getAttribute('menuri') && links[i].getAttribute('menuri').split('/')[1] in { devart:'', notices:'', hottopics:'', helpandfaq:'', deviantart:'' }) {
                links[i].parentNode.removeChild(links[i]);
            }
        }
        chooser.options.callback(chooser.selection, chooser);
        if (document.getElementById('news_url_text')) {
            News.submit_watch_timer = setInterval(News.submitWatchForm, 150);
        }
    }
    ,submit_watch_timer: null
    ,submitWatchForm: function ()
    {
        if (document.getElementById('newsarticle').value) {
            if (!document.getElementById('news_url_text').disabled) {
                document.getElementById('news_url_text').disabled = document.getElementById('news_url_radio').disabled = true;
            }
        }
        else if (document.getElementById('news_url_text').value) {
            if (!document.getElementById('newsarticle').disabled) {
                document.getElementById('newsarticle').disabled = document.getElementById('news_text_radio').disabled = document.getElementById('news_text_button').disabled = true;
            }
        }
        else {
            document.getElementById('news_url_text').disabled = document.getElementById('news_url_radio').disabled = document.getElementById('newsarticle').disabled = document.getElementById('news_text_radio').disabled = document.getElementById('news_text_button').disabled = false;
        }
    }
    ,topicHover: function (link, count)
    {
        var bubble, c;
        bubble = getNodeObject(link);
        if (bubble) {
            setStyle(bubble, 'display', 'block');
        }
        else {
            bubble = createNode(
                'div.newsbubble'
                ,{
                    style: {visibility: 'hidden'}
                }
                ,count == 1 ? '1 story today' : count + ' stories today'
            );
            document.body.appendChild(bubble);
            setNodeObject(link, bubble);
        }
        with (Floaters.findSafeCoordinates(bubble, link)) {
            bubble.style.left = x + 'px';
            bubble.style.top  = y + 'px';
        }
        setStyle(bubble, 'visibility', 'visible');
    }
    ,topicOut: function (link)
    {
        var bubble;
        bubble = getNodeObject(link);
        if (bubble) {
            setStyle(bubble, 'display', 'none');
            setStyle(bubble, 'visibility', 'hidden');
        }
        unsetClass(link, 'subble');
    }
    ,pagerOverride: function (data, options, html, html_base_click)
    {
        var i, total;

        total = 0;
        if (data.path[0] == 'news' && !News.ready) {
            for (i = 0; data.children[i]; i++) {
                total += data.children[i].populartoday;
                html.push(
                     '<a onnnmouseover="News.topicHover(this, '
                    +data.children[i].populartoday
                    +')" onnnmouseout="News.topicOut(this)" menuri="'
                    +data.children[i].path.join('/')
                    +'" class="'
                    +(data.children[i].children != null ? 'f more' : 'f')
                    +'" href="http://news.deviantart.com/browse/'
                    +data.children[i].path.slice(1).join('/')
                    +'/"'
                    //+html_base_click // no onclicks
                    +'>'
                    +data.children[i].title
                    +(
                        data.children[i].populartoday != 0
                        ?
                        (
                             ' <sup class="new">'
                            +data.children[i].populartoday
                            +'</sup>'
                        )
                        :
                        ''
                    )
                    +'</a>'
                );
            }
            html.push('</div>');
            if (data.path.length == 1) { // total
                Tree.get(Tree.get('#news'), 'h1').appendChild(Tree.create('sup.new', {}, ' ' + total));
                Tree.get(Tree.get('#news'), 'h1').appendChild(Tree.create('sup', {}, ' popular stories today'));
            }
            return html;
        }
        return false;
    }
    ,submitPreview: function ()
    {
        var edit, preview, loading, button;
        edit = Tree.get('#newsarticle');
        preview = Tree.get('#news_text_preview');
        loading = Tree.get('#news_text_loading');
        button = Tree.get('#news_text_button');
        if (edit.style.display == 'none') {
            preview.style.display = 'none';
            edit.style.display = 'block';
            edit.disabled = false;
        }
        else {
            edit.disabled = button.disabled = true;
            Station.apply(loading, 'opacity', .6);
            loading.style.visibility = 'visible';
            DiFi.pushPost('News', 'preview', [edit.value], News.submitPreviewReady, News);
            DiFi.send();
        }
    }
    ,submitPreviewReady: function (success, data) {
        var preview, edit, loading, button;
        loading = Tree.get('#news_text_loading');
        edit = Tree.get('#newsarticle');
        preview = Tree.get('#news_text_preview');
        button = Tree.get('#news_text_button');
        loading.style.visibility = 'hidden';
        if (success) {
            preview.style.width = edit.offsetWidth + 'px';
            preview.style.height = edit.offsetHeight + 'px';
            edit.style.display = 'none';
            preview.innerHTML = '<div class="pp"><a class="a" href="#" onclick="News.submitPreview();return false">Back to Editing</a><br/><br/>' + data.response.content + '</div>';
            preview.style.display = 'block';
        }
        else {
            alert('Unable to generate preview. Please try again shortly.');
            edit.disabled = false;
        }
        button.disabled = false
    }
    ,submitValidate: function (form)
    {
        var data, errors;
        data = serializeForm(form);
        //spillObject(data);
        errors = [];
        if (!data.newstitle) {
            errors.push('You did not give the story a Headline.');
        }
        if (!(data.href || data.newsarticle)) {
            errors.push('You must either type the News Story URL, or type the Full Story Text.');
        }
        if (data.href && data.href.indexOf('ht'+'tp://') != 0) {
            errors.push('The news story URL must be in this format: ht'+'tp://www.example.com/etc/');
        }
        if (!data.newssummary) {
            errors.push('You did not type the story\'s Summary.');
        }
        if (!data.newscat) {
            errors.push('You did not specify the story\'s Topic.');
        }
        if (errors.length) {
            if (errors.length > 1) {
                errors.unshift('');
                errors = errors.join("\n- ");
            }
            else {
                errors = "\n" + errors[0];
            }
            alert("Sorry. The Story is not ready to submit.\n" + errors);
            return false;
        }
        if (Tree.get('#newsarticle').style.display == 'none') {
            News.submitPreview(); //  turn off preview to re-enable the main textarea
        }
        return true;
    }
    ,loaded: function ()
    {
        Tree.removeClass(Tree.get('#news-main'), 'unscripted');
        Tree.removeClass(Tree.get('#news-side'), 'unscripted');
    }
    ,getArticle: function (node_or_id) {
        if (node_or_id.nodeType) {
            return Tree.ancestor(node_or_id, 'div.report');
        }
        else {
            //return Tree.get('#jsid-article-' + node_or_id);
            return Tree.get('#n' + node_or_id);
        }
    }
    ,getArticleID: function (node) {
        return News.getArticle(node).id.substr(1);
    }
    ,love: function (node_or_id, type)
    {
        var id, node, link;
        node = News.getArticle(node_or_id);
        link = Tree.get(node, 'a.love');
        id = News.getArticleID(node);
        if (News.love_busy[id]) {
            return;
        }
        if (type == -1) {
            // do do
            DiFi.pushPost('Ratings', 'UnregisterRating', [id, 1], News.loveBack, id);
        }
        else {
            // undo
            DiFi.pushPost('Ratings', 'RegisterRating', [id, type, 1], News.loveBack, id);
        }
        News.love_busy[id] = true;
        DiFi.send();
        if (type <= 0) { // love or undo
            if (type == 0 && node.offsetHeight > 400 && !Tree.hasClass(node_or_id, 'love')) {
                Station.push(
                     (Browser.isGecko ? document.documentElement : document.body)
                    ,'scrollTop'
                    ,{from: (Browser.isGecko ? document : document.body).scrollTop, to: Ruler.document.node(node).x - 4, time:400, f: Interpolators.pulse}
                    ,function ()
                    {
                        setTimeout(function (){ Tree.addClass(link, 'active')    }, 200);
                        setTimeout(function (){ Tree.removeClass(link, 'active') }, 700);
                        setTimeout(function (){ News.showLove(node, Page.deviant, type == -1) }, 750);
                    }
                );
                News.getArticle(node_or_id);
            }
            else {
                News.showLove(node_or_id, Page.deviant, type == -1);
            }
        }
        else {
            link.style.display = 'none';
        }
    }
    ,loveMouseDown: function (node, active)
    {
        var lover;
        lover = Tree.get(News.getArticle(node), 'a.love');
        if (lover) {
            if (active) {
                Tree.addClass(lover, 'active');
            }
            else {
                Tree.removeClass(lover, 'active');
            }
        }
    }
    ,love_busy: {}
    ,showLove: function (node_or_id, user, undo)
    {
        var node, lover, overlay, eax, is_me;
        is_me = user.username.toLowerCase() == (Page.deviant.username || '').toLowerCase();
        node = News.getArticle(node_or_id);
        lover = Tree.gets(node, 'div.love').pop();
        overlay = Station.overlay(lover);
        eax = Tree.get(lover, 'span');
        if (undo && is_me && !hasClass(lover, 'loved')) {
            // undoing rejection
        }
        else {
            eax.firstChild.nodeValue = Number(eax.firstChild.nodeValue) + (undo ? -1 : 1);
        }
        if (is_me) { // born of loveclick
            if (undo) {
                Tree.removeClass(lover, 'loved');
            }
            else {
                Tree.addClass(lover, 'loved');
            }
            Tree.get(lover, 'a').style.display = undo ? 'block' : 'none';
        }
        Station.push(overlay, 'opacity', { from: .99, to: 0, time: 450, f: Interpolators.sineCurve }, Station.overlayEnd);
        do {
            eax = Tree.get(Tree.get(node, 'div.line1'), 'span.user');
            if (!eax) {
                Tree.get(Tree.get(node, 'div.line1'), 'small').appendChild(Tree.create('span', {}, ' Last +fav: '));
                Tree.get(Tree.get(node, 'div.line1'), 'small').appendChild(eax = Tree.create('span.user'));
            }
        } while (!eax);
        eax.innerHTML =
             user.symbol
            +'<a class="u" href="ht'
            +'tp://'
            +user.username.toLowerCase()
            +'.deviantart.com/">'
            +user.username
            +'</a>'
        ;
    }
    ,loveBack: function (success, data)
    {
        var html;
        News.love_busy[this] = false;
        if (success) {
            if (data.request.method == 'UnregisterRating') {
                html = News.love_html.neutral;
            }
            else {
                if (data.request.args[1] == 0) {
                    html = News.love_html.loved;
                }
                else {
                    html = News.love_html.rejected;
                }
            }
        }
        else {
            if (!data.request) {
                html = 'Unable to Connect. Please try again later.';
            }
            else {
                if (data.request.method == 'UnregisterRating') {
                    // failed undo
                    html = 'Unable to Undo. Please try again later.';
                }
                else {
                    if (data.request.args[1] == 0) {
                        // failed love
                        News.showLove(this, Page.deviant, true);
                    }
                    else {
                        // failed reject
                        Tree.get(News.getArticle(this), 'a.love').style.display = 'none'
                    }
                    return;
                }
            }
        }
        Tree.get(News.getArticle(this), 'div.line2').innerHTML = '<small>' + html + '</small>'; 
    }
    ,love_html: {
         neutral:
             '<a href="" class="a" onclick="News.love(this, 0);return false">Add to Favourites</a> &nbsp; '
            +'<a href="" class="a" onclick="News.love(this, 5);return false">Reject</a>'
        ,loved: '<a href="" class="a" onclick="News.love(this, -1);return false">Undo Favourite</a>'
        ,rejected: '<a href="" class="a" onclick="News.love(this, -1);return false">Undo Rejection</a>'
    }
}
$j(News.go);
//BackForward.register(News.newHash);

Sprinkler = {
     sprinkles: []
    ,supply: function ()
    {
        DiFi.pushPrivateGet('News', 'sprinkler', [], this.gotSupplies, this);
        DiFi.timer(20000);
    }
    ,local_adjust: true
    ,gotSupplies: function (success, data)
    {
        var i, eax, node;
        if (success) {
            //Bug.bump('download');
            // HACK DiFi.cache does not empty on use
            DiFi.cached['News;sprinkler;'] = null;
            if (!this.timer) {
                setTimeout("Sprinkler.tick(true)", 100);
            }
            if (this.local_adjust) {
                // check for own-votes in next90seconds and apply immediately on initial load
                for (i = 0; eax = data.response.content.data[i]; i++) {
                    if (eax.username == Page.deviant.username) {
                        if (node = News.getArticle(eax.articleid)) {
                            node = Tree.get(node, 'div.love');
                            with (Tree.get(node, 'span')) {
                                innerHTML = (Number(innerHTML) || 0) + 1;
                                className = 'loved';
                            }
                            Tree.get(node, 'a').style.display = 'none';
                        }
                    }
                }
                this.local_adjust = false;
            }
            this.now = data.response.content.now;
            while (this.sprinkles.length && this.sprinkles[this.sprinkles.length - 1].time > this.now) {
                // remove everything in the future; it is about to be replaced
                this.sprinkles.pop();
            }
            for (i = 0; data.response.content.data[i]; i++) {
                this.sprinkles.push(data.response.content.data[i]); // push.apply was freaking out in IE
            }
            setTimeout("Sprinkler.supply()", 50000); // + 20 second difi window (see Sprinkler.supply)
        }
        else {
            // fail. try again in 30 seconds
            //debug('FAILURE');
            //spillObject(data.response.content);
            setTimeout("Sprinkler.supply()", 30000);
        }
    }
    ,now: null
    ,timer: null
    ,tick: function (read_only)
    {
        var eax;
        this.timer = null;
        if (this.sprinkles.length) {
            //Bug.update('tank', this.sprinkles.length);
            if (!read_only) {
                eax = this.sprinkles.shift();
                if (eax.username != Page.deviant.username) { // stop animating yourself
                    //Bug.update('love', eax.articleid + ' + ' + eax.username);
                    if (News.getArticle(eax.articleid)) {
                        News.showLove(eax.articleid, eax);
                    }
                }
            }
            if (this.sprinkles.length) {
                //this.timer = setTimeout("Sprinkler.tick()", Bug.update('setTimeout', Math.max((this.sprinkles[0].time - Sprinkler.now) * 1000, 200)));
                this.timer = setTimeout("Sprinkler.tick()", Math.max((this.sprinkles[0].time - Sprinkler.now) * 1000, 200));
            }
            else {
                //Bug.update('setTimeout', 'off');
                //Bug.update('tank', 'EMPTY');
            }
        }
        else {
            //Bug.update('setTimeout', 'off');
            //Bug.update('tank', 'bzjhhhEMPTY');
        }
    }
}
