// Contains the validator classes
dojo.provide("max_formValidator");
dojo.require("max_base");
dojo.require("max_ajax_base");

dojo.declare('max_formValidator', max_base, {
    constructor: function(form, validateObject) {
        this.form = dojo.byId(form);
        /* B4 I realized that id overwrites form id
		var processed_http = form.action.replace("http://", "");
		var processed_http = processed_http.split("/");
		this.type = processed_http[1] + "-" + processed_http[2];/**/

        var form_name_start_string = "form_";
        var rest_name = form.id.substr(form_name_start_string.length);
        this.type = rest_name.split("_id_")[0];
		
        this.validateUrl = '';
        //url for validation
        if (validateObject.validateUrl) {
            this.validateUrl = validateObject.validateUrl;
        }
		
        this.submitConnection = dojo.connect(this.form, 'submit', this, this.submit);

        if (validateObject.callSubmitAfterValidation
            && dojo.isFunction(validateObject.callSubmitAfterValidation))
            {
            this._submObj = validateObject;
            this.callSubmitAfterValidation = true;
        }
    },
	
    submit: function(e) {
        dojo.stopEvent(e);
        //stop the submit
        this.changeSubmitButtonStyle(false);
        this.doRequest(this.validateUrl + 'form/form/' + this.type, true);
    },
	
    changeSubmitButtonStyle: function (booleanDisable)
    {
        dojo.query("#" + this.form.id + " input[type=submit]").forEach(function(el){
            el.disabled = (booleanDisable == false);
        });
    },

    doRequest: function(ajax_validate_url, submitOnSuccess) {
        var request_object = new max_ajax_validate_submitForm(this.form, ajax_validate_url, this);
        dojo.xhrPost(request_object);
    },

    clearErrors: function() {
        dojo.query("#" + this.form.id + " input,textarea").forEach(function(field){
            var error_box = dojo.byId('error_' + field.id);
            if (error_box) {
                dojo._destroyElement(error_box);
            //remove the error box if it existed
            }
            dojo.removeClass(field, "error");
        });
    },

    displayErrors: function(messages) {
        //var fields = Object.keys(messages);
        for (var x in messages) {
            //every field that generated an error
            var field = dojo.byId(x + "-label");
            if (!field){
                field = dojo.byId(x);
            }
            // Check that field is correct!
            if (field) {
                var id = 'error_' + x;
                //id for error box
				
                var html = '<div  class="form_error" id="' + id + '" style="">';
				
                var list = '<ul>';
                for (var y in messages[x]) {
                    list += '<li>';
                    list += messages[x][y];
                    list += '</li>';
                }
                list += '</ul>';
                html += list + '</div>';
				
                dojo.addClass(field, 'error');
				
                var error_field = dojo.byId("field_" + id);
                if (error_field)
                {
                    error_field.innerHTML = list;
                    dojo.style(error_field, "display", "block");
                    this.flashAnim(error_field, "#FFAAAAA", 3000).play();
                }else{
                    new dojo.NodeList(field).addContent(html, 'last');
                    this.flashAnim(id, "#FFAAAAA", 3000).play();
                }
            }else{
                console.debug("Error when looking for this field: '"+ x + "'! Check validator! ");
                alert("Error occured when validating. Please notify administrator to correct error");
            }
        }
    },

    realSubmit: function() {
        if (this.callSubmitAfterValidation){
            this._submObj.callSubmitAfterValidation(this.form);
        }else{
            dojo.byId(this.form).submit();
        }
    }
});

dojo.declare('max_ajax_validate_submitForm', max_ajax_submitForm, {
    constructor: function(form, ajax_validate_url, parentObject) {
        // Overwrites the max_ajax_base constructor which thinks form is an url
        this.url = ajax_validate_url;
        this.form = form.id;
        this.parent = parentObject;
    },

    load: function(response, ioArgs){
        // Success
        // Clear any old errors
        this.parent.clearErrors();

        if (!response.success)
        {
            if (!response.messages && response.token_error)
            {
                var html = '<h1 style="color: red">Critical error: ' + response.token_error;
                html += '</h1>';
			
                var el = dojo.query("#" + this.form.id + " input[type=submit]");
                for(var i in el){
                    el[i].value = "X";
                    el[i].disabled = true;
                    el[i].addClassName('error');
                    new dojo.NodeList(el[i]).addContent(html, 'after');
                }
            }else if (response.messages){
                //validation failed
                this.parent.displayErrors(response.messages);
                this.parent.changeSubmitButtonStyle(true);
            }else{
                // Major error probably causing a abrupt stop
                dojo.byId(this.form).innerHTML = '<pre>' + response + '</pre>';
            }
        } else {
            // If there was no data in the ajax response in
            // Propagate submit as a real submit since this has only been an ajax submit
            this.parent.realSubmit();
        }
		
        return response;
    }
});
