// zzss v2.2.4
// mini-pico-tiny convenience micro-framework
// Ad.ZZSS
// last modified 2011.8.8
/**
 * 上线环境
 * SH: shanghai server
 * test: 80 test server
 * local: 106
 */
window.serverEnvironment = "test";

/**
 * 应用环境设置
 * ZZSS.JS的应用环境配置
 * 文件的可用环境如下
 * application:	应用程序，JS应停止多数初始化内容，仅保留部分客户端必要内容
 * brand:		品牌球，加载品牌球的相关内容
 * page：		页面应用，例如首页的新闻列表，与品牌球相关的内容停止加载
 */
window.applicationContext = "application";

/**
 * LOG日志环境配置
 * 环境配置选项为
 * INFO		log.debug不工作
 * DEBUG	log.debug工作
 * ERROR	log.debug不工作
 */
window.logLevel = "DEBUG";

/**
 * 点击效果延迟时间配置
 */
var CLICK_ANIMATION_DURATION = 1000;
/**
 * tap动作判断使用的间隔时间
 * 即touchend事件与touchstart事件间，触发的间隔时间
 */
var TAP_INTERVAL = 500;

/**
 * 数据关键码
 * 
 * 如果不存在则创建
 */
if (!window.dataKeys) {
	window.dataKeys = {};
}

if(!window.dataEnum){
	window.dataEnum = {};
}

/**
 * 用户信息关键码
 */
dataKeys.userInfo = {
	userName : "userName",
	password : "password",
	sex : "sex",
	age : "age",
	phoneNum : "phoneNum",
	nickname : "nickname",
	email : "email",
	zsAgreeFlag : "zsAgreeFlag"
};

/**
 * 用户信息枚举
 */
dataEnum.userInfo = {
	sex : {male : "male", female : "female"}
};

/**
 * 取得元素
 */
function $(id){
	if(tools.isHTMLElement(id)){
		return id;
	}else if(tools.isString(id)){
		return document.getElementById(id);
	}else{
		return null;
	} 
}

/**
 * 创建document对象
 * @param {String} tagName 标签名
 */
function $CE(tagName){
	return document.createElement(tagName);
}

/**
 * 创建文本对象
 * @param {String} 文本内容
 */
function $CT(text){
	return document.createTextNode(text);
}

/**
 * 改变元素中的HTML内容
 * @param {String} id	元素ID
 * @param {String} html	需要赋值的HTML代码
 */
function html(id, htmlCode){ $(id).innerHTML = htmlCode; }

/**
 * 添加一个css属性
 * @param {Object} id		元素ID
 * @param {Object} style	属性字符串
 */
function css(id, style){ $(id).style.cssText += ';'+style; }

/**
 * 給元素添加一个class属性
 * @param {Object} id		元素ID
 * @param {Object} cName
 */
function cn(id, cName){$(id).className+= " "+ cName;}

/**
 * 判断元素是否包含一个class
 * 包含则返回true，否则返回false
 * 
 * @param {HTMLElement || String} id
 * @param {String} className
 */
function hasClass(id ,className) {
	var ele = $(id);
	
	if(!tools.isString(className) || !ele){
		return;
	}
	
	return ele.getAttribute("class").match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}

/**
 * 添加一个class
 * @param {HTMLElement || String} id
 * @param {String} className
 */
function addClass(id,className) {
	var ele = $(id), eleClass;
	
	if(!tools.isString(className) || !ele){
		return;
	}
	
	eleClass = ele.getAttribute("class");
	ele.setAttribute("class", (eleClass ? eleClass + " " : "") + className);
}

/**
 * 删除一个class属性
 * @param {HTMLElement || String} id
 * @param {String} className
 */
function removeClass(id, className){
	var ele = $(id), eleClass;
	
	if(!tools.isString(className) || !ele){
		return;
	}
	
	eleClass = ele.getAttribute("class");
	if(tools.isNotBlankStr(eleClass)){
		ele.setAttribute("class", eleClass.replace(new RegExp('(\\s*|^)'+className+'(\\s*|$)', 'g'), ""));
	}
}

/**
 * 如果存在（不存在）就删除（添加）一个类。
 * 
 * @param {HTMLElement || String} ele
 * @param {String} className
 */
function toggleClass(ele, className){
	if(hasClass(ele, className)){
		removeClass(ele, className);
	}else{
		addClass(ele, className);
	}
}

/**
 * 判断元素是否包含一个style
 * 包含则返回true，否则返回false
 * 
 * @param {HTMLElement || String} id
 * @param {String} style
 */
function hasStyle(id ,style) {
	var ele = $(id);
	
	if(!tools.isString(style) || !ele){
		return;
	}
	
	return ele.getAttribute("style").match(new RegExp('(\\s|^)'+style.replace('-', "\\-")+'(\\s|$)'));
}

/**
 * 添加一个style
 * @param {HTMLElement || String} id
 * @param {String} style
 */
function addStyle(id,style) {
	var ele = $(id), eleStyle;
	
	if(!tools.isString(style) || !ele){
		return;
	}
	
	eleStyle = ele.getAttribute("style");
	ele.setAttribute("style", (eleStyle ? eleStyle + " " : "") + style);
}

/**
 * 删除一个style
 * @param {HTMLElement || String} id
 * @param {String} style
 */
function removeStyle(id, style){
	var ele = $(id), eleStyle;
	
	if(!tools.isString(style) || !ele){
		return;
	}
	
	eleStyle = ele.getAttribute("style");
	if(tools.isNotBlankStr(eleStyle)){
		ele.setAttribute("style", eleStyle.replace(new RegExp('(\\s*|^)'+style.replace(/(\(|\))/g, "\\$1")+'(\\s*|$)', 'g'), ""));
	}
}

/**
 * 清除一组元素的class属性
 * 依据传入的元素ID，循环清除传入的它们的class
 * 
 * @param {vararg} x	变长参数，String类型，元素ID
 */
function cl(x){for(i=0; i< arguments.length; i++){$(arguments[i]).className='';}}

/**
 * 清楚一组元素的CSS属性
 * 依据传入的元素ID，循环清除传入的它们的style
 * @param {vararg} x	变长参数，String类型，元素ID
 */
function cl2(x){for(i=0; i< arguments.length; i++){$(arguments[i]).style.cssText='';}}

/**
 * 通过CSS添加动画
 * @param {Object} id			元素ID
 * @param {Object} transform
 * @param {Object} opacity
 * @param {Object} dur			持续时间
 */
function anim(id, transform, opacity, dur){  
css(id, '-webkit-transition:-webkit-transform'+
',opacity '+(dur||0.5)+'s,'+(dur||0.5)+'s;-webkit-transform:'+
transform+';opacity:'+(opacity||1));
}

/**
 * 返回domain地址
 */
function getDomain(){
	switch(window.serverEnvironment){
		case "local" : return ("http://221.130.11.81:8081/");
		case "test" : return ("http://221.130.11.81:8081/");
		case "SH" :  
		default: return ("http://ms.zzss.com/"); 
	}
}

/**
 * 获取操作系统版本
 * 例如2.2返回22；1.6返回16
 */
function getOSVersion(){
	return ua.osVersion + ua.osMinorVersion;
}

/**
 * 对客户端版本号进行比对
 * 如果API获取的版本号大于传入的版本号，返回1
 * 如果API获取的版本号小于传入的版本号，返回-1
 * 如想两者相等，返回0
 * @param {Object} versionStr	版本号，格式为"1.1.1"
 */
function compareClientVersion(versionStr){
	if(window.demo.getVersion && window.demo.getVersion() && versionStr){
		var clientVersion = new String(window.demo.getVersion());
		var clientVerParts = clientVersion.split(".");
		var versionStrParts = versionStr.split(".");
		
		//循环比较，如果API中的版本号大于
		for(var i = 0; i < clientVerParts.length; i++){
			var paramVersionPart = parseInt(versionStrParts[i] || 0);
			var clientVersionPart = parseInt(clientVerParts[i]);
			if(clientVersionPart > paramVersionPart)
				return 1;
			else if(clientVersionPart < paramVersionPart)
				return -1;
		}
		
		return 0;
	}
	
	return -1;
}

/**
 * 页面跳转
 * 如果target的值为browser
 * 则在本地浏览器中打开页面
 * 
 * 其余则在本页面打开
 * 
 * @param {string} url
 * @param {string} target
 */
