//系统常用
var H = {
	post : function(url, arg, callback, dataType, ele){
		if(ele){
			$(ele).ajaxSending();
		}
		$.ajax({
			url : url,
			data : arg,
			type : 'POST',
			dataType : dataType || 'html',
			success : function(json){
				$(ele).ajaxDone();
				json.msg = '';
				if(json.status == 0 && H.isset(json.Exception)){
					json.msg += json.Exception + '<br>';
				}
				if(json.status == 0 && H.isset(json.error) && typeof json.error == 'string'){
                    json.msg += json.error + '<br>';
				}
				if(json.status == 0 && H.isset(json.info) && typeof json.info == 'string'){
                    json.msg += json.info + '<br>';
				}
				if(json.msg){
					//H.info(json.msg.replace(/\<br\>$/,''), 3);
					H.alert('danger', json.msg.replace(/\<br\>$/,''))
				}
				callback(json);
			},
			error : function(){
				$(ele).ajaxDone();
				//H.alert('danger','系统发生错误，请稍后重试!');
				callback({status:0, info : '系统发生错误，请稍后重试!'});
			}
		});
	},
	isset:function(){
		var a = arguments,
			l = a.length,
			i = 0,
			undef;
		if (l === 0) {
		  throw new Error('Empty isset');
		}

		while (i !== l) {
		  if (a[i] === undef || a[i] === null) {
		    return false;
		  }
		  i++;
		}
		return true;
	},
	empty : function(mixed_var){
		var undef, key, i, len;
		var emptyValues = [undef, null, false, 0, "", "0"];

		for (i = 0, len = emptyValues.length; i < len; i++) {
			if (mixed_var === emptyValues[i]) {
				return true;
			}
		}

		if (typeof mixed_var === "object") {
			for (key in mixed_var) {
			// should we check for own properties only?
			//if (mixed_var.hasOwnProperty(key)) {
				return false;
			//}
			}
			return true;
		}
		return false;
	},
	date : function(min,max,isHour,skin){
		new WdatePicker({
			skin: skin || 'custom',
			errDealMode:1,
			dateFmt: isHour ? 'yyyy-MM-dd HH:mm' : 'yyyy-MM-dd',
			minDate: min ? "#F{$dp.$D('"+min+"')}" : '',
			maxDate: max ? "#F{$dp.$D('"+max+"')}" : '',
			lang:'zh-cn'
		});
	},
	del : function(url, ele){
		var delId = $('.js-check-one').serializeArray();
		if(H.empty(delId)){
			alert('请选择要删除的记录！');
			return;
		}
		H.info('<font class="text-danger">确认要删除？</font><br>此操作将不可恢复！请谨慎执行。', 4, function(v){
			if(v){
				H.post(url , delId, function(json){
					if(json.status == 1){
						location.href = location.href;
					}else {
						if(H.isset(json.data))
							alert(json.data);
					}
				},'json', ele)
			} else
				return false;
		})

	},
	//弹出 type:success, info, warning, danger
	alert : function(type,str){
		var h = '<div class="alert alert-'+type+' alert-dismissable input_error"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <span>'+str+'</span> </div>';
		if($('.modal:visible').size()){
			$('.modal:visible').find('.modal-body').prepend(h);
		} else if($('#js-alert-box').size()){ //自己在页面中定义一个位置
			$('#js-alert-box').html(h);
			$('#js-alert-box .alert').fixed2Top();
		}else{
			$('#sys-js-alert-box').html(h); //系统自己找位置
			$('#sys-js-alert-box .alert').fixed2Top();
		}
		//$('html, body').animate({scrollTop:0}, 'slow');
	},
	/**
	 * 弹出框
	 * @param  type  1 提示 2成功 3失败 4确认 5前台提示 6前台确认
	 */
	infoCount : 0,
	info : function(msg, type, callback){
		var html = '<div id="js-alert-info-'+H.infoCount+'" class="modal fade"  role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >'+
		    '<div class="modal-dialog">'+
		       ' <div class="modal-content" style="width:500px">'+
		            '<div class="modal-header" style="padding-top:5px;padding-bottom:0px;">'+
		                '<button type="button" class="close js-alert-close-btn"> × </button>'+
		                '<h5 class="modal-title text-info" id="myModalLabel"> 提示 ! </h5>'+
		           '</div>'+
		           '<div class="modal-body">'+
		            	msg +
		            '</div>'+
		            '<div class="modal-footer" style="text-align:center">'+
		            '<button type="button" class="js-alert-sure-btn btn btn-sm btn-primary">';
					if(type == 5 || type == 6) {
						html += '确定';
					} else {
						html += '<i class="glyphicon glyphicon-ok"></i>&nbsp;&nbsp;确定 ';
					}
					html += '</button>';
		            if(type == 4){
		                html += '<button type="button" class="js-alert-close-btn btn btn-sm btn-default"><i style="top:1px" class="glyphicon glyphicon-remove"></i>&nbsp;&nbsp;取消 </button>';
		            } else if(type == 6) {
						html += '<button type="button" class="js-alert-close-btn btn btn-sm btn-default">取消</button>';
					}
		            html += '</div></div></div></div>';
		$('body').append(html);
		var $ele = $('#js-alert-info-'+H.infoCount);
		$('#js-alert-info-'+H.infoCount).modal({backdrop:'static', keyboard : false});
		$ele.find('.js-alert-sure-btn').click(function(){
			if($.isFunction(callback)){
				callback(true);
			}
			$ele.modal('hide');
		});
		$ele.find('.js-alert-close-btn').click(function(){
			if($.isFunction(callback)){
				callback(false);
			}
			$ele.modal('hide');
		});
		$ele.on('hidden.bs.modal', function(){
			$ele.remove();
		})
		H.infoCount++;
	},
	//重载验证码
	reCaptcha : function(ele) {
		$(ele).attr('src' ,H.captchaUrl + '?t=' + new Date().getTime());
	},
	exec : function(command, arg1) {
	    $.get('http://127.0.0.1:5201', {command : command, arg : arg1});
	},
	//返回两位小数点数字
	backTwoDecima : function(field){
		var num = isNaN(field)?0.00:field;
		var f_num = Math.round(num*100)/100;
		var x_num = f_num.toString()
		var pos_decimal = x_num.indexOf('.');
		if (pos_decimal < 0){
			pos_decimal = x_num.length;
			x_num += '.';
		}
		while (x_num.length <= pos_decimal + 2)
		{
			x_num += '0';
		}
		return x_num;
	},
	search : function(ele, re){
		if(H.isset(re)){
			$(ele).parents('form').reset();
			return false;
		}
		var arg = re || $(ele).parents('form').serializeArray();
		//为什么不直接用arg做参数? 因为会引起一些问题
		var url = H.getUrl(arg, $(ele).parents('form'));
		location.href = url.replace(/\/page\/\d+/g, "");
		return false;
	},
	getUrl : function(arg, ele){
		url = location.href;
		url = url.replace(/\/$/, '') + '/';
		//先去掉checkbox的name的url字段
		ele.find('[type="checkbox"]').each(function(){
			var name = $(this).attr('name');
			if(!name)
				return true;//跳到下个循环
			name = name.replace('[]','');
			var reStr = "(\/)"+name+"\/.*\/"; // 将类似 /type/2/ 替换成 /
			var re = new RegExp(reStr, "gm");
			url = url.replace(re, "$1");
		})

		var data = {};
		$.each(arg, function(k, v){
			v.name = v.name.replace('[]','');  // 将 name[] 变成 name
			var reStr = "(\/)"+v.name+"\/.*\/"; // 将类似 /type/2/ 替换成 /
			var re = new RegExp(reStr, "gm");
			url = url.replace(re, "$1");

			if($.trim(v.value) == ''){
				return true;//跳到下个循环
			}
			v.value = encodeURI(v.value);
			if(!H.isset(data[v.name])){
				data[v.name] = v.value;
			}else{
				if(typeof data[v.name] == 'object'){
					data[v.name].push(v.value);
				} else{
					var arr = new Array;
					arr.push(data[v.name])
					arr.push(v.value)
					data[v.name] = arr;
				}
			}
		})
		
		$.each(data, function(k, v){
			if(typeof v == 'string'){
				url += k + '/' + v + '/';
			}else{
				$.each(v, function(i, value){
					url += k + '/' + value + '/';
				})
			}
		})
		return url;
	},
	CenterWindow : function(url,w,h){
		var x = window.screen.availHeight;
		var y = window.screen.availWidth;
		var CenterTop=(x-h)/2;
		var CenterLeft=(y-w)/2;
		window.open(url,"","width="+w+",height="+h+",top="+CenterTop+",left="+CenterLeft+",scrollbars=yes");
	}

}
//jquery扩展
//使用方法 $('button').ajaxSending()
jQuery.fn.extend({
	//通讯时转圈圈效果
	ajaxSending : function(img){
		var $this = $(this);
		var offset = $this.offset();
		var h = $this.outerHeight();
		var w = $this.outerWidth();
		$this.hide();
		$this.before('<div class="ajaxsending"><img src=""/></div>');
		var imgres = 'data:image/gif;base64,R0lGODlhGAAYAPQAAP///wBc/87g//r8/+Dr/7DN/+jw/463/8jc/5zA/9jm/6jI/8DX//L3/3eo/4ay/7jS/2mf/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/wBc/yH5BAkHAAAAIf4aQ3JlYXRlZCB3aXRoIGFqYXhsb2FkLmluZm8AIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAGAAYAAAFriAgjiQAQWVaDgr5POSgkoTDjFE0NoQ8iw8HQZQTDQjDn4jhSABhAAOhoTqSDg7qSUQwxEaEwwFhXHhHgzOA1xshxAnfTzotGRaHglJqkJcaVEqCgyoCBQkJBQKDDXQGDYaIioyO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DA6TAAnAEAkCdQ8ORQcHTAkLcQQODLPMIgIJaCWxJMIkPIoAt3EhACH5BAkHAAAALAAAAAAYABgAAAWtICCOJNA0ZZoOpGGQrDoOBCoSxNgQsQzgMZyIlvOJdi+AS2SoyXrK4umWHM5wNiV0UN3xdLiqr+mENcWpM9TIbrsBkEck8oC0DQqBQGGIz+t3eXtob0ZTPgNrIwQJDgtGAgwCWSIMDg4HiiUIDAxFAAoODwxDBWINCEGdSTQkCQcoegADBaQ6MggHjwAFBZUFCm0HB0kJCUy9bAYHCCPGIwqmRq0jySMGmj6yRiEAIfkECQcAAAAsAAAAABgAGAAABbIgII4k0DRlmg6kYZCsOg4EKhLE2BCxDOAxnIiW84l2L4BLZKipBopW8XRLDkeCiAMyMvQAA+uON4JEIo+vqukkKQ6RhLHplVGN+LyKcXA4Dgx5DWwGDXx+gIKENnqNdzIDaiMECwcFRgQCCowiCAcHCZIlCgICVgSfCEMMnA0CXaU2YSQFoQAKUQMMqjoyAglcAAyBAAIMRUYLCUkFlybDeAYJryLNk6xGNCTQXY0juHghACH5BAkHAAAALAAAAAAYABgAAAWzICCOJNA0ZVoOAmkY5KCSSgSNBDE2hDyLjohClBMNij8RJHIQvZwEVOpIekRQJyJs5AMoHA+GMbE1lnm9EcPhOHRnhpwUl3AsknHDm5RN+v8qCAkHBwkIfw1xBAYNgoSGiIqMgJQifZUjBhAJYj95ewIJCQV7KYpzBAkLLQADCHOtOpY5PgNlAAykAEUsQ1wzCgWdCIdeArczBQVbDJ0NAqyeBb64nQAGArBTt8R8mLuyPyEAOw==';
		var src = img || imgres;
		$('.ajaxsending img').attr('src' , src);
		$('.ajaxsending').css({
			'display' : 'inline-block',
			'height'   : h,
			'width'    : w
		});
	},
	//通信结束 配合上面的函数
	ajaxDone : function(){
		$('.ajaxsending').remove();
		$(this).show();
	},
	//选择全部
	//@param jquery选择对象 同时选中的集合 如 $('slecet')
	//使用方法 $('全部选中').checkAll($('所有要改变的集合'))
	checkAll : function(ele){
		$(this).change(function(){
			if($(this).is(':checked')){
				ele.not(':disabled').attr('checked', 'checked');
			}else{
				ele.not('disable').removeAttr('checked');
			}
		});
	},
	reset : function(){
		$(this).find('input').not('input[type="checkbox"]').val('');
		$(this).find('select').val('');
		$(this).find('input[type=checkbox]').attr('checked',false);
	},
	fixed2Top : function(){
		var $this = $(this);
		var top = $('#js-header').height() + 2;
		var width = $this.parent().width();
		var height = $this.height()+50;
		var h = $('<div id="js-alert-pandding" style="height:'+height+'px"></div>');
		if($(document).scrollTop() > (top)){
			$this.after(h);
			$this.css({position:'fixed', 'z-index':100, width: width, 'display':'block', 'top': top});
		}
		$(window).scroll(function(){
			if($(document).scrollTop() > (top)){
				$this.after(h);
				$this.css({position:'fixed', 'z-index':100, width: width, 'display':'block', 'top': top});
			} else{
				$this.css({position:'static'});
				h.remove();
			}
		});
	}
})

