
var debugMode=false; // 是否是调试模式

$(function() {
	var requrl = getSysBaseUrl();
	debugMode = (requrl.startsWith("http://localhost") || requrl.startsWith("http://192.168."));
//	console.log('debugMode='+debugMode+', requrl='+requrl);
	
});

/*
wx.ready(function(){
	// 隐藏所有非基础按钮接口
	wx.hideAllNonBaseMenuItem();
});
*/

/**
 * 获取请求的地址,不包括具体页面路径,到ContextPath止
 * eg. http://192.168.1.10:8080/oa
 */
function getSysBaseUrl(){
	var url = window.location.protocol+'//'+window.location.host;
	var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0,index+1);
    url += result;
    return url;
}

// 微信JS授权配置接口
function getJsConfig(){
	$.getJSON('http://wx.szxgl.cn/qywx/api/jsconfig?url='+encodeURIComponent(window.location.href), function(data) {
  		if(data.ret == 0) {
              wx.config({
            	  beta: true,	// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
                  debug: false,
                  appId : data.appId,
                  timestamp : data.timestamp,
                  nonceStr : data.nonceStr,
                  signature : data.signature,
                  jsApiList: [
                	  'onMenuShareAppMessage'
                	  , 'onMenuShareWechat'
                	  , 'chooseImage'
                	  , 'previewImage'
                	  , 'uploadImage'
                	  , 'downloadImage'
                	  , 'previewFile'
                	  , 'getNetworkType'
                	  , 'openLocation'
                	  , 'getLocation'
                	  , 'onHistoryBack'
                	  , 'hideOptionMenu'
                	  , 'showOptionMenu'
                	  , 'hideMenuItems'
                	  , 'showMenuItems'
                	  , 'hideAllNonBaseMenuItem'
                	  , 'showAllNonBaseMenuItem'
                	  , 'closeWindow'
                	  , 'scanQRCode'
                	  , 'selectEnterpriseContact'
                	  , 'openEnterpriseChat'
                	  , 'chooseInvoice'
                  ]
              });
          } else {
              alert("微信授权失败：" + data.msg);
          }
	});
}

//获取HTTP URL的参数
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]); return null;
}

// 判断字符串是否以str开始
String.prototype.startWith=function(str){     
var reg=new RegExp("^"+str);     
return reg.test(this);        
}
//判断字符串是否以str结尾
String.prototype.endWith=function(str){     
var reg=new RegExp(str+"$");     
return reg.test(this);        
}
// 字符串全部替换
String.prototype.replaceAll = function(s1,s2){
	return this.replace(new RegExp(s1,"gm"),s2);
}
// 字符串截取
function subString(str, len){
	if(isBlank(str))return str;
	if(str.length<=len)return str;
	str = str.substring(0,len)+"...";
	return str;
}


// toast提示信息, 默认为错误信息
function toastMsg(msg){
	toastMsg(msg, -1);
}
//toast提示信息, -1为错误信息, 1为成功的提示信息
function toastMsg(msg,type){
	var $toast = $('#toastBox');
	if(!($toast.length > 0)){
		var toastHtml = 
				 	'<div id="toastBox" style="display: none;">'
				   +'<div class="weui-mask_transparent"></div>'
				   +'<div class="weui-toast">'
				   +'	<i class="weui-icon-cancel weui-icon_toast"></i>'
				   +'	<p class="weui-toast__content"></p>'
				   +'</div>'
				   +'</div>';
		$(document.body).append(toastHtml);
		$toast = $('#toastBox');
	}
	
	if(type == 1){
		// 成功
		$toast.find('.weui-icon_toast').removeClass('weui-icon-cancel');
		$toast.find('.weui-icon_toast').addClass('weui-icon-success-no-circle');
	}else{
		// 失败
		$toast.find('.weui-icon_toast').addClass('weui-icon-cancel');
		$toast.find('.weui-icon_toast').removeClass('weui-icon-success-no-circle');
	}
	
	$toast.find('.weui-toast__content').html(msg);
	$toast.fadeIn(100);
	setTimeout(function () {
		$toast.fadeOut(100);
	}, 2000);
}