function jump(url, target){		
	if(target == "browser"){
		window.demo.nativebrowser(url);
	}else{
		window.location.href= url;
	}
}
function isUndefined(e){		// 判断对象是否未定义
	return (e === undefined);
}
function isset(e){			// 判断对象是否没有被设置值
	return ((!isUndefined(e)) && (e !== null));
}
/**
 * 返回屏幕高度
 */
function screenH(){
	var width = window.demo.getPhoneScreenWidth(),
		height = window.demo.getPhoneScreenHeight();
	
	if(width >= 480){
		return height;
	}else{
		return height;
	}
}
/**
 * return screen width
 */
function screenW(){
	var width = window.demo.getPhoneScreenWidth();
	if(width >= 480){
		return width;
	}else{
		return width;
	}
}

//获取容器的宽
function getContainerWidth(){
	return document.body.offsetWidth > screenW() ? document.body.offsetWidth : screenW();
}

//获取容器的高
function getContainerHeight(){
	var getMaxHeightOfNodes = function(nodes){
		if(!tools.isArray(nodes)){
			return;
		}
		
		var i, maxHeight = 0, node;
		for(i = 0; i < nodes.length; i++){
			node = nodes[i];
			if(tools.isHTMLElement(node) && node.offsetHeight && node.offsetHeight > maxHeight){
				maxHeight = node.offsetHeight;
			}
		}
		
		return maxHeight;
	};
	return document.body.offsetHeight > screenH() ? document.body.offsetHeight : screenH();
}

/**
 * 跳转至某品牌
 * @param {String} action	品牌名
 */
function goPoster(action){
	window.demo.goPoster(action);
}

/**
 * 进入品牌球
 * @param {String} brandName	品牌名
 */
function goBrand(brandName){
	goBrandPage(brandName, "index.html");
}

/**
 * 进入品牌球中的某张页面
 * @param {String} brandName	品牌名
 * @param {String} fileName		页面文件名
 */
function goBrandPage(brandName, fileName){
	if(tools.isBlankStr(fileName)){
		fileName = "index.html";
	}
	
	window.demo.goInner(brandName, fileName);
}

/**
 * 展示所有品牌
 * 即跳转至品牌球宫格页面
 */
function showBrands(){
	window.demo.goBrandBall();
}

/**
 * 返回上一页
 * @param {String} brand	品牌名
 */
function goback(brand){
	window.zzss.back(brand);
}
/**
 * 插入记录
 * @param {String} key
 * @param {String} value
 */
function setData(key, value){
	key += "ZZSS";
	window.demo.setDic(key, value);
}
/**
 * 获得记录
 * @param {String} key
 */
function getData(key, funcName){
	key += "ZZSS";
	
	//如果funcName不存在，或者不是方法名，则直接返回调用API返回数据
	if(funcName && typeof(window[funcName]) == 'function'){
		if (window.demo.os == 'iphone') {
			window.demo.getDic(key, funcName);
		}
		else {
			window[funcName](formatAndroidData(window.demo.getDic(key)));
		}
	}else{
		return formatAndroidData(window.demo.getDic(key));
	}
}

/**
 * 将android中获得的数据进行格式化，转换为string类型
 * @param {Object} obj
 */
function formatAndroidData(obj){
	if(obj){
		obj = obj + "";
	}
	
	return obj;
}

/**
 * 下载文件
 * @param {Array||String} files
 */
function downloadFiles(files){
	//判断是否是字符串类型，如果是则转换为数组形式
	if (typeof(files) == "string") {
		files = [files];
	}
	
	//判断是否是数组类型，是数组类型则调用API
	if (files instanceof Array) {
		window.demo.downLoadFile(files);
	}
}

/**
 * 生成视频node对象
 * IPhone的视频地址与Android不同
 * IPhone使用HTML标签进行动态添加播放，需要提供父标签用于将
 * video添加至页面上，使用流媒体进行传输，URL使用视频格式结尾
 * 
 * Android使用API实现，需要完全下载后方可播放，URL使用ZIP格式结尾
 * 
 * @param {
 * posterImg: String	用于显示的视频触发图片
 * videoURLForAndroid : String	用于播放android视频的地址
 * videoURLForIPhone : String	用于播放iphone视频的地址
 * width : Integer		视频的宽
 * height : Integer		视频的高
 * } args
 * 
 * return 返回创建完毕的标签
 */
function generateVideo(args){
	//如果是iphone则创建HTML5的video标签，否则创建DIV，调用android的API
	if(window.demo.os && window.demo.os == "iphone" && args.videoURLForIPhone){	//iphone创建
		//创建VIDEO标签
		var video = $CE("video");
		//视频源
		video.setAttribute("src", args.videoURLForIPhone);
		//可控制
		video.setAttribute("controls", "controls");
		//视频预览图片
		video.setAttribute("poster", args.posterImg || "");
		
		//如果参数中包含高宽，则设置
		if((args.width && !isNaN(args.width)) && (args.height && !isNaN(args.height))){
			video.setAttribute("width", parseInt(args.width));
			video.setAttribute("height", parseInt(args.height));
		}
		
		return video; 
	}else if(args.videoURLForAndroid){	//android创建
		//创建DIV
		var videoDIV = $CE("div");
		var videoStyle = "";
		//增加背景图片
		videoStyle += "background:url('" + (args.posterImg || "") + "') no-repeat center;";
		
		//增加高度与宽度
		if ((args.width && !isNaN(args.width)) && (args.height && !isNaN(args.height))) {
			videoStyle += "width: " + args.width + "px; height: " + args.height + "px;";
		}
		
		//设置样式
		videoDIV.setAttribute("style", videoStyle);
		//绑定点击播放事件
		videoDIV.addEventListener("click", function(){window.demo.downLoadVideo(args.videoURLForAndroid);});
		
		return videoDIV;
	}
}

//音频实现暂时为空
function generateAudio(args){
	
}

/**
 * 设置壁纸
 * @param {Object} imageURI
 */
function setWallpage(imageURI){
	//如果是IPHONE，则直接返回，IPHONE不支持设置壁纸
	if (window.demo.os && window.demo.os == "iphone") {
		return;
	}
	
	window.demo.setWallpaper(imageURI);
}

//获取客户端的IMEI号
function getIMEI(){
	return window.demo.getuserid() + "";
}
/**
 * 打开通讯录
 * @param {String} funcName	回调函数方法名
 */
function openContacts(funcName){
	window.demo.accessContactWithCallBack(funcName);
}

/**
 * 打开加载对话框
 * 如果没有传入文本则直接return，不能运行
 * @param {String} loadingTxt	加载对话框中文本
 */
function openLoadingDialog(loadingTxt){
//	if (!loadingTxt) {
//		loadingTxt = "loading...";
//	}
//	
//	window.demo.openProgressForAjax(loadingTxt + "");
	loadingDialog.open();
}

/**
 * 关闭加载对话框
 */
function closeLoadingDialog(){
//	window.demo.closeProgressForAjax();
	loadingDialog.close();
}

/**
 * 弹出信息框
 * @param {String} title	弹出框标题
 * @param {String} content	弹出框文本内容
 * @param {String} btn1Txt	弹出框按钮1文本
 * @param {String} btn2Txt	弹出框按钮2文本
 * @param {String} callBack1Name	按钮1触发函数的函数名
 * @param {String} callBack2Name	按钮2触发函数的函数名
 */
function openDialog(title, content, btn1Txt, btn2Txt, callBack1Name, callBack2Name){
	if (btn1Txt && btn2Txt && callBack1Name && callBack1Name != "") {
		window.demo.openDialog(title, content, btn1Txt, btn2Txt, callBack1Name, callBack2Name);
	}else{
		window.demo.openDialog(title, content);
	}
}

function gup(name){		// 通过URL取得当前页面的参数
//	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec(window.location.href);
	  if( results === null ){
		return "";
	  }
	  else{
		return results[1];
	  }
}

/**
 * 打开摄像头
 * 拍照成功后，调用回调函数，并将图片的URI传入
 * (本方法仅为API的封装)
 * 
 * @param {String} brandName	品牌名
 * @param {String} fileName		文件名（iPhone API暂不使用）
 * @param {String} callback		回调方法名
 */
