if(document.domain=='0096.com'){
	var _url='http://0096.com/';
}else{
	var _url='http://www.0096.com/';
}
//var _url='http://192.168.0.36/';
//var _url='http://192.168.0.55/136/';
//var _url='http://new.0096.com/';

var _chat = {
	loop_lock:0,	//是否锁定定时器
	ajaj_lock:0,
	alive_time:0,	//最后活动时间
	request:{		//请求数据包
		key_user:'',
		c_key:'',
		key_ver:1,
		is_online:1,
		key_win:1,
		hava_chat:''
		//robot_answer:0
	},
	interval_id:'',	//定时器id
	diff_time:0,	//时间差,服务器-客服端
	user_name:'我',	//用户名
	kefu_name:'客服',		//客服名称
	kefu_id:0,		//客服id
	win_open:0,		//聊天窗口是否打开
	kefu_online:1,	//1:在线,0:不在线
	life_time:180000,	//窗口超时时间
	start_time:new Date().getTime(),	//开始时间
	self_goods_id:0,		//id
	is_scroll:0,
	have_chat:0, //曾经聊过天
	interval_check_open:'',
	chat_msg_count:0,
	
	//fanglin,唯一id
	randStr : function (len) {
		var var_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		
		var str = "";
		var rand_number = "";
		for (i = 0; i < len; i++) {
			rand_number = Math.floor(Math.random() * 62);
			str += var_str.charAt(rand_number);
		}
		
		return str;
	},
	
	//fanglin, 得到chat_cookie
	chat_user_cookie_function : function(){
		var chat_user_cookie = _chat.getCookie("chat_user_cookie");
		if (chat_user_cookie == '') {
			_chat.setCookie("chat_user_cookie", _chat.randStr(32));
		}
		return _chat.getCookie("chat_user_cookie");
	},
	
	init:function(){
		_chat.request.key_win = _chat.request.key_win = new Date().getTime();
		if(_chat.diff_time==0){
			_chat.diff_time=_chat.getCookie('diff_time');
			if(_chat.diff_time==''){
				_chat.request.time=1;
				_chat.diff_time=0;
			}else{
				_chat.diff_time=parseInt(_chat.diff_time);
			}
		}
		if(_chat.interval_id!=''){return;}
		_chat.request.key_user = _chat.getCookie('key_user');
		_chat.request.c_key = _chat.getCookie('c_key');
		_chat.interval_id = setInterval('_chat.timeLoop(1)',3000);
		_chat.request.goodsid = _chat.getCookie('_chat.ids');//goods_list状态(滚动条/时间)列表
		_chat.request.user = 1;
		_chat.request.chat_user_cookie = _chat.chat_user_cookie_function();//fanglin
		
		_chat.timeLoop(1);
		/*
		_box.showMsg({
			type:1,
			time:_chat.getHMS(),
			msg:'您好,很高兴为您服务!'
		});
		*/

	},
	timeLoop:function(s){
		if( _chat.loop_lock || _chat.ajaj_lock) {return;}
		if( s==1 && new Date().getTime()-_chat.request.key_win>_chat.life_time){
			return;
		}
		_chat.ajaj_lock = 1;
		_chat.ready();
		$.get(_url+'chat.php', _chat.request, function(){_chat.ajaj_lock = 0;}, 'script');
	},
	ready:function(){
		_chat.request.key_url=location.href;
		if(_chat.request.key_user=='' || _chat.request.c_key==""){
			_chat.request.key_user=_chat.getCookie('key_user');
			_chat.request.c_key=_chat.getCookie('c_key');
		}
	},
	open:function(){
		_box.init();
		_chat.init();
		_chat.loop_lock=0;
		_chat.setCookie('win_open',1);
		_chat.win_open=1;
		_chat.request.is_close=0;
		if(_chat.interval_check_open == 1){ //打开时清除cron
			clearInterval(_chat.interval_check_open);
		}
		$('#right_div').hide();
	},
	close:function(){
		_chat.loop_lock=0;
		_chat.request.is_close=1;
		_chat.timeLoop();
		_chat.loop_lock=1;
		_chat.setCookie('win_open',0);
		_chat.win_open=0;
		_box.boxShow(0);
		_chat.kefu_force_open_interval();//关闭时执行
		//1表示没有回答问题,fanglin
		if(_chat.getCookie('robot_answer') == 1){
			_chat.setCookie('auto_open',1);
			_robot.robot_right_question();
		}
		$('#right_div').show();
	},
	kefu_force_open_interval:function(){
		if(_chat.request.hava_chat == 1){//曾是否聊过天
			_chat.loop_lock=0;
			_chat.ajaj_lock=0
			if(_chat.interval_check_open == ''){
				_chat.interval_check_open = setInterval('_chat.timeLoop(1)',6000);
			}
			_chat.interval_check_open=1;
		}
	},
	send:function(){
		_chat.request.msg=_box.getMsg();
		if(_chat.request.msg==''){
			alert('内容为空,不可发送');
			delete _chat.request.msg;
			return false;
		}else if(_chat.request.msg.length>200){
			_box.insertHtml(_chat.request.msg);
			alert('单个消息长度不能超过200个字符');
			delete _chat.request.msg;
			return false;
		}
		_chat.chat_msg_count = _chat.chat_msg_count + 1;
		if(_chat.chat_msg_count == 5){
			$.post(_url+'index.php?n=chat&h=chat_msg_count');
		}
		_box.showMsg({
			type:0,
			time:_chat.getHMS(),
			msg:_chat.request.msg
		});
		_chat.loop_lock=0;
		//_chat.setCookie('have_chat','1',86400 * 1000 * 365); //fanglin加，曾聊过天
		_chat.setCookie('have_chat','1'); //fanglin加，曾聊过天
		_chat.timeLoop();
	},
	callback:function(json){
		if(typeof json.set_black!='undefined'){
			_chat.timeLoop=function(){};
			_box.prompt(1);			
			return;
		}
		if(typeof json.key_ver!='undefined'){
			_chat.request.key_ver=json.key_ver;
		}
		if(typeof json.user_name!='undefined'){
			_chat.user_name=json.user_name;
		}
	
		if(typeof json.time!='undefined'){
			_chat.diff_time=json.time-new Date().getTime();
			_chat.setCookie('diff_time',_chat.diff_time);
		}
		if(typeof json.close!='undefined'){
			_chat.request.key_win=0;
		}
		if(json.outline==1){
			_box.prompt(1);
		}else if(json.outline==0){
			_box.prompt(0);
		}
		if(typeof json.kefu_id!='undefined'){
			if(_chat.kefu_id!=json.kefu_id)
				$("#chat_title").text('与'+json.kefu_id+'号客服交谈中...');
		}
		if(json.del.length>0){
			for(var i=0;i<json.del.length;i++){
				delete _chat.request[json.del[i]];
			}
		}
		if(typeof json.key_user!='undefined'){
			_chat.request.key_user=json.key_user;
			_chat.setCookie('key_user',json.key_user);
		}
		if(typeof json.c_key!='undefined'){
			_chat.request.c_key=json.c_key;
			_chat.setCookie('c_key',json.c_key);
		}
		if(typeof json.url!='undefined'){
			_box.openUrl(json.url);
		}
		//修改为强有消息时强制打开
		if(json.hava_chat==1){
			_chat.request.hava_chat=1;
			if(typeof json.msg!='undefined'){
				_chat.open();
				for(var i in json.msg){
					_box.showMsg(json.msg[i]);
				}
			}
		}else{
			if(typeof json.msg!='undefined'){
				for(var i in json.msg){
					_box.showMsg(json.msg[i]);
				}
			}
		}
	},
	getHMS:function (){
		var dt = new Date();
		dt.setTime(dt.getTime()+_chat.diff_time);
		var h = dt.getHours();
		var m = dt.getMinutes();
		var s = dt.getSeconds();
		return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s);
	},
	keydown:function (e) {
		//判断浏览器
		if(navigator.appName == 'Microsoft Internet Explorer'){
			if(e.keyCode == 13 && e.ctrlKey){
				_chat.send();
			} else {
				return;
			}
		}else{
			if(e.ctrlKey && e.which == 13){
				_chat.send();
			} else {
				return;
			}
		}
	},
	setCookie:function (name, value, expires, path, domain, secure){
		var expires=60,path='/';
		if(location.href.indexOf('0096.com')!=-1)domain='0096.com';
		var liveDate = new Date();
		expires = liveDate.setTime(liveDate.getTime() + expires*60*1000);//分钟转成毫秒
		document.cookie = name + "=" + encodeURIComponent(value) +
		((expires) ? "; expires=" + liveDate.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	},
	
	getCookie:function (name){
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
		if(arr != null) return decodeURIComponent(arr[2]); return '';
	},
	
	setGoodsid:function(){
		var url=location.href;
		if(url.indexOf('0096.com')){
			if(_chat.self_goods_id==0){
				var temp=url.match(/goodsid=(\d+)/);
				if(temp){
					_chat.self_goods_id=temp[1];
				}else{
					return '';
				}
			}	
			
			var ids=_chat.getCookie('_chat.ids');
			var key=','+_chat.self_goods_id+'_';
			var info=key+_chat.is_scroll+'__'+parseInt((new Date().getTime()-_chat.start_time)/1000);
			if(ids.indexOf(key)==-1){
				ids+=info;
			}else{
				ids = ids.replace(new RegExp(key+'[^,]+'),info);
			}
			_chat.setCookie('_chat.ids',ids);
			setTimeout(_chat.setGoodsid,60000);
			return ids;
		}
		return '';
	},
	
	statusDate:function(){
		_chat.setGoodsid();
		$(window).one('scroll',function(){
			_chat.is_scroll=1;
			_chat.request.goodsid=_chat.setGoodsid();
		}).unload(function(){
			_chat.request.goodsid=_chat.setGoodsid();
			_chat.loop_lock=0;
			_chat.timeLoop();
		});
	},
	end:true
}
	
