window.config = {
	app_version: '2.0.0',
	web_path: 'http://www.bhwh.gov.cn',// 正式地址链接
	dev_path: 'http://www.bhwh.gov.cn/',// 测试地址,'http://web-whsx-whsxdev.apps.koala-cloud.com/',//'https://ewatch.okayapps.com/wenhuasuixing-master', //http://new.bhwh.gov.cn //接口地址 //https://ewatch.okayapps.com/wenhuasuixing-master
	max_time: 1800,
	ajax_timeout: 20,
	list_pagesize: 10
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 通用
// ------------------------------------------------------------------
// ------------------------------------------------------------------
//下拉刷新
function fnInitPullRefresh(cbk) {
	api.setRefreshHeaderInfo({
		visible: true,
		loadingImg: 'widget://image/refresh.png',
		bgColor: '#f0f0f0',
		textColor: '#888',
		textDown: '下拉刷新...',
		textUp: '松开刷新...',
		showTime: false
	}, function(ret, err) {
		cbk(ret)
	});
};

//上滑加载
function fnInitScrollToBottom(cbk) {
	api.addEventListener({
		name: 'scrolltobottom',
		extra: {
			threshold: 55 //设置距离底部多少距离时触发，默认值为0，数字类型
		}
	}, function(ret, err) {
		cbk(ret)
	});
};
//图片缓存
function fnCacheImage(datas, index) {
	if(datas.length <= index) { //如果数组的长度小于等于								//index的时候
		return; //返回
	}
	api.imageCache({
		url: datas[index].thumbnail.url //要缓存的图片									   //的路径
	}, function(ret, err) {
		var thumbnail = $api.byId('thumbnail_' + datas[index].id);
		//设置一个变量为要缓存的img元素
		if(thumbnail) { //如果这个元素存在
			thumbnail.src = ret.url; //改变这个元素的src属								  //性为本地路径
		}
		fnCacheImage(datas, index + 1); //继续执行缓存图片的
		//方法,一直到执行完毕。
	});
};
//图片选择
function select_pic(cbk) {
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['拍照上传', '从相册选择']
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if(index == 1 || index == 2) {
			var sourceType = index == 1 ? 'camera' : 'album';
			api.getPicture({
				sourceType: sourceType,
				encodingType: 'jpg',
				mediaValue: 'pic',
				destinationType: 'base64',
				quality: 50,
				saveToPhotoAlbum: false
			}, function(ret, err) {
				if(ret) {
					if(ret.data != '') {
						cbk(ret)
					}
				} else {
					api.toast({
						msg: err
					})
				}
			});
		}
	});
}
//图片多张选择
function select_album(max, cbk) {
	api.getPicture({
			sourceType: 'album',
			encodingType: 'jpg',
			mediaValue: 'all',
			destinationType: 'url',
			allowEdit: true,
			quality: 50,
			saveToPhotoAlbum: false
	}, function(ret, err) {
			if (ret) {
				ret.path = ret.data;
				cbk(ret);
			} else {
				alert(err.msg);
			}
	});
	var UIAlbumBrowser = api.require('UIAlbumBrowser');
	/*UIAlbumBrowser.open({
		max: max,
		styles: {
			bg: '#fff',
			mark: {
				icon: '',
				position: 'bottom_left',
				size: 20
			},
			nav: {
				bg: 'rgba(0,0,0,0.6)',
				titleColor: '#fff',
				titleSize: 18,
				cancelColor: '#fff',
				cancelSize: 16,
				finishColor: '#fff',
				finishSize: 16
			}
		},
		rotation: true,
	}, function(ret) {
		if(ret && ret.list.length > 0) {
			var length = ret.list.length;
			for(var i = 0; i < length; i++) {
				UIAlbumBrowser.transPath({
					path: ret.list[i].path
				}, function(res) {
					cbk(res);
				});
			}
		}
	});*/
	/*var mediaScanner = api.require('UIMediaScanner');
	mediaScanner.open({
		exchange: true,
		column: 4,
		classify: false,
		max: max,
		sort: {
			key: 'time',
			order: 'desc'
		},
		texts: {
			stateText: '已选择*项',
			cancelText: '取消',
			finishText: '完成'
		},
		styles: {
			bg: '#fff',
			mark: {
				icon: '',
				position: 'bottom_left',
				size: 20
			},
			nav: {
				bg: '#519ade',
				stateColor: '#fff',
				stateSize: 18,
				cancelBg: 'rgba(0,0,0,0)',
				cancelColor: '#000',
				cancelSize: 18,
				finishBg: 'rgba(0,0,0,0)',
				finishColor: '#000',
				finishSize: 18
			}
		}
	}, function(ret) {
		if(ret && ret.list.length > 0) {
			var length = ret.list.length;
			for(var i = 0; i < length; i++) {
				mediaScanner.transPath({
					path: ret.list[i].path
				}, function(ret) {
					cbk(ret)
				});
			}
		}
	});*/
}
//打开窗口
function open_win(name, url, bounces) {
	var delay = 0;
	if(api.systemType != 'ios') {
		delay = 100;
	}
	api.openWin({
		name: name,
		url: url,
		bounces: bounces,
		delay: delay,
		slidBackEnabled: true,
		vScrollBarEnabled: false,
		animation: {
			type: 'fade',
			duration: 300
		},
		allowEdit:true
	});
}
//打开页面
function open_frame(name, url, id, bounces) {
	var header = $api.byId(id)
	var headerPos = $api.offset(header);
	api.openFrame({
		name: name,
		url: url,
		bounces: bounces,
		rect: {
			x: 0,
			y: headerPos.h,
			w: 'auto',
			h: 'auto'
		},
		vScrollBarEnabled: false,
		allowEdit:true
	})
}
//关闭窗口
function close_win() {
	api.closeWin({});
}
//关闭frame
function close_frame() {
	api.closeFrame({});
}
//点赞收藏接口
//data_type	True	int	数据类型（0：文章，1：场馆，2：活动）
//type	True	int	交互类型(0:点赞，1:收藏)