function openCamera(brandName, fileName, callback){
	//如果brandName为空，则直接返回
	if(tools.isBlandStr(brandName)){
		return;
	}
	
	//文件名若为空，则直接返回
	if(tools.isBlankStr(fileName)){
		return;
	}
	
	//如果回调函数不是方法，直接返回
	if(tools.isFunction(callback)){
		return;
	}
	
	window.demo.openCamera(brandName, fileName, callback);
};

/**
 * 打开本地图片选择器
 * 图片选择成功后，调用回调函数，并将图片的URI传入
 * (本方法仅为API的封装)
 * 
 * @param {String} brandName	品牌名（iPhone API暂不使用）
 * @param {String} callback		回调方法名
 */
function openPictureSystem(brandName, callback){
	//如果brandName为空，则直接返回
	if(tools.isBlandStr(brandName)){
		return;
	}
	
	//如果回调函数不是方法，直接返回
	if(tools.isFunction(callback)){
		return;
	}
	
	window.demo.openPictureSystem(brandName, callback);
};

/**
 * 上传数据
 * (本方法仅为API的封装)
 * 
 * @param {String} brandName		品牌名
 * @param {String} uri				文件的路径（可通过打开图片选择器或者拍照API获得）
 * @param {String} text				上传文件的描述文本
 * @param {String} successCallback	上传成功后的回调函数
 */
function uploadData(brandName, uri, text, successCallback){
	//如果brandName或者uri或者text为空，则直接返回
	if(tools.isBlandStr(brandName) || tools.isBlankStr(uri) || tools.isBlankStr(text)){
		return;
	}
	
	//如果回调函数不是方法，直接返回
	if(tools.isFunction(successCallback)){
		return;
	}
	
	window.demo.uploadData(brandName, uri, text, successCallback);
};

/***************************************************
 * getters and setters for private user information
 **************************************************/
function getUserName(){
	return getData(window.dataKeys.userInfo.userName);
}

function setUserName(userName){
	if(tools.validateUserName(userName)){
		setData(window.dataKeys.userInfo.userName, userName);
	}
}

function getSex(){
	return getData(window.dataKeys.userInfo.sex);
}

/**
 * 当且仅当传入的值与枚举的值相同时才执行set操作
 * 
 * @param {Object} sexStr
 */
function setSex(sexStr){
	if(tools.validateSex(sexStr)){
		setData(window.dataKeys.userInfo.sex, sexStr);
	}
}

function getAge(){
	return getData(window.dataKeys.userInfo.age);
}

function setAge(age){
	if(tools.isNumber(age)){
		setData(window.dataKeys.userInfo.age, age);
	}
}

function getPhoneNum(){
	return getData(window.dataKeys.userInfo.phoneNum);
}

function setPhoneNum(phoneNumStr){
	if(tools.validatePhoneNum(phoneNumStr)){
		setData(window.dataKeys.userInfo.phoneNum, phoneNumStr);
	}
}

function getEmail(){
	return getData(window.dataKeys.userInfo.email);
}

function setEmail(emailStr){
	if(tools.validateEmail(emailStr)){
		setData(window.dataKeys.userInfo.email, emailStr);
	}
}

function getNickname(){
	return getData(window.dataKeys.userInfo.nickname);
}

function setNickname(nickname){
	setData(window.dataKeys.userInfo.nickname, nickname);
}

/**
 * 返回用户是否已经注册
 */
function hasRegister(){
	var userName = getUserName(),
		nickname = getNickname(),
		sex = getSex(),
		phoneNum = getPhoneNum();
	
	return tools.validatePhoneNum(phoneNum) && tools.validateUserName(userName) &&
			tools.isNotBlankStr(nickname) && tools.validateSex(sex);
}

/**
 * 返回用户信息是否允许在所有内容中使用
 * 
 * @return 允许使用则返回true，否则返回false
 */
function isPublicUserInfo(){
	var flagValue = getData(window.dataKeys.userInfo.zsAgreeFlag);
	
	if(flagValue == "true"){
		return true;
	}else{
		return false;
	}
}

/**
 * 设置用户数据是否允许在所有内容中使用
 * 
 * @param {Boolean} zsAgreeFlag
 */
function setPublicAgree(zsAgreeFlag){
	var flagValue;
	//如果是boolean类型的值
	if( ( tools.isBoolean(zsAgreeFlag) && zsAgreeFlag ) ||
		 ( tools.isString(zsAgreeFlag) && zsAgreeFlag == "true" ) ){
		flagValue = "true";
	}else{
		flagValue = "false";
	}
	
	setData(window.dataKeys.userInfo.zsAgreeFlag, flagValue);
}

/**
 * 按比例缩小元素（beta版）
 * 依据传入的元素宽度进行缩小
 * 缩小的元素会被一个wrapper包裹
 * 并重新被添加到父元素中
 * 
 * @deprecated
 * @param {String or HTMLElement} element
 */
function scaleElement(option){
	var element = option.element,
		width = option.width,
		oneScreen = option.oneScreen,
		/**
		 * 创建一个viewport标签，并添加到head中
		 * @param {Object} width
		 */
		addViewport = function(width){
			if(tools.isNumber(width)){
				var meta = $CE("meta"),
					head = document.getElementsByTagName("head")[0];
				meta.setAttribute("name", "viewport");
				meta.setAttribute("content", "width=" + width);
				head.appendChild(meta);
				
				return meta;
			}
			
			return null;
		},
		/**
		 * 创建一个wrapper
		 * 由于container使用scale缩小以后，
		 * 虽然内容缩小了，但是width与height是不会改变的，
		 * 因此创建一个wrapper，
		 * 整个wrapper用于包含所有的内容，
		 * 并依据width与height进行设置，将超出部分隐藏
		 * 
		 * @param {Object} container
		 * @param {Object} width
		 * @param {Object} height
		 */
		createWrapper = function(container, width, height){
			var wrapper = $CE("div");
			wrapper.style.position = "relative";
			wrapper.style.width = width + "px";
			wrapper.style.height = height + "px";
			wrapper.style.overflow = "hidden";
			wrapper.appendChild(container.cloneNode(true));
			
			return wrapper;
		},
		/**
		 * 对container进行放大缩小
		 * 缩小的比例依据传入的width进行计算
		 * 缩小的中心点为整个元素的左上角
		 * 方法执行完毕后返回缩小的比例
		 * 
		 * @param {Object} container
		 * @param {Object} width
		 */
		scaleContainer = function(container, width){
			var rate;
			
			if(tools.isNumber(width)){
				rate = width / container.offsetWidth;
			}else{
				rate = 1;
			}
			
			container.style.webkitTransformOrigin = "0px 0px";
			container.style.webkitTransform = "scale(" + rate + ")";
			
			return rate;			
		},
		wrapper,	//用于包含整个container
		rate,		//保存缩小container的比例
		width = width || screenW(),
		container = $(element),
		parentNode;
		if(tools.isNull(container)){
			return;
		}
		
		parentNode = container.parentNode;
		addViewport(width);
		rate = scaleContainer(container, width);
		wrapper = createWrapper(container, container.offsetWidth * rate, (oneScreen ? screenH() : container.offsetHeight * rate));
		if(wrapper){
			parentNode.replaceChild(wrapper, container);
		}
}

/**
 * 绑定事件方法
 * @param {
 * 	event			: String
 * 	element			: HTMLElement
 * 	func			: Function
 *  once			: Function
 *  activeStyle		: String
 *  activeClass		: String
 * } option
 */
