// register the global ajax response handlers
Ajax.Responders.register({
    onCreate: function(request) {
        // switch the cursor to indicate activity
        // through the request
        document.body.style.cursor = 'wait';
    },
    onComplete: function(request) {
        document.body.style.cursor = 'default';

        // the user is not logged in - force a login
        if (request.transport.status == 401) {
            forceLogin();
        }
    }
});


var articlePopupElem = $('articlePopup');
var articlePopup;
if (articlePopupElem) {
    articlePopup = new Popup('articlePopup');
}

if ($('arrowingDialog')) {
    arrowDialog = new Dialog('arrowingDialog');
}

function onClickArticlePopup(event, article) {
    event.stop();

    if (!(event.findElement('.arrowup') || event.findElement('.arrowdown'))) {
        return;
    }

    var element = event.element();
    var articlePopupElemTop = articlePopupElem.viewportOffset()['top'];

    var articleId = Article.getId(article);
    var channelId = Article.getChannelId(article);

    var arrow;
    if (element.hasClassName('arrowup')) { 
        arrow = 'up';
    } else {
        arrow = 'down';
    }

    // check if we're just clearing an arrow
    if (arrow == 'up' && article.up('.story').hasClassName('downed')) {
        articlePopup.hide();
        var url = "/article/cleararrow/" + articleId + "?channel=" + channelId;
        new Ajax.Request(url, {
            onSuccess: function(transport) {
                Article.arrowUp(article);
            }
        });
        return;
    }

    articlePopup.hide();

    TuningDialog.show(article, arrow);
}




/*********************/
/*   ON LOAD STUFF   */
/*********************/

window.onload = function() {

    decorateLogin();

    decorateArticles();

    decorateQueryBox();

    decorateFeedback();

    Navbar.decorate();

    decorateHelpLinks();

    checkBrokenImages();

    decorateHelpText();

    Footer.decorate();

    if (typeof(messageToFlash) != 'undefined' && messageToFlash) {
        flashMessage(messageToFlash);
    }

    $$('.flash').each(function(elem) {
        var startcolor = '#FFFFFF';
        var highlightcolor = '#F9EB69';
        new Effect.Highlight(elem, {
            startcolor: startcolor, 
            endcolor: highlightcolor, 
            restorecolor: highlightcolor, 
            duration: 1.0,
            afterFinish: function() {
                new Effect.Highlight(elem, {startcolor: highlightcolor, endcolor: startcolor, restorecolor: startcolor, delay: 5.0, duration: 1.0});
            }
        });
    });

}


function decorateLogin() {
    var placeholder = $('password_placeholder');
    if (!placeholder) return;

    placeholder.observe('focus', function() {
        placeholder.hide();
        var passwordInput = $('login_password');
        passwordInput.show();
        passwordInput.activate();
    });

    // swap the placeholder into place if the user hasn't started typing text
    var password = $('login_password');
    if (password.value == '') {
        password.hide();
        placeholder.show();
    }

    var form = $('signinForm');
    if (form) {
        form.observe('submit', function(event) {
            var loginEmail = $('login_email');
            var loginPassword = $('login_password');
            if (loginEmail.hasClassName('helptext') || loginEmail.value.strip() == '') {
                alert('Please enter your e-mail address.');
                event.stop();
                return false;
            } else if (form.down('#password_placeholder').visible() || loginPassword.value.strip() == '') {
                alert('Please enter your password.');
                event.stop();
                return false;
            }
        });
    }
}


function decorateHelpText(container) {
    var helptextFields;
    if (container) {
        helptextFields = container.select('.helptext');
    } else {
        helptextFields = $$('.helptext');
    }
    helptextFields.each(function(elem) {
        var title = elem.title;
        if (elem.value != title && elem.value != '') elem.removeClassName('helptext');
        elem.observe('focus', function(event) {
            if (elem.hasClassName('helptext')) {
                elem.value = '';
                elem.removeClassName('helptext');
            }
        });
        elem.observe('blur', function(event) {
            if (elem.value == '') {
                elem.addClassName('helptext');
                elem.value = title;
            }
        });
        // set the text if the field isn't already focused
        if (typeof document.activeElement == "undefined" || !document.activeElement || document.activeElement != elem) {
            if (elem.value == '') elem.value = title;
        } else {
            elem.removeClassName('helptext');
        }
    });
}