//字符串扩展
$.extend(String.prototype,{
	replaceAll:function(os, ns){
		return this.replace(new RegExp(os,"gm"),ns);
	},
	//验证字符串是否以xxx开头
	startsWith:function (pattern){
		return this.indexOf(pattern) === 0;
	},
	endsWith:function(pattern) {
		var d = this.length - pattern.length;
		return d >= 0 && this.lastIndexOf(pattern) === d;
	}
});


//全局事件
$(document).on('init',function(){
	//必填
	$('[data-rule*="required"]').before('<i class="i-required">*</i>').parent().css('position', 'relative');
	//全选，如果.js-check-all只有一个，选中.js-check-all，则选中所有.js-check-one
	if($('.js-check-all').length == 1){
		$(document).on('change','.js-check-all',function(){
			if($(this).is(':checked')){
				$('.js-check-one').not(':disabled').attr('checked', 'checked');
			}else{
				$('.js-check-one').not('disable').removeAttr('checked');
			}
		})
	}else{
		//可以考虑一下多个，后期优化 @modify yangjiekang
		$(document).on('change','.js-check-all',function(){
			var thisTable = $(this).parents('table');
			if($(this).is(':checked')){
				thisTable.find('.js-check-one').not(':disabled').attr('checked', 'checked');
			}else{
				thisTable.find('.js-check-one').not('disable').removeAttr('checked');
			}
		})
	}

	$('#js-show-search').click(function(){
        if($('#js-search-box').is(':hidden')){
            $('#js-search-box').show();
        }else
            $('#js-search-box').hide();
    })

	$('.js-toggle').each(function(){
		$(this).css({cursor: 'pointer'});
		if($(this).hasClass('js-toggle-hide'))
			$(this).parent().children().not('.js-toggle').not(':hidden').hide();
		else
			$(this).addClass('js-toggle-show')
	});
	$('.js-toggle').click(function(event){
		var ele = $(this).parent().children().not('.js-toggle');
		var hiddenEle = $(this).parent().children(':hidden');
		if($(this).hasClass('js-toggle-show')){
			ele.hide();
			hiddenEle.addClass('js-hiddenEle');
			$(this).addClass('js-toggle-hide').removeClass('js-toggle-show');
		}else{
			ele.not('.js-hiddenEle').show();
			$(this).addClass('js-toggle-show').removeClass('js-toggle-hide');
		}
		event.preventDefault();
		event.stopPropagation();
	})
	// $('#search-btn').parents('form').find('input').keydown(function(){
 //        if(event.keyCode==13){
 //            $('#search-btn').click();
 //            return false;
 //        }
 //    })

	$('.btn-info').parents('form').find('input').keydown(function(event){
        if(event.keyCode==13){
            $('.btn-info').click();
            return false;
        }
    })
    //分页大小更改
    $(document).on('change', '#js-pagesize_change', function(){
    	$(this).ajaxSending();
		var url = $(this).attr('url');
		url = url.replace(/\/$/, '');
		if(url.indexOf('.html') != -1){
			url = url.replace(/\.html$/, '');
			url = url.replace(/\/pagesize\/\d+/, '') + '/pagesize/'+$(this).val() + '.html';
		}else
			url = url.replace(/\/pagesize\/\d+/, '') + '/pagesize/'+$(this).val();
		location.href = url;
    })
    $('.js-top-error').fixed2Top();
})
$(function(){
	$(document).trigger('init');
})


window.alert = function(msg){H.info(msg);}