function bindEvent(option){
	//如果参数不存在，或者事件名不存在，或事件名不是字符串，则直接跳出方法执行
	if(	!option || 
		!(option.event && tools.isString(option.event)) ||
		!(option.element && tools.isHTMLElement(option.element)) ||
		!(option.func && tools.isFunction(option.func))){
		return;
	}
	
		//绑定一次性方法，调用后会从事件中删除
	var bindOnceEvent = function(element, event, func){
			element.addEventListener(event, function tempFunc(e){
				try {
					tools.callFunction(func, e);
				}catch(ex){log.error(ex);}
				this.removeEventListener(event, tempFunc);
			});
		},
		//绑定方法封装，判断是否是绑定一次性方法，如果是，则调用绑定一次性方法函数
		//如果不是，则进行正常绑定
		bindNormalEvent = function(element, event, func, once){
			if(once && once == true){
				bindOnceEvent(element, event, func);
			}else{
				element.addEventListener(event, func);
			}
		},
		//获取touch end事件
		getTouchEndEvent = function(){
			if(ua.isMobile){
				return "touchend";
			}else{
				return "mouseup";
			}
		},
		//获取touch start事件
		getTouchStartEvent = function(){
			if(ua.isMobile){
				return "touchstart";
			}else{
				return "mousedown";
			}
		};
	
	if(option.event.toLowerCase() == "tap" || option.event.toLowerCase() == "click"){
		(function(){
			var startTime,
				isActive = false,
				touchmoved = false,
				/**
				 * 添加点击效果
				 */
				addActiveCSS = function(){
					//增加点击样式
					if(option.activeStyle && tools.isNotBlankStr(option.activeStyle)){
						addStyle(option.element, option.activeStyle);
					}
					
					//增加点击class
					if(option.activeClass && tools.isNotBlankStr(option.activeClass)){
						addClass(option.element, option.activeClass);
					}
					
					isActive = true;
				},
				/**
				 * 移除点击效果
				 */
				removeActiveCSS = function(){
					if(isActive){
						//增加点击样式
						if(option.activeStyle && tools.isNotBlankStr(option.activeStyle)){
							removeStyle(option.element, option.activeStyle);
						}
						
						//增加点击class
						if(option.activeClass && tools.isNotBlankStr(option.activeClass)){
							removeClass(option.element, option.activeClass);
						}
					}
					
					isActive = false;
				};
			
			//绑定touch start事件
			bindNormalEvent(option.element, getTouchStartEvent(), function(e){
				startTime = (new Date()).getTime();
				addActiveCSS();
				setTimeout(removeActiveCSS, TAP_INTERVAL);
				
			}, option.once);
			//绑定touch move事件
			bindNormalEvent(option.element, "touchmove", function(e){
				touchmoved = true;
			});
			//绑定 touch end事件
			bindNormalEvent(option.element, getTouchEndEvent(), function(e){
				var endTime = (new Date()).getTime();
				
				//如果没有touchmove产生，并且持续时间小于5，则出发click事件方法
				if( ( !ua.isMobile || !touchmoved ) && ( endTime - startTime <= TAP_INTERVAL ) ){
					tools.callFunction(option.func, e);
					removeActiveCSS();
				}
				
				touchmoved = false;
			}, option.once);
		})();
	}else{
		bindNormalEvent(option.element, option.event, option.func, option.once);
	}
}

/**
 * 加载对话框
 */
var loadingDialog = (function(){
	var createLoadingDialog = function(){
			var loadingWidth = 30,
				loadingHeight = 30,
				//添加旋转的CSS
				createStyle = function(){
					loadingCSSStr = ".zzssWhiteBusy{width:" + loadingWidth + "px;height:" + loadingHeight + "px;-webkit-background-size:" + loadingWidth + "px " + loadingHeight + "px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAABRZJREFUaN7dmU1sVUUYhp+3lD9pSoGCJbSEnxsBYUFkY0ATiL8LF5q4wYQoG7eGlSvjgp0bdUFiwqIadwZNjCwwsiCICCZIiVghQrmBmlap/NSKhbZ5XTA3np7OuX+co8iX3OSemTNn5p33e7+Z+QYKNNu9/sd6+T+a7e2eaS8W1V9LgVi2R8o23xdAbHfbPmp7wHaf7cdzZHCB7fW2N9pea3t2kYy8AXSH/+3AB7bbcwAxC+gBZoWiecCyIoF0p57bgd05ELIkAaJihTJyIsaS7e57YGM2sDRSdatIIL3AYKT8rXtgY0WkbAL4vTAgkkaBvZGqZyLCL9cjcGBBpGpI0lSh4VfSV8DJSNU7jQLJYONPSX/8W+tIjJVu27sb0MaSDEEP3/M6YrvL9pu237X9mu22DFb6gU8zhF8tHJcT4TYm8BuSxrNCdBhfyfZK23OmjSn18n6glJqdfZKORT7cDhwNIXgaW5J6ba8CLqXqVksqBza6UnVTwM8xbdheGNwwOfi/JJ3Pcq1S6rkL2BsYKkWE/35k8tpDfRl4CTgSfjtCGZE1A+BqGoTt+aHf1SkQAPOrMfIF0FbFNQ4FhsYSbQ4CjybeeUXSiTqi1apE0biki6mVfgWwuMpnpiT9kAVkcxByNTBjwEeSDiRcrCLyk7VARELvVNDGVChfGjxhVjUQwGVJN6NAwofagJeBV2uM5QKwJ8lODvutUtplMqLaDDdsiUSkMUkfAjuBviofLAXAednSGiDGgH5Jw7GA0FJl4RuWtAfY02xsz8nuABckXZB0p+kFUVKfpJ3AvjArSevLccBjER38Iqm/HvdVg37cBjwfgkGfpDyBVL7fFkBca3S/9UCYwkxsAFZm7ESnbeiAU5JGCk5czA0L69w6Xh+VNCrbrwNPNtjXe5JOFQRiMfBIg82utjQBAuC5AgnpaiZ0tzwoGmkBvm6i3ZcFjmmwiTZXk2LfUEeD+1HstyRde7DCbwMzNQ/YEvZEA5IGcmaiA+gAJoFhSZO5A7G9DXiau1nAiu3PC0wAkcwNTwJlSXVpprWODtaEXe6iSPUaIC9WOiJjK4Xk3zlJN5oCYnsR8ELq9Pdf2Dxgs+2RsAserwtI0METwFM1OhgCjuUcdjurnE47gU7bZWAwrR9F3GhXSgdpGwcOS/omESq3hLorkq7UqYnOMDiAi5ImQnl3OM9Xc/tJ4GzS3dJA3q4B4hRwMEmv7V1MvwL4pBaYAGJbouimpCOJ+tZwAq22XZlMpqlaI/4Ys4EAYCg1oK3MvMfoAa6E+p6ExvoTADtTbRbaXlvJpAS3OWd7MADqqCWL1ojfL088Xw8A+jNW38cyXK9ySNqRKH/Y9mfhtDcRabfO9uWKi1XyB0BfYLCUmuixakA+DiJfBFySdLgKtTsiW4jbwI+VgUfa9AA/AZeBdUzP/c4GNgGnI8ftEWAkZC87wmSVM4FIug4cqEOoy4CNkarjkm6H/7HoMyf0M2H7fBh40lbaHkjmq1LjKzedfMiw7Rknte/r3lLc1UPsVmpTs9v4RrcSpeAiaTvURP+nY+uF7eWFA0kJmEbXj4jvD+XBSqP37FuZeY3QLBsVOxspe8j2+iIZid3efhuuGNJ2p05WbgHnI1VLigQyGgm3WdmU6w1892JkbSn0evo48FsCxOeJcNv86e7uIvhdAszNDJbyOSE2qKcu4NlU8RlJZ4rKovyb9muR6aBikgHScPB9Elv1wq4n/gZGzjH4jnexGwAAAABJRU5ErkJggg==);-webkit-animation-duration:1s;-webkit-animation-iteration-count:infinite;-webkit-animation-timing-function:linear;-webkit-animation-name:loading-spinner-keyframes;}@-webkit-keyframes loading-spinner-keyframes{from{-webkit-transform:rotate(0deg);}8.32%{-webkit-transform:rotate(0deg);}8.33%{-webkit-transform:rotate(30deg);}16.65%{-webkit-transform:rotate(30deg);}16.66%{-webkit-transform:rotate(60deg);}24.99%{-webkit-transform:rotate(60deg);}25%{-webkit-transform:rotate(90deg);}33.32%{-webkit-transform:rotate(90deg);}33.33%{-webkit-transform:rotate(120deg);}41.65%{-webkit-transform:rotate(120deg);}41.66%{-webkit-transform:rotate(150deg);}49.99%{-webkit-transform:rotate(150deg);}50%{-webkit-transform:rotate(180deg);}58.32%{-webkit-transform:rotate(180deg);}58.33%{-webkit-transform:rotate(210deg);}66.65%{-webkit-transform:rotate(210deg);}66.66%{-webkit-transform:rotate(240deg);}74.99%{-webkit-transform:rotate(240deg);}75%{-webkit-transform:rotate(270deg);}83.32%{-webkit-transform:rotate(270deg);}83.33%{-webkit-transform:rotate(300deg);}91.65%{-webkit-transform:rotate(300deg);}91.66%{-webkit-transform:rotate(330deg);}99.99%{-webkit-transform:rotate(330deg);}to{-webkit-transform:rotate(360deg);}}";
					var styleEle = $CE("style");
					styleEle.appendChild($CT(loadingCSSStr));
					document.getElementsByTagName("head")[0].appendChild(styleEle);
				},
				//创建最外层容器
				createContainer = function(){
					var container = $CE("div");
			
					//外层容器的高宽
					addStyle(container, "width: " + getContainerWidth() + "px; height: " + getContainerHeight() + "px; position: absolute; top: " + (document.body.scrollTop ? document.body.scrollTop : 0) + "px; left: 0px; z-index: 10000; background: rgba(0, 0, 0, 0.6)");
					return container;
				},
				//创建loading元素
				createLoading = function(){
					var loadingDIV = $CE("div"),
						left = getContainerWidth() / 2 - loadingWidth / 2,
						top = parseInt(document.body.scrollTop) + ( screenH() / 2 ) - loadingHeight / 2;
					addClass(loadingDIV, "zzssWhiteBusy");
					addStyle(loadingDIV, "position: absolute; left:" + left + "px; top:" + top + "px;");
					
					return loadingDIV;
				},
				container = createContainer(),
				loading = createLoading();
			
			createStyle();
			container.appendChild(loading);
			document.body.appendChild(container);
			//loading元素位置
			loading.style.top =  + 'px';
			
			return container;
		},
		/**
		 * 打开loading对话框
		 */
		open = function(){
			if(!loadingEle){
				loadingEle = createLoadingDialog();
			}
			loadingCount++;
		},
		/**
		 * 关闭loading对话框
		 */
		close = function(){
			loadingCount--;
			
			if(loadingEle && loadingCount <= 0){
				loadingEle.parentNode.removeChild(loadingEle);
				loadingEle = null;
			}
		},
		loadingCount = 0,
		loadingEle;
		
	return {
		open : open,
		close : close
	};
})();