var Navbar = {

    sortableReordered: false,

    decorate: function() {
        var navbar = $('navbar');
        if (!navbar) return;

        this.initSortables();

        // handle delete case
        navbar.observe('click', function(event) {
            var deleteElem = event.findElement('.delete-channel');
            if (!deleteElem) return;
    
            if (page == 'channel') {
                // if it's the current channel, just do full
                // refresh
                var li = event.findElement('li');
                var cid = li.id.substring(3);
                if (cid == channelId) {
                    return;
                }
            }

            event.stop();
            new Ajax.Request(deleteElem.href, {
                parameters: {'xhr': 'true'},
                onSuccess: function(transport) {
                    var channel = transport.responseJSON.channel;
                    var message = transport.responseJSON.message;
                    if (message) flashMessage(message);
                    Navbar.removeChannel(channel.id);

                    if (page == 'overview') {
                        updatePage();
                    }
                }
            });
        });

        // decorate the links to ensure that the sorting clicks aren't registered as link clicks
        navbar.select('.navSection ul a').invoke('observe', 'click', this.checkSortable.bind(this));

        $('navAddSectionLink').observe('click', function(event) {
            event.stop();
            $('navAddSectionLink').hide();
            $('navAddSectionForm').show();
            $('navAddSectionForm').down('input').activate();
        });

        $('navAddSectionForm').down('input').observe('blur', function(event) {
            $('navAddSectionForm').hide();
            $('navAddSectionLink').show();
        });

        var self = this;
        $('navAddSectionForm').observe('submit', function(event) {
            event.stop();
            var form = event.element();
            new Ajax.Request(form.action, {
                evalJSON: 'force',
                parameters: Form.serialize(form),
                onSuccess: function(transport) {
                    var section = transport.responseJSON;
                    form['sectionName'].value = '';
                    form.hide();
                    $('navAddSectionLink').show();
                    self.addSection(section.id, section.urlpart, section.name);
                }
            });
         });
    },

    initSortables: function() {
        var navbar = $('navbar');

        var containers = [];
        var lists = navbar.select('.navSection ul');
        var sections = navbar.select('.navSection');
        containers = containers.concat(lists);
        containers = containers.concat(sections);

        // store a reference to use in nested closures
        // see http://www.alistapart.com/articles/getoutbindingsituations/
        var self = this;

        var onChangeChannelOrder = self.onChangeChannelOrder.bind(self);
        var onUpdateChannelOrder = self.onUpdateChannelOrder.bind(self);
 
        lists.each(function(list) {
            Sortable.create(list, {
                containment: containers,
                dropOnEmpty: true,
                scroll: window,
                onChange: onChangeChannelOrder,
                onUpdate: onUpdateChannelOrder
            });
        });
        sections.each(function(list) {
            Sortable.create(list, {
                tag: 'li',
                containment: containers,
                dropOnEmpty: true,
                scroll: window,
                onChange: onChangeChannelOrder,
                onUpdate: onUpdateChannelOrder
            });
        });

        // sort the sections themselves
        Sortable.create('navSections', {
            tag: 'div',
            only: 'navSection',
            scroll: window,
            onChange: this.onChangeSectionOrder,
            onUpdate: this.onUpdateSectionOrder
        });
    },
    
    addSection: function(id, urlpart, name) {
        // add the HTML
        var sectionElem = new Element('div', {'id': 'sh_' + id, 'class': 'navSection group'});
        sectionElem.insert(new Element('a', {'href': '/section/' + id + '/' + urlpart}).update(name));
        sectionElem.insert(new Element('ul', {'id': 'sl_' + id}));
        $('navSections').insert({bottom: sectionElem});

        // enable resorting - all sortables must be re-created
        // to allow for new container element
        this.initSortables();
    },

    removeSection: function(id) {
        $('sh_' + id).remove();
    },

    updateSectionOrder: function(id, prevId) {
        var sectionElem = $('sh_' + id);
        if (prevId) {
            var prevSectionElem = $('sh_' + prevId);
            prevSectionElem.insert({after: sectionElem});
        } else {
            $('navSections').insert({top: sectionElem});
        }
    },

    addChannel: function(id, urlpart, label, sectionid) {
        var navId = 'nc_' + id;

        // check that it's not already there
        if ($(navId)) return;

        var navList = $('sl_' + sectionid);
        var a = new Element('a', {'class': 'c', 'href': '/channel/' + id + '/' + urlpart}).update(label);
        var li = new Element('li', {'id': navId}).update(a);
        var remove = new Element('a', {'class': 'delete-channel', 'href': '/channels/delete/' + id}).update('X');
        li.insert({bottom: remove});
        navList.insert({bottom: li});

        new Effect.Highlight(li, {duration: 2.0});

        // update the sortables
        this.initSortables();
    },

    removeChannel: function(id) {
        $('nc_' + id).remove();
    },

    updateChannelLink: function(oldChannelId, newChannel) {
        var elem = $('nc_' + oldChannelId);
        elem.id = 'nc_' + newChannel.id;
        var link = elem.down('a');
        link.href = '/channel/' + newChannel.id + '/' + newChannel.urlpart;
        link.update(newChannel.label);

        var img = link.next('img');
        if (img) img.remove();
    },

    moveChannel: function(id, sectionid) {
        var channelElem = $('nc_' + id);
        var sectionElem = $('sl_' + sectionid);
        sectionElem.insert({bottom: channelElem});
    },

    onChangeChannelOrder: function(element) {
        this.sortableReordered = true;
        lastSorted = element;
    },

    onUpdateChannelOrder: function(container) {
        var sectionid = container.id.substring(3);
        new Ajax.Request("/channels/reorder?section=" + sectionid + '&' + Sortable.serialize(container, {name: 'channel'}), {
            method: "post",
            parameters: {'xhr': 'true'}
        });

        // ensure the sorted element is in the container for this callback
        // since it's invoked on both the origin and destination
        if (lastSorted && container.down('#' + lastSorted.id)) {
            // if it's a div container, append to the ul
            // NOTE: This assumes that dragging to the div is the top of the div,
            // which is always the case. Need to get event and check mouse position
            // to determine whether to append on the top or the bottom of list.
            if (container.tagName == 'DIV') {
                container.down('ul').insert({top: lastSorted});
            }

            // if we're on the front page, try to reorder it in the GUI
            if (page == 'overview') {
                updatePage();
            }
        }
    },

    onChangeSectionOrder: function(element) {
        lastSortedNavSection = element;
    },

    onUpdateSectionOrder: function(container) {
        new Ajax.Request("/icprofile/reorder?" + Sortable.serialize(container, {name: 'section'}), {
            method: "post",
            parameters: {'xhr': 'true'},
            onSuccess: function() {
                // TODO: Reorder frontpage
                var sectionid = lastSortedNavSection.id.substring(3);
                var prevSection = lastSortedNavSection.previous('.navSection');

                flashMessage("Your sections have been re-ordered.");
            }
        });
    },

    checkSortable: function(event) {
        // ensures that link clicks in the sorting process aren't registered.
        if (this.sortableReordered) {
            Event.stop(event);
            this.sortableReordered = false;
        }
    }

};



