// JScript 文件

var getmsgid="undefined";//获取新消息计时ID
//#2009-07-19############
var step=0;//标题闪烁计数
var sendtype=1;//信息提交方式 Enter=1 Ctrl+Enter=2
var flashtitleid="undefined";//标题闪烁计时ID
var title=document.title;//获取当前标题
var handlerpath = "/Chating/messagehandler.aspx"; //"/Chating/messagehandler.aspx";
var feedbackurl="/Feedback/FeedBack.ashx";//留言提交
var closetime=600;//单位秒 指定时间内不回复就关闭当前页面
//var closetimeid="undefined";//关闭窗口倒计时ID
var tohref="http://www.meilieasy.com/";//关闭窗口跳转页面
var pageclosetime=closetime;//1000;//页面显示倒计时时间
var pageclosetimeid="undefined";//
var contentpadleft="10px";//聊天消息左边距
var lastMessageDateTime=null;//从客服接收到的最后一条消息的时间
var isstop=false;//是否停止所有方法
var uniqueId=$("#UniqueId").val();//唯一标识符 用于识别窗口


//发送信息给客服
function sendMsg()
{
    if (isstop)
    {
        alert("很抱歉！该页面已失效，请刷新后重试！");          
        return false;
    }else
    {
     //alert(uniqueId);
    }
	if($.trim($("#areaContent").val())==""||$.trim($("#areaContent").val())=="\r\n")
	{
		 alert("消息不能为空");
		 $("#areaContent").focus()
		 return false;
	}
	if($("#areaContent").val().length>200)
	{
		 alert("不能超过200个字");
		 $("#areaContent").focus()
		 return false;
	}
    //更新最后发送时间
    
    var myDate = new Date();
    var nt=myDate.toLocaleTimeString();
    var msg=formatMsg($("#areaContent").val());
    var da="action=add"
               //+"&resolution="+window.screen.width+"*"+window.screen.height
                +"&content="+ msg
                +"&t="+nt
                +"&uni="+uniqueId;
            
            //contentAppend([twname:"我",wname:"我",itime:""+nt+"",content:""+msg+"",nourl:"1",msgtype:"1",isStop:0]) ;   
            $("#areaContentShow").append("<b>我</b> "+nt+":<br /><div style='padding-left: "+contentpadleft+";'>"+msg+"</div>");
            $("#areaContent").val("");
			//#2009-07-19#########
            $.ajax({
                //sync:true,
                type: "POST",
                url: handlerpath,
                dataType: "json",
                cache: false,
                data: da,
                success: function(r) {
                  //  alert("success");

                    //返回非空数据
                    if (r != null) {
                        contentAppend(r);

                    }
                    else {
                        lastMessageDateTime = new Date();
                        lastMessageType = "2";
                    }
                    if (!isstop) {
                        if (lastMessageType == "1" || lastMessageType == "2") {
                            //重新开始关闭倒计时
                            if (pageclosetimeid != "undefined") {
                                pageclosetime = closetime; //1000;

                            }
                        }
                        scrollToEnd();
                    }


                },
                error: function(err) {
                   // alert(err.responseText);
                    scrollToEnd();
                }


            }); 
		scrollToEnd();   
		//#############   
}
//获取客服发过来的信息
function getMsg()
{
   
    if (isstop)
    {
        
     clearInterval(   getmsgid);
     
        return false;
    }else
    {
    
    
     //alert(uniqueId);
    }
          $.ajax({
            type:"POST",
            url:handlerpath,
            cache:false,
			dataType:"json",
            data:"action=get&dt=json&uni="+uniqueId,
            success:function(r)
            {
                if(r!=null)
                {
                    contentAppend(r);

					if(!isstop)
					{
					    //$("#areaContentShow").scrollTop(99999); 
					     scrollToEnd();
                    
                        //标题栏闪烁
                        if(flashtitleid=="undefined")
                        {
                            flashtitleid=window.setInterval("flashTitle()",1000);
                        }
                        //接收到新消息后 重新倒计时
                       if(lastMessageType=="1"||lastMessageType=="2")
                       {
					         pageclosetime=closetime;
                             if(pageclosetimeid=="undefined")
                             {
						        pageclosetimeid=setInterval("closeTimer()",1000);
					         }
					    }
					    lastMessageDateTime=new Date();
					     //$("#lastMessageType").html(lastMessageType);
					 }
					 else
					 {
					    //alert("返回错误");
					 }
				}
				
                else
                {
                    //
                    if(!isstop)
                    {
                       
                    }
                }
               
            }
        });
        
       
}

