function doValidation(field, type, language) {
    if (undefined == language) {
        language = 1;
    }
    var value = dojo.trim(field.value);
    dojo.xhrGet( {
        url : "/validate/index/type/" + type + "/value/" + escape(value) +
                "/language/" + language + "/format/json/",
        handleAs : "json",
        timeout : 50000,
        load : function(response, ioArgs) {
            if (response.status == 'valid') {
                displayError(field);
            } else {
                displayError(field, response.message, response.errorCode);
            }
            return response;
        },
        error : function(response, ioArgs) {
            console.log(response);
            field.className = 'inputTimeout';
            return response;
        }
    });
}

/**
 * This function will set the error for the field using message. If message is
 * blank, it is assumed the field is valid, and the field will be styled as
 * such, otherwise the field is invalid and styled as such with the error
 * message being shown.
 * 
 * @param field node
 * @param message string
 * @return void
 */
function displayError(field, message, code) {
    if (undefined == message) {
        dojo.removeClass(field, 'inputInvalid');
        dojo.addClass(field, 'inputValid');
        dojo.destroy(dojo.byId(field.id + 'Error'));
        return;
    }
    // Make sure error field does not already exist
    dojo.destroy(dojo.byId(field.id + 'Error'));
    dojo.removeClass(field, 'inputValid');
    dojo.addClass(field, 'inputInvalid');
    var errorField = dojo.create('div', {
        id : field.id + 'Error',
        className : 'inputErrorMessage',
        innerHTML : message
    }, dojo.byId(field.id.match(/Field$/) ? field.id : field.id + 'Field'));
    dojo.attr(errorField, 'onclick', 'dojo.destroy(this)');
    if (undefined != code && undefined != s) {
        s.prop8 = code;
        s.t();
    }
}
function handleSelect(field)
{
	if(''==field.value)
	{
		displayError(field, reqFieldTxt, 'required_field_empty_' + field.name);
	}
	else
	{
		displayError(field);
	}
}

function pwdVerify(field) {
    var value1 = field.value;
    var value2 = dojo.byId("password").value;
    if (value1 != value2) {
        /**
         * This should be migrated to an ajax request for localizbility
         */
        displayError(field, 'Passwords do not match', 'password_no_match');
    } else {
        displayError(field);
    }
}

function validateForm(form, langId, autoSubmit) {
	if (undefined == langId) {
        var langId = 1;
    }
    var revalidated = false;
    if (undefined == autoSubmit) {
    	autoSubmit = false;
    }
    if (form.id) {
    	var validForm = true;
        var fields = dojo.query('form#' + form.id + ' [required]');
        dojo.forEach(fields, function(item) {
            var validated = false;
            //if (!autoSubmit) {
                if (item.tagName.match(/^input$/i)) {
                    if (item.type.match(/^text$/i)) {
                        if ('' == dojo.trim(item.value)) {
                            validForm = false;
                            /**
                             * This should be migrated to an ajax request for localizbility
                             */
                            displayError(item, reqFieldTxt, 'required_field_empty_' + item.name);
                            validated = true;
                        }
                    } else if (item.type.match(/^radio$/i)) {
                        var buttons = dojo.query('form#' + form.id + ' [name='
                                + item.name + ']');
                        var buttonSelected = false;
                        dojo.forEach(buttons, function(button) {
                            if (button.checked) {
                                buttonSelected = true;
                            }
                        });
                        if (!buttonSelected) {
                            validForm = false;
                            /**
                             * This should be migrated to an ajax request for localizbility
                             */
                            displayError(dojo.byId(item.name + 'Field'), reqFieldTxt, 'required_field_empty_' + item.name);
                            validated = true;
                        } else {
                            displayError(dojo.byId(item.name + 'Field'));
                        }
                    } else if (item.type.match(/^checkbox$/i)) {
                        if (!item.checked) {
                            validForm = false;
                            /**
                             * This should be migrated to an ajax request for localizbility
                             */
                            displayError(item, reqFieldTxt, 'required_field_empty_' + item.name);
                            validated = true;
                        }
                    }
                } else if (item.tagName.match(/^select$/i)) {
                    if ('' == item.value) {
                        validForm = false;
                        /**
                         * This should be migrated to an ajax request for localizbility
                         */
                        displayError(item, reqFieldTxt, 'required_field_empty_' + item.name);
                        validated = true;
                    }
                    else
                    {
                    	displayError(item);
                    }
                }
            //}
            if (dojo.hasAttr(item, 'validator') && !item.className.match('inputValid')) {
                validForm = false;
                if (!autoSubmit && !validated) {
                    doValidation(item, dojo.attr(item, 'validator'), langId);
                    if (!revalidated) {
                        revalidated = true;
                        setTimeout(function(){validateForm(form, langId, true);}, 500);
                    }
                }
            }
        });
        if (validForm) {
        	console.log('submit');
            form.submit();
        } else if (!validForm && !revalidated) {
            //setTimeout(function(){validateForm(form, langId, true);}, 250);
        }
        return validForm;
    }
}
dojo.addOnLoad(function() {
    /*if (undefined == langId) {
        var langId = 1;
    }*/
    var forms = dojo.query('form');
    dojo.forEach(forms, function(form) {
        dojo.attr(form, 'onsubmit', 'return validateForm(this, langId)');
        var inputs = dojo.query("#" + form.id + " *");
        dojo.forEach(inputs, function(input) {
            if (dojo.hasAttr(input, 'validator')) {
                dojo.connect(input, 'onchange', null, function() {doValidation(this, dojo.attr(input, 'validator'), langId)});
            }
            else {
            	dojo.connect(input, 'onchange', null, function() {handleSelect(this)});                
            }
        });
    });
});