function decorateHelpLinks() {
    $$('.helplink').invoke('observe', 'click', function(event) {
        var a = event.findElement('a');
        event.stop();
        openHelpLink(a.href);
        return;
    });
}

function openHelpLink(href) {
    var w = window.open(href, 'icPopup', 'width=750,height=700,scrollbars=yes');
    w.focus();
}

function decorateQueryBox() {
    var searchForm = $('searchForm');
    if (searchForm) {
        searchForm.observe('submit', validateQuery);

        var query = $('query');
        var submit = searchForm.down('.submit');
        if (query.value == '' || query.value == query.title) {
            submit.disable();
            submit.addClassName('disabled');
        }
        query.observe('keyup', function(elem) {
            if (query.value != '' && query.value != query.title) {
                if (submit.disabled) {
                    submit.enable();
                    submit.removeClassName('disabled');
                }
            } else {
                if (!submit.disabled) {
                    submit.disable();
                    submit.addClassName('disabled');
                }
            }
        });
        new TopicInput(query, {
            booleanMode: true,
            url: '/icresource/complete_search',
            onSelectCompletion: function() {
                searchForm.submit();
            }
        });
    }
}

function decorateFeedback() {
    var form = $('feedbackForm');
    if (!form) return;

    form.observe('submit', function(event) {
        event.stop();

        var form = event.element();
        var submit = form.down('.submit input');
        submit.hide();
        new Ajax.Request('/feedback/send', {
            asynchronous:true, 
            evalScripts:true, 
            parameters:Form.serialize(form),
            onSuccess: function() {
                form.select('textarea')[0].value = '';
                var feedbackThanks = $('feedbackThanks');
                feedbackThanks.show();
                new Effect.Highlight(feedbackThanks, {
                    duration: 1.0,
                    afterFinish: function() {
                        Effect.Fade(feedbackThanks, {
                            duration: 0.2,
                            afterFinish: function() {
                                submit.show();
                            }
                        });
                    }
                });
            }
        });
    });
}