document.write('<link href="'+_url+'public/default/css/chat_ajaj.css" rel="stylesheet" type="text/css" />');

var _box = {
	all_box:'',
	msg_box:'',
	_win:'',
	_doc:'',
	_doc_body:'',
	face_tb:'',
	face_show_n:0,
	offset:[],
	ps:'',
	ps_timeout_id:'',
	
	init:function(flag){//fanglin,flag
		if(_box.all_box!=""){
			_box.all_box.css({
				'left':document.documentElement.scrollLeft+parseInt((window.screen.availWidth-_box.all_box.width()+455)/2)+'px',
				'top':document.documentElement.scrollTop+parseInt((window.screen.availHeight-_box.all_box.height())/4)+'px'
			});
			_box.boxShow(1);
			return;
		}

		this.box_init(flag);//fanglin,flag
		_box.showMsg({
			type:1,
			time:_chat.getHMS(),
			msg:'您好,很高兴为您服务!'
		});
		this.iframe_init();
		this.face_box_init();
		drag222('trace_user',1);
		//fanglin,flag
		if(typeof flag=='undefined'){
			_box.all_box = $("#trace_user").show();
		}

	},
	box_init:function(flag){
		var h='<div class="box" id="trace_user" style="">\
	<div class="title" id="trace_bar">\
		<span id="chat_title">紫蔻在线客服</span>\
		<a href="#" class="t_minbutton"><img src="'+_url+'public/default/images/min_button.jpg" id="top_close1" /></a>\
		<a href="#" class="t_maxbutton"><img src="'+_url+'public/default/images/max_button.jpg"/></a>\
		<a href="#" class="t_closebutton"><img src="'+_url+'public/default/images/close_button.jpg" id="top_close2" /></a>\
	</div>\
	<div class="title2"><span>聊天</span></div>\
	<div class="title3"></div>\
	<div class="maincontent">\
		<div class="left">\
			<div class="l_title"><span>在线咨询</span></div>\
			<div class="output" id="show_message"><div class="ps">客服不在线</div></div>\
			<div class="" id="show_face_img"></div>\
			<div class="changes" id="face_tb_bar"><img src="'+_url+'public/default/images/changes.jpg" width="335" height="22" border="0" /></div>\
			<iframe src="" frameborder="0" name="editor_frame" id="editor_frame" class="input"></iframe>\
			<div class="chat_button">\
				<a href="#" class="bottom_button" id="msg_send">发送</a>\
				<a href="#" class="bottom_button" id="bottom_close">关闭</a>\
			</div>\
		</div>\
		<div class="right">\
			<div class="r_title"><span>对方形象</span></div>\
			<div class="photo" id="you_photo"><a href="http://www.0096.com/index.php?n=product&h=show&goodsid=701" target="_blank"><img src="http://www.0096.com/public/blackstyle/images/chat_photo1.jpg"></a></div>\
			<div class="r_title"><span>我的形象</span></div>\
			<div class="photo" id="my_photo"><a href="http://www.0096.com/mmc3/" target="_blank"><img src="http://www.0096.com/public/blackstyle/images/chat_photo2.jpg"></a></div>\
		</div>\
	</div>\
</div>';
		_box.all_box=$('body').append(h).find("#trace_user");
		_box.boxDraw('trace_user','trace_bar');
		$("#top_close1,#top_close2,#bottom_close").click(function(){_chat.close();return false;});
		$("#msg_send").click(function(){_chat.send();return false;});
		/*
		_box.all_box.find('#my_photo').click(function(){
			if(this.src.indexOf('user1.jpg')!=-1){
				this.src=''+_url+'public/blackstyle/images/chat_photo1.jpg';
			}else{
				this.src=''+_url+'public/blackstyle/images/chat_photo2.jpg';
			}
		});
		*/
		_box.msg_box=$("#show_message");
		_box.ps=_box.msg_box.find('.ps');
		//fanglin,加flag参数
		if(typeof flag != 'undefined' && flag == 1){
			_box.all_box.hide();
		}
		if(_chat.getCookie('Moo_goodsid') != ''){//聊天形象照
			var you_photo = $("#you_photo");
			var my_photo = $("#my_photo");
			$.getJSON('index.php?n=chat&h=get_chat_photo',function(data){
				if(data.length == 2){
					for(var i=0;i<data.length;i++){
					
						if(i==0){
							you_photo.find('a').attr('href','index.php?n=product&h=show&goodsid='+data[i]['goodsid']);
							you_photo.find('img').attr('src',data[i]['imagsurl']);
						}else{
							my_photo.find('a').attr('href','index.php?n=product&h=show&goodsid='+data[i]['goodsid']);
							my_photo.find('img').attr('src',data[i]['imagsurl']);
						}
						
					}
				}
			})
			
		}
	},
	iframe_init:function(){
		this._win=$('#editor_frame')[0].contentWindow;
		this._doc=this._win.document;
		this._doc.designMode = 'On';
		this._doc.write('<html style="overflow-x:hidden">\
						<body style="margin:5px;width:308px;height:65px;word-wrap:break-word; word-break:break-all; font-size:12px;"></body>\
					</html>');
		this._doc.close();
		$(this._doc).keydown(function(event){
			_chat.keydown(event);
		})
		$(this._doc).click(function(){
			_box.face_tb.hide();
		})
		_box._doc_body=$(_box._doc).find("body").empty();
	},
	face_box_init:function(){
		var facehtml = '';
		facehtml += '<table border="0" cellspacing="0" cellpadding="0" bgcolor="#dddddd">';
		facehtml += '<tr><td colspan="15" background="'+_url+'public/default/images/m_titlebg.jpg">　添加表情</td></tr>';
		for(i = 0 ;i < 9 ; i ++){
			facehtml += '<tr bgcolor="#ffffff">';
			for(j = 0 ;j < 15 ; j ++){
				facehtml += '<td>';
				facehtml += '<img style="border:0px;" src="'+_url+'public/default/images/qqface/' + (i * 15 + j) + '.gif" />';
				facehtml += '</td>';
			}
			facehtml += '</tr>';
		}
		facehtml += '</table>';
		_box.face_tb=$("#show_face_img").html(facehtml).hide();
		_box.face_tb.find('img').click(function(){
			_box.insertImg(this.src);
		});
		$(document).click(function(){
			if(_box.face_show_n>0) _box.face_show_n--;
			if(_box.face_show_n<=0)	_box.faceShow(0);
		});
		$("#face_tb_bar").click(function(){_box.faceShow(1);});
	},
	boxShow:function(m){
		if(m){
			_box.all_box.show();
		}else{
			_box.all_box.hide();
		}
	},
	faceShow:function(m){
		if(m){
			_box.face_show_n=2;
			_box.face_tb.show();
		}else{
			_box.face_tb.hide();
		}
	},
	insertImg:function(path){
		_box._win.focus();
		_box._doc.execCommand('InsertImage' , '' , path );
		$('#show_face_img').hide();
		_box._win.focus();
	},
	insertHtml:function(sHtml){
		_box._win.focus();
		if($.browser.msie ){
			_box._doc.selection.createRange().pasteHTML( sHtml ) ;
		}else{
			_box._doc.execCommand('InsertHtml' , '' , sHtml );
		}
	},
	getMsg:function(){
		var msg = _box._doc_body.html().replace(/<(?!img)(?!br)[^<>]+>/ig,'').replace(/<img[^>]+?src="([^"]+)"[^>]*>/ig, '<img src="$1" \/>');
		_box._doc_body.empty();
		return msg;
	},
	showMsg:function(json){
		_box.msg_box.append('<div class="'+(json.type==1?'msg_admin':'msg_user')+'"><span>'+(json.type==1?_chat.kefu_name:_chat.user_name)+' '+json.time+'</span><p>'+json.msg+'</p></div>');
		_box.msg_box[0].scrollTop　=　_box.msg_box[0].scrollHeight;
	},
	boxDraw:function( box_id, bar_id ){
		
		var box = $("#"+box_id);
		var bar = $("#"+bar_id);
		var s_h = window.screen.availHeight; //屏幕可用工作区域宽度
		var s_w = window.screen.availWidth;  //屏幕可用工作区域高度
		
		box.css({'position':'absolute','z-index':'9997','clip':'rect(auto, auto, auto, auto)','left':document.documentElement.scrollLeft+parseInt((s_w-box.width()+455)/2)+'px','top':document.documentElement.scrollTop+parseInt((s_h-box.height())/4)+'px'});
		bar.css('cursor','move');
		
		
		bar.mousedown(function(e){
			var mouse_xy = e ? [e.clientX, e.clientY] : [event.clientX, event.clientY] ;
			var box_xy = box.offset();
			_box.offset = [box_xy.left - mouse_xy['0'],box_xy.top - mouse_xy['1']];
		});
		box.mousemove(function(e){
			if( _box.offset == '' ) return;
			var mouse_xy = e ? [e.clientX, e.clientY] : [event.clientX, event.clientY] ;
			var l = mouse_xy['0']+_box.offset['0'];
			var t = mouse_xy['1']+_box.offset['1'];
			if( mouse_xy['0'] > 0 && mouse_xy['0'] < s_w-10 ){
				box.css('left',l+'px');
			}
			if( mouse_xy['1'] > 0 && mouse_xy['1'] < s_h-10 ){
				box.css('top',t+'px');
			}
			
		});
		box.mouseup(function(e){_box.offset='';});
	},
	prompt:function(m){
		if(typeof _box.ps=='string')return;
		if(m){
			_box.ps.show();
		}else{
			_box.ps.hide();
		}
	},
	openUrl:function(url){
		var open_box1 = $("#open_box1");
		var open_box2 = $("#open_box2");
		if(open_box1.length==0){
			$("body").append('<div id="open_box1" class="black_overlay"></div>\
	<div  id="open_box2" class="white_content">\
		<div class="show_pic"> \
			<h3>客服推荐</h3>\
				<div class="show_box">\
					客服向您推荐了一个网址 请点击"确定"在新窗口打开 \
					<p align="center"><input type="button" class="show_btn" value="确定"> </p>\
				</div>\
		</div>\
	</div>\
');
			open_box1 = $("#open_box1");
			open_box2 = $("#open_box2");
		}
		//salert(document.documentElement.scrollTop);
		open_box1.show().css('height',$('body').height());

		open_box2.show().css({
			'left':document.documentElement.scrollLeft+parseInt((window.screen.availWidth- open_box2.width())/2)+'px',
			'top': document.documentElement.scrollTop+ parseInt((window.screen.availHeight-open_box2.height())/4)+'px'
		});
		//salert(32432);
		
		
		
		//open_box1.css('top',open_box1.top+open_box1.scrollTop());
		$('body').one('click',function(){
			window.open(url);
			open_box1.hide();
			open_box2.hide();
			$('body').css('overflow','auto');
		});
	},
	end:true
}

