_.templateSettings = {
    interpolate: /\[\[(.+?)\]\]/g
};

$(function(){
    var save_proposal_data = function(cb) {
        var form = $('form#proposal-data');
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: form.attr('action'),
            data: JSON.stringify({
                id: form.find('#id_id').val(),
                title: form.find('#id_title').val(),
                client_full: form.find('#id_client_full').val(),
                client_short: form.find('#id_client_short').val()
            }),
            success: function() {
                cb && cb();
            },
            error: function(resp) {
                alert("Error saving proposal.");
            }
        });
    };
    $('form#proposal-data input').change(function() {
        save_proposal_data();
    });
    $('#save-draft-button').click(function() {
        save_proposal_data(function() {
            window.location = '/proposals/';
        });
        return false;
    });
    $('#publish-button').click(function() {
        save_proposal_data(function() {
            $('#publish-form').submit();
        });
        return false;
    });
    $('.remove-snippet').live('click', function() {
        var id = $(this).parents('.proposal-snippet').find('.id').text();
        ProposalSnips.remove(id);
        $(this).parents('.proposal-snippet').remove();
        save_ordering();
        return false;
    });

    // Base ------------------------------------------------------------------------
    window.SnippetVersion = Backbone.Model.extend({
        defaults: {},
        clear: function() {
            this.destroy();
        },
        remove: function() {
        }
    });

    // Library Snippets ------------------------------------------------------------
    window.LibrarySnipList = Backbone.Collection.extend({
        model: SnippetVersion,
        url: '/snippets/a/snippetversion/'
    });
    window.LibrarySnips = new LibrarySnipList;

    window.LibrarySnipView = Backbone.View.extend({
        tagName:  "article",
        template: _.template($('#templates .librarysnip').html()),
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('remove', this.remove, this);
            // TODO: remove this.
            this.model.view = this;
            SetupLibrarySnipUI($(this.el));
        },
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        },
        remove: function() {
            $(this.el).remove();
        },
        clear: function() {
            this.model.clear();
        }
    });
    window.LibraryView = Backbone.View.extend({
        el: $('#snippet-library'),

        addSnip: function(sv) {
            var view = new LibrarySnipView({model: sv});
            this.$('#snippet-library-list').append(view.render().el);
        },
        addAll: function(svs) {
            svs.each(this.addSnip);
        },
        initialize: function() {
            LibrarySnips.bind('add',   this.addSnip, this);
            LibrarySnips.bind('reset', this.addAll, this);
            LibrarySnips.bind('all',   this.render, this);
        },
    });
    window.Library = new LibraryView;


    // Proposal Snippets -----------------------------------------------------------
    window.ProposalSnipList = Backbone.Collection.extend({
        model: SnippetVersion,
        url: '/snippets/a/snippetversion/'
    });
    window.ProposalSnips = new ProposalSnipList;

    window.ProposalSnipView = Backbone.View.extend({
        tagName:  "article",
        template: _.template($('#templates .proposalsnip').html()),
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('remove', this.remove, this);
            SetupProposalSnipUI($(this.el));
        },
        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
            $(this.el).find('.tooltip').tipsy();
            return this;
        },
        remove: function() {
            $(this.el).remove();
            $('.tipsy').remove();
        },
        clear: function() {
            this.model.clear();
        }
    });
    window.ProposalView = Backbone.View.extend({
        el: $('#proposal'),

        addSnip: function(sv) {
            var view = new ProposalSnipView({model: sv});
            this.$('#proposal-snippets').append(view.render().el);
        },
        addAll: function(svs) {
            svs.each(this.addSnip);
        },
        initialize: function() {
            ProposalSnips.bind('add',   this.addSnip, this);
            ProposalSnips.bind('reset', this.addAll, this);
            ProposalSnips.bind('all',   this.render, this);
        }
    });
    window.Proposal = new ProposalView;

    // Set up the UI ---------------------------------------------------------------
    var save_ordering = function() {
        var ids = $('#proposal-snippets .id').map(function(i, e) { return $(e).text(); }).get();
        var current_proposal = $('#proposal-id').text();

        $.ajax({
            type: 'post',
            dataType: 'json',
            url: '/proposals/a/' + current_proposal + '/reorder/',
            data: JSON.stringify({
                snippet_versions: ids.join(',')
            }),
            success: function(resp) {
                $('#proposal-snippets .library-snippet').remove();
                $('#proposal-snippets .proposal-snippet').remove();
                $('#snippet-library-list .library-snippet').remove();

                LibrarySnips.remove(LibrarySnips.models);
                LibrarySnips.reset(resp.lib_sv_json);
                ProposalSnips.remove(ProposalSnips.models);
                ProposalSnips.reset(resp.prop_sv_json);
            },
            error: function(resp) {
                alert("Error reordering snippets.");
            }
        });
    }
    $('#proposal-snippets').sortable({
        'tolerance': 'intersect',
        update: function(event, ui) {
            save_ordering();
        },
    });
    window.SetupLibrarySnipUI = function(el) {
        el.draggable({
            connectToSortable: "#proposal-snippets",
            helper: "clone",
            revert: "invalid",
            stop: function(event, ui) {
                var id = $(event.target).find('.id').text();
                LibrarySnips.remove(id);
                save_ordering();
            }
        });
    };
    window.SetupProposalSnipUI = function(el) {
    };

    $('form a.custom-button').click(function() {
        $(this).parents('form').submit();
        return false;
    });
});