﻿﻿/**
 * @author cileon
 * @version 0.1
 */

/**
 * 중계웹 페이지 함수들 ON GATE1000
 **/

/**
 * 중계웹 페이지 에서 사용하기 위한 변수
 **/

var conn_no_val = "";
var room_id_val = "";
var conn_name_val = "";

var subdomain_auth_addr_val = "";
var subdomain_relay_addr_val = "";

var chk_agree_flag = false;
var chk_agree_localrecord_client_flag = false;
var chk_pincode_flag = false;
var chk_room_satus = 0;
var chk_room_type = 0;
var chk_room_product_type = "";
var client_file_nm = "";

var noticeServerRecord = false;
var noticeServerRecordUrl = '';

var timeId;
var oXhrRequest = null;

var chkJvm = "";

if (window.chkAcxModule == undefined) window.chkAcxModule = false; //Acx체크

var LInkManager = function() {
  $('#functionBtn401').click(function() {
    if ($.browser.msie) {
      window.external.AddFavorite(location.href, "Remote Control Service 5.0");
    } else {
      window.sidebar.addPanel("Remote Control Service 5.0", location.href, "");
    }
  });
  $('#functionBtn402').click(function() {
  var poplink = subdomain_relay_addr_val + "/WebRelay/HURI1000?relay_uri=" + top_relay_uri + "&conn_no=" + conn_no_val;
    window.open(poplink, "popup_livecall", 'width=460,height=290,top=50,left=150');
  });
  $('#functionBtn403').click(function() {
    window.location.reload();
  });
};

$(document).ready(function() {
  var wh = jQuery.iUtil.getClient();
  $('#overlay').find('p').css({ top: wh.h / 2 - 32, left: wh.w / 2 - 16 });

  scriptAgreeText();
  $('#SUPPORT_NAME_AREA').html('<input id="conn_name" type="text" class="rl_inputName" maxlength="50" style="text-align:center" />');

  LInkManager();

  if (typeof (relay_type) != 'undefine' && relay_type == "2") {
    GetIconList();
    CheckRelayStatus();
  } else {
    $('#SUPPORT_ID_AREA').html('<input id="conn_no" type="text" class="rl_input" maxlength="7" style="ime-mode:disabled;text-align:center" />');

    if (conn_no.length > 1) {
      switch (conn_no_length) {
        case 9: $("#conn_no").val(conn_no.slice(0, conn_no.length).substr(0, 3) + ' ' + conn_no.slice(0, conn_no.length).substr(3, 3) + ' ' + conn_no.slice(0, conn_no.length).substr(6, 3));
          break;
        case 8: $("#conn_no").val(conn_no.slice(0, emp3_result.length).substr(0, 4) + ' ' + conn_no.slice(0, conn_no.length).substr(4, 4));
          break;
        case 7: $("#conn_no").val(conn_no.slice(0, conn_no.length).substr(0, 3) + ' ' + conn_no.slice(0, conn_no.length).substr(3, 4));
          break;
        case 6: $("#conn_no").val(conn_no.slice(0, conn_no.length).substr(0, 3) + ' ' + conn_no.slice(0, conn_no.length).substr(3, 3));
          break;
        default: $("#conn_no").val(conn_no.slice(0, conn_no.length));
          break;
      }
    }
    $("#conn_no").focus();

    // 3자리수 공백입력 및 전각 처리
    $("#conn_no").keyup(function(e) {
      var _2byteChar = '０１２３４５６７８９';

      var input = $(this);
      var text = input.val();
      if (!text.length) return;
      var _newText = '';
      for (var i = 0; i < text.length; i++) {
        var idx = _2byteChar.indexOf(text.charAt(i));
        _newText += (idx >= 0) ? idx : text.charAt(i);
      }
      input.val(text = _newText);

      var space = function(str, spa) {
        if (str.match(' ')) return str;
        var newStr = [];
        for (var j = 0; j < str.length; j++) {
          if (j == spa) newStr.push(' ');
          newStr.push(text.charAt(j));
        }
        return newStr.join('');
      };

      switch (conn_no_length) {
        case 9:
          if (text.length >= 3) input.val(space(text, 3));
          else if (text.length == 7) input.val(text + " "); // 이 경우는 뭘까요?
          break;
        case 8:
          if (text.length >= 4) input.val(space(text, 4));
          break;
        case 7:
          if (text.length >= 3) input.val(space(text, 3));
          break;
        case 6:
          if (e.which == 8) break;
          else if (text.length >= 3) input.val(space(text, 3));
          break;
        default:
          break;
      }
    });

    $(document).keypress(function(e) {
      if (e.which == 13) {
        if (!checkConnNo($("#conn_no").val())) {
          $("#conn_no").val("");
          $("#conn_no").focus();
        }
      }
    });

    $("#form1").submit(function() {
      return false;
    });

    $("#supportid_btn").click(function() {
      if (!checkConnNo($("#conn_no").val())) {
        $("#conn_no").val("");
        $("#conn_no").focus();
      }
    });

    $("#conn_no").keydown(function(e) {
      var opt = [13];
      var key = e.charCode || e.keyCode || 0;
      return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 9 || key == 8 || opt.indexOf(key) >= 0);
    });
  }
});

