if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
// 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
WEB_SOCKET_SWF_LOCATION = "/plugins/websocket/WebSocketMain.swf";
// 开启flash的websocket debug
WEB_SOCKET_DEBUG = true;

var ws, client_list={};

// 连接服务端
function connect() {
   // 创建websocket
   ws = new WebSocket("ws://"+ websocket_ip +":"+ websocket_port);
   // 当socket连接打开时，输入用户名
   ws.onopen = onopen;
   // 当有消息时根据消息类型显示不同信息
   ws.onmessage = onmessage; 
   ws.onclose = function() {
    console.log("连接关闭，定时重连");
    connect();
   };
   ws.onerror = function() {
    console.log("出现错误");
   };
}

// 连接建立时发送登录信息
function onopen()
{
    if(!name)
    {
        show_prompt();
    }
    // 登录
    var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"'+ room_id +'","client_logo":"'+logo+'"}';
    //console.log("websocket握手成功，发送登录数据:"+login_data);
    ws.send(login_data);
}

// 服务端发来消息时
function onmessage(e)
{
    //console.log(e.data);
    var data = eval("("+e.data+")");
    switch(data['type']){
        // 服务端ping客户端
        case 'ping':
            ws.send('{"type":"pong"}');
            break;
        // 登录 更新用户列表
        case 'login':
            //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
            //say(data['client_id'], data['client_name'], data['client_name']+' 进入了课堂', data['time'], data['client_logo']);
            if(data['client_list'])
            {
                client_list = data['client_list'];
            }
            else
            {
                client_list[data['client_id']] = data['client_name']; 
            }
            flush_client_list();
            //console.log(data['client_name']+"登录成功");
            break;
        // 发言
        case 'say':
            //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
            say(data['from_client_id'], data['from_client_name'], data['content'], data['time'], data['client_logo']);
            break;
        // 用户退出 更新用户列表
        case 'logout':
            //{"type":"logout","client_id":xxx,"time":"xxx"}
            //say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time'], data['client_logo']);
            delete client_list[data['from_client_id']];
            flush_client_list();
    }
}

// 输入姓名
function show_prompt(){  
    name = prompt('输入你的名字：', '');
    if(!name || name=='null'){  
      name = '游客';
    }
}

// 提交对话
function onSubmit() {
  var input = document.getElementById("textarea");
  var to_client_id = "all";
  var to_client_name = "所有人";
  var content = input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r');
  if(content==""){
    dialog.alert({
        //title:"系统提示",
        msg:'你要说什么呢',
        buttons:['确定']
    },function(ret){
        console.log(ret);
    });
    return false;
  }
  ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+content+'"}');
  input.value = "";
  input.focus();
  $.ajax({
    url: '/yidong/pptlive/sayok', 
    type: 'POST',
    dataType: "json", 
    data: {ketangid:room_id, content:content},
    success: function(data){
      console.log(data);
    },
    error: function(){
      //console.log("发言保存失败");
    }
  });
  return false;
}

// 刷新用户列表框
function flush_client_list(){
  var userlist_window = $("#userlist");
  var client_list_slelect = $("#client_list");
  userlist_window.empty();
  client_list_slelect.empty();
  userlist_window.append('<h4>在线用户</h4><ul>');
  client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
  for(var p in client_list){
    userlist_window.append('<li id="'+p+'">'+client_list[p]+'</li>');
    client_list_slelect.append('<option value="'+p+'">'+client_list[p]+'</option>');
  }
  $("#client_list").val(select_client_id);
  userlist_window.append('</ul>');
  var onlinenum = $("#userlist").find("li").length;
  $("#client_number").html(onlinenum +"人");
}

// 发言
function say(from_client_id, from_client_name, content, time, from_client_logo){
  var timearr = time.split(" ");
  var timeshort = timearr[1];
  var words = '<li>';
  words += '  <a class="item-content">';
  words += '    <div class="item-inner">';
  words += '      <div class="item-title-row">';
  words += '        <div class="item-title">'+from_client_name+'</div>';
  words += '        <div class="item-after"><span style="font-size:14px;">'+timeshort+'</span></div>';
  words += '      </div>';
  words += '      <div class="item-text">'+content+'</div>';
  words += '    </div>';
  words += '  </a>';
  words += '</li>';
  $("#dialog").find("li").first().before(words);
}

// 翻页
function pptcontrol(goway) {
  var msg = '{"type":"slide","to_client_id":"all","to_client_name":"所有人","content":"'+goway+'"}';
  ws.send(msg);
  //console.log(msg);
}

$(function(){
  select_client_id = 'all';
  $("#client_list").change(function(){
    select_client_id = $("#client_list option:selected").attr("value");
  });
});

connect();