var Scoller = (function(){
	var preventScoller = function(evt){
			evt.preventDefault();
			evt.stopPropagation();
		},
		disable = function(){
			document.addEventListener("touchmove", preventScoller);
		},
		enable = function(){
			
		};
	
})();

(function(){		// 创建一个闭包
	
/**
 * UA管理对象
 * 
 * @methods:
 * 	--> getTouchStartEvent: 		give the corresponding start event
 * 	--> getTouchMoveEvent: 			give the corresponding move event
 * 	--> getTouchEndEvent: 			give the corresponding end event
 * 	--> isLatestPhone: 				如果是iPhone或者1.5以上版本的GPhone为true
 * 
 * @attributes:
 *  --> isWebkit: 					Indicates whether webkit is available
 *  --> isMobile: 					Indicates whether the platform is a mobile
 *  --> isIPhone: 					Indicates whether the platform is a IPhone
 *  --> isIPod:						Indicates whether the platform is a IPod
 *  --> isIPad: 					Indicates whether the platform is a IPad
 *  --> isAndroid: 					Indicates whether the platform is a Android
 *  --> isSafari: 					Indicates whether the browser is Safari
 *  --> isMozilla: 					Indicates whether the browser is Mozilla
 *  --> webkitVersion: 				The webkit major version
 *  --> webkitMinorVersion: 		The webkit minor version
 *  --> webkitUpdateVersion: 		The webkit update version
 *  --> browserVersion: 			The browser major version
 *  --> browserMinorVersion: 		The browser minor version
 *  --> browserUpdateVersion: 		The browser update version
 *  --> osVersion: 					The OS major version
 *  --> osMinorVersion: 			The OS minor version
 *  --> osUpdateVersion: 			The OS update version
 *  --> supportGradient: 			Indicates whether the browser supports gradients
 *  
 * 各版本手机举例 : 
 * |----------------------------------------------------------------------------------------------------|
 * | Plaform			| webkitV 	| wMV 	| wUV 	| browserV 	| bMV 	| bUV 	| osV 	| osMV 	| osUV 	|
 * |----------------------------------------------------------------------------------------------------|
 * |IPhone OS 3			| 528		| 18	| 0		| 4			| 0		| 0		| 3		| 1		| 2	 	|
 * |IPhone OS 2			| 525		| 18	| 1		| 3			| 1		| 1		| 2		| 2		| 1	 	|
 * |Android HTC Hero	| 528		| 5		| 0		| 3			| 1		| 2		| 1		| 5		| 0	 	|
 * |PC					| 531		| 21	| 8		| 4			| 0		| 4		| 0		| 0		| 0	 	|
 * |----------------------------------------------------------------------------------------------------|
 * 
 * @compatibility
 *  --> Iphone OS2, Iphone OS3, Android 1.1, Android 1.5, Android 2.1
 * 
 */
window.ua = 
{
	isWebkit 				: false,
	isMobile 				: false,
	isIPhone 				: false,
	isIPod 					: false,
	isIPad 					: false,
	isAndroid 				: false,
	isSafari 				: false,
	isMozilla 				: false,
	webkitVersion 			: 0,
	webkitMinorVersion 		: 0,
	webkitUpdateVersion 	: 0,
	browserVersion 			: 0,
	browserMinorVersion 	: 0,
	browserUpdateVersion 	: 0,
	osVersion 				: 0,
	osMinorVersion 			: 0,
	osUpdateVersion 		: 0,
	supportGradient 		: false,
	isLatestPhone			: false,

	/**
	 * Returns the corresponding start event
	 */
	getTouchStartEvent: function() 
	{
		if (this.isMobile == true)
		{
			return 'touchstart';
		}
		else
		{
			return 'mousedown';
		}
	},
		
	/**
	 * Returns the corresponding move event
	 */
	getTouchMoveEvent: function()
	{
		if (this.isMobile == true)
		{
			return 'touchmove';
		}
		else
		{
			return 'mousemove';
		}
	},
		
	/**
	 * Returns the corresponding end event
	 */
	getTouchEndEvent: function() 
	{
		if (this.isMobile == true)
		{
			return 'touchend';
		} 
		else
		{
			return 'mouseup';
		}
	},
	
	isLastestPhone: function(){
		return (this.isIphone || (this.isAndroid && (this.osVersion+ this.osMinorVersion > "15")));
	},

	
	/**
	 * This method retrieve all necessary informations about the platform.
	 */
	_updatePlatformInfo: function()
	{
		this.isWebkit = RegExp(" AppleWebKit/").test(navigator.userAgent);
	
		if (isset(navigator) && isset(navigator.platform))
		{
			var reg = new RegExp(/iphone/i);
			if (reg.test(navigator.platform))
			{
				this.isIPhone = true;
				this.isLatestPhone = true;
			}
			reg = new RegExp(/ipod/i);
			if (reg.test(navigator.platform))
			{
				this.isIPod = true;
			}
			reg = new RegExp(/ipad/i);
			if (reg.test(navigator.platform))
			{
				this.isIPad = true;
			}
		}
	
		if (isset(navigator) && isset(navigator.appVersion))
		{
			var reg = new RegExp(/android/i);
			if (reg.test(navigator.appVersion))
			{
				this.isAndroid = true;
			}
			var reg = new RegExp(/safari/i);
			if (reg.test(navigator.appVersion))
			{
				this.isSafari = true;
				
				var version = this._extractVersion(navigator.appVersion, "( Version/)([^ ]+)", ".");
				this.browserVersion = version.major;
				this.browserMinorVersion = version.minor;
				this.browserUpdateVersion = version.update;
			}
		}
		if (this.isSafari == false)
		{
			this.isMozilla = RegExp(/mozilla/i).test(navigator.userAgent);
		}
		
		this.isMobile = this.isIPhone || this.isIPod || this.isAndroid || RegExp(" Mobile/").test(navigator.userAgent);
		
		if (this.isWebkit)
		{
			var version = this._extractVersion(navigator.userAgent, "( AppleWebKit/)([^ ]+)", ".");
			this.webkitVersion = version.major;
			this.webkitMinorVersion = version.minor;
			this.webkitUpdateVersion = version.update;
			
			this.supportGradient = (this.webkitVersion >= 528); // TODO determine supportGradient attribute more precisely
		}
		
		if (this.isMobile && isset(navigator) && isset(navigator.appVersion))
		{
			if (this.isAndroid)
			{
				var versionOs = this._extractVersion(navigator.appVersion, "( Android )([^ ]+)", ".");
				this.osVersion = versionOs.major;
				this.osMinorVersion = versionOs.minor;
				this.osUpdateVersion = versionOs.update;
				this.isLatestPhone= ((versionOs.major+ versionOs.minor)> "15");
			}
			else
			{
				var versionOs = this._extractVersion(navigator.appVersion, "( OS )([^ ]+)", "_");
				this.osVersion = versionOs.major;
				this.osMinorVersion = versionOs.minor;
				this.osUpdateVersion = versionOs.update;
			}
		}
		return this;
	},
	/**
	 * Extracts the version number in the given string.
	 * 
	 * @parameters:
	 *  --> str: the working source string
	 *	--> reg: the regular expression that identifies the working substring
	 *	--> separator: the separator between the version parts
	 */
	_extractVersion: function(str, reg, separator)
	{
		var result = {
			major: 0,
			minor: 0,
			update: 0
		};
		var fields = RegExp(reg).exec(str);
		if (isset(fields) && fields.length > 1)
		{
			var versionString = fields[2];
			var invalidCharacter = RegExp("[^\\" + separator + "0-9]").exec(versionString);
			if (isset(invalidCharacter))
			{
				versionString = versionString.slice(0, invalidCharacter.index);
			}
			var version = versionString.split(separator);
			if (version.length > 0)
			{
				result.major = version[0];
			}
			if (version.length > 1)
			{
				result.minor = version[1];
			}
			if (version.length > 2)
			{
				result.update = version[2];
			}
		}
		return result;
	}
	
}._updatePlatformInfo();

	//创建window.demo namespace(window.demo namespace为客户端交互时的功能空间）
	if(!window.demo){
		//判断是否为iphone或者ipad，如果不是则强制设置为服务器环境为local
		if(!(ua.isIPhone || ua.isIPad)){
			window.serverEnvironment = "local";
		}
		
		window.demo= {};
		//操作系统，如果不含有window.demo对象则暂时默认为iphone客户端
		window.demo.os = 'iphone';
		
		//添加body的onload时间，加载IMEI
		window.addEventListener("DOMContentLoaded", function(){
			switch(window.serverEnvironment){
				case "local" : window.IMEI = "354059024883544";break;
				case "test" :
				case "SH" : 
				default:  
					jump("ZZSS://getIMEI?func=setIMEI");
					break;
			};
		});
		
		//imei构造, JS被加载时会主动调用，并设置相关内容
		window.setIMEI = function(imei){
			window.IMEI = imei;
			
			//设置VERSION
			switch(window.serverEnvironment){
				case "local" : break;
				case "test" :
				case "SH" : 
				default: 
					jump("ZZSS://getVersion?func=setVersion");
					break;
			};
		};
	
		//获得IMEI
		window.demo.getuserid = function(){
			return window.IMEI;
		};
		
		//设置client版本号
		window.setVersion = function(version){
			window.version = version;
		};
		
		//获得client版本号
		window.demo.getVersion = function(){
			return window.version;
		};
		
		//手机屏幕的高
		window.demo.getPhoneScreenHeight= function (){return window.innerHeight;};
		
		//手机屏幕的宽
		window.demo.getPhoneScreenWidth= function (){return window.innerWidth;};
		
		//跳转品牌球
		window.demo.goPoster = function(brand){
			window.location.href = "ZZSS://goPoster?brand="+ brand;
		};
		
		/**
		 * 进入品牌球中的某张页面
		 * @param {String} brandName	品牌名
		 * @param {String} fileName		页面文件名
		 */
		window.demo.goInner = function(brandName, fileName){
			window.location.href = "ZZSS://goBrandPage?brand=" + encodeURI(brandName) + "&goto=" + encodeURI(fileName);
		};
		
		//跳转至品牌宫格页面
		window.demo.goBrandBall = function(){
			jump("ZZSS://goBrand");
		};
		
		/**
		 * 访问通讯录，完成后调用回调函数
		 * 匿名函数不可使用
		 * @param {String} callBackName	回调函数的方法名
		 */
		window.demo.accessContactWithCallBack = function(callBackName){
			window.location.href = "ZZSS://openContacts?func=" + callBackName;
		};
		
		/**
		 * 弹出信息框
		 * @param {String} title	弹出框标题
		 * @param {String} content	弹出框文本内容
		 * @param {String} btn1Txt	弹出框按钮1文本
		 * @param {String} btn2Txt	弹出框按钮2文本
		 * @param {String} callBack1Name	按钮1触发函数的函数名
		 * @param {String} callBack2Name	按钮2触发函数的函数名
		 */
		window.demo.openDialog = function(title, content, btn1Txt, btn2Txt, callBack1Name, callBack2Name){
			//如果只含有2个参数，则使用alert，反之使用confirm
			if(btn1Txt && btn2Txt && callBack1Name && callBack1Name != ""){
				switch (window.serverEnvironment) {
					case "test":
					case "SH": 
						jump("ZZSS://openDialog?title=" + encodeURI(title) + "&content=" + encodeURI(content) + "&lefttext=" + encodeURI(btn1Txt) + "&leftfunc=" + callBack1Name + "&righttext=" + encodeURI(btn2Txt) + "&rightfunc=" + callBack2Name);
						break;
					case "local":
					default:
						var result = confirm(content);
						if (result) {
							window[callBack1Name]();
						}
						else {
							if (callBack2Name && callBack2Name != "") 
								window[callBack2Name]();
						}
						break;
				}
				
			}else{
				switch(window.serverEnvironment){
					case "test" : 
					case "SH" : 
						window.location.href= "ZZSS://openDialog?title=" + encodeURI(title) + "&content=" + encodeURI(content);
						break;
					case "local" :
					default: alert(content); break;
				}
			}
		};
		
		/**
		 * 打开Ajax进度条
		 * @param {Object} loadTxt
		 */
		window.demo.openProgressForAjax = function(loadTxt){
//			loadingDialog.open();
		};
		
		/**
		 * 关闭Ajax进度条
		 */
		window.demo.closeProgressForAjax = function(){
//			loadingDialog.close();
		};
		
		/**
		 * 下载文件
		 * @param {Array} files
		 */
		window.demo.downLoadFile = function(files){
			var url = "ZZSS://downloadfile?";
			
			//判断传入的参数是否为数组
			if(files instanceof Array){
				for(var i in files){
					var fileURL = files[i];
					
					//判断是否是字符串类型，是的话则进行拼接
					if(typeof(fileURL) == "string"){
						url += "&name=" + encodeURI(fileURL);
					}
				}
				fileName = files;
			}
			
			window.location.href = url;
		};
		
		//返回（如果带有品牌名则作为品牌球跳转处理）
		window.demo.back = function (brand){
			if (brand) {
				//如果含有版本号，则使用客户端的back API进行返回
				//如果不含有版本号，则使用goPoster进行跳转
				if(window.demo.getVersion())
					jump("ZZSS://back");
				else
					window.demo.goPoster(brand);
			}
			else {
				window.history.back(-1);
			}
		};
		
		//打开新的页面
		window.demo.nativebrowser = function(url){
			jump("ZZSS://openBrowser?url=" + encodeURIComponent(url));
		};
	
		/**
		 * 插入记录
		 * @param {String} key
		 * @param {String} value
		 */
		window.demo.setDic = function(key, value){
			localStorage.setItem(key, value);
		};
		
		/**
		 * 获得记录
		 * @param {String} key
		 */
		window.demo.getDic = function(key, funcName){
			return localStorage.getItem(key);
		};
		
		/**
		 * 拨打电话
		 * @param {Object} phoneNum
		 */
		window.demo.callphone = function(phoneNum){
			jump("tel:" + phoneNum);
		};
		
		/**
		 * 打开摄像头
		 * 拍照成功后，调用回调函数，并将图片的URI传入
		 * 
		 * @param {String} brandName	品牌名
		 * @param {String} fileName		文件名（iPhone API暂不使用）
		 * @param {String} callback		回调方法名
		 */
		window.demo.openCamera = function(brandName, fileName, callback){
			jump("ZZSS://takePicture?func=" + callback + "&brand=" + brandName);
		};
		
		/**
		 * 打开本地图片选择器
		 * 图片选择成功后，调用回调函数，并将图片的URI传入
		 * 
		 * @param {String} brandName	品牌名（iPhone API暂不使用）
		 * @param {String} callback		回调方法名
		 */
		window.demo.openPictureSystem = function(brandName, callback){
			jump("ZZSS://openAlbum?func=" + callback);
		};
		
		/**
		 * 上传数据
		 * 
		 * @param {String} brandName		品牌名
		 * @param {String} uri				文件的路径（可通过打开图片选择器或者拍照API获得）
		 * @param {String} text				上传文件的描述文本
		 * @param {String} successCallback	上传成功后的回调函数
		 */
		window.demo.uploadData = function(brandName, uri, text, successCallback){
			jump("ZZSS://uploadData?func=" + successCallback + "&brand=" + brandName + "&imgURL=" + encodeURI(uri) + "&text=" + encodeURI(text));
		};
	}
	
	//forward compatibility 
	if(!window.zzss){
		window.zzss = {};
		
		window.zzss.back = function(brand){
			if(brand && window.demo.os){
				window.demo.back(brand);
			}else{
				window.demo.back();
			}
		};
	}
	
	function xhr(){		// 创建一个ajax对象
		this.reset = function() {
			this.onLoading = function() { };
			this.onLoaded = function() { };
			this.onInteractive = function() { };
			this.onCompletion = function() { };
			this.onFail = function() { };
		};

		this.create= function(){	
			if (window.XMLHttpRequest){
				try{this.xhrObject = new XMLHttpRequest();
				} catch (e)	{
					this.xhrObject = null;
				}
			}else
				return false;
		};
		
		this.reset();
		this.create();
	}
	
	/**
	 * 转换数据
	 * 如果数据是字符串则直接返回
	 * 如果不是字符串，且上传数据类型不为JSON
	 * 则迭代获取内容并编码
	 * 如果上传类型为JSON，则将数据按JSON格式进行转换后返回
	 * 
	 * @param {Object} data
	 * @param {String} uploadType
	 */
	xhr.prototype.parseParam = function(data, uploadType){
		if(data){
			if(tools.isString(data)){
				return data;
			}else{
				if(uploadType.toUpperCase() == "JSON"){
					return JSON.stringify(data);
				}else{
					var key, value, params=[];
					for(key in data){
						value = data[key];
						
						//如果获取的值不是字符串，则将对象转换为JSON格式字符串
						if(!tools.isString(value)){
							value = JSON.stringify(value);
						}
						
						params.push(key + "=" + encodeURI(value));
					}
					
					return params.join("&");
				}
			}
		}
		
		return "";
	};
	
	/**
	 * 获取上传方式，默认post
	 * @param {String} type
	 */
	xhr.prototype.getType = function(type){
		if(type && tools.isNotBlankStr(type) && 
			(type.toLowerCase(type) == "post" || type.toLowerCase(type) == "get")){
			return type;
		}
		
		return "post";
	};
	
	/**
	 * 获取上传数据的方式
	 * 使用JSON方式上传或者是使用FORM上传
	 * 
	 * @param {Object} type
	 */
	xhr.prototype.getUploadType = function(type){
		if(type && tools.isNotBlankStr(type) && 
			(type.toUpperCase(type) == "JSON" || type.toUpperCase(type) == "FORM")){
			return type;
		}
		
		return "FORM";
	};
	
	/**
	 * 返回超时时间
	 * 默认为5S
	 * 
	 * @param {Object} timeout
	 */
	xhr.prototype.getTimeout = function(timeout){
		if(tools.isNumber(timeout)){
			return timeout;
		}
		
		return 5000;
	};
	
	/**
	 * 判断是否打开loading对话框
	 * 如果openLoading存在，且不为false
	 * 则返回true
	 * 否则返回false
	 * 
	 * @param {boolean} openLoading
	 * @return 
	 */
	xhr.prototype.isOpenLoading = function(openLoading){
		if(openLoading){
			return true;
		}else{
			return false;
		}
	};
	
	/**
	 * ajax 上传
	 * 
	 * @param {
	 * 	url : String	url字符串
	 * 	data : Object || String	参数
	 * 	type	: String	请求方式
	 * 	uploadType	: String	上传数据类型
	 * 	timeout	: Integer	超时时间（默认5秒）
	 * 	success : Function	成功后回调函数
	 * 	fail	: Function	失败或者超时后回调函数
	 * 	loading : Boolean 是否打开加载对话框
	 * } options
	 */
	xhr.prototype.send= function(options){
		//如果没有传入任何参数，或者没有传入url，则直接返回
		if(!options || !options.url){
			return;
		}
		
			//target URL
		var url = options.url,
			//upload data type
			uploadType = this.getUploadType(options.uploadType),
			//data for upload
			params = this.parseParam(options.data, uploadType),
			//send method
			type = this.getType(options.type),
			//boolean of opening the loading dialog 
			openLoading = this.isOpenLoading(options.loading),
			//success function
			successFunc = options.success,
			//fail function
			failFunc = options.fail,
			//encapsulate the fail function
			fail = function(){
				if(timeoutID){
					clearTimeout(timeoutID);
				}
				
				tools.callFunction(failFunc);
			},
			//boolean of timeout
			isTimeout = false,
			//timeout ID
			timeoutID = setTimeout(function(){
				isTimeout = true;
				if(openLoading){
					closeLoadingDialog();
				}
				fail();
			}, this.getTimeout(options.timeout));
	
		//open loading dialog
		if(openLoading){
			openLoadingDialog("loading");
		}
		
		var _this = this; // 保存当前的上下文
		
		if (!isset(this.xhrObject)){
			fail();
			return;
		}
			
		//send data
		try{
			this.xhrObject.open(type, url);
			//send data by JSON stream
			if(tools.isString(uploadType) && uploadType.toUpperCase() == "JSON"){
				this.xhrObject.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
				this.xhrObject.setRequestHeader('Content-Type', 'application/json; charset=utf-8;');
				this.xhrObject.send(encodeURI(params));
			}else{//send data by form
				this.xhrObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8;');
				this.xhrObject.send(params);
			}
		} catch (e){
			log.debug(e);
			fail();
			return;
		}

		this.xhrObject.onreadystatechange = function(){
					switch (_this.xhrObject.readyState) {
						case 1:
							_this.onLoading();
							break;
						case 2:
							_this.onLoaded();
							break;
						case 3:
							_this.onInteractive();
							break;
						case 4:
							if(!isTimeout){
								clearTimeout(timeoutID);
								if(openLoading){
									closeLoadingDialog();
								}
								if(_this.xhrObject.status ==200 || _this.xhrObject.status ==0){
									
									var responseText;
									try {
										responseText = JSON.parse(_this.xhrObject.responseText);
									}catch(e){
										responseText = _this.xhrObject.responseText;
									}
									
									tools.callFunction(successFunc, responseText);
								}else{
									fail();
								}
							}
							break;
					}
		};
	};
	
	// Expose to the world
	window.xhr = xhr;	
})();