/* jQuery Document UNLOAD */
$(window).unload(function() {
  if (typeof (timeId) != 'undefine') clearTimeout(timeId);
  try {
    if (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null) {
      abortRequest(oXhrRequest);
    }
  } catch (e) { }
});

function abortRequest(request) {
  function doNothing() {}
  request.onreadystatechange = doNothing;
  try {//IE7 error
    request.abort();
  } catch (a) {}
  delete request;
}

function checkConnNo(conn_no) {
  var chck_conn_no = conn_no.replace(" ", "").replace(" ", "").replace(" ", "");
  var conn_name = $("#conn_name").val();
  var chkRoomNo = false;

  if ($.trim(chck_conn_no) != "" && chck_conn_no.length == conn_no_length) {
    conn_no_val = chck_conn_no;
    conn_name_val = conn_name;
    chkRoomNo = true;
  }
  else if (conn_no_val != null && conn_no_val != "" && conn_no_val.length == conn_no_length) {
    chkRoomNo = true;
  } else {
    alert(svc_GATE1000_msg_1);
    return false;
  }
  
  //CHECK SUBDOMAIN PROCESS
  if (!chk_subdomain) checkSubDomainByConnNo(conn_no_val);
  
  //CHECK AGREE & PINCODE USING
  checkSupportInfoByConnNo(conn_no_val);

  if (chk_room_satus != "0" && chk_room_type != "0" && room_id_val != "") {
    //IF USING AGREE ONLY FOR VIEWER
    if (chk_room_type == "2" && chk_room_satus == "2" && chk_agree_flag && client_file_nm != "") procSupportAgree();

    //IF USING PINCODE & NO AGREE
    if ((chk_agree_flag === false && chk_room_type == "2" && chk_room_satus == "2" && chk_pincode_flag && client_file_nm != "")) procSupportPincode();

    if ((chk_room_type == "1" && chk_room_satus == "2" && chk_pincode_flag)) procSupportPincode();

    //GO REMOTE SERVICE
    if (!(chk_room_type == "2" && chk_room_satus == "2" && chk_agree_flag && client_file_nm != "") && !chk_pincode_flag) GOTO_SERVICE();

    return true;
  } else {
    alert(svc_GATE1000_msg_2);
    return false;
  }
}

//CHECK SUBDOMAIN PROCESS
function checkSubDomainByConnNo(conn_no) {
  if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }
  oXhrRequest = $.ajax({
    type: "POST",
    url: "/WebRelay/GATE1001",
    data: "conn_no=" + conn_no,
    async: false,
    dataType: "jsonp",
    success: function(data) {
      subdomain_auth_addr_val = data.subdomain_auth_addr;
      subdomain_relay_addr_val = data.subdomain_relay_addr;
    }
  });
  delete oXhrRequest;
}

//CHECK AGREE & PINCODE USING
function checkSupportInfoByConnNo(conn_no) {
  if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }
  oXhrRequest = $.ajax({
      type: "POST",
      url: "/WebRelay/GATE1002",
      data: "conn_no=" + conn_no + "&subdomain=" + subdomain_auth_addr_val,
      async: false,
      dataType: "jsonp",
      success: function(data) {
          chk_agree_flag = (data.agree === "false") ? false : data.agree;
          chk_agree_localrecord_client_flag = (data.localrecord_client === "false") ? false : data.localrecord_client;//동의 사용여부
          chk_pincode_flag = (data.pincode === "false") ? false : data.pincode;
          room_id_val = data.room_id;
          chk_room_satus = data.room_status;
          chk_room_type = data.room_type;
          chk_room_product_type = data.product_type;
          client_file_nm = data.client_file_nm;
          noticeServerRecord = data.noticeServerRecord;
          noticeServerRecordUrl = data.noticeServerRecordUrl
      }
  });
  delete oXhrRequest;
}

