/*
 * author: blueflu
 */
(function($) {

	$.fn.validator = function(options) {
		$.fn.validator.setting(options, $(this));
		var opts = $.fn.validator.defaults;
		
		if (opts.errorContainer) {
			$(opts.errorContainer).hide();
		}
		$('input,select,textarea', this).each(function(i) {
			if (opts.onchange) {
				$(this).change(function() { $(this).valid() });
			}
			if (opts.onkeyup) {
				$(this).keyup(function() { $(this).valid() });
			}
			if (opts.onblur) {
				$(this).blur(function() { $(this).valid() });
			}
		});
		
		$(this).submit(function chkall() {
			if (!opts.onsubmit || !opts.enabled) return true;
			var flag = true; var is_focus = false;
			flag = opts.submitHandler(this, opts);
			$('input,select,textarea', this).each(function(i) {
				if ($(this).valid() == false) {
					flag = false;
					if (!is_focus) {
						$(this).focus();
						is_focus = true;
					}
				}
			});
			return flag;
		});
	};

	$.fn.valid = function() {
		var name = $(this).attr('name');
		var opts = $.fn.validator.defaults;
		var flag = opts.customizeValid($(this));
		
		var validates = name in opts.rules ? opts.rules[name]['valid'] : $(this).attr('valid');
		var messages = name in opts.rules ? opts.rules[name]['errmsg'] : $(this).attr('errmsg');

		if (validates) validates = validates.split('|'); else return true;
		if (messages) messages = messages.split('|'); else return true;		
		
		for (j=0; j<validates.length; j++) {
			var validate = validates[j];
			var message = messages[j];
			if (messages.length <= 1) {
				message = messages[0];
			}
			switch(validate) {
				case 'required':
					if ($(this).val() == '') {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'string':
					var patrn=/^[A-Za-z]+$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'password':
					var patrn=/^(.+){6,16}$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'strlen':
					var length = $(this).val().length;
					var arr = $(this).val().match(/[\u4e00-\u9fa5]/ig); //ÖÐÎÄÁ½×Ö½Ú
					if (arr != null) length += arr.length;

					_min = parseInt(opts.rules[name]['minlen'] ? opts.rules[name]['minlen'] : $(this).attr('minlen'));
					_max = parseInt(opts.rules[name]['maxlen'] ? opts.rules[name]['maxlen'] : $(this).attr('maxlen'));
					if (length < _min || length > _max) {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'range':
					_min = parseInt(opts.rules[name]['min'] ? opts.rules[name]['min'] : $(this).attr('min'));
					_max = parseInt(opts.rules[name]['max'] ? opts.rules[name]['max'] : $(this).attr('max'));
					if (parseInt($(this).val()) < _min || parseInt($(this).val()) > _max) {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'notZero':
					if (parseFloat($(this).val()) == 0) {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'equal':
					var compare = opts.rules[name]['compare'] ? opts.rules[name]['compare'] : $(this).attr('compare');
					if ($(compare).val() != $(this).val() && compare != $(this).val()) {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'notEqual':
					var compare = opts.rules[name]['compare'] ? opts.rules[name]['compare'] : $(this).attr('compare');
					if ($(compare).val() == $(this).val() || compare == $(this).val()) {
						$.showError($(this), message);
						return false;
					}
					break;
				case 'email':
					var patrn=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'numeric':
					var patrn=/^\d+(\.\d+)?$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'telphone':
					var patrn=/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
				case 'zip':
					var patrn=/^[1-9]\d{5}$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'chinese':
					var patrn=/[\u4e00-\u9fa5]/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'currency':
					var patrn=/^\d+(?:\.\d{0,2})?$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
				case 'idCard':
					var patrn=/^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X)?$/;
					if( !patrn.exec($(this).val()) ){
						$.showError($(this), message);
						return false;
					}
					break;
			}
			$.showSuccess($(this));
		}
		return flag;
	};
	
	$.showError = function (obj, message) {
		var name = $(obj).attr('name') ? $(obj).attr('name') : $(obj).attr('id');
		v = name.split('['); for(i = 0; i < v.length; i++) { name = name.replace('[', '').replace(']', ''); }
		
		var html = '<span id="'+name+'-invalid" class="errmsg">'+message+'</span>';
		var opts = $.fn.validator.defaults;
		$(obj).addClass('invalid');
		//$(obj).focus();
		if (!$('#'+name+'-invalid').text()) { 
			$('#'+name+'-invalid').remove();
			if (opts.errorContainer) {
				$(opts.errorContainer).show().append(html);
			} else {
				$(obj).parent().append(html);
			}
		}
	};
	
	$.showSuccess = function (obj, message) {
		var name = $(obj).attr('name') ? $(obj).attr('name') : $(obj).attr('id');
		v = name.split('['); for(i = 0; i < v.length; i++) { name = name.replace('[', '').replace(']', ''); }

		$('#'+name+'-invalid').remove();
		$(obj).removeClass('invalid');
	};
	
	$.fn.validator.setting = function(options, form) {
		$.fn.validator.defaults = $.extend($.fn.validator.defaults, options);
		$.fn.validator.defaults.currentForm = form;
	};

	$.fn.validator.defaults = {
		enabled: 1,
		currentForm: '',
		errorClass: 'invalid',
		errorContainer: false,
		onkeyup: false,
		onchange: false,
		onblur: false,
		onsubmit: true,
		rules: {},
		submitHandler: function() { return true; },
		customizeValid: function() { return true; }
	};
	
	
	$.fn.selected = function (s)
	{
		if (!s) return;
		var tmp = s.split('|');

		for(i=0; i<this[0].length; i++)
		{
			for(j=0; j<tmp.length; j++) {
				if (this[0][i].value == tmp[j]) {
					this[0][i].selected = true;
					break;
				} else {
					this[0][i].selected = false;
				}
			}
		}
	};
	
	$.fn.selectAll = function (s)
	{
		for(i=0; i<this[0].length; i++)
		{
			this[0][i].selected = s;
		}
	};
	
	$.fn.checked = function (s)
	{
		$(this).each(function (){
			$(this)[0].checked = (s.indexOf($(this)[0].value) >= 0);
		});
	};
	
	$.fn.checkAll = function (s, bt_id)
	{
		$(this).each(function (){
			$(this)[0].checked = s;
		});
		if (bt_id) {
			$(bt_id).each(function (i) {
				$(bt_id)[i].disabled = !s;
				if (s) { $(bt_id).removeClass('disabled'); }
				else { $(bt_id).addClass('disabled'); }
			})
		}
	};
	
	$.fn.checkItem = function (s, bt_id)
	{
		var flag = true;
		var bt_flag = false;
		$('input[name="'+this[0].name+'"]').each(function (){
			if (!this.checked) {
				flag = false;
			} else {
				bt_flag = true;	
			}
		});
		
		if (bt_id) {
			if (bt_flag) { 
				$(bt_id).each(function (i) {
					$(bt_id)[i].disabled = false;
					$(bt_id).removeClass('disabled');
				})
			} else {
				$(bt_id).each(function (i) {
					$(bt_id)[i].disabled = true;
					$(bt_id).addClass('disabled');
				})
			}
		}
		$(s)[0].checked = flag;
	}
})(jQuery);


$.fn.extend({
	onsubmit:function (url, note)
	{
		var flag = true;
		$(this).attr('action', url);
		if (note) { flag = confirm(note); }
		if (flag) {	$(this).submit(); }
	}
});
