var mobileClickTimes = 0;
var zPush = null;

//jquery加载器函数
$(function(){
//	zPush = new ZPush({server: 'http://push.zzwtec.com', port: 9906});
//	zPush = new ZPush({server: 'http://10.0.0.214', port: 9906})
	zPush = new ZPush({server: 'http://push2.zzwtec.com', port: 9906});
	
	zPush.init(
			function (success) {
				if(success){
					console.log('ZPush init初始化成功');
					//发送心跳
					var feedbackAlias = $(':input[name=feedbackAlias][type=hidden]').val();
					zPush.heartbeat(feedbackAlias,function(){
					});
					
					var wait = function () {
				            setInterval(function () {
				            	zPush.heartbeat(feedbackAlias,function(){
				            		console.log('ZPush 心跳'); 
								});
				            },14000);
				        };
				    wait();
					
					
					var registerData={};
					registerData.t=2;
					registerData.topic=getTopics(),
					registerData.num="";
					zPush.register(registerData,function () {
						console.log('ZPush 订阅频道成功'); 
					});
				}
			},function(){});

	
	//发生ajax请求提交sessionID
	var data = {};
	data.sessionId = $(":input[type=hidden][name=sessionId]").val();
	/*
	doDataPost(data, false, ctx+"/index", function(repJson){
		//把当前sessionID提交到服务端
	});
    */
	//设置菜单区和工作区域宽度与高度
//	$('div.leftsidebar_box').css('width', $('div#left_menu_area').width()+'px');
//	$('div.leftsidebar_box').css('height', $(window).height()+'px');
//	$('div#work_area').css('height',$(window).height()+'px');
	//设置左菜单宽度保持与菜单区宽度同步
	$(window).on('resize',function(){
		$('div.leftsidebar_box').css('width', $('div#left_menu_area').width()+'px');
		$('div.viewFramework-work-area').css('width', ($(window).width()-$('div.viewFramework-sidebar').width()) +'px');
		if($(window).width()<992){
			 $(".viewFramework-body").removeClass("viewFramework-sidebar-full");
			 $(".viewFramework-body").addClass("viewFramework-sidebar-mini");
		}else{
			 $(".viewFramework-body").removeClass("viewFramework-sidebar-mini");
			 $(".viewFramework-body").addClass("viewFramework-sidebar-full");
		}
		if($(window).height()<700){
			$(".copyright").hide();
		}else{
			$(".copyright").show();
		}
		resizeTable();
		resizeTable();
	});

	//退出图片点击事件
	$('#tuichu-btn_modal').click(function(){
		  middleModal("ifexit-modal");
		  $("#ifexit-modal").attr('data-backdrop','false');
	      $("#ifexit-modal").modal("show");
	});

	//修改密码弹窗
	$("#updatePwd-btn_modal").click(function(){
		middleModal("updatePwd-modal");
		$("#updatePwd-modal").show();
		$("#updatePwd-modal").attr("data-backdrop",'false');
        $("#updatePwd-modal").modal("show");
        
    });

	//切换小区弹窗
	$("#changeCommunity-btn_modal").click(function(){
        selManageCommunity();
        
    });
	$('#adminInfoBtn').click(function(){		
		var r = $(this).attr('data');
		var areaWidth = $('div.viewFramework-work-area').width();
		doDataPost({}, false, ctx+"/"+r+"/admin_info", function(htmlText){
			indexLayer = layer.open({
		        type: 1,
		        title: '个人信息',
		        offset: ['56px',($(window).width()-areaWidth)+'px'],
		        area: [areaWidth+'px', 'auto'],
		        content: htmlText //注意，如果str是object，那么需要字符拼接。
			});
			$('.layui-layer-content').css('height','auto');
		});
	});
    //刷新图标点击事件
    $("#refresh-btn").click(function(){
    	waiting();
    	location.reload();
    });
    
    $("#menu_title").click(function(){
    	$(".viewFramework-body").toggleClass("viewFramework-sidebar-full");
    	$(".viewFramework-body").toggleClass("viewFramework-sidebar-mini");
		$('div.leftsidebar_box').css('width', $('div#left_menu_area').width()+'px');
		$('div.viewFramework-work-area').css('width', ($(window).width()-$('div.viewFramework-sidebar').width()) +'px');
    	resizeTable();
		resizeTable();
    });
    $(".sidebar-switch").click(function(){
    	$(".viewFramework-body").toggleClass("viewFramework-sidebar-full");
    	$(".viewFramework-body").toggleClass("viewFramework-sidebar-mini");
		$('div.leftsidebar_box').css('width', $('div#left_menu_area').width()+'px');
		$('div.viewFramework-work-area').css('width', ($(window).width()-$('div.viewFramework-sidebar').width()) +'px');
		resizeTable();
		resizeTable();
    });
	 //右上角的图标在鼠标移上去之后背景前景色改变
	 $('#refresh_div').hover(function(){
		   $(this).addClass("greenbackground");
		   $(this).find('span').css('color', '#fff');
		  },function(){
			$(this).removeClass("greenbackground");
			$(this).find('span').css('color', '#9D9D9D');
		});
	 //右上角的图标在鼠标移上去之后背景前景色改变
	 $('#dropdown_div').hover(function(){
		   $(this).addClass("bluebackground");
		   $(this).find('span').css('color', '#fff');
		  },function(){
			$(this).removeClass("bluebackground");
			$(this).find('span').css('color', '#9D9D9D');
		});
	//右上角的图标在鼠标移上去之后背景前景色改变
	 $('#exit_div').hover(function(){
		   $(this).addClass("redbackground");
		   $(this).find('span').css('color', '#fff');
		  },function(){
			$(this).removeClass("redbackground");
			$(this).find('span').css('color', '#9D9D9D');
		});
	 if($(window).width()<992){
		 $(".viewFramework-body").removeClass("viewFramework-sidebar-full");
		 $(".viewFramework-body").addClass("viewFramework-sidebar-mini");
	 }
	$('div.viewFramework-work-area').css('width', ($(window).width()-$('div.viewFramework-sidebar').width()) +'px');
	if($(window).height()<580){
		$(".copyright").hide();
	}
	resizeTable();
	resizeTable();
    if($("#currentManageCommunityId").val()==""){
        selManageCommunity();
    }
});	
/* 滚动表格 */
function scrollPane(){
	if($('.scroll-pane')==null || $('.scroll-pane').length<=0){
		return ;
	}
	for(var i=0; i<$('.scroll-pane').length; i++){
		var scroll_pane = $($('.scroll-pane')[i]);
		var y = scroll_pane.parent()[0].offsetTop;
		var headH = scroll_pane.parent().find('.my-table-head').outerHeight(true);
		var bodyH = scroll_pane.parent().find('.my-table-body').outerHeight(true);
		var footH = scroll_pane.parent().find('.my-table-foot').outerHeight(true);
		var h = $(window).height() - y - headH - footH - 60;
		if(h > 0){
			var setH = 0;
			if(bodyH>h){
				setH = h;
			}else{
				setH = bodyH;
			}
			scroll_pane.css('width',$('.my-table').width()+'px');
			scroll_pane.css('height',setH+'px');
			scroll_pane.jScrollPane({
				animateScroll : true
			});
		}
	}
}