function validateQuery(event) {
    var queryElem = $('query');
    queryElem.value = queryElem.value.strip();
    if (queryElem.value == '') {
        alert('Please enter a query.');
        event.stop();
    }
}


function checkBrokenImages() {
    $$('img.headlineImg').each( function(elem) {
        if (!isImageOk(elem)) elem.hide();
    });
}


function isImageOk(img) {
    // check for IE
    if (!img.complete) {
        return false;
    }

    // check for Firefox
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // no other way of checking: assume it's ok
    return true;
}


/**
 * Methods pertaining to article behavior.
 */
function decorateArticles(container) {
    var context = container || $('container');

    var articles = context.select('.article');
    articles.invoke('observe', 'click', onClickArticle);
}

// handle the article popup
function onPopupArticle(element) {
    var article = element.up('.article');
    var story = element.up('.story');
    if (!article) return;


    // unregister old event handlers, and register new event handlers
    // with the article in the execution context
    Event.stopObserving(articlePopupElem, 'click');
    articlePopupElem.observe('click', onClickArticlePopup.bindAsEventListener(this, article));

    //articlePopup.article = article;
    if (story.hasClassName('downed')) {
        articlePopupElem.addClassName('downed');
    } else {
        articlePopupElem.removeClassName('downed');
    }
}

var metadataPopupElem = $('metadataPopup');
var metadataPopup;

if (metadataPopupElem) {
    metadataPopup = new Popup('metadataPopup');

    // decorate the arrows
    var arrowUpElem = metadataPopupElem.down('.arrowup');
    var arrowDownElem = metadataPopupElem.down('.arrowdown');
    arrowUpElem.observe('click', function(event) {
        var type = metadataPopup.arrowed_type;
        var id = metadataPopup.arrowed_id;
        var context = metadataPopup.context;
        var url;
        var cid;
        if (page == 'channel' || page == 'shared') {
            cid = channelId;
        } else {
            var articleElem = context.up('.article');
            cid = Article.getChannelId(articleElem);
        }
        url = '/channels/' + cid + '/add_' + type + '/' + id;
        location.href = url;
    });

    arrowDownElem.observe('click', function(element) {
        var type = metadataPopup.arrowed_type;
        var id = metadataPopup.arrowed_id;
        var context = metadataPopup.context;
        var url;
        var cid;
        if (typeof page != 'undefined' && (page == 'channel' || page == 'shared')) {
            cid = channelId;
        } else {
            var articleElem = context.up('.article');
            cid = Article.getChannelId(articleElem);
        }
        url = '/channels/' + cid + '/exclude_' + type + '/' + id;
        location.href = url;
    });
}


function onPopupArrowable(element) {
    var popupMessage = $('popupMessage');
    var type;
    var id;
    if (element.hasClassName('entity')) {
        type = 'entity';
        id = element.id.substring(1);
    } else if (element.hasClassName('category')) {
        type = 'category';
        id = element.id.substring(1);
    } else if (element.hasClassName('source')) {
        type = 'source';
        id = element.id.substring(1);
    }
    if (element.hasClassName('preferred')) {
        metadataPopupElem.removeClassName('excluded');
        metadataPopupElem.addClassName('preferred');
        var objtype = (type == 'source')? 'source': 'topic';
        updateMetadataPopupMessage(objtype + '_already_preferred_template',
                                   {name: element.innerHTML});
        popupMessage.show();
    } else if (element.hasClassName('excluded')) {
        metadataPopupElem.removeClassName('preferred');
        metadataPopupElem.addClassName('excluded');
        var objtype = (type == 'source')? 'source': 'topic';
        updateMetadataPopupMessage(objtype + '_already_excluded_template',
                                   {name: element.innerHTML});
        popupMessage.show();
    } else {
        metadataPopupElem.removeClassName('preferred');
        metadataPopupElem.removeClassName('excluded');
        popupMessage.hide();
    }
    metadataPopup.arrowed_type = type;
    metadataPopup.arrowed_id = id;
    metadataPopup.context = element;
}

