/**
 * jQuery preSubmit plugin file.
 *
 * @author Aliaksandr Astashenkau
 * @author-email dfsq.dfsq@gmail.com
 * @author-website http://dfsq.info
 * @license MIT License - http://www.opensource.org/licenses/mit-license.php
 * @version 1.0
 */
;(function($) {
	$.fn.preSubmit = function(options) {
	    return this.each(function() {
	        var is, fields;
	        is = options || {};

	        if (options.fields) fields = $(options.fields);
	        else {
	        	$(this).find('input[type="text"],input[type="password"],select,textarea').addClass('_preSubmit');
	        	fields = $(this).find('._preSubmit');
	        }

	        if (options.but) {
	            fields = fields.not(options.but);
	        }

	        $(this).submit(function(e) {
	            e.preventDefault();
	            var checked = 0;

	            fields.each(function(k, el) {
            		if($(this).hasClass('email')) {
            			var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(!$(this).val().toUpperCase().match(regEmail)){
							$(this).focus();
		                    if (options.errClass) $(this).addClass(options.errClass);
		                    if (options.onFail) {
			                    options.onFail.call(this);
			                }
							return false;
						}
            		}
            		if($(this).hasClass('multiple_selectbox')) {
            			for (var i = 0; i < el.options.length; i++) {
                            el.options[i].selected = true
                        }
            			if(el.options.length == '0') {
            				$(this).focus();
            				if (options.errClass) $(this).addClass(options.errClass);
            				if (options.onFail) {
    		                    options.onFail.call(this);
    		                }
        					return false;
        		        }
            		}
	                if (!$.trim($(this).val()) || $(this).val() == $(this).attr('ignore')) {
	                    $(this).focus();
	                    if (options.errClass) $(this).addClass(options.errClass);
	                    if (options.onFail) {
		                    options.onFail.call(this);
		                }
	                    return false;
	                }
	                if (options.errClass) $(this).removeClass(options.errClass);
	                checked++;
	            });

	            if (fields.length == checked) {
	                if (options.submit) {
	                    if (options.submit.call(this)) $(this).unbind().submit();
	                } else {
	                	$(this).unbind().submit();
	                }
	            }

	            return false;
	        });
	    });
	};
})(jQuery);