/**设置弹窗垂直居中**/
function middleModal(modalId){
	$('#'+modalId).on('shown.bs.modal', function (e) {
		$(this).find('.modal-dialog').css({'margin-top':'0px','margin-left':'0px'});
		var modalHeight = $(this).find('.modal-dialog').outerHeight(true);
		var dialogWidth = $(this).find('.modal-dialog').width();
		$(this).find('.modal-dialog').css({
			'margin-top': function () {
				return ($(window).height() - modalHeight) / 2;
			},
			'margin-left': function () {
				return ($(window).width() - dialogWidth + $('div.viewFramework-sidebar').width())/2;
			}
		});
	});
}

/* 等待控件 */
function waitingStop(){
	if($("#waitingModal")!=null && $("#waitingModal").length>0){
		$("#waitingModal").slideUp("slow");
	}
}
function waiting(){
	var temp = 
		'<div class="modal waiting-modal"  id="waitingModal">'+
	    '	<figure>'+
	    '		<section><div></div></section>'+
	    '		<section><div></div></section>'+
	    '		<section><div></div></section>'+
	    '		<section><div></div></section>'+
	    '		<section><div></div></section>'+
		'		<section><div></div></section>'+
		'		<section><div></div></section>'+
		'		<section><div></div></section>'+
		'	</figure>'+
		'</div>';
	if($("#waitingModal").length==0){
		$(".viewFramework-body").append(temp);
	}
	var modalHeight = $('#waiting-modal').find('figure').outerHeight(true);
	var dialogWidth = $("#waitingModal").find('figure').width();
	$("#waitingModal").find('figure').css({
		'top': '30%',
		'left': function () {
			return ($(window).width() - dialogWidth + $('div.viewFramework-sidebar').width())/2;
		}
	});
	$("#waitingModal").slideDown("slow");
}