function contentAppend(r)
{
    if(r!=null)
    {
        if (r.length>0)
        {
            for(var i=0;i<r.length;i++)
            {
               if(r[i].wname!=""&&r[i].content!="")
               {
                    //alert(r[i].content);
                    if(r[i].nourl=="1")
				    {
				        $("#areaContentShow").append("<div><b>"+r[i].wname+"</b> "+r[i].itime+":<br /><div style=\"padding-left: "+contentpadleft+";\">"+htmlDecode(r[i].content)+"</div></div>");
				    }
				    else
				    {    
					    $("#areaContentShow").append("<div><a href='to_"+r[i].twname+".shtml'><b>"+r[i].wname+"</b></a> "+r[i].itime+":<br /><div style=\"padding-left: "+contentpadleft+";\">"+htmlDecode(r[i].content)+"</div></div>");
				    }
			    }
			    //alert(r[i].msgtype);
				lastMessageType=r[i].msgtype;
				scrollToEnd();
			   
                if(lastMessageType=="4")//停止浏览器页面执行
                {
                
                     isstop=true;
                     break;
                }
                else if(lastMessageType=="5")  //不可识别或已过期的聊天窗口
                {
                    isstop=true;
                     break;
                } 
                else if(lastMessageType=="6")  //客服离线
                {
                    isstop=true;
                     break;
                }
                if(!isstop)
                {
                    
				}
			}
	    }
    }
}

//格式化信息，添加样式信息以及屏蔽用户输入的html标签
function formatMsg(str)
{
         str=str.replace(/\</g,"&lt;").replace(/\>/g,"&gt;");
         str=str.replace(/\n/g,"<br />");
     return str.replace(/<p>/g,"").replace(/<\/p>/g,"");
}
//获取下拉列表选中的值
function getSelected(selectid)
{
    var rv="";
    $("#"+selectid+">option").each
    (
        function()
        {
           if( $(this).attr("selected"))
           {
                rv = $(this);
           }
        }
    );
    return rv;
}
//替换非HTML标签
function replaceTag(input)
{
  var tinput=input;
  tinput=tinput.replace(/\[u=(.*?)\]/gi,"<a href='$1' target='_blank'>$1</a>");
  tinput=tinput.replace(/\[img=(.*?)\]/gi,"<img src='$1'/>");

  return tinput;
}
//页面显示完毕
$(document).ready(
    function(){ 
     
        
        uniqueId=$("#UniqueId").val();
       // alert(uniqueId);
	getmsgid=setInterval("getMsg()",2000); //获取新消息
        //closetimeid=window.setTimeout("closeForm()",closetime);//关闭窗口倒计时
		 if(pageclosetimeid!="undefined")
         {
             //window.clearTimeout(closetimeid);
             window.clearInterval(pageclosetimeid);
         } 
		pageclosetimeid=setInterval("closeTimer()",1000);
		//alert(pageclosetimeid);
	

    }
);
$("#areaContent").keydown(
    function(e)
    {
        //Ctrl+Enter换行
        if(e.ctrlKey&&e.keyCode==13)
        {
            $(this).val($(this).val()+"\n\r");
        }
        //回车发送
        else if(e.keyCode==13)
        {
            if($(this).val()=="")
            {
                alert("请您先输入内容");
                return false;
            }
            else
            {
                sendMsg();
                return false;
            }
        }
    }
);