function procSupportAgree() {
  if (chk_agree_flag) {
    var dialog = $('#relay_agree_dialog');
    var height = 297;
    
    if (chk_agree_localrecord_client_flag) {
      dialog.find('.record_agree_box').show();
    } else {
      dialog.find('.record_agree_box').hide();
      height -= 77;
    }
    if (noticeServerRecordUrl == 'http://') {
      dialog.find('a.record_detail').hide();
    } else {
      dialog.find('a.record_detail').show().attr('href', noticeServerRecordUrl);
    }
    
    if (noticeServerRecord) {
      dialog.find('p').show();
    } else {
      dialog.find('p').hide();
      height -= 32;
    }
    
    dialog.dialog({
      width: 347, height: height, // small -> 160
      minWidth: 347, minHeight: 220,
      maxWidth: 347, maxHeight: 287,
      modal: true,
      draggable: true
    });
    
    if (chk_agree_localrecord_client_flag) $("#relay_agree_chkbox_2").css("display", "block");
    else $("#relay_agree_chkbox_2").css("display", "none");
    
    $('#use_localrecord_client').attr('checked', false);// default : checked = false
    dialog.css("display", "block");
    $("#overlay").show();
    $("#relay_agree_btn_1").focus();
    
    if ($.browser.msie && $.browser.version == '6.0') {
      dialog.parents('.ui-dialog:first').find('.ui-resizable-ne').css('right', '-1px');
      dialog.parents('.ui-dialog:first').find('.ui-resizable-e').css('right', '-1px');
      dialog.parents('.ui-dialog:first').find('.ui-resizable-s').css('bottom', '-1px');
    }
  }
}

function procSupportPincode() {
  if (chk_pincode_flag) {
    $("#relay_pincode_dialog").dialog({
      width: 347, height: 160,
      minWidth: 347, minHeight: 160,
      maxWidth: 347, maxHeight: 160,
      modal: true,
      draggable: true
    });
    $("#relay_pincode_dialog").css("display", "block");
    $("#overlay").show();
    $("#relay_pincode_text").focus().keyup(function(e) {
      var _2byteChar = '０１２３４５６７８９';
      var input = $(this);
      var text = input.val();
      if (!text.length) return;
      var _newText = '';
      for (var i = 0; i < text.length; i++) {
        var idx = _2byteChar.indexOf(text.charAt(i));
        _newText += (idx >= 0)? idx : text.charAt(i);  
      }
      input.val(_newText);
    });
  }
}

//CONFIRM AGREE
var procSupportAgreeConfirm = function() {
  var ctrlcode = 0;
  var localrecord_client = 0;
  if ($("#use_keyboard_mouse").attr("checked")) ctrlcode = 3;
  if (chk_agree_localrecord_client_flag && $("#use_localrecord_client").attr("checked")) localrecord_client = 1;
  $("#relay_agree_dialog").dialog('destroy');
  if (confirmSupportAgreeAjax(ctrlcode, localrecord_client)) {
    if (chk_pincode_flag === true) procSupportPincode();
    else GOTO_SERVICE();
  } else {
    alert(svc_GATE1000_msg_3);
    $("#overlay").hide();
  }
};

var confirmSupportAgreeAjax = function(ctrlcode, localrecord_client) {
  if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }

  var confirm_result_flag = false;
  oXhrRequest = $.ajax({
    type: "POST",
    url: "/WebRelay/GATE1003",
    data: "ctrlcode=" + ctrlcode + "&localrecord_client=" + localrecord_client + "&conn_no=" + conn_no_val + "&subdomain=" + subdomain_auth_addr_val,
    async: false,
    dataType: "jsonp",
    success: function(data) {
      confirm_result_flag = data.result;
    }
  });

  delete oXhrRequest;
  return confirm_result_flag;
};

//CONFIRM PINCODE
var procSupportPincodeConfirm = function() {
  if ($("#relay_pincode_value").val() != "") {
    if (confirmSupportPincodeAjax($("#relay_pincode_value").val())) {
      $("#relay_pincode_dialog").dialog('destroy');
      GOTO_SERVICE();
    } else {
      alert(svc_GATE1000_msg_4);
      $("#relay_pincode_value").val("");
      $("#relay_pincode_text").focus();
    }
  } else {
    alert(svc_GATE1000_msg_5);
    $("#relay_pincode_value").val("");
    $("#relay_pincode_text").focus();
  }
};