function updateMetadataPopupMessage(key, args) {
    var popupMessage = $('popupMessage');
    var messageTemplate = $(key);
    var message = messageTemplate.innerHTML;
    popupMessage.innerHTML = message.interpolate(args);
}


// TODO: Move to Article
function onClickArticle(event) {
    // the click elements are star, headline, headlineImg, uparrow, downarrow
    // if (event.findElement('.headline') || event.findElement('.headlineImg')) {
    //     Article.read(event);
    //     return;
    // } 

    if (event.findElement('.twitter')) {
        event.stop();

        window.open(event.element().href, 'icSharer','toolbar=0,status=0,width=700,height=500');
        return;

        // NOTE: DISABLING - changing the URL triggered popup blockers in Safari
        // mint the urlstore token
        /* var elem = Article.getElement(event);
        var id = Article.getId(elem);
        new Ajax.Request('/shorturl/mint/' + id, {
            asynchronous: false,
            method: 'get',
            onSuccess: function(transport) {
                var result = transport.responseJSON;
                var url = 'http://icurrent.com/' + result.token;
                var title = result.document.title;

                // shorten the title to fit the length
                var maxlen = 140 - url.length - result.document.source.name.length - 4;
                if (title.length > maxlen) {
                    title = title.truncate(maxlen - 3);
                }

                var message = title + ' [' + result.document.source.name + '] ' + url;
                var twitterUrl = 'http://twitter.com/home?status=' + message + '&source=iCurrent';

                window.open(twitterUrl, 'icSharer','toolbar=0,status=0,width=700,height=500');
            }
        });
        return; */
    }

    if (event.findElement('.facebook')) {
        event.stop();
        window.open(event.element().href, 'icSharer','toolbar=0,status=0,width=700,height=500');
        return;

        // NOTE: DISABLING - changing the URL triggered popup blockers in Safari
        // mint the urlstore token
        /* var elem = Article.getElement(event);
        var id = Article.getId(elem);
        new Ajax.Request('/shorturl/mint/' + id, {
            asynchronous: false,
            method: 'get',
            onSuccess: function(transport) {
                var result = transport.responseJSON;
                var url = 'http://icurrent.com/' + result.token;
                var fbUrl = 'http://www.facebook.com/sharer.php?u=' + url + '&t=' + result.document.title;

                window.open(fbUrl, 'icSharer','toolbar=0,status=0,width=700,height=500');
            }
        });
        return; */
    }

    var star = event.findElement('.star');
    if (star) {
        if (star.hasClassName('unstarred')) {
            Article.star(event);
        } else {
            Article.clearStar(event);
        }
        event.stop();
        return;
    }

    var fun = event.findElement('.fun');
    if (fun) {
        new Ajax.Request(fun.href);
        event.stop();
        return;
    }

}


