var FormValidator = function() {
    // html tags witch be validate
    var tags = ['input', 'textarea'];
    var rules = {
        email : {
            reg     : /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
            message : "This field require a valid email address"},
        text : {
            reg     : /[^\s]+/,
            message : "This field require a text"},
        phone: {
            reg     : /^\+?\d{0,3}\s?(\(\d{3,6}\)|\d{1,2})(\s|-|\d)+\d+$/,
            message : "This field require a valid phone number"}

    };

    var errorTemplate = "!";

    var checkForValid = function() {
        var value = this.value;
        if (value != "") {
            this.onkeyup = function() {
            };
            var marker = this.nextSibling;
            this.parentNode.removeChild(marker);
        }
    }

    var cleanItem = function(){
        this.value = this.hiddenValue || "";
        this.style.color = "black";
        this.onfocus = function(){};
    }

    var setItemNotValid = function(item, message) {
        if (!item.nextSibling) {
            var node = document.createElement('span'); //create markNode witch add to item
            node.style.color = 'red';
            node.style.marginLeft = '2px';
            node.style.fontSize = 'bold';
            var text = document.createTextNode(errorTemplate);
            node.appendChild(text);
            item.parentNode.appendChild(node);
        }

        item.onkeyup = checkForValid; // check need of markNode 

        item.style.color = "lightgrey";
        item.hiddenValue = message == item.value ? "" : item.value;
        item.value = message; //display required message

        item.onfocus = cleanItem; //clean requirement message on focus
    }

    var validateItem = function(item, type) {
        if (rules[type].reg.test(item.value.trim())) {
            return true;
        } else {
            setItemNotValid(item, rules[type].message);
            return false;
        }
    }

    var validateForm = function(e) {
        var form = e.target;
        var validForm = true;
        for (var i = 0; i < tags.length; i++) {
            var nodes = form.getElementsByTagName(tags[i]);
            for (var j = 0; j < nodes.length; j++) {
                var node = nodes[j];
                var rAttribute = node.getAttribute('required');
                if (rAttribute) {
                    var validItem = validateItem(node,rAttribute.toLowerCase());
                    validForm = validForm ? validItem : false;
                }
            }
        }
        return validForm;
    };

    var init = function() {
        var forms = document.getElementsByTagName('form');
        for (var i = 0; i < forms.length; i++) {
            forms[i].onsubmit = validateForm;
        }
    }
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
    return {
        init : init
    }
}();