function opera(id, data_type, type, cbk) {
	if($api.getStorage('token')) {
		get_data('/api/interact/opera', 'post', {
			token: $api.getStorage('token'),
			data_id: id,
			data_type: data_type,
			type: type,
			from: 1,
		}, function(ret) {
			cbk(ret)
		})
	} else {
		api.toast({
			msg: '您还未登录！'
		});
	}
}
//拨打电话
function call(number) {
	api.call({
		number: number
	})
}
//移除数组中指定元素
function removeByValue(arr, val) {
	for(var i = 0; i < arr.length; i++) {
		if(arr[i] == val) {
			arr.splice(i, 1);
			break;
		}
	}
}
// 数组插入
Array.prototype.insert = function(index, item) {
	this.splice(index, 0, item);
};

// ucs-2转utf-16（将表情图转换为实体字符）
function ucs2_to_utf16(str, clear) {
	var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
	str = str.replace(patt, function(char) {
		if(clear) {
			return '';
		}
		var H, L, code;
		if(char.length === 2) {
			H = char.charCodeAt(0); // 高位
			L = char.charCodeAt(1); // 低位
			code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
			return "&#" + code + ";";
		} else {
			return char;
		}
	});
	return str;
}

// utf-16转ucs-2（将实体字符转换回表情图）
function utf16_to_ucs2(str) {
	var patt = /&#[0-9]+;/g;
	str = str.replace(/&amp;/g, '&').replace(/&amp;/g, '&').replace(/&#039;/, '\'').replace(patt, function(char) {
		var code = char.substr(2);
		code = code.substr(0, code.length - 1);
		H = Math.floor((code - 0x10000) / 0x400) + 0xD800 // 高位
		L = (code - 0x10000) % 0x400 + 0xDC00 // 低位
		return unescape('%u' + H.toString(16)) + unescape('%u' + L.toString(16));
	});
	return str;
}

// 滑动中触屏事件处理（禁止单击事件）
var click_allowed = true;

function scroll_click(systype) {
	if(systype == 'android') {
		var scroll_timer = 0;
		$(window).on('scroll', function() {
			scroll_timer = scroll_timer + 1;
			var scroll_timer_temp = scroll_timer;
			click_allowed = false;
			setTimeout(function() {
				if(scroll_timer_temp == scroll_timer) {
					click_allowed = true;
				}
			}, 150);
		}).on('touchstart', function(e) {
			scroll_timer = 0;
			if(!click_allowed) {
				setTimeout(function() {
					click_allowed = true;
				}, 150);
			}
		})
	} else {
		var scroll_top = 0;
		$(window).on('scroll', function() {
			click_allowed = true;
		}).on('touchmove', function() {
			click_allowed = false;
			scroll_top = $(window).scrollTop();
		}).on('touchend', function() {
			if(scroll_top == $(window).scrollTop()) {
				click_allowed = true;
			}
		})
	}
}
// 压缩图片文件
function compressImg(obj, cbk, err) {
	var qulity = 1;
	var target_w = 720;
	if(obj.qulity != null) {
		qulity = obj.qulity;
	}
	if(obj.width != null) {
		target_w = obj.width;
	}

	var imageFilter = api.require("imageFilter");
	imageFilter.getAttr({
		path: obj.src
	}, function(ret, err) {
		if(ret.status) {
			var original_w = ret.width;
			var original_h = ret.height;
			if(original_w <= target_w) {
				imageFilter.compress({
					img: obj.src,
					quality: qulity,
					scale: 1,
					save: {
						album: false,
						imgPath: api.cacheDir + '/upload/',
						imgName: obj.id + ".jpg"
					}
				}, function(ret, err) {
					if(ret.status && cbk) {
						cbk(api.cacheDir + '/upload/' + obj.id + ".jpg", obj.id);
					} else if(!ret.status && err) {
						err();
					}
				});
			} else if(original_w > target_w) {
				var scale = target_w / original_w;
				imageFilter.compress({
					img: obj.src,
					quality: qulity,
					scale: scale,
					save: {
						album: false,
						imgPath: api.cacheDir + '/upload/',
						imgName: obj.id + ".jpg"
					}
				}, function(ret, err) {
					if(ret.status && cbk) {
						cbk(api.cacheDir + '/upload/' + obj.id + ".jpg", obj.id);
					} else if(!ret.status && err) {
						err();
					}
				});
			}
		} else if(err) {
			err();
		}
	});
}

// 检查用户是否已登录然后跳转到页面
function checkLogin() {
	var login = $api.getStorage('login');
	if(login && login.key) {
		return true;
	} else {
		openWin_Login();
		return false;
	}
}

// GCJ02坐标转BD09坐标（腾讯地图坐标转百度地图坐标）
function Convert_GCJ02_To_BD09(lat, lon) {
	var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	var x = parseFloat(lon);
	var y = parseFloat(lat);
	var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
	var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
	var lon = z * Math.cos(theta) + 0.0065;
	var lat = z * Math.sin(theta) + 0.006;
	return {
		lat: lat,
		lon: lon
	};
}