var tools;
if(!tools){
	tools = {};
}

tools = {
	// Used for trimming whitespace
	trimLeft: /^\s+/,
	trimRight: /\s+$/,
	//check the string like "22.2px" or "22em" or "22" etc.
	digitWithUnit: /^\d+(\.\d+)?(?:(em)|%|px)?$/,
	emailPattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	phoneNumReg: /^1[3-5|8][0-9]\d{8}$/,
	userNameReg: /^(([a-zA-Z· ]{1,8})|([\u4e00-\u9fa5]{1,4}))$/,
	
	/**
	 * 产生一个随机整数
	 * 
	 * @param {integer} max	最大值，不包含在随机数范围中
	 * @param {integer} min	最小值，包含在随机数范围中
	 */
	randomNum : function(max, min){
		if(!this.isNumber(max)){
			return 0;
		}
		
		if(!this.isNumber(min)){
			min = 0;
		}
		
		return Math.floor(Math.random() * (max - min) + min);
	},
	
	/**
	 * 判断传入的参数值是否是boolean类型
	 *
	 * @param {Object} obj
	 * @return 是boolean返回true，否则返回false
	 */
	isBoolean : function(obj){
		return !this.isNull(obj) && typeof(obj) == "boolean";
	},
	
	/**
	 * 判断传入的参数值是否是字符串类型
	 *
	 * @param {String} str
	 * @return 是字符串返回true，否则返回false
	 */
	isString: function(str){
		return !this.isNull(str) && typeof(str) == "string";
	},
	
	/**
	 * 判断传入的参数值是否是数字类型
	 *
	 * @param {number} number
	 * @return 是数字返回true，否则返回false
	 */
	isNumber: function(number){
		return number != null && number != undefined && !isNaN(number);
	},
	
	/**
	 * 判断传入的参数值是否是HTML元素
	 *
	 * @param {Object} ele
	 * @return 是HTML元素返回true，否则返回false
	 */
	isHTMLElement: function(ele){
		return this.isNotNull(ele) && ele.nodeType && (ele.nodeType == 1 || ele.nodeType == 9);
	},
	
	/**
	 * 判断传入的元素是否是text元素
	 * 
	 * @param {Object} ele
	 */
	isTxtElement : function(ele){
		return this.isNotNull(ele) && ele.nodeType && ele.nodeType == 3;
	},
	
	/**
	 * 判断传入的参数值是否是zzss封装的Object
	 *
	 * @param {Object} obj
	 * @return 是zsObject返回true，否则返回false
	 */
	isZSElement: function(obj){
		return obj.length && obj.item && this.isFunction(obj.item) && obj.isZSObject;
	},
	
	/**
	 * 判断传入的参数是否是数组
	 *
	 * @param {Object} obj
	 * @return 是数组返回true，否则返回false
	 */
	isArray: function(obj){
		return obj && typeof(obj) == "object" && obj.constructor === Array;
	},
	
	/**
	 * 判断传入的参数是否是function
	 *
	 * @param {Object} obj
	 * @return 是方法返回true，否则返回false
	 */
	isFunction: function(obj){
		if(this.isString(obj) && this.isNotBlankStr(obj)){
			obj = window[obj];
		}
		return obj && typeof(obj) == "function";
	},
	
	/**
	 * 判断传入的参数是否为空或者undefined
	 *
	 * @param {Object} obj
	 * @return 如果传入的值为undefined或者null，返回true，否则返回false
	 */
	isNull: function(obj){
		return obj === undefined || obj === null || obj == "";
	},
	
	/**
	 * 判断传入的参数是否非空或者非undefined
	 *
	 * @param {Object} obj
	 * @return 如果传入的值为undefined或者null，返回true，否则返回false
	 */
	isNotNull : function(obj){
		return !this.isNull(obj);
	},
	
	/**
	 * 是否是空白字符串
	 * @param {string} str
	 */
	isBlankStr : function(str){
		return this.isNull(str) || !this.isString(str) || this.trim(str) == "";
	},
	
	/**
	 * 判断是否是非空白字符串
	 * 若是非空白字符串则返回true
	 * 是空白字符串则返回false
	 * @param {string} str
	 */
	isNotBlankStr : function(str){
		return this.isString(str) && !this.isBlankStr(str);
	},
	
	/**
	 * 是否为一个合理的用于CSS中设置的含单位的内容
	 * 主要用于width, height, margin等内容的设置
	 *
	 * @param {string} str	字符串内容
	 * @return	如果传入的值为符合验证规则，返回true，否则返回false
	 */
	isDigitWithUnit: function(str){
		return this.digitWithUnit.test(str);
	},
	
	/**
	 * tirm方法，用于删除字符串左右多余的空格
	 *
	 * @param {string} str
	 * @return 返回处理后的字符串，如果传入的内容不是string类型，则返回空字符串
	 */
	trim: function(str){
		if (this.isString(str)) {
			return str.replace(this.trimLeft, "").replace(this.trimRight, "");
		}
		
		return "";
	},
	
	/**
	 * 邮箱验证
	 * @param {Object} emailStr
	 */
	validateEmail : function(emailStr){
		if(!this.isNull(emailStr)){
			return tools.emailPattern.test(emailStr);
		}
		
		return false;
	},
	
	/**
	 * 手机号码验证
	 * @param {String} phoneNum	手机号码
	 */
	validatePhoneNum : function(phoneNum){
		if(!this.isNull(phoneNum)){
			return tools.phoneNumReg.test(phoneNum);
		}
		
		return false;
	},
	
	/**
	 * 验证用户名
	 * @param {String} userName
	 */
	validateUserName : function(userName){
		if(!this.isNull(userName)){
			return tools.userNameReg.test(userName);
		}
		
		return false;
	},
	
	/**
	 * 验证性别是否是正确的枚举类型
	 * @param {Object} sex
	 */
	validateSex : function(sex){
		if(!this.isNull(sex) && 
			(dataEnum.userInfo.sex.male === sex || dataEnum.userInfo.sex.female === sex)){
			return true;
		}
		
		return false;
	},
	
	/**
	 * 调用回调方法
	 * @param {String || Function} callback	回调方法
	 * @param {Object} args		参数
	 */
	callFunction : function(callback, args){
		if(tools.isString(callback) && tools.isFunction(window[callback])){
			window[callback](args);
		}else if(tools.isFunction(callback)){
			callback(args);
		}
	}
};