var confirmSupportPincodeAjax = function(pincode_val) {
  if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }
  var confirm_result_flag = false;
  oXhrRequest = $.ajax({
    type: "POST",
    url: "/WebRelay/GATE1004",
    data: "pincode=" + pincode_val + "&conn_no=" + conn_no_val + "&subdomain=" + subdomain_auth_addr_val,
    async: false,
    dataType: "jsonp",
    success: function(data) {
      confirm_result_flag = data.result;
    }
  });
  delete oXhrRequest;
  return confirm_result_flag;
};

//CANCEL DIALOG
var cancleDialogBtn = function(div_id) {
  $("#relay_pincode_value").val("");
  $(div_id).dialog('destroy');
  $("#overlay").hide();
  //TODO: IFRAME 내로 포커스 이동
};

//GO PROCESS(CHAT or VIEWER)
var GOTO_SERVICE = function() {
    var customer_id_val = createCutomerInformation();
    if (customer_id_val != "") {
        var scheight = screen.height;
        var scwidth = screen.width;
        var leftpos = scwidth / 2 - 300 / 2;
        var toppos = scheight / 2 - 500 / 2;

        if (chk_room_type == "2" && chk_room_satus == "2" && client_file_nm != "") {
            if (chkAcxModule) {
                if (chk_room_product_type == "RSALE") {
                    doAcxRC5SalesConnect(conn_no_val);
                } else {
                    doAcxRC5Connect(conn_no_val);
                }
            } else {
                //VIEWER
                //JVM CHECK by OLD CODE
                //chkJvm = $("#isJvm").val();
                //TODO: HTTPS?JVM?
                var tmpStr = "" + document.location;
                if (tmpStr.indexOf("https://") > -1 && client_file_nm.indexOf("http://") > -1) {
                    client_file_nm = client_file_nm.replace('http://', 'https://');
                }
                location.href = client_file_nm;
            }
        } else {
            //CHAT
            var poplink = subdomain_relay_addr_val + "/webchat/CUST1000?conn_no=" + conn_no_val + "&customer_id=" + customer_id_val;
            window.open(poplink, "_blank", 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=1,width=380,height=500,left=' + leftpos + ',top=' + toppos);
        }
        //GOTO CONNPAGE

        if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
            if (typeof (timeId) != 'undefine') clearTimeout(timeId);
        }
        timeId = setTimeout("GetConnectionInit(" + conn_no_val + ")", 1000);
    } else {
        alert(svc_GATE1000_msg_6);
    }
    $("#overlay").hide();
};

//CREATE CUSTOMER INFORMATION ON ALLCLEAR STATUS
var createCutomerInformation = function() {
  if ((relay_type == "2") && (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null)) {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }
  var customer_id_val = "";
  oXhrRequest = $.ajax({
    type: "POST",
    url: "/WebRelay/GATE1005",
    data: "conn_no=" + conn_no_val + "&conn_name=" + encodeURI(conn_name_val) + "&subdomain=" + subdomain_auth_addr_val,
    async: false,
    dataType: "jsonp",
    success: function(data) {
      customer_id_val = data.customer_id;
    }
  });

  delete oXhrRequest;
  return customer_id_val;
};


// ICON RELAY PROCESS
var GetIconList = function() {
  if (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null) {
    delete oXhrRequest;
    abortRequest(oXhrRequest);
  }
  var oXhrRequestSecond = null;
  oXhrRequestSecond = $.ajax({
    type: "POST",
    url: "/WebRelay/GATE1010",
    data: "relay_uri=" + relay_uri,
    async: false,
    dataType: "jsonp",
    success: function(data) {
      $("#ICON_AREA").html("");
      if (data && data.lists && data.lists.length > 0) {
        
        //대기상담원 있을 경우 출력
        $("#supportName").css({ display: "block" });
        $("#reply_empty").css({ display: "none" });
        
        if ($.isArray(data.lists)) {
          //한 Row에 max 5개 상담원 출력, 이상시 width값 360px 고정
          styleWidth = (data.lists.length > 5) ? 360 : data.lists.length * 72 
        } else {
          styleWidth = 72;
        }
        
        var listElem_content = [];
        listElem_content.push('<div id="relay_icon"><div class="relay_icon_array" style="width:' + styleWidth + 'px;">');
        
        if ($.isArray(data.lists)) {
          $('.rl_inputName').attr('tabindex', '1');
          $.each(data.lists, function(i, list) {
            listElem_content.push(GetIconListItem(i, (i + 2), list));
          });
        } else {
          listElem_content.push(GetIconListItem(0, 1, data.lists));
        }
        
        listElem_content.push('</div></div>');
        $("#ICON_AREA").append(listElem_content.join(''));
      } else {
        //대기상담원 없을 경우 출력
        $("#reply_empty").css({ display: "block" });
        $("#supportName").css({ display: "none" });
      }
      
      $("#conn_name").focus();
    }
  });
  delete oXhrRequestSecond;
}