// BD09坐标转GCJ02坐标（百度地图坐标转腾讯地图坐标）
function Convert_BD09_To_GCJ02(lat, lon) {
	var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	var x = parseFloat(lon) - 0.0065;
	var y = parseFloat(lat) - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
	var lon = z * Math.cos(theta);
	var lat = z * Math.sin(theta);
	return {
		lat: lat,
		lon: lon
	};
}

// 获取地理位置
function getposition(cbk) {
	var bMap = api.require('bMap');
	bMap.getLocation({
		accuracy: '10m'
	}, function(ret,error) {
		var sta = ret.status;
		if(!sta){
			api.toast({
				msg: '定位失败'
			})
		}
		var lat = ret.lat;
		var lon = ret.lon;
		if(api.systemType == 'ios') {
			bMap.initMapSDK(function(ret,err) {
				console.log('initMap',JSON.stringify(ret),JSON.stringify(err));
				if (ret.status) {
					console.log('地图初始化成功');
					bMap.getNameFromCoords({
						lon: lon,
						lat: lat
					}, function(ret, err) {
						if(ret.status) {
							cbk(ret)
							bMap.close();
						} else {
							console.log(JSON.stringify(err));
							api.toast({
								msg: '定位失败，请手动点击定位图标！'
							})
						}
					})
				}
			});
		}else{
			bMap.getNameFromCoords({
				lon: lon,
				lat: lat
			}, function(ret, err) {
				if(ret.status) {
					cbk(ret)
					bMap.close();
				} else {
					console.log(JSON.stringify(err));
					api.toast({
						msg: '定位失败，请手动点击定位图标！'
					})
				}
			})
		}
	})
}