var Article = {

    getElement: function(event) {
        return event.findElement('.article');
    },

    getId: function(elem) {
        var id = elem.id;
        id = id.substring(1); // strip off 'h'
        if (id.indexOf(':') >= 0) {
            id = id.substring(0, id.indexOf(':'));
        }
        return id;
    },

    getChannelId: function(elem) {
        var index = elem.id.indexOf(':');
        if (index >= 0) {
            return elem.id.substring(index + 1);
        }
        return null;
    },

    arrowUp: function(elem) {
        elem.addClassName('upped');
    },

    arrowDown: function(elem) {
        Effect.Fade(elem, {duration: 1.0});
    },

    mouseOver: function(event) {
        var elem = event.findElement('.article');
        var inner = elem.down('.addtlActions');
        if (inner) {
            Effect.Appear(inner, {
                duration: 0.25,
                afterSetup: function() {
                    elem.down('.star').addClassName('active');
                }
            });
        }
    },

    mouseOut: function(event) {
        var elem = event.findElement('.article');
        var inner = elem.down('.addtlActions');
        if (inner) {
            Effect.Fade(inner, {
                duration: 0.25,
                afterSetup: function() {
                    elem.down('.star').removeClassName('active');
                }
            });
        }
    },

    read: function(event) {
        var elem = Article.getElement(event);
        var id = Article.getId(elem);
        var channelId = Article.getChannelId(elem);
        var a = event.findElement('a');
        if (!a) return;

        var url = '/article/markread/' + id;
        if (channelId) url = URL.appendRequestParam(url, 'channel', channelId);

        // check for the ref
        if ($('overview')) {
            if (a.up('#topForYou')) {
                url = URL.appendRequestParam(url, 'ref', 'topForYou');
            } else if (a.up('#topNews')) {
                url = URL.appendRequestParam(url, 'ref', 'topNews');
            } else if (a.up('.block.general')) {
                url = URL.appendRequestParam(url, 'ref', 'newsAndWeb');
            } else {
                url = URL.appendRequestParam(url, 'ref', 'frontpage');
            }
        } else if ($('channelfront')) {
            url = URL.appendRequestParam(url, 'ref', 'channel');
        } else if ($('sectionfront')) {
            url = URL.appendRequestParam(url, 'ref', 'section');
        } else if ($('sharedfront')) {
            url = URL.appendRequestParam(url, 'ref', 'shared');
        } else if ($('gallery')) {
            url = URL.appendRequestParam(url, 'ref', 'gallery');
        } else if ($('starred')) {
            url = URL.appendRequestParam(url, 'ref', 'starred');
        }

        new Ajax.Request(url);
    },

    star: function(event) {
        var elem = Article.getElement(event);
        var id = Article.getId(elem);
        var channelId = Article.getChannelId(elem);
        var elem = event.findElement('.star');
        if (!elem) return;

        elem.removeClassName('unstarred');
        elem.addClassName('starred');
        elem.removeClassName('onroll');
        var url = '/article/star/' + id;
        if (channelId) url += '?channel=' + channelId;
        new Ajax.Request(url, {
            parameters: {'xhr': true}
        });
    },

    clearStar: function(event) {
        var elem = Article.getElement(event);
        var id = Article.getId(elem);
        var channelId = Article.getChannelId(elem);
        var elem = event.findElement('.star');
        if (!elem) return;

        elem.removeClassName('starred');
        elem.addClassName('unstarred');
        elem.addClassName('onroll');
        var url = '/article/unstar/' + id;
        if (channelId) url += '?channel=' + channelId;
        new Ajax.Request(url, {
            parameters: {'xhr': true}
        });
    },

    getTitle: function(elem) {
        return elem.down('.headline').down('a').innerHTML;
    },

    getUrl: function(elem) {
        return elem.down('.headline').down('a').href;
    }
}

var URL = {
   
    appendRequestParam: function(url, name, val) {
        val = encodeURIComponent(val);
        if (url.indexOf('?') > 0) {
            return url + '&' + name + '=' + val;
        } else {
            return url + '?' + name + '=' + val;
        }
    }
}

function decorateSaveChannelDialog() {
    $('saveSection').observe('change', function(event) {
        var selectBox = event.element();
        var option = selectBox.options[selectBox.selectedIndex];
        if (option.id == 'newSectionOption') {
            selectBox.hide();
            selectBox.disable();
            $('newsection').enable();
            $('newsection').show();
            $('newsection').activate();
        }
    });
}

function flashMessage(message) {
    var div = new Element('div', {'class': 'flashMessage', 'style': 'display: none;'});
    $('container').insert({'before': div});
    div.setStyle({'position': 'fixed', 'width': '100%'});
    var paddedContainer = new Element('div');
    var messageDiv = new Element('div', {'class': 'flashMessageContent'}).update(message);
    paddedContainer.insert(messageDiv);
    div.insert(paddedContainer);
    new Effect.BlindDown(div, {
        delay: .2, // avoid flash by allowing browser to redraw
        duration: .5,
        afterFinish: function() {
            new Effect.BlindUp(paddedContainer, {delay: 3, duration: .5});
        }
    });
}


var Footer = {

    decorate: function() {
        var footer = $('footer');
        if (footer) footer.observe('click', Footer.onClick);
    },

    onClick: function(event) {
        var a = event.findElement('a');
        if (event.findElement('.popup')) {
           Footer.openPopup(a.href);
           event.stop();
        }
    },

    openPopup: function(href) {
        var w = window.open(href, 'icFooterPopup', 'width=800,height=570,scrollbars=auto');
        w.focus();
    }

}