// 数据加载中提示
function showLoading(){
	/*
	var $loadingToast = $('#loadingToast');
	if(!($loadingToast.length > 0)){
		var loadingHtml = 
				 '<div id="loadingToast" style="display:none;">'
			   + '<div class="weui-mask_transparent"></div>'
			   + '<div class="weui-toast">'
			   + '	<i class="weui-loading weui-icon_toast"></i>'
			   + '	<p class="weui-toast__content">加载中...</p>'
			   + '</div>'
			   + '</div>';
		$(document.body).append(loadingHtml);
		$loadingToast = $('#loadingToast');
	}
	if ($loadingToast.css('display') != 'none') return;
    $loadingToast.fadeIn(100);
    */
	showLoading('加载中...');
}

function showLoading(text){
	var $loadingToast = $('#loadingToast');
	if(!($loadingToast.length > 0)){
		var loadingHtml = 
				 '<div id="loadingToast" style="display:none;">'
			   + '<div class="weui-mask_transparent"></div>'
			   + '<div class="weui-toast">'
			   + '	<i class="weui-loading weui-icon_toast"></i>'
			   + '	<p class="weui-toast__content"></p>'
			   + '</div>'
			   + '</div>';
		$(document.body).append(loadingHtml);
		$loadingToast = $('#loadingToast');
	}
	if(isBlank(text)){
		$loadingToast.find('.weui-toast__content').html('加载中...');
	}else{
		$loadingToast.find('.weui-toast__content').html(text);
	}
	if ($loadingToast.css('display') != 'none') return;
    $loadingToast.fadeIn(100);
}
// 关闭数据加载中提示
function hideLoading(){
	$('#loadingToast').fadeOut(100);
}


// 弹出确认提示框
function showConfirmDialog(content,callback){
	var title='提示';
	if(isBlank(content))content='';
	var iosDialog = $('#iosDialog1');
	if(!(iosDialog.length > 0)){
		var loadingHtml = 
		 	 '<div class="js_dialog" id="iosDialog1" style="display: none;">'
	        +'	<div class="weui-mask"></div>'
	        +'	<div class="weui-dialog">'
	        +'		<div class="weui-dialog__hd"><strong class="weui-dialog__title"></strong></div>'
	        +' 		<div class="weui-dialog__bd"></div>'
	        +'		<div class="weui-dialog__ft">'
	        +'  		<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default" onclick="hideConfirmDialog()">取&nbsp;消</a>'
	        +'    		<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" id="btn-dialog-confirm">确&nbsp;认</a>'
	        +'		</div>'
	        +'	</div>'
	        +'</div>';
		$(document.body).append(loadingHtml);
		iosDialog = $('#iosDialog1');
	}
	iosDialog.find('.weui-dialog__title').text(title);
	iosDialog.find('.weui-dialog__bd').text(content);
	iosDialog.unbind(); // 先移除绑定事件，不然多次调用会响应多次回调函数
	iosDialog.on('click','#btn-dialog-confirm',function(){
		callback(); // 点击确认按钮的回调函数
	});
	iosDialog.fadeIn(100); // 弹出确认框
}
//关闭确认提示框
function hideConfirmDialog(){
	$('#iosDialog1').fadeOut(200);
}


//对Date的扩展，将 Date 转化为指定格式的String 
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
//例子： 
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.format = function(fmt) {
	if(fmt==null)fmt="yyyy-MM-dd hh:mm";
	var o = {
	"M+" : this.getMonth()+1,                 //月份 
	"d+" : this.getDate(),                    //日 
	"h+" : this.getHours(),                   //小时 
	"m+" : this.getMinutes(),                 //分 
	"s+" : this.getSeconds(),                 //秒 
	"q+" : Math.floor((this.getMonth()+3)/3), //季度 
	"S"  : this.getMilliseconds(),         	  //毫秒
	"T" : "T"	//we-ui datetime-local固定设值格式:"yyyy-MM-ddTHH:mm:ss"
	};
	if(/(y+)/.test(fmt)){
	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o){
	    if(new RegExp("("+ k +")").test(fmt)){
	  		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
	    }
	}
	return fmt;
}

function formatDate(timestamp){
	formatDate(timestamp,"yyyy-MM-dd hh:mm");
}

function formatDate(timestamp,format){
	if(timestamp == null || timestamp == '')return null;
	else return new Date(timestamp).format(format);
}

// 判断是否为空
function isBlank(str){
	var result = !(str && str!=undefined && str!=null && $.trim(str)!='');
	return result;
}
// 去空格
function trimToEmpty(str){
	var result = '';
	if(!isBlank(str))result=$.trim(str);
	return result;
}

//判断是否微信中打开
function isWeiXin(){
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}

