var DEBUG = false;

var Masuelli = {
    open : function() {
        var main = $('main');
        if (main.hasClassName('open')) return;
        if (main.hasClassName('mission')) this.close();

        new Effect.Scale('header', 30, {scaleX : false, beforeSetup : function() {
            $('header_content').style.top = '';
            $('header_content').style.left = '';
        }, queue : 'end'});
        $('content').slideDown({queue : 'end'});
        main.addClassName('open');

    },
    close : function() {
        this.unSelect();
        var main = $('main');
        if (main.hasClassName('mission')) {
            main.removeClassName('mission');
            new Effect.Move('header_content', { x : 0, y : 0, mode : 'absolute', queue: 'end'});
        }
        if (main.hasClassName('open')) {
            main.removeClassName('open');
            $('content').slideUp({queue : 'end'});
            new Effect.Scale('header', 333.5, {scaleX : false, queue : 'end'});
        }
    },
    goToMission : function() {
        this.unSelect();
        var main = $('main');
        if (main.hasClassName('mission')) return;
        main.addClassName('mission');
        new Effect.Move('header_content', { x : -800, y : 0, mode : 'relative', queue : 'end'});
    },
    unSelect : function() {
        $('menu').select('a').each(function(a) {
            a.removeClassName('selected');
            $('content').removeClassName(a.id);
        });
    },
    goTo : function(link) {
        this.section = link.id;
        this.unSelect();
        link.addClassName('selected');
        $('content').addClassName(this.section);

        var parameters = {action : 'get_page', page : this.section};
        new Ajax.Request('action.php', {
            parameters : parameters,
            method : 'get',
            onSuccess: this.generate.bind(this)
        });
    },
    generate : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.success) {
            $('content').update(json.html);

            if (this.section == 'link_contact') this.contact = new Contact();
            if (this.section == 'link_messages') this.msgBoard = new Messages();
            if (this.section == 'link_home') this.newsBoard = new News();
            if (this.section == 'link_store') this.store = new Store();

            this.open();
        }
    }
}

document.observe('dom:loaded', function() {
    $('menu').select('a').each(function(a) {
        a.observe('click', function() {this.goTo(a)}.bindAsEventListener(Masuelli));
    });

    $('link_mission').observe('click', function() {
        Masuelli.goToMission();
    });

    $('link_back_from_mission').observe('click', function() {
        Masuelli.close();
    });

    $('link_intro').observe('click', function() {
        Masuelli.close();
    });

    $('mission').setOpacity(0.8);

});

/*
    Generic Board
*/
var Board = Class.create({
    initialize : function() {
        this.setup();
    },
    setup : function() {
        this.config = {
            urlAction : 'action.php',
            getAction : 'get_messages',
            sendAction : 'send_message',
            deleteAction : 'delete_message',
            getJSONAction : 'get_messages_json',
            prefix : 'MSG'
        };

        this.form = $('message_form');
        this.fields = [$('name_field'), $('email_field'), $('message_field')];
        this.holder = $('messages_content');
        this.errorContainer = $('message_errors');
    },
    formSetUp : function() {
        this.fields.each(function(field) {
            if (!field) return;
            field.observe('focus', function() {
                if (field.hasClassName('edited')) return;
                field.addClassName('edited');
                field.value = '';
            });
        }, this);
    },
    working : function() {
        $$('body').first().addClassName('working');
    },

    idle : function() {
        $$('body').first().removeClassName('working');
    },
    get : function() {
        var parameters = {action : this.config.getAction};
        new Ajax.Request(this.config.urlAction,{
            parameters : parameters,
            method : 'get',
            onSuccess: this.generate.bind(this)
        });
    },
    getJSON : function(id, handler) {
        if (!handler || typeof handler != 'function') return;
        var parameters = {action : this.config.getJSONAction};
        if (id) parameters.id = id;
        new Ajax.Request(this.config.urlAction,{
            parameters : parameters,
            method : 'get',
            onSuccess: function(transport) {handler(transport.responseText.evalJSON(true))}
        });
    },
    send : function() {
        if (this.sending) return;

        this.resetErrors();

        parameters = this.form.serialize(true);
        parameters.action = this.config.sendAction;

        new Ajax.Request(this.config.urlAction,{
            parameters : parameters,
            method : 'post',
            onSuccess: this.sendConfirm.bind(this)
        });

        this.sending = true;
        this.working();

    },
    remove : function(id) {
        parameters = {action : this.config.deleteAction, id : id};

        new Ajax.Request(this.config.urlAction,{
            parameters : parameters,
            method : 'get',
            onSuccess: this.deleteConfirm.bind(this)
        });
    },
    generate : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.success) {
            this.holder.update(json.html);
        }
    },
    sendConfirm : function(transport) {
        this.sending = false;
        this.idle();

        var json = transport.responseText.evalJSON(true);

        if (json.success) {
            if (!DEBUG) this.form.switchOff({queue : 'end'});
            this.holder.insert({top : json.html});
            this.holder.down('div').slideDown({queue : 'end'});
        } else {
            if (json.errors.length) this.report(json.errors);
        }
    },
    deleteConfirm : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.success) {
            node = $(this.config.prefix + json.id);
            if (node) node.puff();
        } else {
            alert(json.error);
        }
    },
    report : function(errors) {
        var node = this.errorContainer;
        if (!node) return;

        var html = '';

        errors.each(function(error) {
            html += '<li>' + error + '</li>';
        });
        html = new Template('<ul>#{content}</ul>').evaluate({content : html});

        node.update(html);
        node.slideDown({queue : 'end'});
    },
    resetErrors : function() {
        var node = this.errorContainer;

        if (!node) return;

        node.hide();
        node.update('');
    }
});