var Channel = {

    onFollow: function(event) {
       var options = Object.extend({ 
            onComplete: Prototype.emptyFunction,
            onSuccess: Prototype.emptyFunction
        }, arguments[1] || { });

        event.stop();
        var followElem = event.findElement('.follow');

        new Ajax.Request(followElem.href, {
            method: 'post',
            parameters: {'xhr': 'true'},
            onSuccess: function(transport) {
                var response = transport.responseJSON;
                flashMessage(response.message);

                var channel = response.channel;
                Navbar.addChannel(channel.id, channel.urlpart, channel.label, channel.section.id);

                event.findElement('.follow').hide();

                options.onSuccess(transport);
            },
            onComplete: options.onComplete
        });
    },

    onDelete: function(event) {
       var options = Object.extend({ 
            onComplete: Prototype.emptyFunction,
            onSuccess: Prototype.emptyFunction
        }, arguments[1] || { });

        event.stop();
        var confirmed = confirm('Are you sure you want to delete this Channel?');
        if (!confirmed) return;

        var deleteElem = event.findElement('a');

        new Ajax.Request(deleteElem.href, {
            parameters: {'xhr': 'true'},
            onSuccess: function(transport) {
	        var response = transport.responseJSON;
	        var channel = response.channel;
                flashMessage(response.message);

                // remove the navbar item
                Navbar.removeChannel(channel.id);

                options.onSuccess(transport)
            },
            onComplete: options.onComplete
        });
    }

}


var TuningDialog = {

    show: function(article, arrow) {
        var articleId = Article.getId(article);
        var channelId = Article.getChannelId(article);

        var url = '/dialog/arrow/' + articleId + '?arrow=' + arrow + '&channel=' + channelId;
        new Ajax.Request(url, {
            method: 'get',
            onSuccess: function(transport) {
                $('arrowingContent').update(transport.responseText);

                TuningDialog.decorate(channelId, article, arrow);
                arrowDialog.show();
            }
        });
    },

    decorate: function(channelId, article, arrow) {
        var cancelButton = $('arrowCancelButton');
        if (cancelButton) {
            cancelButton.observe('click', TuningDialog.onClickCancel);
        }

        var tuningForm = $('tuningForm');
        tuningForm.observe('submit', TuningDialog.onSubmitArrowingForm.bindAsEventListener(this, channelId, article, arrow));

        // decorate the add your own topic box
        var addTopicInput = $('addTopic');
        if (addTopicInput) {
            var addTopicCheckbox = $('addTopicCheckbox');
            decorateHelpText($('arrowingContent'));
            addTopicInput.observe('focus', TuningDialog.onFocusTopicInput);
            addTopicInput.observe('blur', TuningDialog.onBlurTopicInput);
            addTopicCheckbox.observe('click', TuningDialog.onClickTopicInput);
        }
    },

    onSubmitArrowingForm: function(event, channelId, article, arrow) {
        var arrowingForm = $('tuningForm');

        // if they checked anything and aren't on the overview, reload
        var hijack = true;
        if (page != 'overview' && page != 'section') {
            arrowingForm.getInputs().each(function(input) {
                if (input.checked) hijack = false;
            });
        }

        if (hijack) {
            event.stop();
            arrowingForm.request({
                parameters: {'xhr': 'true'},
                onSuccess: function(transport) {
                    var response = transport.responseJSON;
                    var channel = response.channel;
                    var message = response.message;

                    if (arrow == 'up') { 
                        Article.arrowUp(article);
                    } else {
                        Article.arrowDown(article);
                    }

                    // check if the result has a new channel id
                    if (channel.id != channelId) {
                        updateChannelLinks(channelId, channel);
                    }
                    if (message) {
                        flashMessage(message);
                    }
                },
                onComplete: function(transport) {
                    arrowDialog.hide();
                }
            });
        }
    },

    onClickCancel: function(event) {
        arrowDialog.hide();
    },

    onFocusTopicInput: function(event) {
        var addTopicCheckbox = $('addTopicCheckbox');
        addTopicCheckbox.checked = true;
        $('addTopic').addClassName('focused');
    },

    onBlurTopicInput: function(event) {
        var addTopicInput = $('addTopic');
        var addTopicCheckbox = $('addTopicCheckbox');
  
        addTopicInput.removeClassName('focused');
        if (addTopicInput.value == '' || 
                addTopicInput.value == addTopicInput.title) {
            addTopicCheckbox.checked = false;
            addTopicInput.removeClassName('active');
        } else {
            addTopicCheckbox.checked = true;
            addTopicInput.addClassName('active');
        }
    },

    onClickTopicInput: function(event) {
        var addTopicInput = $('addTopic');
        var addTopicCheckbox = $('addTopicCheckbox');

        if (addTopicInput.value == addTopicInput.title) {
            addTopicInput.value = '';
        }
        if (addTopicCheckbox.checked) {
            addTopicInput.activate();
        }
    }

}