$(function(){
	 //fanglin,cookie标识
	_chat.chat_user_cookie_function();
	
	$('body').append('<div id="right_div">\
						<img id="img1" src="'+_url+'public/default/images/service.gif" style="cursor:pointer;" onclick="_chat.open()"/>\
						<div id="serviceBox" style="display:none;">\
							<div id="msgBox" style="cursor:pointer;">\
							您对哪款产品感兴趣呢需要我给你介绍一下吗？\
							</div>\
						</div>\
					</div>');
	
	try{
		$("#right_div").floatdiv("rightbottom");
	}catch(e){
		$.getScript(_url+'public/js/jquery.floatDiv.js',function(){
			$("#right_div").floatdiv("rightbottom");
		});
	}
	_chat.statusDate();
	
	$(document).mousemove(function(e){
		var t=new Date().getTime();
		if(t-_chat.request.key_win>1000){
			var win_open=_chat.getCookie('win_open');
			if( _chat.win_open!=win_open){
				if(win_open==1){
					_chat.open();
				}else{
					_chat.close();
				}
			}
		}
		_chat.request.key_win = t;
	});


		
	//浏览一定数量后，自动弹出询问
	var ids=_chat.getCookie('_chat.ids');

	if(_chat.getCookie('have_chat') != 1 && _chat.getCookie('auto_open') != 1){
		if(((ids.split(',').length)-1) >= 5){
			_box.init(1);
			_chat.init();
		};
	}

	
	////////////////////////未回答点关闭时处理
	if(_chat.getCookie('robot_answer') == 1){
		_robot.robot_right_question();
	}
	$("#serviceBox").click(function(){
		$("#right_div #img1").show();
		$("#serviceBox").hide();
		_robot.click_question();
		_chat.open();
	});

	
	//robot's question
	if(document.domain=='www.0096.com' || document.domain=='0096.com'){
		$.post(_url+'index.php?n=chat&h=get_robot_message',function(data){
			var question_arr = new Array();
			var json = eval('('+data+')');
			for(var i=0;i<json.length;i++){
				question_arr.push(json[i]);
			}
			_robot.question = question_arr;
		});
	}

});