// 气泡提示 传入loc的位置就以loc的位置为准，否则就在中央
function toast(str, loc) {
	var location = loc ? loc : 'middle';
	api.toast({
		msg: str,
		duration: 2000,
		location: location,
		global: true
	});
}
// 气泡提示 传入loc的位置就以loc的位置为准，否则就在中央
function alertBtn(title,str,callback) {
	api.alert({
    title: title,
    msg: str,
}, function(ret, err) {
    if(callback){
			callback();
		}
});
}
// 动态加载CSS文件
function loadCSS(href) {
	var nodes = document.getElementsByTagName('link');
	var temp_href = href.substr(0, href.lastIndexOf('.css') + 4);
	var link = document.createElement('link');
	link.type = 'text/css';
	link.rel = 'stylesheet';
	link.href = href;
	for(var i = nodes.length; i >= 0; i--) {
		var node = nodes[i];
		if(node && node.getAttribute('href') != null && node.getAttribute('href').indexOf(temp_href) > -1) {
			node.parentNode.replaceChild(link, node);
			return;
		}
	}
	document.getElementsByTagName("head")[0].appendChild(link);
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// QQ、微信相关
// ------------------------------------------------------------------
// ------------------------------------------------------------------

// QQ登录（绑定）
function login_qq(cbk, error) {
	var obj_qq = api.require('qq');
	obj_qq.login(function(ret, err) {
		if(ret.status) {
			if(cbk) {
				cbk(ret);
			} else {
				hideLoading();
			}
		} else if(error) {
			error(err.msg);
		}
	});
}

// 微信登录（绑定）
function login_wechat(cbk, error) {
	var obj_wx = api.require('wx');
	obj_wx.auth({}, function(ret, err) {
		if(ret.status) {
			obj_wx.getToken({
				code: ret.code
			}, function(ret, err) {
				if(ret.status && cbk) {
					cbk(ret);
				} else {
					var code = err.code;
					if(code == -1) {
						toast('未知错误');
					} else if(code == 4) {
						toast('网络超时');
					} else {
						toast('登录失败');
					}
				}
			});
		} else if(error) {
			error(err.code);
		}
	});
}
//////////////////////////////////////////////////////////////////////////////////////
function share(cbk) {
	var userinfo = $api.getStorage('userinfo');
	if(userinfo == undefined || userinfo == null) {
		toast('请登录后再试')
		openWin_Login();
		return;
	}
	var MNActionButton = api.require('MNActionButton');
	MNActionButton.open({
		layout: {
			row: 1,
			col: 4,
			rowSpacing: 0,
			colSpacing: 10,
			offset: 0
		},
		animation: true,
		autoHide: true,
		styles: {
			maskBg: 'rgba(0,0,0,0.4)',
			bg: 'rgba(0,0,0,0)',
			cancelButton: {
				size: 50,
				bg: 'rgba(0,0,0,0.4)',
				icon: 'widget://image/close.png'
			},
			indicator: {
				color: '#c4c4c4',
				highlight: '#9e9e9e'
			}
		},
		items: [{
			icon: 'widget://image/1.png',
			highlight: 'widget://image/1.png',
			title: '微信'
		}, {
			icon: 'widget://image/2.png',
			highlight: 'widget://image/2.png',
			title: '好友圈'
		},
		{
			icon: 'widget://image/3.png',
			highlight: 'widget://image/3.png',
			title: '微博'
		},
		{
			icon: 'widget://image/4.png',
			highlight: 'widget://image/4.png',
			title: 'QQ'
		}]
	}, function(ret) {
		if(ret) {
			cbk(ret.index)
		}
	});
};
//////////////////////////////////////////////////////////////////////////////////////
// QQ分享
function share_qq(opt, cbk) {
	var obj_qq = api.require('qq');
	var data = {
		title: opt.title,
		imgUrl: opt.img,
		description: opt.des,
		url: opt.url,
		type: opt.type
	}
	obj_qq.shareNews(data, function(ret, err) {
		if(ret.status){
			share_addpoints('qq')
		}
		if(ret.status && cbk) {
			cbk();
		} else {
			var code = err.code;
			if(code == 10000 || code == 10001) {
				toast('发送失败');
			} else if(code == 10009) {
				toast('当前设备未安装QQ客户端');
			}
		}
	});
}
// 微博分享
function share_weibo(opt, cbk) {
	var obj_weibo = api.require('weibo');
	var data = {
		text: opt.text,
		title: opt.title,
		thumb: opt.thumb,
		description: opt.description,
		contentUrl: opt.contentUrl
	}
	obj_weibo.shareWebPage(data, function(ret, err) {
		if(ret.status){
			share_addpoints('weibo')
		}
		if(ret.status && cbk) {
			cbk();
		} else {
			var code = err.code;
			if(code == 2 || code == 3) {
				toast('发送失败');
			} else if(code == 1) {
				toast('用户取消');
			}
		}
	});
}
// 微信分享（第一步）  opt传入对象为分享的内容
function share_wechat(opt, cbk) {
	var obj_wx = api.require('wx');
	var data = {
		scene: opt.scene,
		title: opt.title,
		description: opt.des,
		contentUrl: opt.url,
		thumb: opt.thumb
	}
	share_wechat_act(obj_wx, data, cbk);
}

// 微信分享（第二步）
function share_wechat_act(obj_wx, data, cbk) {
	obj_wx.shareWebpage(data, function(ret, err) {
		console.log(JSON.stringify(ret))
		if(ret.status){
			var f = data.scene=='timeline'?'weixinline':'weixin';
			share_addpoints(f)
		}
		if(ret.status && cbk) {
			cbk();
		} else {
			var code = err.code;
			if(code == -1) {
				toast('未知错误');
			} else if(code == 3) {
				toast('发送失败');
			} else if(code == 4) {
				toast('授权拒绝');
			} else if(code == 6) {
				toast('当前设备未安装微信客户端');
			}
		}
	});
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 与服务器数据交互
// ------------------------------------------------------------------
// ------------------------------------------------------------------
function get_data(url, method, data, cbk) {
	api.showProgress({
		title: '正在加载...'
	});
	var url = window.config.dev_path + url;
	/*console.log(url);
	console.log(JSON.stringify(data));*/
	api.ajax({
		url: url,
		method: method,
		timeout: window.config.ajax_timeout,
		data: {
			values: data
		},
		returnAll: false
	}, function(ret, err) {
		//console.log(JSON.stringify(ret),JSON.stringify(err))
		api.hideProgress();
		if(ret) {
			//console.log(JSON.stringify(ret))
			cbk(ret)
		} else {
			//console.log(JSON.stringify(err))
			api.toast({
				msg: '网络不稳定！'
			});
			api.refreshHeaderLoadDone();
		}
	});
}

function post_img(url, data, cbk) {
	console.log(data);
	api.ajax({
		url: window.config.dev_path + url,
		method: 'post',
		timeout: window.config.ajax_timeout,
		data: {
			files: {
				file: data
			}
		},
		returnAll: false
	}, function(ret, err) {
		if(ret) {
			cbk(ret)
		} else {
			//alert(JSON.stringify(err))
			api.toast({
				msg: '网络不稳定！'
			});
		}
	});
}
//存储用户信息
function save_userinfo(ret) {
	/*$api.setStorage('userinfo', {
		uid: ret.data.uid,
		mobile: ret.data.mobile,
		nickname: ret.data.nickname,
		realname: ret.data.realname,
		id_card: ret.data.id_card,
		avatar: ret.data.avatar,
		sex: ret.data.sex,
		area: ret.data.area,
		age: ret.data.age,
		intro: ret.data.intro,
		education: ret.data.education,
		duties: ret.data.duties,
		auth_status: ret.data.auth_status,
		have_speech: ret.data.have_speech,
		have_stat: ret.data.have_stat,
		have_send_message: ret.data.have_send_message,
		have_work_train: ret.data.have_work_train,
		have_speech_view: ret.data.have_speech_view,
		have_preview:ret.data.have_preview,
		have_preview:ret.data.have_preview,
	});*/
	$api.setStorage('userinfo', ret.data);
	// 缓存是否接受推送
	$api.setStorage('receivepush', {
		receivepush: ret.data.receivepush,
	});
}
//从服务器获取用户信息
function getuserinfo() {
	get_data('/api/User/getUser', 'post', {
		token: $api.getStorage('token')
	}, function(ret) {
		if(ret.status == 1) {
			//			console.log(JSON.stringify(ret))
			save_userinfo(ret);
		} else {
			$api.rmStorage('token'); //清除token
			$api.rmStorage('userinfo'); //清除用户信息
		}
	})
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 创建新页面
// ------------------------------------------------------------------
// ------------------------------------------------------------------

// 打开登录页面
function openWin_Login() {
	api.openWin({
		name: 'login',
		url: 'widget://html/login/login.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}

// 打开注册页面
function openWin_Reg() {
	api.openWin({
		name: 'reg',
		url: 'widget://html/login/reg.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开活动详情页面
function openWin_activity(id) {
	$api.setStorage('activity_id', id);
	api.openWin({
		name: 'activity_detail',
		url: 'widget://html/activity/activity_detail.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开场馆详情页面
function openWin_venue_detail(id) {
	$api.setStorage('venue_detail_id', id)
	api.openWin({
		name: 'venue_detail',
		url: 'widget://html/venue/venue_detail.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开文化管理员详情页面
function openWin_cul_detail() {


	api.openWin({
		name: 'culadmin_detail',
		url: 'widget://html/my/culadmin_detail.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开场馆导航页面
function openWin_map(lat, lon) {
	$api.setStorage('venue_lat', lat)
	$api.setStorage('venue_lon', lon)
	api.openWin({
		name: 'map',
		url: 'widget://html/map/map.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开活动预约页面
function openWin_yuyue() {
	api.openWin({
		name: 'activity_reservation',
		url: 'widget://html/activity/activity_reservation.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开搜索结果页面
function openWin_searchResult(type, keywords,data=null) {
	var storageData = {
		type: type,
		keywords: keywords
	};
	$api.setStorage('search',storageData)
	api.openWin({
		name: 'search_result',
		url: 'widget://html/search/search_result.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开预定信息详情页面
function openWin_order_detail(id,type) {
	$api.setStorage('orderid', id)
	$api.setStorage('order_type', type)
	api.openWin({
		name: 'search_result',
		url: 'widget://html/my/order_detail.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开文章图文列表页面
function openWin_article_list(id, txt) {
	if(id == '1'){
		//活动预告
		stat_app_modules('yugao_count');
	}else if(id == '43'){
		//招标信息
		stat_app_modules('xinxi_count');
	}else if(id == '44'){
		//文化365
		stat_app_modules('365_count');
	}else if(id == '16'){
		//掌上展厅
		stat_app_modules('zhanting_count');
	}else if(id == '33'){
		//文物
		stat_app_modules('wenwu_count');
	}else if(id == '29'){
		//非遗
		stat_app_modules('feiyi_count');
	}else if(id == '30'){
		//滨海名家
		stat_app_modules('mingjia_count');
	}else if(id == '31'){
		//民间艺术
		stat_app_modules('yishu_count');
	}else if(id == '27'){
		//企业社团
		stat_app_modules('shetuan_count');
	}else if(id == '10'){
		//外来建设者
		stat_app_modules('wailai_count');
	}else if(id == '7'){
		//滨海艺术节
		stat_app_modules('yishujie_count');
	}else if(id == '19'){
		//评剧新苗
		stat_app_modules('pingju_count');
	}else if(id == '8'){
		//社区文化节
		stat_app_modules('shequ_count');
	}else if(id == '9'){
		//国际观鸟节
		stat_app_modules('guoji_count');
	}else if(id == '41'){
		//产业资源
		stat_app_modules('chanzi_count');
	}else if(id == '42'){
		//产业动态
		stat_app_modules('chandong_count');
	}else if(id == '17'){
		//抢福利
		stat_app_modules('fuli_count');
	}else{

	}
	$api.setStorage('article_list', {
		id: id,
		txt: txt
	})
	if(id==1){
		api.openWin({
			name: 'article_list_365',
			url: 'widget://html/article/article_list.html',
			bounces: false,
			vScrollBarEnabled: false,
			hScrollBarEnabled: false,
			slidBackEnabled: true,
			animation: {
				type: 'fade',
				duration: 300
			}
		});
	}else{
		api.openWin({
			name: 'article_list',
			url: 'widget://html/article/article_list.html',
			bounces: false,
			vScrollBarEnabled: false,
			hScrollBarEnabled: false,
			slidBackEnabled: true,
			animation: {
				type: 'fade',
				duration: 300
			}
		});
	}

}
// 打开文章详情页面
function openWin_article_detail(id) {
	console.log('di:'+id);
	$api.setStorage('article_id', id)

	api.openWin({
		name: 'article_detail',
		url: 'widget://html/article/article_detail.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		},
		allowEdit:true
	});
}
// 打开文章二级列表页面
function openWin_article_list_2(id, txt) {
	$api.setStorage('article_list_2', {
		id: id,
		txt: txt
	})
	api.openWin({
		name: 'article_list_2',
		url: 'widget://html/article/article_list_2.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开外部链接
function openWin_url(url) {
	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	if(url=='http://m.weibo.cn/n/%E6%BB%A8%E6%B5%B7%E5%8F%91%E5%B8%83'){
		  stat_app_modules('bhfb_count');
	}else if(url=='http://bhsb.tjbh.com'){
			stat_app_modules('bhsb_count');
	}else if(url=='http://bhsjt.qingk.cn'){
			stat_app_modules('bhsjt_count');
	}else{

	}
	$api.setStorage('weburl', url)
	api.openWin({
		name: 'webBrowser',
		url: 'widget://html/webBrowser/webBrowser.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开外部链接
function openYd_url(url) {
	stat_app_modules('szyd_count');

	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	$api.setStorage('ydurl', url)
	api.openWin({
		name: 'webYuedu',
		url: 'widget://html/webBrowser/yuedu.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开外部链接
function openHd_url(url) {
	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	$api.setStorage('weburl', url)
	api.openWin({
		name: 'webInteract',
		url: 'widget://html/webBrowser/interact.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
function open365_url(url) {
	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	$api.setStorage('weburl365', url)
	api.openWin({
		name: 'webWh365',
		url: 'widget://html/webBrowser/wh365.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
function openQt_url(url) {
	if(url == '') {
		return;
	}
	$api.setStorage('weburl', url)
	api.openWin({
		name: 'myprizelist',
		url: 'widget://html/webBrowser/myprizelist.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
function openVedio_url(url) {
	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	$api.setStorage('vediourl', url)
	api.openWin({
		name: 'webVedio',
		url: 'widget://html/webBrowser/vedio.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
// 打开志愿者申请详情页面
function openWin_volunteer_detail(id) {
	var islogin = $api.getStorage('token');
	$api.setStorage('volunteerId', id);
	if(islogin){
		api.openWin({
			name: 'volunteer_detail',
			url: 'widget://html/volunteer/volunteer_detail.html',
			bounces: false,
			vScrollBarEnabled: false,
			hScrollBarEnabled: false,
			slidBackEnabled: true,
			animation: {
				type: 'fade',
				duration: 300
			}
		});
	}else{
		api.openWin({
				name: 'login',
				url: '../login/login.html',
		});
	}

}
//获取app首页广告位图片
function app_indexgg(t) {
	get_data('/api/Party/app_indexgg', 'post', {

	}, function(ret) {
		if(ret.status == 1) {
			console.log(JSON.stringify(ret))
			t.attr('src',ret.data);
		}
	})
}
//统计app访问量接口
function stat_app(){

		get_data('/api/siteviewcount/count', 'post', {

		}, function(ret) {

		})
}

function stat_app_modules(view_field){
		console.log(JSON.stringify($api.getStorage('userinfo')));
		var uid = $api.getStorage('userinfo')?$api.getStorage('userinfo').uid:0;
		get_data('/api/siteviewcount/app_modules_visit', 'post', {
			'view_field':view_field,
			'deviceId' :api.deviceId,
			'uid':uid
		}, function(ret) {
			// console.log(JSON.stringify(ret));
			// console.log(view_field);
		})
}
//分享链接加积分，点赞加积分
function share_addpoints(share_place){
	var behavior = $api.getStorage('behavior');
	var share_field = $api.getStorage('share_field');
	var share_id =$api.getStorage('share_id');
	var token = $api.getStorage('token');

	get_data('/api/point/inpoint', 'post', {
		'behavior':behavior,
		'type':1,
		'token':token,
		'share_from':share_field,
		'share_id':share_id,
		'share_place':share_place
	}, function(ret) {

		 if(ret.data.points){
			 $api.setStorage('points', ret.data.points);
		 }

		 api.toast({
			 msg: ret.msg
		 });

		// console.log(view_field);
	})
}

function fmtDate(date,type){
	var dateNum = parseInt(date) * 1000
	var dateStr = new Date(dateNum);
	var year = 1900+dateStr.getYear();
	var month = dateStr.getMonth() + 1;
	month = month < 10 ? ('0' + month) : month;
	var day = dateStr.getDate();
	day = day < 10 ? ('0' + day) : day;
	var hour = dateStr.getHours();
	hour = hour < 10 ? ('0' + hour) : hour;
	var minute = dateStr.getMinutes();
	var second = dateStr.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	if(type == 'h'){
		return year + '-' + month + '-' + day +' '+ hour;
	}else if(type == 'm'){
		return year + '-' + month + '-' + day +' '+ hour + ':' + minute;
	}else if(type == 's'){
		return year + '-' + month + '-' + day +' '+ hour + ':' + minute + ':' + second;
	}else{
		return year + '-' + month + '-' + day;
	}
}
function openmodulelink(param,l){
	if(!!l){
		// openVedio_url(l)
		// add 周弦 20190321
		switch(param){
			case 'wh365':
				openVedioShare_url(l)
			  break;
			default:
				openVedio_url(l)
		}
		// end 周弦 20190321
	}else{
		switch(param){
			case 'act_pre':
				//活动预告
				click_act_pre();
				break;
			case 'law':
				//政策法规
				click_law();
				break;
			case 'yuedu':
				//数字阅读
				click_yuedu();
				break;
			case 'jiangtang':
				//讲堂
				click_jiangtang();
				break;
			case 'volunt':
				//设施
				click_volunt();
				break;
			case 'zhaobiao':
				//招标
				click_zhaobiao();
				break;
			case 'cultural':
				//社团风采
				click_cultural();
				break;
			case 'all':
				//更多
				click_all();
				break;
			case 'zhanting':
				openWin_article_list('16','掌上展厅');
				break;
			case 'wenwu':
				openWin_article_list('33','文物');
				break;
			case 'feiyi':
				//非遗
				open_win('feiyi','feiyi.html',false);
				break;
			case 'mingjia':
				openWin_article_list('30','滨海名家');
				break;
			case 'minjian':
				openWin_article_list('31','民间艺术');
				break;
			case 'shetuan':
				openWin_article_list('27','企业社团');
				break;
			case 'wailai':
				openWin_article_list('10','外来建设者艺术节');
				break;
			case 'binhaiyishu':
				openWin_article_list('7','滨海艺术节');
				break;
			case 'shaoer':
				openWin_article_list('19','少儿评剧节');
				break;
			case 'shequyishu':
				openWin_article_list('8','社区艺术节');
				break;
			case 'guanniao':
				openWin_article_list('9','国际观鸟节');
				break;
			case 'ziyuan':
				openWin_article_list('41','产业资源');
				break;
			case 'dongtai':
				openWin_article_list('42','产业动态');
				break;
			case 'chaditu':
				//查地图
				var url="/api/venue/isShowNavigation";
				var isShow = true;
				get_data(url, 'post',{},function(res){
					// var ret = JSON.stringify(ret);
					isShow = res.data;
					//console.log(isShow);
					if(!isShow){
						alert("功能暂未开放");
						return false;
					}
					open_win('map_sou','map/map_sou.html',false);
				});
				break;
			case 'souxinxi':
				//搜信息
				open_win('search','search/search.html',false);
				break;
			case 'huanfuli':
				//换福利
				click_fuli();
				break;
			case 'qiandao':
				//签到
				open_qiandao();
				break;
		}
	}
}
/*换福利 */
function click_fuli() {
	stat_app_modules('fuli_count');
	var islogin = $api.getStorage('token');
	console.info("--------");
	console.info(islogin)
	if(islogin){
		open_win('point_store','./points/point_store.html',false);
	}else{
		// alertBtn('','登录后才能签到哦！');
		api.openWin({
				name: 'login',
				url: 'login/login.html',
		});
	}
	// open_win('signIn','points/signIn_frame.html',false);//点击跳转到签到页面
	// 清除福利消息在本地缓存
	// updateFuliCache(false);
}
/*签到 */
function open_qiandao() {
	//var islogin = $api.getStorage('token');
	get_data('/api/point/is_login', 'post', {
		token: $api.getStorage('token')
	}, function(ret) {
		if(ret.status==-1){
			api.openWin({
				name: 'login',
				url: 'login/login.html',
			});
		}else{
			api.openWin({
				name: 'signIn',
				url: 'points/signIn.html',
			});
		}
	});
}
/**
 * 活动预告点击
 */
function click_act_pre(){
	openWin_article_list('1','活动预告');
	updateMsgCache($("#div_act_pre"),Config.getConstant("TYPE_PUSH_HOME_ACT_PRE"),false);
}
/**
 * 政策法规点击
 */
function click_law(){
	open_win('law','law.html',false);
	updateMsgCache($("#div_law"),Config.getConstant("TYPE_PUSH_HOME_FAGUI"),false);
}
/**
 * 招标信息点击
 */
function click_zhaobiao(){
	openWin_article_list('43','招标信息');
	updateMsgCache($("#div_zhaobiao"),Config.getConstant("TYPE_PUSH_HOME_ZHAOBIAO"),false);
}
/**
 * 文化365点击
 */
// function click_365(){
// 	openWin_article_list('44','文化365');
// 	updateMsgCache($("#div_365"),Config.getConstant("TYPE_PUSH_HOME_365"),false);
// }
/**
 * 掌上展厅点击
 */
function click_handin(){
	openWin_article_list('16','掌上展厅');
	updateMsgCache($("#div_handin"),Config.getConstant("TYPE_PUSH_HOME_INHAND"),false);
}
/**
 * 文化超市点击
 */
function click_market(){
	open_win('wenhuacs','wenhuacs.html',false);
	updateMsgCache($("#div_market"),Config.getConstant("TYPE_PUSH_HOME_MARKET"),false);
}
/**
 * 志愿服务点击
 */
function click_volunt(){
	open_win('volunteer','./volunteer/volunteer.html',false);
	updateMsgCache($("#div_volunt"),Config.getConstant("TYPE_PUSH_HOME_VOLUNT"),false);
}
/**
 * 全部点击
 */
function click_all(){
	open_win('more','more.html',false);
	updateMsgCache($("#div_all"),Config.getConstant("TYPE_PUSH_HOME_ALL"),false);
}

/**
 * 根据本地缓存点亮未读消息
 */
function initHomeFrameMsgCache(){
	 // 活动预告
	 loadCacheMsg($("#div_act_pre"),Config.getConstant("TYPE_PUSH_HOME_ACT_PRE"));
	 // 政策法规
	 loadCacheMsg($("#div_law"),Config.getConstant("TYPE_PUSH_HOME_FAGUI"));
	 // 招标信息
	 loadCacheMsg($("#div_zhaobiao"),Config.getConstant("TYPE_PUSH_HOME_ZHAOBIAO"));
	 // 文化365
	//  loadCacheMsg($("#div_365"),Config.getConstant("TYPE_PUSH_HOME_365"));
	 // 掌上展厅
	 loadCacheMsg($("#div_handin"),Config.getConstant("TYPE_PUSH_HOME_INHAND"));
	 // 文化超市
	 loadCacheMsg($("#div_market"),Config.getConstant("TYPE_PUSH_HOME_MARKET"));
	 // 志愿服务
	 loadCacheMsg($("#div_volunt"),Config.getConstant("TYPE_PUSH_HOME_VOLUNT"));
	 // 全部功能
	 loadCacheMsg($("#div_all"),Config.getConstant("TYPE_PUSH_HOME_ALL"));
}

function loadCacheMsg(container,moduel){
 api.getPrefs({
		 key: moduel
 }, function(ret, err) {
		 var isOn = ret && ret.value && ret.value == '1' ;
		 updateMsgCache(container,moduel,isOn);
 });
}

function updateMsgCache(container,moduel,isOn){
	var value = isOn ? "1" : "0";
	api.setPrefs({
			key: moduel,
			value: value
	});
	if(isOn) {
		$(container).append("<div class='msg-new'></div>");
	} else {
		$(container).find('div .msg-new').remove();
		$(container).find('.msg-new').remove();
	}
}
// 数字阅读
function click_yuedu(){
	get_data('/api/information/generatelink', 'post',{},function(ret){
		// var ret = JSON.stringify(ret);
		//console.log(ret);
		if(ret.status == 1){
			linkUrl = ret.data.link;
			openYd_url(linkUrl);
		}else{
			console.log(ret.msg);
		}
	});
}
//文化消费
function click_cultural(){
	open_win('cultural','./cultural/cul_index.html',false);
	// updateMsgCache($("#div_all"),Config.getConstant("TYPE_PUSH_HOME_ALL"),false);
}
//预约活动列表
function click_activety(){
	open_win('bebefits','./benefits.html',false);
	// updateMsgCache($("#div_all"),Config.getConstant("TYPE_PUSH_HOME_ALL"),false);
}
function click_jiangtang(){
	openVedio_url('http://www.bhwh.gov.cn/home/page/jiangzuo.html');
}
// 周弦 打开链接带分享 add 周弦 20190321
function openVedioShare_url(url){
	if(url == '') {
		//		toast('网络不稳定','bottom');
		return;
	}
	$api.setStorage('vediourl', url)
	api.openWin({
		name: 'webVedioShare',
		url: 'widget://html/webBrowser/vedio_share.html',
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		slidBackEnabled: true,
		animation: {
			type: 'fade',
			duration: 300
		}
	});
}
//调用本机导航软件
function fnOpenMap(location1,location2,title){
	var url="/api/venue/isShowNavigation";
	var isShow = true;
	get_data(url, 'post',{},function(res){
		// var ret = JSON.stringify(ret);
		isShow = res.data;
		console.log(isShow);
		if(!isShow){
			alert("功能暂未开放");
			return false;
		}
		doFnOpenMap(location1,location2,title);
	});
}
function doFnOpenMap(location1,location2,title){	
	var _arr = [{
		type: 'iosamap',
		name: '高德地图'
	}, {
		type: 'baidumap',
		name: '百度地图'
	},{
		type: 'qqmap',
		name: '腾讯地图'
	}/*, {
		type: 'comgooglemap',
		name: 'google地图'
	}*/],
	_param = {
		cancelTitle: '取消',
		buttons: []
	}
	_fnAppInstalled(0, function(){
		api.actionSheet(_param, function(ret, err) {
			var _temp = _arr[ret.buttonIndex-1];
			if( _temp ){
				if(location1>0&&location2>0){
					//有目的地定位
					callMap.fnOpenMap({
						type: _temp.type,
						end: {
							lat: location1,
							lon: location2
						},
						title:title
					})
				}else{
					//无目的地定位
					callMap.fnOpenMapSearch({
						type: _temp.type,
					})
				}
			}
		});
	})
	function _fnAppInstalled(_num, _cb) {
		if (_num < _arr.length) {
			callMap.fnAppInstalled(_arr[_num].type, function(ret){
				var _name = _arr[_num]['name'];
				if(!ret.installed){
					_name = _name + ' (未安装)';
				}
				_param.buttons.push(_name);
				_fnAppInstalled(++_num, _cb);
			})
		} else {
			_cb && _cb();
		}
	}
}
function getUserAgent(){
	var userAgent =  api.getPrefs({
		sync: true,
		key:'userAgent'
	});
	return userAgent;
}
function checkUserAgent(){
	var userAgent = getUserAgent();
	var result = false;
	if('wenhuasuixing'==userAgent){
		result = true;
	}
	return result;
}
function goback() {
	browser = api.require('webBrowser');
	browser.historyBack(
		function(ret, err) {
			if(!ret.status) {
				api.closeWin();
			}
		}
	);
}
function goForward() {
	browser = api.require('webBrowser');
	browser.historyForward(
		function(ret, err) {
			if(!ret.status) {
				api.closeWin();
			}
		}
	);
}
function openView(url,h,y=0){
	var browser = api.require('webBrowser');
    browser.openView({
        url: url,
        headers:{
            'Usera-Agent':'whsx',
        },
        rect: {
            x: 0,
            y: y,
            w: 'auto',
            h: h
        },
        progress:{
            color:'rgba(100,100,100,0.5)',
        }
    }, function(ret, err) {
		console.log(JSON.stringify(ret),JSON.stringify(err));
	});
}
//获取手机本地文件 非本地文件则缓存 返回文件列表
function getPhoneImages(filelist){
	filelist.forEach(function(file,index){
		var result = getPhoneImage(file.img);
		if(result.url){
			filelist[index].localImg = result.url;
		}
		if(!!filelist[index].localImg){
			filelist[index].localImg = result.link;
		}
	});
	return filelist;
}
function getModelImages(filelist){
	var iconLocalUrls =[] 
	filelist.forEach(function(file,index){
		var result = getPhoneImage(file.img);
		if(result.url){
			filelist[index].img = result.url;
		}
		if(!!filelist[index].img){
			filelist[index].img = result.link;
		}
		iconLocalUrls.push({id:file.icon,url:result.url});
	});
	$api.setStorage('iconLocalUrls',iconLocalUrls);
	return filelist;
}
//url本地链接 link网络链接
function getPhoneImage(imgUrl){
	var url="",
		link=imgUrl;
	var fs = api.require('fs');
	fs.exist({
		path: imgUrl
	}, function(fret, ferr) {
		if(!fret.exist){
			//文件不存在
			api.imageCache({
				url : imgUrl,
				thumbnail:false,
			}, function(result, err) {
				if (result) {
					url = result.url;
				}else{
					//若图片缓存失败
					url = false;
				}
				if(err){
					console.log(JSON.stringify(err));
				}
			});
		}else{
			//本地有该文件
			url = imgUrl;
		}
		if(ferr){
			console.log(Json.stringify(ferr));
		}
	})
	return {url:url,link:link};
}

//极光信息推送