/**
 * 调整带滚动条表格高度 
 * @param tableClass '.scroll-pane > .my-table-body'
 */
function adjustmentTableHeight(){	
	var tableClass = '.scroll-pane > .my-table-body';
	var table = $(tableClass);
	var trs = table.find('tr');
	var h = $(table).outerHeight();
	var height = 32 * trs.length;
	var max = Math.max(h,height);
	$(table).outerHeight(max);
	
}
/* 表格处理 */
function adjustTableCellWidth(tableDivId){
	//console.log('tableDivId:'+tableDivId);
	var theadTHs = $('#'+tableDivId).find('table.my-table-head > thead > tr > th');
	var tbodyTDs = $('#'+tableDivId).find('table.my-table-body > tbody > tr > td');
	if(tbodyTDs!=null && tbodyTDs.length>0){		
		for(var i=0; i<theadTHs.length-1; i++){
			//console.log(i+'th'+$(tbodyTDs[i]).width());
			$(theadTHs[i]).width($(tbodyTDs[i]).width());
			$(theadTHs[i]).outerWidth($(tbodyTDs[i]).outerWidth());
			$(theadTHs[i]).innerWidth($(tbodyTDs[i]).innerWidth());
		}	
	}
	if($('.my-table div.opt')!=null && $('.my-table div.opt').length>0){
		var optWidth = $('.my-table div.opt').width();
		var spanWidth = $('.my-table div.opt').parent().find('span').width();
		var thWidth = $('.my-table div.opt').parent().width();
		if(thWidth-optWidth*2-spanWidth<8){
			$('.my-table div.opt').parent().css('text-align','left');
		}else{
			$('.my-table div.opt').parent().css('text-align','center');
		}
	}
	
	$('#'+tableDivId).find('div.scroll-pane').hover(
			function () {
				$(this).find('div.jspVerticalBar').fadeIn("slow");;
			},
			function () {
				$(this).find('div.jspVerticalBar').fadeOut("slow");;
			}
		);
}

/**
 * 调整表格宽度
 */
function resizeTable(){
	if($('.my-table').length>0){
		for(var i=0; i<$('.my-table').length; i++){
			var table = $('.my-table')[i];
			var id = $(table).attr('id');
			if(id!=null && id.length>0){
				adjustTableCellWidth(id);
			}
		}
	}
	scrollPane();
	if($('.my-table').length>0){
		for(var i=0; i<$('.my-table').length; i++){
			var table = $('.my-table')[i];
			var id = $(table).attr('id');
			if(id!=null && id.length>0){
				$('#'+id).find('div.scroll-pane').hover(
					function () {
						$(this).find('div.jspVerticalBar').fadeIn("slow");;
					},
					function () {
						$(this).find('div.jspVerticalBar').fadeOut("slow");;
					}
				);
			}
		}
	}
}
//var w = 0;
//function resizeTableCellWidth(tableDivId){
//	$(window).resize(function () {
//		var v = Math.abs(w - $(window).width());
//		if(v > 10){
//			console.log('v:'+v);
//			adjustTableCellWidth(tableDivId);
//		}
//		w = $(window).width();
//	});
//}
/**
 * 获取分页数据
 * @param dataV
 * @param urlV
 */
function getPageData(dataV,urlV){
	doDataPost(dataV, false, urlV, function(msg){
		addPage(msg);
	});
}

/**
 * 提交data数据
 * @param data 要提交的data
 * @param cache
 * @param url 表达提交的url
 * @param successCallbackF 成功回调处理方法
 */
function doDataPost(data,cache,url,successCallbackF){
	$.ajax({
		type:"POST",
		url:url,
		cache:cache,
		data:data,
		success:function(repJson){
			if(isOK(repJson)){
				successCallbackF(repJson);
			}
		},
		complete:function(){
			waitingStop();
		},
		beforeSend:function(){
			waiting();
		},
		error:function (xxx) {
			console.log(xxx);
        }
	});
}