var _robot = {
	question_num:0,
	question:0,
	interval_id:0,
	robot_right_question:function(){
		$("#right_div #img1").hide();
		$("#serviceBox").show();
		if(this.interval_id == 0){
			this.interval_id = setInterval("_robot.roll_question()",6000);
			this.interval_id = 1;
		}
	},
	roll_question:function(){
		$("#msgBox").html(this.question[this.question_num]);
		(this.question_num<this.question.length-1) ? this.question_num++ : this.question_num=0;
	},
	click_question:function(){
		var click_num = 0;
		if(this.question_num == 0) click_num=0;
		else	click_num = this.question_num - 1;
		$.post(_url+'index.php?n=chat&h=get_click_robot_question',{message:this.question[click_num]});
	},
	end:true
}


function drag222(o,s)  
{  
    if (typeof o == "string"){
		var o = document.getElementById(o);  
	}
    //o.orig_x = parseInt(o.style.left) - parseInt(document.documentElement.scrollLeft);  
	var top = document.body.scrollTop | document.documentElement.scrollTop;
    o.orig_y = parseInt(o.style.top) - parseInt(top);  
    //o.orig_index = o.style.zIndex;  
	
    if (s)  
    {  
        var orig_scroll = window.onscroll?window.onscroll:function (){};  
        window.onscroll = function ()  
        {  
            orig_scroll();  
            //o.style.left = o.orig_x + document.body.scrollLeft;  
			//o.style.left = o.orig_x + document.documentElement.scrollLeft;  
			
            //o.style.top = o.orig_y + document.body.scrollTop;  
			var top = document.body.scrollTop | document.documentElement.scrollTop;
			o.style.top = parseInt(o.orig_y) + parseInt(top)+'px';  

        }  
    }  
}  