var log;
if(!log){
	log = {};
}

/**
 * 日志DEBUG方法
 * 
 * 环境变量不是正式服务器时，进行日志输出
 * 如果是PC环境，使用控制台进行日志输出
 * 手机环境则使用message
 */
log.debug = function(message){
	if(window.serverEnvironment != "SH" && window.logLevel === "DEBUG"){
		if(!ua.isMobile && console){
			console.log(message);
		}else{
			alert(message);
		}
	}
};

/**
 * 日志error方法
 * 
 * 环境变量不是正式服务器时，进行错误日志输出
 * 如果是PC环境，使用控制台进行错误日志输出
 * 手机环境则使用alert进行输出
 */
log.error = function(message){
	if(window.serverEnvironment != "SH"){
		if(!ua.isMobile && console){
			console.error(message);
		}else{
			alert(message);
		}
	}
	
	openDialog("ZZSS致尚", "网络传输不通畅,请稍后重试!");
};

/**
 * 添加stats统计用的JS
 */
(function(){
	document.addEventListener("DOMContentLoaded", function(){
		/**
		 * 仅当应用环境为brand时，加载JSON文件及stats文件
		 */
		if(window.applicationContext == "brand"){
			var createStatsScript = function(){
				createJSFile("http://ms.zzss.com/ZZSSBrandFramework/statistics.js");
			};
			
			if(!JSON){
				createJSFile("http://ms.zzss.com/ZZSSBrandFramework/json2.js", createStatsScript);
			}else{
				createStatsScript();
			}
		}
	});
})();