/**
 * 提交data数据(不出现loading的异步加载)
 * @param data 要提交的data
 * @param cache
 * @param url 表达提交的url
 * @param successCallbackF 成功回调处理方法
 */
function doDataPostNoWaiting(data,cache,url,successCallbackF){
    $.ajax({
        type:"POST",
        url:url,
        cache:cache,
        data:data,
        success:function(repJson){
            if(isOK(repJson)){
                successCallbackF(repJson);
            }
        },
        error:function (xxx) {
            console.log(xxx);
        }
    });
}

function doDataPostSync(data,cache,url,successCallbackF){
	$.ajax({
		type:"POST",
		url:url,
		cache:cache,
		data:data,
		async:false,
		success:function(repJson){
			if(isOK(repJson)){
				successCallbackF(repJson);
			}
		}
	});
}

/**
 * 提交data数据
 * @param data 要提交的data
 * @param cache
 * @param url 表达提交的url
 * @param successCallbackF 成功回调处理方法
 * 与doDataPost方法不同的是 不出现等待转圈 在excel查进度的时候使用
 */
function doExcelCachePost(data,cache,url,successCallbackF){
	$.ajax({
		type:"POST",
		url:url,
		cache:cache,
		data:data,
		success:function(repJson){
			if(isOK(repJson)){
				successCallbackF(repJson);
			}
		}
	});
}
/**
 * 提交form表单数据 适用于整个表单数据的提交
 * @param formName 表单名即form标签的name
 * @param url 表达提交的url
 * @param successCallbackF 成功回调处理方法
 */
function doFormPost(formName,url,successCallbackF){
	var inputs = $("form[name="+formName+"] :input");
	var data = {};
	$(inputs).each(function(){
		var input = $(this);
		if(this.tagName.toLowerCase()=='checkbox' ||
			(this.tagName.toLowerCase()=='input' && this.type.toLowerCase()=='checkbox')){
			if(data[input.attr('name')]==null){
				data[input.attr('name')] = [];
			}
			data[input.attr('name')].push(input.val());
		}else{
			data[input.attr('name')]=input.val();

		}
	});
//	alert(JSON.stringify(data));
	$.ajax({
		type:"POST",
		url:url,
		data:data,
		success:function(repJson){
			if(isOK(repJson)){
				successCallbackF(repJson);
			}
		},
		complete:function(){
			waitingStop();
		},
		beforeSend:function(){
			waiting();
		}
	});
}

/**
 * 获取表单数据，需要该表单名在浏览器中唯一
 * @param formName
 */
function getFormData(formName){
	var inputs = $("form[name="+formName+"] :input");
	var data = {};
	$(inputs).each(function(){
		var input = $(this);
		if(this.tagName.toLowerCase()=='checkbox' ||
			(this.tagName.toLowerCase()=='input' && this.type.toLowerCase()=='checkbox')){
			if(data[input.attr('name')]==null){
				data[input.attr('name')] = [];
			}
			data[input.attr('name')].push(input.val());
		}else{
			data[input.attr('name')]=input.val();
		}
	});
	return data;
}

/**
 * 以layer控件形式打开一个窗口
 */
function openLayerWin(htmlText,area){	
	var display_w = $(window).width();
	var display_h = $(window).height();	
	//计算出左菜单宽度
	var left_menu_w = $('.leftsidebar_box').width();
	//计算出当前div宽度	
	var wk_w = display_w - left_menu_w;	
	var div_h = area.h;
	var div_w = area.w;	
	var positionX = (wk_w-div_w)/2 + left_menu_w;
	var positionY = (display_h - div_h)/2;	
	window.index = indexLayer = layer.open({
	  title:'',
	  type: 1,
	  skin: 'layui-layer-rim', //加上边框
	  offset: [positionY+'x',positionX+'px'],
	  area: [div_w+'px', div_h+'px'], //宽高
	  content: htmlText
	});		
}

/**
 * 为表单添加滚动条，表单需要满足一定的规格
 */