/*
    Messages
*/
var Messages = Class.create(Board, {
    initialize : function($super) {
        $super();
        this.formSetUp();
        this.get();
    },
    send : function($super) {
        if (!this.fields[2].hasClassName('edited') && !DEBUG) return;

        $super();
    },
    deleteMessage : function(id) {
        if (!id) return;
        if (!confirm('Delete Message?')) return;

        this.remove(id);
    }
});

/*
    News
*/
var News = Class.create(Board, {
    setup : function($super) {
        $super();

        this.config.getAction = 'get_news';
        this.config.sendAction = 'send_story';
        this.config.deleteAction = 'delete_story';
        this.config.editAction = 'edit_story';
        this.config.getJSONAction = 'get_news_json';
        this.config.prefix = 'STORY';

        this.form = $('news_form');
        this.fields = [$('title_field'), $('content_field')];
        this.holder = $('news_content');
        this.errorContainer = $('news_errors');
    },
    send : function($super, id) {
        if (id) {
            this.resetErrors();
            var form = $('story_form_' + id)

            parameters = form.serialize(true);
            parameters.action = this.config.editAction;

            new Ajax.Request(this.config.urlAction,{
                parameters : parameters,
                method : 'post',
                onSuccess: this.editConfirm.bind(this)
            });
        } else {
            $super();
        };

    },
    editConfirm : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.success) {
            var story = $(this.config.prefix + json.id);
            var form = $('story_form_' + json.id);

            form.remove();
            story.replace(json.html);
        } else {
            if (json.errors.length) this.report(json.errors);
        }
    },
    deleteStory : function(id) {
        if (!id) return;
        if (!confirm('Delete story?')) return;

        this.remove(id);
    },
    editStory : function(id) {
        if (!id) return;
        var story = $(this.config.prefix + id);
        var form = $('story_form_' + id);
        if (!story || !form) return;

        story.switchOff({queue : 'end'});
        form.slideDown({queue : 'end'});
    },
    cancelEdit : function(id) {
        if (!id) return;
        var story = $(this.config.prefix + id);
        var form = $('story_form_' + id);
        if (!story || !form) return;

        form.switchOff({queue : 'end'});
        story.slideDown({queue : 'end'});
    }
});


/*
    Store
*/
var Store = Class.create(Board, {
    initialize : function($super) {
        $super();
        this.formSetUp();
    },
    setup : function($super) {
        $super();

        this.config.getAction = 'get_products';
        this.config.sendAction = 'send_product';
        this.config.deleteAction = 'delete_product';
        this.config.editAction = 'edit_product';
        this.config.getJSONAction = 'get_products_json';
        this.config.prefix = 'PID';

        this.form = $('store_form');
        this.fields = [$('title_field'), $('description_field'), $('photo_field'), $('buy_field'), $('price_field')];
        this.holder = $('store_content');
        this.errorContainer = $('store_errors');
    },
    send : function($super, id) {
        if (id) {
            this.resetErrors();
            var form = $('product_form_' + id)

            parameters = form.serialize(true);
            parameters.action = this.config.editAction;

            new Ajax.Request(this.config.urlAction,{
                parameters : parameters,
                method : 'post',
                onSuccess: this.editConfirm.bind(this)
            });
        } else {
            $super();
        };

    },
    editConfirm : function(transport) {
        var json = transport.responseText.evalJSON(true);
        if (json.success) {
            var story = $(this.config.prefix + json.id);
            var form = $('product_form_' + json.id);

            form.remove();
            story.replace(json.html);
        } else {
            if (json.errors.length) this.report(json.errors);
        }
    },
    deleteProduct : function(id) {
        if (!id) return;
        if (!confirm('Delete Product?')) return;

        this.remove(id);
    },
    editProduct : function(id) {
        if (!id) return;
        var product = $(this.config.prefix + id);
        var form = $('product_form_' + id);
        if (!product || !form) return;

        product.switchOff({queue : 'end'});
        form.slideDown({queue : 'end'});
    },
    cancelEdit : function(id) {
        if (!id) return;
        var product = $(this.config.prefix + id);
        var form = $('product_form_' + id);
        if (!product || !form) return;

        form.switchOff({queue : 'end'});
        product.slideDown({queue : 'end'});
    }
});


var Contact = Class.create(Board, {
    initialize : function() {
        this.setup();
    },
    setup : function($super) {
        $super();

        this.config.sendAction = 'send_contact_message';

        this.holder = $('content');

        this.form = $('contact_form');
        this.errorContainer = $('contact_errors');

        this.formSetUp();
    },
    formSetUp : function() {
        this.fields.each(function(field) {
            field.observe('focus', function() {
                if (field.hasClassName('edited')) return;
                field.addClassName('edited');
                field.value = '';
            });
        }, this);
    },
    working : function() {
        $$('body').first().addClassName('working');
    },

    idle : function() {
        $$('body').first().removeClassName('working');
    },
    sendConfirm : function(transport) {
        this.sending = false;
        this.idle();

        var json = transport.responseText.evalJSON(true);

        if (json.success) {
            this.holder.update(json.html);
        } else {
            if (json.errors.length) this.report(json.errors);
        }
    }
});