/**
 * 创建一个JS文件
 * JS文件创建完毕后调用callback方法
 * 
 * @param {string} url
 * @param {function} loadedCallback
 */
function createJSFile(url, loadedCallback){
	var script = $CE("script");
		script.setAttribute("type", "text/javascript");
		script.setAttribute("src", url);
		document.getElementsByTagName("head")[0].appendChild(script);
		
		if(tools.isFunction(loadedCallback)){
			script.addEventListener("load", loadedCallback, false);
		}
}

/**
 * 添加日期的format方法
 * @param {Object} fmt
 */
Date.prototype.Format = function(fmt) 
{ //author: meizz 
  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()             //毫秒 
  }; 
  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 setscroll()
{
	document.documentElement.scrollLeft=0;
	var ua = navigator.userAgent;
                ua = ua.toLowerCase();
                var match = /(webkit)[ \/]([\w.]+)/.exec(ua) ||
                /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) ||
                /(msie) ([\w.]+)/.exec(ua) ||
                !/compatible/.test(ua) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(ua) ||
                [];
	
	//alert(parseInt(match[2]) === 6||parseInt(match[2]) === 7||parseInt(match[2]) === 8);
	if(parseInt(match[2]) === 6||parseInt(match[2]) === 7||parseInt(match[2]) === 8)
	{
		document.documentElement.scrollLeft=(1349-window.screen.width)/2;
	}
	document.body.scrollLeft=(1349-window.screen.width)/2;
}

function mkf()
{
	alert("抱歉,此功能暂未开放！");
}