function formScroll(divId){
	var scroll_pane = $('#'+divId+' div.scroll-pane');
	$(scroll_pane).css({'padding':'0px','border':'none'});
	$('#'+divId+' .scroll-pane').css({'padding':'0px'});
	$('#'+divId+' .scroll-pane > div').css({'margin':'20px','margin-right':'20px'});
	scroll_pane.jScrollPane({
		animateScroll : true
	});
	//去除水平滚动条
	var scroll_x = $('#'+divId+' .scroll-pane').find('.jspHorizontalBar');
	$(scroll_x).css('display', 'none');	
	$('#'+divId).find('div.scroll-pane').hover(			
		function () {			
			$(this).find('div.jspVerticalBar').fadeIn("slow");				
		},
		function () {			
			$(this).find('div.jspVerticalBar').fadeOut("slow");				
		}
	);
}


/**
 * 为表单加上纵向滚动条(需要满足一定的规格，如小区设备配置多选项卡的表单)
 */
function scrollForm(){
	var scroll_pane = $('.scroll-pane');
	$(scroll_pane).css({'padding':'0px','border':'none'});
	scroll_pane.jScrollPane({
		animateScroll : true
	});
	//去除水平滚动条
	var scroll_x = scroll_pane.find('.jspHorizontalBar');
	$(scroll_x).css('display', 'none');	
	scroll_pane.hover(			
		function () {			
			$(this).find('div.jspVerticalBar').fadeIn("slow");				
		},
		function () {			
			$(this).find('div.jspVerticalBar').fadeOut("slow");				
		}
	);
}

/**
 * 禁用当前按钮，防止重复提交
 */
function disableBtn(btn){
	$(btn).attr('disabled','disabled');
}
/**
 * 判断当前按钮是否处于禁用状态
 */
function isDisabled(btn,msg){	
	var x = ($(window).width() - 260 + $('div.viewFramework-sidebar').width())/2;
	var y = ($(window).height() / 2 - 73);
	var state = $(btn).attr('disabled');	
	if('disabled' == state){	
		layer.alert(msg,{
			  icon: 0,
			  title:'提示',
			  area: ['260px', '146px'],
			  offset: [y+'px', x+'px']
		});		
		return true;
	}else{
		return false;
	}
}

/**
 * doAction
 */ 
function doAction(para,fun){
	if(isDisabled(para.btn,para.msg)){
		return;
	}else{
		fun();
		disableBtn(para.btn);
	}	
}

/**
 * 获取推送别名
 */
function getAlias(){
	var feedbackAlias = $(':input[name=feedbackAlias][type=hidden]').val();
	return feedbackAlias;
}
/**
 * 获取订阅主题 数组类型
 */
function getTopics(){
	var topics=new Array(); 
	var feedback_topic = $(':input[name=feedbackTopic][type=hidden]').val();
	if(feedback_topic=="s_feedback" || feedback_topic.indexOf("adf_")==0){//总后台标签主题 广告后台 工单推送标签主题adf_广告商id
		topics.push(feedback_topic);
	}else{//物业后台 工单推送标签主题cf_小区id
		/*console.log('工单频道列表:'+topic_id);*/
		var topic_ids = feedback_topic.split(",");
		for(var i=0;i<topic_ids.length;i++){
			topics.push('cf_'+topic_ids[i]);
		}
	}
	topics.push("mobile");
	return topics;
}

/**
 * 选择管理小区
 */
function selManageCommunity(){
    var areaWidth = $('div.viewFramework-work-area').width();
    var currentManageCommunityName=$("#currentManageCommunityName").val();
    doDataPost({"currentManageCommunityName":currentManageCommunityName}, false, ctx+"/adm/community/change/form_ui", function(htmlText){
        indexLayer = layer.open({
            type: 1,
            title: '选择管理小区',
            offset: ['56px',($(window).width()-areaWidth)+'px'],
            area: [areaWidth+'px', 'auto'],
            content: htmlText //注意，如果str是object，那么需要字符拼接。
        });
        $('.layui-layer-content').css('height','auto');
    });
}

/**
 * 去掉字符串前后的空格
 * @returns {string}
 */
String.prototype.trim=function() {
    return this.replace(/(^\s*)|(\s*$)/g,'');
};
/**
 * 当屏幕宽度小于768时 左侧菜单自动收缩
 * @returns
 */
function closeLeftMenu(){
	if(screen.width<768){
		$("#menu_title").click();
	}
}
