﻿if(EWS == undefined){
    var EWS = {};
}

EWS.Monitor = {};

EWS.Monitor.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;};var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;};expires='; expires='+date.toUTCString();};var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;};};};return cookieValue;};};if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z';};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){return escapeable.test(string)?'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}return{stringify:function(value,replacer,space){var i;gap='';indent='';if(space){if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}}if(!replacer){rep=function(key,value){if(!Object.hasOwnProperty.call(this,key)){return undefined;}return value;};}else if(typeof replacer==='function'||(typeof replacer==='object'&&typeof replacer.length==='number')){rep=replacer;}else{throw new Error('JSON.stringify');}return str('',{'':value});},parse:function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}if(/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');},quote:quote};}();}


EWS_Monitor_Server ='http://ent1.khews.com/monitor/';  // 存放邀请框图片的目录

EWS.Monitor.V = function() {
	
	return {

		cardname:'',     //访客名称
		allurl : '',     // 完整地址
		referer : '',    // 来源网址

		Invite : '',
		SendUrl : '',  // 负责提交数据的网址 (负责提交页面，其它同时打开的页面不提交)
		CloseUrl : '',   // 关闭了的页面网址 (保存关闭了的页面网址，提交后清空)

			// COOKIES
		SendUrl_Cookie : EWS_Monitor_Arg.cid+'EWS_Monitor_V_EWS_SendUrl_Cookie',  //负责发送的网址
		SaveUrl_Cookie : EWS_Monitor_Arg.cid+'EWS_Monitor_V_EWS_CloseUrl',        //保存各网址的关闭与打开情况
		Invite_Cookie : EWS_Monitor_Arg.cid+'EWS_Monitor_V_Invite',  // 邀请保存的cookies

		
		GetUrl : EWS_Monitor_Server + 'Client_EWS.aspx',  // 第一次提交的网址及刷新提交网址
		PostNextUrl : EWS_Monitor_Server + 'PostNextUrl_EWS.aspx',  // 间隔更新时间网址
		Url_Invite5 :EWS_Monitor_Server + 'Inviteing5.aspx',   // 访客拒绝时提交的页面
		ChatUrl : EWS_Monitor_Server + 'Chat_Visitor.aspx',
		SendNickNameUrl:  EWS_Monitor_Server + 'SaveNickName.aspx',  // 用于登陆框登陆后，提交呢称的网址
		
		nexttime : 5000,

		nextTime_Name : '',

		jsok : 0, // 是否加载完成
		
		
		myLang:'zh_cn',   //默认语言包
		
		Lang:{
		ok:{zh_cn:'%e9%a9%ac%e4%b8%8a%e9%80%9a%e8%af%9d',en:'yes'},
		no:{zh_cn:'%e6%9a%82%e6%97%b6%e4%b8%8d%e6%83%b3',en:'no'},
		message:{zh_cn:'%e9%82%80%e8%af%b7%e6%8f%90%e7%a4%ba',en:'invite message'},
		invitecontent:{zh_cn:'%E6%82%A8%E5%A5%BD%EF%BC%8C%E5%AE%A2%E6%9C%8D%E9%82%80%E8%AF%B7%E6%82%A8%E8%81%8A%E5%A4%A9',en:'Hello, may I help you with anything?'}
		},
		
		main : function() {		
			
		
			var _this = this;
			this.allurl= window.location.href;
				
			if (this.request("EWS_Monitor_SaveImg", this.allurl) !== "") {
				return;
			}
			_this.main2();

//				$.getScript(EWS_Monitor_Server+ 'script/jquery/scripts.js',function() {
//							_this.main2();
//					});

							
		
		},

		
		main2 : function() {
			
				
			if( this.request("lang")=='en' )
			{
				this.myLang='en';
			}
			
			var _this=this;
			
			
			this.referer = decodeURIComponent(document.referrer.toLowerCase().replace("http://",
					''));

			this.Loadcss(EWS_Monitor_Server + 'style/css/dialogcss.css');
			
			this.Writecookie(); // 检查是否为空，写入当前网址作为提交网址

			this.LoadGetData(); // 第一次提交数据(写SQL数据，检查是否有自动邀请并返回)
			
		
			$(window).bind('resize',function(){
					_this.midden();    //居中
				});
				
			$(window).bind('scroll',function(){
					_this.midden();    //居中
			});

			$(window).bind('beforeunload',function(){
                 	 _this.Close();  //关闭页面触发
           	});
		},

		// 第一次取得是否邀请的数据
		LoadGetData : function() {

			var _this = this;
			var ref="";
			if(this.referer!='')
			{
				ref="&ref="+encodeURIComponent(this.referer);
			}

			var member='';
			var CIDCookies=EWS.Monitor.cookie(EWS_Monitor_Arg.cid);
			if(CIDCookies != null){
				member='&'+CIDCookies.split('&')[1];
			}

			
			var url = this.GetUrl + '?cid=' + EWS_Monitor_Arg.cid + '&Urlid=' + EWS_Monitor_Arg.urlid + ref + member;
			

			$.getScript(url, function() {
						if(EWS.Monitor.V.Invite != '')
						{
						   var Invite = eval('(' +EWS.Monitor.V.Invite  +')' );
					        }else{
						   var Invite = '';
						}

						//提交访客名称到立体场景
						_this.cardname=Invite.cardname;
						if(typeof EWS_Monitor_Scene == 'function')    
						{
							EWS_Monitor_Scene(_this.cardname);
						}
				
						//没有客服在线时停止提交
						if(Invite.custname=='nocust')
						{
							return ;
						}
					
						EWS.Monitor.cookie(_this.Invite_Cookie, _this.Invite); 
						_this.OpenInviteDialog();
						
						this.nextTime_Name = setTimeout("EWS.Monitor.V.Check_Url_Is_Send()", this.nexttime);
				});
				
			
		},

		// 间隔时间检查
		// 是否由自身提交，需先检查cookies，如果排在前面，即可提交
		Check_Url_Is_Send : function() {
			
			this.Writecookie();  // 每次都检查cookies，保证当前网址显示为在线
			if (EWS.Monitor.cookie(this.SendUrl_Cookie) != null) {
				if (EWS.Monitor.cookie(this.SendUrl_Cookie) == EWS_Monitor_Arg.urlid) {
					this.Post(EWS_Monitor_Arg.urlid);
				}
			}
		
			if (EWS.Monitor.cookie(this.Invite_Cookie) != "{}") {
				this.OpenInviteDialog();
			} else {
				if ($("#EWS_Monitor_Invite_DIV").length > 0) {
					$("#EWS_Monitor_Invite_DIV").remove();  // 删除邀请框
				}
			}
			
			this.nextTime_Name = setTimeout(
					"EWS.Monitor.V.Check_Url_Is_Send()", this.nexttime);
		},

		// 提交数据<将域名数据组提交到网上>
		Post : function(urlid) {
			
			var _this = this;
			var CloseUrlID = '';   // 关闭的网址
			var PostTure = false;
	
				// 循环数据，重新找出需要提交的网址
			if (EWS.Monitor.cookie(_this.SaveUrl_Cookie) != null) {
				var urls = eval('(' + EWS.Monitor.cookie(_this.SaveUrl_Cookie) + ')');
	
				$.each(urls, function(i) {

						// 累加三次后才发送
							if (urls[i]['send'] > 0 && urls[i]['send'] < 3) {
								urls[i]['send'] = urls[i]['send'] + 1
							}

						// 发送
							if (urls[i]['send'] > 2) {
								if (CloseUrlID == '') {
									CloseUrlID = urls[i]['urlid']
								} else {
									CloseUrlID = CloseUrlID + "|" + urls[i]['urlid'];
								}
								urls[i]['send'] = 0;
								PostTure = true;
							}
						});

				EWS.Monitor.cookie(this.SaveUrl_Cookie, JSON.stringify(urls)); // 写入cookies
			}

			// console.log('关闭页面' + CloseUrls);
			//if (PostTure === true) {
				var url = this.PostNextUrl + '?closeUrlID='+ CloseUrlID + '&cid=' + EWS_Monitor_Arg.cid ;
				
				$.getScript(url, function() {
							EWS.Monitor.cookie(_this.Invite_Cookie, _this.Invite); // 邀请写入cookies
							_this.OpenInviteDialog();
						});
			//}
			
		},

	// 打开邀请框
		OpenInviteDialog : function() {
			var _this = this;
			
			if (EWS.Monitor.cookie(this.Invite_Cookie) != null) {
				var data = EWS.Monitor.cookie(this.Invite_Cookie);
				var data = eval('(' + data + ')');
				if (data.invitemsgid ==null) {
					return;
				}
			
				var invitecontent="";
				if(data['invitecontent']==""){
					invitecontent=_this.Lang.invitecontent[_this.myLang];
				}
				else
				{
					invitecontent=data['invitecontent'];
				}
				
				 // 如果已经弹出，不再弹出
				if ($("#EWS_Monitor_Invite_DIV").length==0){  
					var div = $("<div  class='EWS_Monitor_dailog EWS_Monitor_box"
							+ data['style']
							+ "' id='EWS_Monitor_Invite_DIV'>"
							+ "<div  class='b_title'><h3>"+ decodeURIComponent(_this.Lang.message[_this.myLang]) +"</h3><a href='#' class='close' title='close' id='close_button'>close</a></div>"
							+ " <div class='b_con'>"
							+ "  <div class='conbg'>"
							+ "   <div class='b_img'>"
							+ "   <img  src='"
							+ EWS_Monitor_Server
							+ data['custface']
							+ "' />"
							+ " </div>"
							+ "  <div class='b_text'>"
							+ "   <p>"+ decodeURIComponent(data['custname']) +  ':' + decodeURIComponent(invitecontent) +"</p>"
							+ "   <div class='b_btn'>"
							+ "   <button id='EWs_Monitor_Invite_yes'>"+decodeURIComponent(_this.Lang.ok[_this.myLang])+"</button>"
							+ "  <button id='EWs_Monitor_Invite_no'>"+decodeURIComponent(_this.Lang.no[_this.myLang])+"</button>"
							+ "  </div>"
							+ " </div>"
							+ "  </div>"
							+ " </div>"
							+ " <div class='b_btm'></div>" + "  </div>");
					div.find("#EWs_Monitor_Invite_yes").bind('click',
							function() {
								_this.open_url();
							});

					div.find("#EWs_Monitor_Invite_no").bind('click',function() {
								_this.invite5();
							});
					div.find("#close_button").bind('click',function() {
								_this.invite5();
							});

							
					if($("body")){
						$("body").append(div);
					}
					else
					{
						$(document).append(div);
					}
					_this.midden();
					
				}
			}
		},
		
		//打开聊天网址或场景网址
		open_url:function(){
			
			if (EWS.Monitor.cookie(this.Invite_Cookie) === null) {
				$("#EWS_Monitor_Invite_DIV").remove();
				return;
			}
			
			
			
			var data = EWS.Monitor.cookie(this.Invite_Cookie);
			var data = eval('(' + data + ')');
			
				var _this=this;
				if (data['invitemode'] === '1') {
									$("#EWS_Monitor_Invite_DIV").remove();
									window.open(EWS_Monitor_Server + "goto_ewsscene.aspx?invitemsgid="+ data['invitemsgid'] +"&cid="+ EWS_Monitor_Arg.cid);
								}
								else
								{	
									var url=_this.ChatUrl + "?invitemsgid="+ data['invitemsgid']+ "&cid=" 
										+  EWS_Monitor_Arg.cid + "&custname="+ data['custname']
										+"&cardname="+ _this.cardname;
								
								window.open(url,'v' + data.invitemsgid,
												'height=450,width=480,scrollbars=0,toolbar=no, menubar=no,  resizable=yes,location=no, status=no');
									$("#EWS_Monitor_Invite_DIV").remove();
									EWS.Monitor.cookie(_this.Invite_Cookie, '{}');
								
								}
								
		},
	
		//// 层永远居中
		midden:function(){
			if($("#EWS_Monitor_Invite_DIV").length>0){	
			    var PageSize = this.GetPageSize();
				var top=(document.documentElement.scrollTop+(PageSize.WinH-document.getElementById("EWS_Monitor_Invite_DIV").offsetHeight)/2)+"px";   
				var left=(document.documentElement.scrollLeft+(PageSize.WinW-document.getElementById("EWS_Monitor_Invite_DIV").offsetWidth)/2)+"px";       	
				//alert(top)
				document.getElementById("EWS_Monitor_Invite_DIV").style.top=top;
				document.getElementById("EWS_Monitor_Invite_DIV").style.left=left;
			}
		},
		
		
		invite5 : function() {
			clearTimeout(this.nextTime_Name);  // 按取消的时候，先不拿数据，提交完再继续
			EWS.Monitor.cookie(this.Invite_Cookie, '{}');  // 点拒绝时，清空cookies
			var url = this.Url_Invite5 + '?cid=' + EWS_Monitor_Arg.cid ;
			$("#EWS_Monitor_Invite_DIV").remove();
			$.getScript(url,function(){
				this.nextTime_Name = setTimeout("EWS.Monitor.V.Check_Url_Is_Send()", this.nexttime);
			});
			
			
		},

		SaveInvite : function(data) {
			EWS.Monitor.cookie(this.Invite_Cookie, JSON.stringify(data));  // 写入邀请cookies
		},

		Loadcss : function(cssUrl) {
			var fileref = document.createElement("link");
			fileref.setAttribute("rel", "stylesheet");
			fileref.setAttribute("type", "text/css");
			fileref.setAttribute("href", cssUrl);
			document.getElementsByTagName("head")[0].appendChild(fileref);
		},

			// 写入COOKIES二个，1、网址列表 2、负责提交的网址
		Writecookie : function() {
			var _this = this;
			var urls = [];
			// 判断是否为空，空即加入单前网址
			if (EWS.Monitor.cookie(this.SaveUrl_Cookie) == null) {
				var a = {
					urlid : EWS_Monitor_Arg.urlid,// 当前网址
					isonline : 1,  // 是否在线
					send : 0	// 是否需要提交
				};
				urls.push(a);
				EWS.Monitor.cookie(this.SaveUrl_Cookie, JSON.stringify(urls));
			} else {  // 数据不为空，修改
				var pass = false;
				urls = eval('(' + EWS.Monitor.cookie(this.SaveUrl_Cookie) + ')');

				$.each(urls, function(i) {
							if (urls[i].urlid == EWS_Monitor_Arg.urlid) {
							// 如果发现提交为1，并且在线显示为0，改成不在线，并取消提交
								if (urls[i].send > 0) {
									urls[i].isonline = 1; // 设置在线
									urls[i].send = 0; // 不提交
								}
								pass = true;
							}
						});

				if (pass === false) { // 找不到时累加
					var a = {
				        urlid : EWS_Monitor_Arg.urlid,
					    isonline : 1,
					    send : 0
					 };
					urls.push(a);
				}

				EWS.Monitor.cookie(this.SaveUrl_Cookie, JSON.stringify(urls)); 

			}
			// 如果提交网址为空，自己加入(谁责责提交网址)
			if (EWS.Monitor.cookie(this.SendUrl_Cookie) === null  || EWS.Monitor.cookie(this.SendUrl_Cookie) === "") {
				EWS.Monitor.cookie(this.SendUrl_Cookie, EWS_Monitor_Arg.urlid);
			}

		},

		Close : function() {
			var _this = this;
				// 检查当前关闭窗口是否跟自身提交网址相同，相同要清除
			if (EWS.Monitor.cookie(this.SendUrl_Cookie) !== null) {
				if (EWS.Monitor.cookie(this.SendUrl_Cookie) === EWS_Monitor_Arg.urlid) {
					EWS.Monitor.cookie(this.SendUrl_Cookie, '');
				}
			}
			if (EWS.Monitor.cookie(this.SaveUrl_Cookie) !== null) {
				var urls = eval("(" + EWS.Monitor.cookie(this.SaveUrl_Cookie) + ")");

				$.each(urls, function(i) {
							if (urls[i].urlid === EWS_Monitor_Arg.urlid) {
								urls[i].isonline = 0;  // 关闭了，不在线了
								urls[i].send = 1; // 告诉需要提交此网址
							}
						});
				EWS.Monitor.cookie(_this.SaveUrl_Cookie, JSON.stringify(urls));
			}

		},


		
		showz_index : function(div) {
			$("#" + div).css("z-index", 999999);
		},


		request : function(name, allurl) {

			var len = allurl.indexOf('?');
			var str = allurl.substr(len + 1);

			var arrTmp = str.split("&");
			for (var i = 0; i < arrTmp.length; i++) {
				var arrTemp = arrTmp[i].split("=");
				if (arrTemp[0].toUpperCase() == name.toUpperCase()) {
					return arrTemp[1].replace('#','');
				}
			}

			return "";
		}
		,
		// 取得窗体的大小
		GetPageSize : function() {
			var scrW, scrH;

			if (window.innerHeight && window.scrollMaxY) {
				// Mozilla
				scrW = window.innerWidth + window.scrollMaxX;
				scrH = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight) {
				// all but IE Mac
				scrW = document.body.scrollWidth;
				scrH = document.body.scrollHeight;
			} else if (document.body) { // IE Mac
				scrW = document.body.offsetWidth;
				scrH = document.body.offsetHeight;
			}

			var winW, winH;

			if (window.innerHeight) { // all except IE
				winW = window.innerWidth;
				winH = window.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) {
				// IE 6 Strict Mode
				winW = document.documentElement.clientWidth;
				winH = document.documentElement.clientHeight;
			} else if (document.body) { // other
				winW = document.body.clientWidth;
				winH = document.body.clientHeight;
			}

			// for small pages with total size less then the viewport
			var pageW = (scrW < winW) ? winW : scrW;
			var pageH = (scrH < winH) ? winH : scrH;

			return {
				PageW : pageW,
				PageH : pageH,
				WinW : winW,
				WinH : winH
			};
		},
		
		
		//增加一个用于被登陆框Call的事件，提交用户名
		SendNickName:function(){
			
			var member="";
			var CIDCookies="";
			var CIDCookies=EWS.Monitor.cookie(EWS_Monitor_Arg.cid);
				if(CIDCookies != null){
					member='&'+CIDCookies.split('&')[1];
				}
			
			$.getScript(this.SendNickNameUrl +'?cid=' + EWS_Monitor_Arg.cid + member);
		}
		
		,
		
		    // 取得地址栏参数
		request: function(name) {
		                var allurl = window.location.href;
		                var len = allurl.indexOf('?');
		                var str = allurl.substr(len + 1);

		                var arrTmp = str.split("&");
		                for (var i = 0; i < arrTmp.length; i++) {
		                    var arrTemp = arrTmp[i].split("=");
		                    if (arrTemp[0].toUpperCase() == name.toUpperCase()) {
		                        return arrTemp[1].replace('#', '');
		                    }
		                }

		                return "";
		            }
		
	};
}();


$(window).load(function() {
			if(typeof jQuery == 'function'){
				EWS.Monitor.V.main();	
			}        
});

            

		


	



