var ICApp = {};


window.onload = function() {
    $$('.star').invoke('observe', 'click', onClickStar);

    decorateSettings();

    $$('.delete-channel').each(function (elem) {
        elem.href = '#';
        elem.observe('click', onClickDelete);
    });

    if ($('hide-channel-dialog')) {
        ICApp.hideChannelDialog = new ModalDialog('hide-channel-dialog', {
            onClick: HideChannelDialog.onClick
        });
    }

    var hideChannelAction = $('hide-channel-action');
    if (hideChannelAction) {
        hideChannelAction.observe('click', function(event) {
            if (!confirm('Are you sure you want to hide this Channel?')) event.stop();
        });
    }

    var deleteChannelAction = $('delete-channel-action');
    if (deleteChannelAction) {
        deleteChannelAction.observe('click', function(event) {
            if (!confirm('Are you sure you want to delete this Channel?')) event.stop();
        });
    }

    $$('.follow').invoke('observe', 'click', onClickFollow);
    $$('.undo').invoke('observe', 'click', onClickUndoAddChannel);
    $$('.remove').invoke('observe', 'click', onClickRemoveChannel);

    var addInterestForm = $('add-interest-form');
    if (addInterestForm) addInterestForm.observe('submit', onSubmitAddInterestForm);
}

function onSubmitAddInterestForm(event) {
    event.stop();
    var form = event.findElement('form');
    var table = form.up('.main-block').down('table');
    var input = form.down('input[type="search"]');
    new Ajax.Request('/channels/create', {
        parameters: {'q': input.value, 'xhr': 'true'},
        onCreate: function(transport) {
            input.value = '';
        },
        onSuccess: function(transport) {
            var channel = transport.responseJSON.channel;
            addChannelRow(channel, table);
        }
    });
}

function addChannelRow(channel, table) {
    var tr = new Element('tr', {'class': channel.id});
    tr.insert({'bottom': new Element('td').update(new Element('span', {'class': 'channel-link'}).update(channel.label))});

    // add the remove link
    var remove = new Element('a', {'class': 'undo', 'href': '/channels/unsubscribe/' + channel.id});
    remove.update(new Element('span', {'class': 'delete-icon'}));
    remove.insert({'bottom': ' Remove'});
    tr.insert(new Element('td').update(remove));

    remove.observe('click', onClickRemoveChannel);

    table.insert(tr);
}

function onClickFollow(event) {
    event.stop();
    var a = event.findElement('a');
    if (!a) return;

    new Ajax.Request(a.href, {
        parameters: {'xhr': 'true'},
        onCreate: function(transport) {
            a.hide();
        },
        onSuccess: function(transport) {
            var result = transport.responseJSON;
            var channel = result.channel;
            $$('.channel-' + result.channel.id).each(function(elem) {
                var a = elem.down('.follow');
                if (a) {
                    a.hide();
                    showAddChannelUndo(channel, a);
                }
            });
        }
    });
}

function showAddChannelUndo(channel, a) {
    var undo = a.next('.undo');
    if (undo) {
        undo.show();
        return;
    }

    // insert the undo span
    var undo = new Element('a', {'class': 'undo', 'href': '/channels/unsubscribe/' + channel.id}).update(new Element('span', {'class': 'delete-icon'}).update('&nbsp;'));
    undo.insert({'bottom': ' Remove'});
    a.insert({'after': undo});

    // trap undo
    undo.observe('click', onClickUndoAddChannel);
}

function onClickRemoveChannel(event) {
    event.stop();
    var a = event.findElement('a');
    new Ajax.Request(a.href, {
        parameters: {'xhr': 'true'},
        onCreate: function() {
            a.up('tr').remove();
        }
    });
}

function onClickUndoAddChannel(event) {
    event.stop();
    var a = event.findElement('a');
    new Ajax.Request(a.href, {
        parameters: {'xhr': 'true'},
        onCreate: function() {
            a.hide();
            a.previous('.follow').show();
        }
    });
}


function submitChangeSectionForm() {
    var form = $('change-section-form');
    form.request({
        parameters: {'xhr': 'true'},
        onSuccess: function(transport) {
            var result = transport.responseJSON;
            // TODO
        }
    });
}

function decorateSettings() {
    var deliveryForm = $('delivery-settings-form');
    if (!deliveryForm) return;

    deliveryForm.select('input[type="checkbox"]').invoke('observe', 'click', function(event) {
        var checkbox = event.findElement('input[type="checkbox"]');
        if (checkbox && checkbox.name == 'section') {
            var sectionRow = event.findElement('tr');
            var channelRows = sectionRow.nextSiblings();
            if (checkbox.checked) {
                channelRows.each(function(row) {
                    row.down('input[type="checkbox"]').enable();
                });
            } else {
                // if checkbox unchecked, disable all
                channelRows.each(function(row) {
                    row.down('input[type="checkbox"]').disable();
                });
            }
        }
    });
}


function onClickDelete(event) {
    event.stop();

    // get the id of the channel
    var elem = event.findElement('.channel-headlines');
    var id;
    elem.classNames().each(function(name) {
        if (name.startsWith('channel-')) {
            id = name.substring(8);
        }
    });

    ICApp.hideChannelDialog.show({'channel': id});
}


