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

	$.fn.validator = function(options) {
		var opts = $.fn.validator.setting(options);
		if (opts.showContainer) {
			$(opts.showContainer).hide();
		}
		$('input,select,textarea', this).each(function(i) {
			var name = $(this).attr('name');
			if (opts.onchange) {
				$(this).change( function() { $(this).valid(options.rules[name]) });
			}
			if (opts.onkeyup) {
				$(this).keyup( function() { $(this).valid(options.rules[name]) });
			}
			if (opts.onblur) {
				$(this).blur( function() { $(this).valid(options.rules[name]) });
				$(this).focus( function() { $(this).onfocus(options.rules[name]) });
			}
		});
		
		$(this).submit( function () {
			if (!opts.onsubmit || !opts.enabled) return true;
			var flag = true; var isFocus = false;
			$('input,select,textarea', this).each(function(i) {
				var name = $(this).attr('name');
				if ($(this).valid(options.rules[name]) == false) {
					flag = false;
					if (!isFocus) {
						$(this).focus();
						isFocus = true;
					}
				}
			});
			if (options.submitHandler) {
				flag = options.submitHandler(flag, opts);
			}
			return flag;
		});
	};
	
	$.fn.validator.setting = function(options) {
		$.fn.validator.defaults = $.extend($.fn.validator.defaults, options);
		return $.fn.validator.defaults;
	};

	$.fn.validator.defaults = {
		enabled: 1,
		showContainer: false,
		tipClass: 'valid_tip',
		focusClass: 'valid_focus',
		errorClass: 'valid_error',
		successClass: 'valid_success',
		inputTipClass: 'input_tip',
		inputFocusClass: 'input_focus',
		inputErrorClass: 'input_error',
		inputSuccessClass: 'input_success',
		onkeyup: false,
		onchange: false,
		onblur: false,
		onsubmit: true
	};

	$.fn.valid = function(rule) {
		var name = $(this).attr('name');
		var val = $.trim($(this).val());
		
		var func = rule ? rule['func'] : eval($(this).attr('func'));
		var validates = rule ? rule['valid'] : $(this).attr('valid');
		var errorTexts = rule ? rule['errorText'] : $(this).attr('errorText');
		var successText = rule ? rule['successText'] : $(this).attr('successText');

		if (validates) validates = validates.split('|');
		if (errorTexts) errorTexts = errorTexts.split('|');
		if (!validates) validates = [];
		
		for (j=0; j<validates.length; j++) {
			var validate = validates[j];
			var errorText = errorTexts[j];
			if (errorTexts.length <= 1) {
				errorText = errorTexts[0];
			}
			if (!validate) { continue; }
			switch(validate) {
				case 'required':
					if (val == '') {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'string':
					var patrn=/^[A-Za-z]+$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'password':
					var patrn=/^(.+){6,16}$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'strlen':
					var length = val.length;
					var arr = val.match(/[\u4e00-\u9fa5]/ig); //中文两字节
					if (arr != null) length += arr.length;

					_min = rule ? rule['minlen'] : $(this).attr('minlen');
					_max = rule ? rule['maxlen'] : $(this).attr('maxlen');
					if (length < parseInt(_min) || length > parseInt(_max)) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'range':
					_min = rule ? rule['min'] : $(this).attr('min');
					_max = rule ? rule['max'] : $(this).attr('max');
					if (parseInt(val) < parseInt(_min) || parseInt(val) > parseInt(_max)) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'notZero':
					if (parseFloat(val) == 0) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'equal':
					var compare = rule ? rule['compare'] : $(this).attr('compare');
					if ($(compare).val() != val && compare != val) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'notEqual':
					var compare = rule ? rule['compare'] : $(this).attr('compare');
					if ($(compare).val() == val || compare == val) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'lt':
					var compare = rule ? rule['compare'] : $(this).attr('compare');
					if (val != '' && parseFloat($(compare).val()) < parseFloat(val)) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'gt':
					var compare = rule ? rule['compare'] : $(this).attr('compare');
					if (val != '' && parseFloat($(compare).val()) > parseFloat(val)) {
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'email':
					var patrn=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'numeric':
					var patrn=/^\d+(\.\d+)?$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'phone':
					var patrn=/(^0\d{10,11}$)|(^(1|01)\d{10}$)/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'telphone':
					var patrn=/^(0\d{2,3}\-?)?\d{7,8}$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'mobile':
					var patrn=/^(1|01)\d{10}$/;
					if( !patrn.test(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'zip':
					var patrn=/^[1-9]\d{5}$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'chinese':
					var patrn=/[\u4e00-\u9fa5]/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				case 'currency':
					var patrn=/^\d+(?:\.\d{0,2})?$/;
					if( !patrn.exec(val) && val != ''){
						$.showText('error', $(this), errorText);
						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(val) && val != ''){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
				default:
					if(!validate.exec(val) ){
						$.showText('error', $(this), errorText);
						return false;
					}
					break;
			}
			$.showText('success', $(this), successText);
		}
		
		//回调方法
		if (func) { 
			msg = func($(this));
			if (msg != true) {
				$.showText('error', $(this), msg);
				return false;
			}
			else {
				$.showText('success', $(this));
			}
		}

		return true;
	};
	
	$.fn.onfocus = function(rule) {
		var name = $(this).attr('name');
		var opts = $.fn.validator.defaults;
		
		var focusText = rule ? rule['focusText'] : $(this).attr('focusText');
		if (focusText) { $.showText('focus', $(this), focusText); }
	};
	
	$.showText = function (type, obj, msg) {
		var opts = $.fn.validator.defaults;
		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(']', ''); }

		switch (type) {
			case 'tip':
				var curClass = opts.tipClass; 
				var curInputClass = opts.inputTipClass;
				break;
			case 'focus': 
				var curClass = opts.focusClass; 
				var curInputClass = opts.inputFocusClass;
				break;
			case 'error': 
				var curClass = opts.errorClass; 
				var curInputClass = opts.inputErrorClass;
				break;
			case 'success': 
				var curClass = opts.successClass; 
				var curInputClass = opts.inputSuccessClass;
				break;
		}
		
		var html = '<span id="_'+name+'_msg" class="'+curClass+'">'+(msg ? msg : '&nbsp;')+'</span>';
		$(obj).removeClass(opts.inputFocusClass);
		$(obj).removeClass(opts.inputSuccessClass);
		$(obj).removeClass(opts.inputErrorClass);
		$(obj).removeClass(opts.inputTipClass);
		$(obj).addClass(curInputClass);

		$('#_'+name+'_msg').remove();
		if (opts.showContainer) {
			$(opts.showContainer).show().append(html);
		} else {
			$(obj).parent().append(html);
		}
	};
	
	
	$.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)
	{
		s = s.toString();
		$(this).each(function (){
			$(this)[0].checked = (s.indexOf($(this)[0].value) >= 0);
		});
		//$(this).val(s);
	};
	
	$.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, doms)
	{
		var flag = true;
		var bt_flag = false;
		$(doms ? doms : '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(); }
	}
});

$.fn.ready(function() { initForm(); });

function initForm() {
	//$('form').validator({onchange: true})
	$('input, select, textarea, button').each(function() {
		var selected = $(this).attr('data-selected');
		var checked = $(this).attr('data-checked');
		var placeholder = $(this).attr('data-placeholder');
		
		if (selected) {
			$('option[value="'+selected+'"]', this).attr('selected', true);
		}
		if (checked) {
			if ($(this).val() == checked) {
				$(this).attr('checked', true);
			}
		}
		if (placeholder) { //占位符
			if ($(this).val() == '') {
				$(this).css('color', '#999').val(placeholder);
			}
			$(this).focus(function() {
				if ($(this).val() == '' || $(this).val() == placeholder) {
					$(this).css('color', '#333').val('');
				}
			});
			$(this).blur(function() {
				if ($(this).val() == '') {
					$(this).css('color', '#999').val(placeholder);
				}
			});
		}
	});
	$('input[type="radio"], input[type="checkbox"]').css('border', 'none');
    $('input.date').datepicker(
		{dateFormat:'yy/mm/dd'},
		{dayNamesMin: ['1', '2', '3', '4', '5', '6', '7']}
	);
    $('input.currency').blur(function() {
    	var num = $(this).val();
		var patrn=/^\d+(\.\d+)?$/;
		if( !patrn.exec(num) && num != ''){
			num = 0;
		}
        num = Number(num).toFixed(2);
        $(this).val(num);
    });
	$('form').submit(function() {
		$(this).find('input[type=text]').each(function() {
			if ($(this).attr('placeholder') == $(this).val()
				|| $(this).attr('data-placeholder') == $(this).val()) {
				$(this).val('');
			}
		});
	});
}