if(typeof Prototype=='undefined')
throw("WBS Send Form requires the Prototype JavaScript framework");


var WBSSendForm = Class.create();

WBSSendForm.prototype = {

    initialize: function(){
        this.WBSFeedForms = [];
        var forms = $A(document.getElementsByTagName('form'));

        for(i=0; i<forms.length; i++)
        {
            this.makeHandle(forms[i]);
        }
    },

    makeHandle: function(form){
        this.WBSFeedForms.push(new WBSFeedForm(form));
    }
};

var WBSFeedForm = Class.create();

WBSFeedForm.prototype = {

    initialize: function(form) {
        this.frm = form;
        this.onsubmit = $(this.frm).onsubmit;
        $(this.frm).onsubmit = this.submit.bindAsEventListener(this);
    },

    submit: function(e){
        if(typeof this.onsubmit == 'function' && !this.onsubmit())
        return false;

        var myAjax = new Ajax.Request(
        $(this.frm).action,
        {
            method: 'post',
            parameters: Form.serialize(this.frm),
            onComplete: this.proccess.bind(this)
        });

        //Event.stop(e);
        return false;
    },

    proccess: function(request,oJson){

        var errors = $A(document.getElementsByClassName('wbssendform_error'));
        errors.each(function(error)
        {
            Element.remove(error);
        });

        var el = (typeof oJson.element == 'undefined')?this.frm:oJson.element;

        switch(oJson.mode)
        {
            case 'before':
                new Insertion.Before($(el),oJson.message);
                break;
            case 'top':
                new Insertion.Top(el,oJson.message);
                break;
                case 'bottom':
                new Insertion.Bottom(el,oJson.message);
                break;
            case 'after':
                new Insertion.After(el,oJson.message);
                break;
                case 'update':
                Element.update(el,oJson.message);
                break;
            case 'redirect':
                location.href=oJson.message;
                break;
        }
    }
};

function initWBSSendForm() {myWBSSendForm = new WBSSendForm(); }

Event.observe(window, 'load', initWBSSendForm, false);