function onClickStar(event) {
    event.stop();
    var a = event.findElement('a');
    var article = event.findElement('.article');
  
    // get the article id
    var id;
    article.classNames().each(function(name) {
        if (name.startsWith('article-')) {
            id = name.substring(8);
        }
    });

    var params = {'id': id, 'xhr': true};
    if (a.hasClassName('unstarred')) {
        params['val'] = true;
    } else if (a.hasClassName('starred')) { 
        params['val'] = false;
    }
    new Ajax.Request('/article/star', {
        parameters: params,
        method: 'post',
        onCreate: function(transport) {
            changeStar(a, params['val']);
        },
        onFailure: function(transport) {
            // rollback
            changeStar(a, !params['val']);
            // alert user
            flashMessage("Unable to star at this time.");
        }
    });
}

function changeStar(elem, star) {
    if (star) {
        elem.removeClassName('unstarred');
        elem.addClassName('starred');
    } else {
        elem.removeClassName('starred');
        elem.addClassName('unstarred');
    }
}

function flashMessage(msg) {
    alert(msg);
}


var ModalDialog = Class.create({

    initialize: function(element) {
        this.element = $(element);
        this.args = {};
        this.options = Object.extend({
            onClick: Prototype.emptyFunction
        }, arguments[1] || {});

        this.element.setStyle({position: 'absolute'});
        this.element.observe('click', this.options.onClick.bindAsEventListener(this));
    },

    show: function(args) {
        this.args = args;

        // show the dialog in the center of the screen
        this.position = document.viewport.getScrollOffsets();
        
        var viewportHeight = document.viewport.getHeight();
        var viewportWidth = document.viewport.getWidth();

        // check for viewport undefined - occurs on Android browser
        if (typeof(viewportHeight) == 'undefined') viewportHeight = window.innerHeight;
        if (typeof(viewportWidth) == 'undefined') viewportWidth = window.innerWidth;

        this.position['top'] = this.position['top'] + viewportHeight/2 - this.element.getHeight()/2;
        this.position['left'] = this.position['left'] + viewportWidth/2 - this.element.getWidth()/2;
        this.element.setStyle({
            top: this.position['top'] + 'px',
            left: this.position['left'] + 'px'
        });

        $('overlay').show();
        this.element.show();

        if (navigator.userAgent.indexOf('Pre/1.0') >= 0) {
            this.element.scrollTo();
        }
    },

    hide: function() {
        $('overlay').hide();
        this.element.hide();
    }
});

var HideChannelDialog = {

    onClick: function(event) {
        event.stop();
        var anchor = event.findElement('a');
        if (!anchor) return;

        if (anchor.id == 'hide-button') {
            new Ajax.Request('/channels/hide/' + this.args.channel, {
                parameters: {'xhr': true},
                onCreate: function() {
                    this.hide();
                }.bind(this),
                onSuccess: function(transport) {
                    location.reload();
                }.bind(this),
                onFailure: function(transport) {
                    alert("Unable to complete the request at this time.");
                }.bind(this)
            });
        } else if (anchor.id == 'delete-button') {
            new Ajax.Request('/channels/unsubscribe/' + this.args.channel, {
                parameters: {'xhr': true},
                onCreate: function() {
                    this.hide();
                }.bind(this),
                onSuccess: function(transport) {
                    location.reload();
                }.bind(this),
                onFailure: function(transport) {
                    alert("Unable to complete the request at this time.");
                }.bind(this)
            });
            this.hide();
        } else if (anchor.id == 'cancel-button') {
            this.hide();
        }
    }

};



/* ---------------------------------- */
/* ----- METHODS FOR IPHONE APP ----- */
/* ---------------------------------- */

function toggleStar(url, isStarred, displayOnly) {
    var hash = getHash(url);
    if (!hash) return false;
    var article = findArticle(hash);
    if (!article) return;

    var star = article.down('.star');
    changeStar(star, isStarred);

    if (!displayOnly) {
        var params = {'id': hash, 'xhr': true, 'val': isStarred};
        new Ajax.Request('/article/star', {
            parameters: params,
            method: 'post',
            onFailure: function(transport) {
               // rollback
               changeStar(star, !isStarred);
            }
        });
    }
}

function isStarred(url) {
    var hash = getHash(url);
    if (!hash) return false;
    var article = findArticle(hash);
    if (article) return (article.down('.starred') != null);
    else return false;
}

function getArticles() {
    var hrefs = [];
    $$('.headline a').each(function(elem) {
        hrefs[hrefs.length] = elem.href;
    });
    return hrefs;
}

function getHash(url) {
    var pattern = /http:\/\/icurrent.com\/([A-Za-z0-9]*)(\?.*)?/;
    var matches = url.match(pattern);
    if (!matches) return null;
    else return matches[1];
}

function findArticle(hash) {
    var urlprefix = 'http://icurrent.com/' + hash;
    var retval = null;
    $$('.article').each(function(article) {
        var a = article.down('.headline a');
        if (a.href.indexOf(urlprefix) > -1) retval = article;
    });
    return retval;
}