var GetIconListItem = function(id, tabindex, list){
  var text = '';
  text = text + '<a tabindex="' + tabindex + '" id="' + "ICON_" + id + '" onclick="checkConnNo(\'' + list.connNo + '\');">';
  text = text + '<div class="relay_numSect">' + list.iconNo + '</div>';
  text = text + '<div class="relay_numName">' + list.usrDispnm + '</div>';
  text = text + '</a>';
  return text;
}

var CheckRelayStatus = function() {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    try {
      if (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null) {
        abortRequest(oXhrRequest);
      }
    } catch (e) { }

    if (relay_type == "2") {
        try {
            oXhrRequest = $.ajax({
                type: "POST",
                url: "/GATE1000_SP.aspx",
                data: { 'relay_uri': relay_uri, 'src_date': src_date },
                async: true,
                dataType: "json",
                success: function(data) {
                    if (data != null && data.result){
                        src_date = data.src_date;
                        GetIconList();
                    }
                    timeId = setTimeout("CheckRelayStatus()", 1000);
                }
            });
        } catch (e) {
            timeId = setTimeout("CheckRelayStatus()", 1000);
        }

    }
}

// GET CONN STATUS PROCESS
var GetConnectionInit = function(conn_no_data) {
  if (relay_type == "2") {
    if (typeof (timeId) != 'undefine') clearTimeout(timeId);
    try {
      if (typeof (oXhrRequest) != 'undefine' && oXhrRequest != null) {
        abortRequest(oXhrRequest);
      }
    } catch (e) { }
  }
  oXhrRequest = $.ajax({
    type: "POST",
    url: "/GATE1020_SP.aspx",
    data: "conn_no=" + conn_no_data + "&subdomain=" + subdomain_auth_addr_val,
    async: true,
    dataType: "json",
    success: function(data) {
      if (data.result) {
          top.document.location = subdomain_relay_addr_val + '/WebRelay/conn1000?relay_uri=' + top_relay_uri + '&conn_no=' + conn_no_data;
      } else if (relay_type == "2") {
        CheckRelayStatus();
      }
    }
  });
  delete oXhrRequest;
};

var scriptAgreeText = function() {
  $("#relay_agree_btn_1")
    .click(function() { procSupportAgreeConfirm(); })
    .keypress(function(e) { if (e.which == 13) { procSupportAgreeConfirm(); } });

  $("#relay_agree_btn_2")
    .click(function() { cancleDialogBtn("#relay_agree_dialog"); });

  scriptPincodeText();
};

var scriptPincodeText = function() {
  $("#relay_pincode_content").html(relay_pincode_content_val);

  $("#relay_pincode_btn_1")
    .html(relay_pincode_btn_1_val)
    .click(function() { procSupportPincodeConfirm(); });

  $("#relay_pincode_btn_2")
    .html(relay_pincode_btn_2_val)
    .click(function() { cancleDialogBtn("#relay_pincode_dialog"); });

  $("#relay_pincode_text")
    .val(relay_pincode_text_val).show();
  
  $("#relay_pincode_value")
    .keypress(function(e) { if (e.which == 13) { procSupportPincodeConfirm(); } })    
    .blur(function() {
      if ($.trim($(this).val()) == "") {
        $("#relay_pincode_text").show();
        $("#relay_pincode_value").hide();
      }
    })
    .hide();
  
  $("#relay_pincode_text")
    .hover(defaultTextHide)
    .focus(defaultTextHide);
 
  function defaultTextHide(){
    $("#relay_pincode_text").hide();
    $("#relay_pincode_value").show();
    $("#relay_pincode_value").focus()
  }
  
};