//退出聊天
function logOut()
{
    //event.returnValue="确定离开当前页面吗？";
        if(getmsgid!=-1)
        {
            clearInterval(getmsgid);
        }
        if(!isstop)
        {
            $.ajax({
            sync:true,
            type:"POST",
            url:handlerpath,
            cache:false,
            data:"action=logout&uni="+uniqueId
            });
        }
        //return true;
       
}

//留言

function addFeedback()
{
    var action,pid,ftitle,fcontent,fclass,flinkman,fphone,femail,fdata;
    action="add";
    ftitle=$.trim($("#fTitle").val());
    fcontent=$.trim($("#fContent").val());
    fclass=$.trim($("#fClass").val());
    flinkman=$.trim($("#fLinkman").val())+getSelected("appellation");
    fphone=$.trim($("#fPhone").val());
    femail=$.trim($("#fEmail").val());
    
    if($.trim($("#fLinkman").val())=="")
    {
        alert("联系人不能为空");
        $("#fLinkman").focus();
        return false;
    }
    else  if(!(/((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/).test(fphone))
    {
        alert("请正确填写联系电话！");
        $("#fPhone").focus();
        return false;
    }
     else if(fcontent=="")
    {
        alert("留言内容不能为空");
        $("#fContent").focus();
        return false;
    }
   
    fdata="action="+action
            +"&ftitle="+ftitle
            +"&fcontent="+fcontent
            +"&fclass="+"客服留言"
            +"&flinkman="+flinkman
            +"&fphone="+fphone
            +"&femail="+femail
    $.ajax({
                type:"POST",
                url:feedbackurl,
                data:fdata,
                success:function(d)
                {
                   alert("感谢您的留言，我们会尽快给您回复！祝您愉快！");
                    //alert(d);
                    window.location.reload();
                },
                error:function(a){
                   //alert("留言失败");
                  alert(a.responseText);
                }
            });


}
//获取下拉列表选中的值
function getSelected(selectid)
{
    var rv="";
    $("#"+selectid+">option").each
    (
        function()
        {
           if( $(this).attr("selected"))
           {
                rv = $(this).val();
           }
        }
    );
    return rv;
}
//功能切换
function chatToggle(switchid)
{
    if(switchid==1)//servonline
    {
        $("#chatForm").show();
        $("#chatFeedBack").hide();
        //$("#feedback").show();
        $("#sendfeedback").hide();
        $("#sendmsg").show();
        $("#tips").show();
        $("#robot").hide();
        $("#sendrobot").hide();
         
    }
    else if(switchid==2)//robot
    {
        $("#chatForm").hide();
        $("#chatFeedBack").hide();
       // $("#feedback").hide();
        $("#sendfeedback").hide();
        $("#sendmsg").hide();
        $("#sendrobot").show();
        $("#tips").show();
        $("#robot").show();
     getRobot();
       
    }
    else //feedback
    {
        $("#chatForm").hide();
        $("#chatFeedBack").show();
       // $("#feedback").hide();
        $("#sendmsg").hide();
        $("#sendfeedback").show();
        $("#tips").hide();
        $("#robot").hide();
        $("#sendrobot").hide();
    }
}

//获取评论列表
function getRobot(){
    
    var $keywords="";
    if($('#txtrobot').val()!="请输入您要搜索的关键字") 
        $keywords=$('#txtrobot').val();
    
    $.ajax({
	    url:"/ajax.aspx?q=gethelplist&keyword="+escape($keywords)+"&time="+new Date().toString(),
	    type:'GET',	
	    timeout:60000,//超时时间
	    beforeSend: function() {  
	        $('#getrobotslist').html("<li>正在加载...</li>");
        },
        error:function(){
            $('#getrobotslist').html("<li>读取超时，请刷新页面重试!</li>");
        },
	    success:function(){
	   // alert("!dsf:"+arguments[0]);
                $('#getrobotslist').html(arguments[0]);
	    }		
    });
}
//机器人信息提交方式
$("#txtrobot").keydown(
    function(e)
    {
        //Ctrl+Enter发送
        //if(e.ctrlKey&&e.keyCode==13)
        //{
        //   getRobot();
        //}
		//Ctrl+Enter换行
        if(e.ctrlKey&&e.keyCode==13)
        {
            $(this).val($(this).val()+"\n\r");
        }
        //回车发送
        else if(e.keyCode==13)
        {
            if($(this).val()=="")
            {
                alert("请您先输入内容");
                return false;
            }
            else
            {
                getRobot();
            }
        }
    }
);

//闪烁标题
function flashTitle()  
{  
      step++  
      if (step==3) {step=1}  
      if (step==1) {document.title='【你有新的消息】'}  
      if (step==2) {document.title='【　　　　　　】'}  
      //window.focus();
} 
//获得焦点后取消闪烁
$("div").mouseover
(
    function()
    {
        window.clearInterval(flashtitleid);
        flashtitleid="undefined";
        document.title=title;
    }
);
//########2009-07-23#########
//自动关闭聊天窗口
function closeForm()
{
   window.clearInterval(pageclosetimeid);
   window.location.href=tohref;
}
//页面关闭计时器
function closeTimer()
{

    pageclosetime--;
    $("#visitorName").html("剩余服务时间"+pageclosetime+"秒");
	if(pageclosetime<=0)
	{
		window.clearInterval(pageclosetimeid);
		closeForm();
	}

	//	alert(pageclosetime);
}

 
function    htmlDecode(str)   
   {   
         var s = "";   
         if (str.length == 0) return "";   
         s = str.replace(/&lt;/g, "<");   
         s = s.replace(/&gt;/g, ">");   
         s = s.replace(/&nbsp;/g, " ");   
         s = s.replace(/&#39;/g, "\'");   
         s = s.replace(/&quot;/g, "\"");    
         return    s;   
   }
//###2009-07-29#######
//修改留言提交网址
//增加页面关闭倒计时提示
//去掉一对多余DIV
//修复滚动条失效不滚动
//修复超时关闭失败的问题
//消息内容增加左边距设置，更清楚的显示消息内容

function loadImage(url, obj) 
{
            //$(obj).attr("src","http://localhost/img_loading.gif");
            var img = new Image(); //创建一个Image对象，实现图片的预下载
            img.src = url;     
            if (img.complete) 
	    { 
		// 如果图片已经存在于浏览器缓存，直接调用回调函数
		obj.onload=function(){return false;}
		obj.src=url;
                return false; // 直接返回，不用再处理onload事件
            }

            img.onload = function () 
	    { 
		//图片下载完毕时异步调用callback函数。
	        obj.onload=function(){return false;}
		obj.src=url;  ;
                 return false;
            }
              img.onerror=function()
		{
                //图片下载失败
		obj.onload=function(){return false;}
                obj.src="http://img.meilieasy.com/chating/img_error.png";
                return false;
		}
}

//滚动条滚动到最后
function scrollToEnd(eid)
{
	var obj = document.getElementById("areaContentShow");
	obj.scrollTop=obj.scrollHeight;
}

//订单物流信息查询
var str = location.href; //取得整个地址栏
var num = str.indexOf("=")
str = str.substr(num + 1); //取得所有参数
if (str == "1") {
    $("#Ordersearch").show();
    //$("#wn").html($("#areaContentShow").html());
    //$("#main").hide();
}
else {
    $("#Ordersearch").hide();
    $("#main").show();
}

function gosearch() {
    if ($("#okey").val() == "") {
        alert("请输入您的订单号、运单号或手机号中的任何一个！");
        $("#okey").focus();
    }
    else {
        var $tempstr = $("#areaContentShow").html();
        $("#areaContent").val("请帮我查一下我的订单：" + $("#okey").val());
        sendMsg();
        $("#areaContentShow").html($tempstr + "<font style='font-size:13px; color:#ff4400;'>&nbsp;&nbsp;请您稍等，我们的客服人员正在帮您查询您的订单物流信息...</font>");
        $("#Ordersearch").hide();
        $("#main").show();
    }
}
