//window.onload = initWebSocket;
var websServerAddr = "";
if(info.PPP == 1)
{
	if(info.HTTPS==1)
	{
		websServerAddr = "wss://" + info.PPP_IP + ":" + info.PORT;
	}
	else
	{
		websServerAddr = "ws://" + info.PPP_IP + ":" + info.PORT;
	}
}
else
{
	if (window.location.port.length) {
		if (window.location.protocol == "http:") {
			websServerAddr = "ws://" + window.location.host;
		} else if (window.location.protocol == "https:") {
			websServerAddr = "wss://" + window.location.host;
		}
	} else {
		if (window.location.protocol == "http:") {
			websServerAddr = "ws://" + window.location.host + ":80";
		} else if (window.location.protocol == "https:") {
			websServerAddr = "wss://" + window.location.host + ":443";
		}
	}
}
var ipktsWebs = null;
var websProtocolID = "iPECSWeb"; //constants value
var WEBS_MainCodeLen = 4; //constants value
var WEBS_SyncMsgCodeLen = 8; //constants value
var WEBS_SyncMsgSizeLen = 8; //constants value
var WEBS_OperationCodeLen = 8; //constants value
var WEBS_OperationSizeLen = 8; //constants value
var WEBS_RangeNumLen = 2; //constants value
var WEBS_RangeTypeLen = 2; //constants value
var WEBS_RangeLengthLen = 2; //constants value
var WEBS_RangeMaxLen = 40; //constants value
var skipConfirm_flag = false;
var logout_flag = false;

function initWebSocket() {
   if ("WebSocket" in window) {
		if (info.AUTH == 1) {
			$('.navbar-fixed-bottom .status-bar').show();
			$('.navbar-fixed-bottom .status-bar .warning-msg').text(langs.getText(lang_common_type,"read_only"));
			$('#mob_status_bar').html("<img src=\"img/warning.png\" style=\"margin-right:10px\">"+langs.getText(lang_common_type,"read_only")).show();
			$('#list_for_moblie_web .divider:first()').show();
		}

      ipktsWebs = new WebSocket(websServerAddr);
      setWebSDataArray();
      ipktsWebs.onopen = websOpen;
      ipktsWebs.onmessage = websProcess;
      ipktsWebs.onclose = websClose;
      ipktsWebs.onerror = websError;

      IsWebSocketSupport = true;
   } else alert("This browser not support WebSocket!");
}

function sendMsg(main, request, r_type, range, content) {
	if (ipktsWebs.readyState == 3) {
      $('<div />').html(langs.getText(lang_common_type,"disconnect_alertmessage1") + "<br>" + langs.getText(lang_common_type,"disconnect_alertmessage2")).dialog({
         modal: true,
         closeOnEscape: false,
         title: langs.getText(lang_common_type,"notification"),
         open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
         },
         buttons: [
				{
					text: langs.getText(lang_common_type,"refresh"),
					click: function () {
						$(this).dialog("destroy");
						location.href = location.href.replace(/#$/, '');
					}
				},
				{
					text: langs.getText(lang_common_type,"cancel"),
					click: function () {
						$(this).dialog("destroy");
					}
				}
			]
      });
   } else {
		if (((request != "pgm52") && (request != "pgm85") && (request != "pgm31321") && (request != "pgm9800")) || ((request == "pgm85") && (content.trim() == "{}"))) {
			$('.loadingPane').show();
		}

		if (ipktsWebs != null) {
			var sendSyncCode = makeRandomSyncCode();
			if (request == "pgm9800") {
				makeiPECSWebTest(main, sendSyncCode, "pgm98", r_type, range, content);
			} else {
				makeiPECSWebTest(main, sendSyncCode, request, r_type, range, content);
			}
		}
   }
}

function websOpen() {
   debug_mode.flag && console.log("webSocket is connected!");
}

function websProcess(e) {
   var outString = "message from server : ";
   if (typeof e.data === "string") {
      outString += e.data;
      debug_mode.flag && console.log(outString);
      parseiPECSWeb(e.data);
   } else if (e.data instanceof ArrayBuffer) {
      var ba = new Uint8Array(e.data);
      for (var i = 0; i < ba.length; i++) {
         outString += ba[i] + " ";
      }
      debug_mode.flag && console.log(outString);
   } else if (e.data instanceof Blob) {}
}

function websClose() {
   debug_mode.flag && console.log("Connection close ... ");
	$('.navbar-fixed-bottom .status-bar').show();
	$('.navbar-fixed-bottom .status-bar .warning-msg').text(langs.getText(lang_common_type,"disconnected"));
	$('#mob_status_bar').html("<img src=\"img/warning.png\" style=\"margin-right:10px\">"+langs.getText(lang_common_type,"disconnected")).show();
	$('#list_for_moblie_web .divider:first()').show();

   if (!skipConfirm_flag) {
      $('<div />').html(langs.getText(lang_common_type,"disconnect_alertmessage1") + "<br>" + langs.getText(lang_common_type,"disconnect_alertmessage2")).dialog({
         modal: true,
         closeOnEscape: false,
         title: langs.getText(lang_common_type,"notification"),
         open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
         },
         buttons: [
				{
					text: langs.getText(lang_common_type,"refresh"),
					click: function () {
						$(this).dialog("destroy");
						location.href = location.href.replace(/#$/, '');
					}
				},
				{
					text: langs.getText(lang_common_type,"cancel"),
					click: function () {
						$(this).dialog("destroy");
					}
				}
			]
      });
   } else {
      if (logout_flag) {
         $(document).trigger("Log_out");
      }
   }
}

function websError(e) {
   debug_mode.flag && console.log("Connection error: " + e);
}
/*
function sendBinaryTest() {
    if (ipktsWebs != null)
    {
        var size = 10;
        var ba = new Uint8Array(size);
        for (var i = 0; i < size; i++) {
            ba[i] = i + 1;
        }
        var m = ba.buffer;
        ipktsWebs.send(m);
    }
}
*/

function setWebSDataArray() {
   if (ipktsWebs != null) {
      ipktsWebs.binaryType = "arraybuffer";
   }
}

function setWebSDataBlob() {
   if (ipktsWebs != null) {
      ipktsWebs.binaryType = "blob";
   }
}

function makeiPECSWebHeader(mainCode, syncCode, syncEventSize) {
   var mainCode4 = makeFixed4Buffer(mainCode);
   var syncCode8 = makeFixed8Buffer(syncCode);
   var syncEventSize8 = makeFixed8Buffer(syncEventSize.toString(16));
   return websProtocolID + mainCode4 + syncCode8 + syncEventSize8;
}

function makeiPECSWebOperationPacket(operCode, rangeNum, rangeType, range, operValue) {
   var operContent;
   operContent = makeFixed8Buffer(operCode);
   var rangeContent = makeiPECSWebsRange(rangeNum, rangeType, range);
   if (rangeContent != null) {
      var operContentSize = utf8StringByteSize(operValue) + rangeContent.length;
      operContent += makeFixed8Buffer(operContentSize.toString(16));
      operContent += rangeContent;
      operContent += operValue;
      return operContent;
   }
   return null;
}

function makeiPECSWebsRange(rangeNum, rangeType, range) {
   var rangeContent = makeFixed2Buffer(rangeNum.toString(16));
   if (rangeNum > 0) {
      if ((Object.prototype.toString.call(rangeType) === '[object Array]') && (Object.prototype.toString.call(range) === '[object Array]')) {
         for (var rangeNumTemp = 0; rangeNumTemp < rangeNum; rangeNumTemp++) {
            rangeContent += makeFixed2Buffer(rangeType[rangeNumTemp].toString(16));
            rangeContent += makeFixed2Buffer(range[rangeNumTemp].length.toString(16));
            rangeContent += makeVariable40Buffer(range[rangeNumTemp]);
         }
         return rangeContent;
      } else return null;
   }
   return rangeContent;
}

function waitForSocketConnection(callback) {
	setTimeout(function () {
		if (ipktsWebs.readyState === 1) {
			if(callback != null){
				callback();
			}
			return;
		} else {
			console.log("Wait for connection...")
			waitForSocketConnection(callback);
		}
	}, 100);
}

function makeiPECSWebTest(main, sendSyncCode, request, rangeType, range, content) {
   var sendMainCode = null;
   var contentString = content;
   var range_num = 0;
   var syncMsgByteSize = 0;

   range_num = range.length;

   if (main == 0) {
      sendMainCode = "0001";
   } else if (main == 1) {
      sendMainCode = "8001";
   }

   var operContentData = makeiPECSWebOperationPacket(request, range_num, rangeType, range, contentString);
   if (operContentData != null) {
      syncMsgByteSize = operContentData.length - contentString.length + utf8StringByteSize(contentString);
      operContentData = makeiPECSWebHeader(sendMainCode, sendSyncCode, syncMsgByteSize) + operContentData;
      waitForSocketConnection(function(){
			ipktsWebs.send(operContentData);
			debug_mode.flag && console.log("send Message : " + operContentData);
		});
   } else {
      //alert("make content data error!");
      debug_mode.flag && console.log("make content data error!");
   }
}

function makeFixed2Buffer(value) {
   var tempValue = String(value);
   if (tempValue.length > 2) tempValue = tempValue.substring(0, 2);
   var buffer2 = "  ";
   buffer2 += tempValue;
   return buffer2.substring(tempValue.length);
}

function makeFixed4Buffer(value) {
   var tempValue = String(value);
   if (tempValue.length > 4) tempValue = tempValue.substring(0, 4);
   var buffer4 = "    ";
   buffer4 += tempValue;
   return buffer4.substring(tempValue.length);
}

function makeFixed8Buffer(value) {
   var tempValue = String(value);
   if (tempValue.length > 8) tempValue = tempValue.substring(0, 8);
   var buffer8 = "        ";
   buffer8 += tempValue;
   return buffer8.substring(tempValue.length);
}

function makeVariable40Buffer(value) {
   var tempValue = String(value);
   if (tempValue.length > 40) return tempValue.substring(0, 40);
   else return tempValue;
}

function parseiPECSWeb(inputData) {
   debug_mode.flag && console.log(inputData);
   var parsePos = 0;
   var rcvProtocolID = inputData.substring(parsePos, websProtocolID.length);
   parsePos += websProtocolID.length;
   if (rcvProtocolID == websProtocolID) {
      var mainCode4 = inputData.substring(parsePos, parsePos + WEBS_MainCodeLen);
      parsePos += WEBS_MainCodeLen;
      switch (mainCode4) {
      case "0001":
         // admin read command >> invalid at client
         processAdminRDCmdResponse(inputData.substring(parsePos));
         break;
         //remark for testing break;
      case "4001":
         // admin read command response.
         processAdminRDCmdResponse(inputData.substring(parsePos));
         break;
      case "8001":
         // admin write command >> invalid at client
         break;
      case "C001":
         // admin write command response
         processAdminRDCmdResponse(inputData.substring(parsePos));
         break;
      case "8002":
         // system notify event (from server)
         break;
      case "C002":
         // system notify event response (to server) >> invalid at client
         break;
      case "0003":
         // system read command >> invalid at client
         break;
      case "4003":
         // system read command response
         break;
      }
   } else {
      //alert("invalid protocol ID");
   }
}
/*
var websProtocolID = "iPECSWeb"; //constants value
var WEBS_MainCodeLen = 4; //constants value
var WEBS_SyncMsgCodeLen = 8; //constants value
var WEBS_SyncMsgSizeLen = 4; //constants value
var WEBS_OperationCodeLen = 8; //constants value
var WEBS_OperationSizeLen = 4; //constants value
var WEBS_RangeTypeLen = 2; //constants value
var WEBS_RangeNumLen = 2; //constants value
var WEBS_RangeStartLen = 4; //constants value
var WEBS_RangeEndLen = 4; //constants value
*/

function processAdminRDCmdResponse(respMsg) {
   var parsePos = 0;
   var syncCode8 = respMsg.substring(parsePos, parsePos + WEBS_SyncMsgCodeLen);
   parsePos += WEBS_SyncMsgCodeLen;
   var syncEventSize8 = respMsg.substring(parsePos, parsePos + WEBS_SyncMsgSizeLen);
   parsePos += WEBS_SyncMsgSizeLen;
   syncEventSize8 = parseInt(syncEventSize8, 16);
   if (syncEventSize8 == (utf8StringByteSize(respMsg) - parsePos)) {

      var operationCode;
      var operationSize;
      var rangeType;
      var rangeNum;
      var operationValueSize;
      var operationValueLength;
      var operationValue;
      var system_msg = null;
      while (respMsg.length > parsePos) {
         var rangeType = null;
         var rangeLen = null;
         var range = null;
         var render_cancel_flag = false;
         operationCode = respMsg.substring(parsePos, parsePos + WEBS_OperationCodeLen);
         parsePos += WEBS_OperationCodeLen;

         operationSize = respMsg.substring(parsePos, parsePos + WEBS_OperationSizeLen);
         parsePos += WEBS_OperationSizeLen;
         operationSize = parseInt(operationSize, 16);

         rangeNum = respMsg.substring(parsePos, parsePos + WEBS_RangeNumLen);
         parsePos += WEBS_RangeNumLen;
         rangeNum = parseInt(rangeNum, 16);

         if (rangeNum > 0) {
            rangeType = new Array(rangeNum);
            rangeLen = new Array(rangeNum);
            range = new Array(rangeNum);

            for (var rangeIndex = 0; rangeIndex < rangeNum; rangeIndex++) {
               rangeType[rangeIndex] = respMsg.substring(parsePos, parsePos + WEBS_RangeTypeLen);
               parsePos += WEBS_RangeTypeLen;
               rangeType[rangeIndex] = rangeType[rangeIndex].replace(/\s/g, "");
               rangeType[rangeIndex] = parseInt(rangeType[rangeIndex], 16);

               rangeLen[rangeIndex] = respMsg.substring(parsePos, parsePos + WEBS_RangeLengthLen);
               parsePos += WEBS_RangeLengthLen;
               rangeLen[rangeIndex] = rangeLen[rangeIndex].replace(/\s/g, "");
               rangeLen[rangeIndex] = parseInt(rangeLen[rangeIndex], 16);

               range[rangeIndex] = respMsg.substring(parsePos, parsePos + rangeLen[rangeIndex]);
               parsePos += rangeLen[rangeIndex];
               range[rangeIndex] = range[rangeIndex].replace(/\s/g, "");
            }
         }
         //==================if multiple operation is received ====================================
         operationValueSize = operationSize - WEBS_RangeNumLen;
         for (var rangeIndex = 0; rangeIndex < rangeNum; rangeIndex++) {
            operationValueSize -= (WEBS_RangeTypeLen + WEBS_RangeLengthLen + rangeLen[rangeIndex]);
         }
         operationValueLength = utf8ByteStringLength(respMsg.substring(parsePos, respMsg.length), operationValueSize);
         if (operationValueLength == 0) {
            $('.loadingPane').hide();
            $('<div />').html(langs.getText(lang_error_msg_type,"error_parsemsg")).dialog({
               modal: true,
               closeOnEscape: false,
               title: langs.getText(lang_common_type,"notification"),
               open: function (event, ui) {
                  $(".ui-dialog-titlebar-close").hide();
               },
					buttons: [
						{
							text: langs.getText(lang_common_type,"refresh"),
							click: function () {
								location.href = location.href.replace(/#$/, '')
								$(this).dialog("destroy");
							}
						}
					]
            });
            return false;
         }
         operationValue = respMsg.substring(parsePos, parsePos + operationValueLength).replace(/\\n/g,'&#13;&#10;').replace(/\\/g,'\\\\').replace(/\\'/g,'\"');
         parsePos += operationValueLength;

         debug_mode.flag && console.log("respMsg.length : " + respMsg.length + " operationValueSize : " + operationValueSize + " operationValueLength : " + operationValueLength + " parsePos : " + parsePos);

         //==================if just one operation is received ====================================
         //operationValue = respMsg.substring(parsePos, respMsg.length);
         //parsePos = respMsg.length;
         debug_mode.flag && console.log(operationValue);

         try {
            system_msg = JSON.parse(operationValue);
         } catch (e) {
				for(var i=0; i < operationValue.length; i++) {
					if (operationValue.charCodeAt(i) <= 0x00001F) {
						operationValue = operationValue.substr(0, i) + "?" + operationValue.substr(i+1, operationValue.length-1);
					}
				}
				system_msg = JSON.parse(operationValue);
         }

         if (system_msg["RESTART_HTTP_SERVER"]) {
				var curAddr = null;
            if (websServerAddr.match(/^wss\:\/\//)) {
					curAddr = websServerAddr.replace(/^wss\:\/\//,'https://');
            } else {
					curAddr = websServerAddr.replace(/^ws\:\/\//,'http://');
            }
            skipConfirm_flag = true;
            ipktsWebs.close();
            debug_mode.flag && console.log("Restart...");
            if (curAddr == system_msg["RESTART_HTTP_SERVER"][0].V) {
					setInterval(function () {
						$.ajax({
							url: system_msg["RESTART_HTTP_SERVER"][0].V + '/img/iPECS_logo_login.png',
							success: function(result){
								debug_mode.flag && console.log("Restart Completed. Redirect to " + system_msg['RESTART_HTTP_SERVER'][0].V);
								location.href = system_msg['RESTART_HTTP_SERVER'][0].V;
								return false;
							}
						});
					}, 10000);
            } else {
					setTimeout(function () {
						debug_mode.flag && console.log("Redirect to " + system_msg['RESTART_HTTP_SERVER'][0].V);
						location.href = system_msg['RESTART_HTTP_SERVER'][0].V;
					}, 60000);
            }
            break;
         } else if (system_msg["RESET_OK"]) {
				var curAddr = null;

            if (websServerAddr.match(/^wss\:\/\//)) {
					curAddr = websServerAddr.replace(/^wss\:\/\//,'https://');
            } else {
					curAddr = websServerAddr.replace(/^ws\:\/\//,'http://');
            }
            skipConfirm_flag = true;
            ipktsWebs.close();
            debug_mode.flag && console.log("Reset...");
            if (curAddr == system_msg["RESET_OK"][0].V) {
					setInterval(function () {
						$.ajax({
							url: system_msg["RESET_OK"][0].V + '/img/iPECS_logo_login.png',
							success: function(result){
								debug_mode.flag && console.log("Reset Completed. Redirect to " + system_msg['RESET_OK'][0].V);
								location.href = system_msg['RESET_OK'][0].V;
								return false;
							}
						});
					}, 60000);
            } else {
					setTimeout(function () {
						debug_mode.flag && console.log("Redirect to " + system_msg['RESET_OK'][0].V);
						location.href = system_msg['RESET_OK'][0].V;
					}, 120000);
            }
            break;
         } else if (system_msg["RESET_CONFIRM"]) {
            var alertmsg = null;
            var send_resetmsg = null;

            mappingToModel(operationCode, rangeType, range, operationValue, render_cancel_flag);

            if (system_msg["RESET_CONFIRM"][0].V == "1") {
               alertmsg = langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "2") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_sipinit") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "3") {
					if (!offline_mode) {
						if (info.SYSTEM_ID == "iPECS eMG80" || info.SYSTEM_ID == "iPECS eMG100" || info.SYSTEM_ID == "iPECS eMG800") {
							alertmsg = langs.getText(lang_common_type,"reset_reason_ncodech") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage") + "<br><span style='font-weight:bold;color:red'>(" + langs.getText(lang_common_type,"reset_info_dip_emg") + ")</span>";
						} else {
							alertmsg = langs.getText(lang_common_type,"reset_reason_ncodech") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage") + "<br><span style='font-weight:bold;color:red'>(" + langs.getText(lang_common_type,"reset_info_dip") + ")</span>";
						}
					} else {
						alertmsg = langs.getText(lang_common_type,"reset_reason_ncodech") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
               }
            } else if (system_msg["RESET_CONFIRM"][0].V == "4") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_nplanch") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "5") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_devportch") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "6") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_sysconfch") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "7") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_coorderch") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            } else if (system_msg["RESET_CONFIRM"][0].V == "8") {
               alertmsg = langs.getText(lang_common_type,"reset_reason_dbmodify") + "<br>" + langs.getText(lang_common_type,"reset_alertmessage");
            }

            if ((system_msg["RESET_CONFIRM"][0].V != "3") && (system_msg["RESET_CONFIRM"][0].C == "DIP4ON") && (!offline_mode)) {
					if (info.SYSTEM_ID == "iPECS eMG80" || info.SYSTEM_ID == "iPECS eMG100" || info.SYSTEM_ID == "iPECS eMG800") {
						alertmsg += "<br><br><span style='font-weight:bold;color:red'>(" + langs.getText(lang_common_type,"alert_dbinit_emg") + ")</span>";
					} else {
						alertmsg += "<br><br><span style='font-weight:bold;color:red'>(" + langs.getText(lang_common_type,"alert_dbinit") + ")</span>";
					}
            }

            if ((system_msg["RESET_CONFIRM"][0].V == "3") && (!offline_mode)) {
					send_resetmsg = "{\"SYSTEM_RESET\":\"CHECK_DIP_INITDB\"}";
            } else {
					send_resetmsg = "{\"SYSTEM_RESET\":\"YES\"}";
            }

            var dialog_buttons = null;

            if (((ap.render_pgm == "iw002") || (ap.render_pgm == "pgm100")) && (system_msg["RESET_CONFIRM"][0].V == "3")) {
					dialog_buttons = [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								debug_mode.flag && console.log(send_resetmsg);
								var range_type = [];
								var range_val = [];
								packet.setPacket(1, range_type, range_val, send_resetmsg);
								sendMsg(packet.main, "pgm9999", packet.type, packet.range, packet.msg);
								$(this).dialog("destroy");
							}
                  }
               ];
            } else {
					dialog_buttons = [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								debug_mode.flag && console.log(send_resetmsg);
								var range_type = [];
								var range_val = [];
								packet.setPacket(1, range_type, range_val, send_resetmsg);
								sendMsg(packet.main, "pgm9999", packet.type, packet.range, packet.msg);
								$(this).dialog("destroy");
							}
                  },
                  {
							text: langs.getText(lang_common_type,"cancel"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
               ];
            }

            $('<div />').html(alertmsg).dialog({
               modal: true,
               closeOnEscape: false,
               title: langs.getText(lang_common_type,"notification"),
               open: function (event, ui) {
                  $(".ui-dialog-titlebar-close").hide();
               },
               buttons: dialog_buttons
            });
            break;
         } else if (system_msg["RESET_CONFIRM_DIP_INITDB_OFF"]) {
				var alertmsg = null;

				if (info.SYSTEM_ID == "iPECS eMG80" || info.SYSTEM_ID == "iPECS eMG100" || info.SYSTEM_ID == "iPECS eMG800") {
					alertmsg = langs.getText(lang_common_type,"reset_confirm_dip_initdb_off_emg_1") + "<br>" + langs.getText(lang_common_type,"reset_confirm_dip_initdb_off_emg_2");
				} else {
					alertmsg = langs.getText(lang_common_type,"reset_confirm_dip_initdb_off_1") + "<br>" + langs.getText(lang_common_type,"reset_confirm_dip_initdb_off_2");
				}

				$('.loadingPane').hide();

            $('<div />').html(alertmsg).dialog({
               modal: true,
               closeOnEscape: false,
               title: langs.getText(lang_common_type,"notification"),
               open: function (event, ui) {
                  $(".ui-dialog-titlebar-close").hide();
               },
               buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								var send_msg = "{\"SYSTEM_RESET\":\"YES\"}";
								debug_mode.flag && console.log(send_msg);
								var range_type = [];
								var range_val = [];
								packet.setPacket(1, range_type, range_val, send_msg);
								sendMsg(packet.main, "pgm9999", packet.type, packet.range, packet.msg);
								$(this).dialog("destroy");
							}
                  }
               ]
            });
				break;
         } else if (system_msg["REQ_NEXT"]) {
				var cont_to_mapping=0;
				if ($('#pgm52').length && ($.trim(operationCode) == "pgm52")) {
					for (var key in system_msg) {
						if (key.match("PROGRESS") && system_msg[key][0].V) {
							if (system_msg[key][0].V.match("Start")) {
								$('#pgm52 [name='+key+'] .progress-bar').css('width','0%');
								$('#pgm52 [name='+key+'] .percent').text(langs.getText(lang_common_type,"start"));
							} else if (system_msg[key][0].V.match("Error")) {
								$('#pgm52 [name='+key+'] .progress-bar').css('width','0%');
								$('#pgm52 [name='+key+'] .percent').text(langs.getText(lang_error_msg_type,"error"));
							} else if (system_msg[key][0].V.match("Burning")) {
								$('#pgm52 [name='+key+'] .progress-bar').css('width','100%');
								$('#pgm52 [name='+key+'] .percent').text(langs.getText("p52","progress_burning"));
							} else if (system_msg[key][0].V.match("Success")) {
								$('#pgm52 [name='+key+'] .progress-bar').css('width','0%');
								$('#pgm52 [name='+key+'] .percent').text(langs.getText(lang_common_type,"success"));
							} else {
								$('#pgm52 [name='+key+'] .progress-bar').css('width',system_msg[key][0].V);
								$('#pgm52 [name='+key+'] .percent').text(system_msg[key][0].V);
							}

							if (system_msg[key][0].V.match("Disconnected")) {
								$('#pgm52 [name='+key+'] .progress-bar').css('width','0%');
								$('#pgm52 [name='+key+'] .percent').append(' ('+langs.getText(lang_common_type,"disconnected")+')');
							}
						}
					}
				} else if ($('#pgm85').length && ($.trim(operationCode) == "pgm85")) {
					for (var key in system_msg) {
						if (system_msg[key][0].V) {
							if (key.match("VM_BACKUP_RESULT")) {
								var exopt_flag = false;
								_.each(pgm_name_maps[$.trim(operationCode)][key].select, function(opt) {
									if (system_msg[key][0].V == opt.value) {
										$('#pgm85 [name='+key+']').text(opt.option);
										exopt_flag = true;
									}
									if (!exopt_flag) {
										$('#pgm85 [name='+key+']').text("");
									}
								});
							} else if (key.match("VM_BACKUP_PROGRESS") && (system_msg[key][0].V == "Complete")) {
								$('#pgm85 [name='+key+']').text(langs.getText(lang_common_type,"complete"));
							} else if (key.match("REQ_NEXT") && (system_msg[key][0].V == "cont")) {
								cont_to_mapping = 1;
							} else {
								$('#pgm85 [name='+key+']').text(system_msg[key][0].V);
							}
						}
					}
				}

				if (system_msg["REQ_NEXT"][0].V == "END") {
					break;
				}

				var send_msg = "{\"REQ_STATUS\":\"\"}";
				var range_type = [];
				var range_val = [];
				setTimeout(function () {
					sendMsg(0, $.trim(operationCode), range_type, range_val, send_msg);
				}, 2000);
				if(cont_to_mapping==0)
				{
					break;
				}
         } else if (system_msg["MOVE_SUCCESS"]) {
            $('<div />').html(langs.getText("p315","move_success")).dialog({
               modal: true,
               closeOnEscape: false,
               title: langs.getText(lang_common_type,"notification"),
               open: function (event, ui) {
                  $(".ui-dialog-titlebar-close").hide();
               },
               buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								pgm_models.get_model(ap.render_pgm, true);
								$(this).dialog("destroy");
							}
						}
					]
            });
            break;
         } else if (system_msg["NEXT"]) {
            var send_msg = "";
				var real_pgm = ap.render_pgm;

				if (active_base == "tab_function_base" || active_base == "tab_install_wizard") {
					for (var idx = 0; idx < pgm_views[ap.render_pgm].collection.models[0].attributes.elements[0].tab.length; idx++) {
						if (pgm_views[ap.render_pgm].collection.models[0].attributes.elements[0].tab[idx].key) {
							real_pgm = pgm_views[ap.render_pgm].collection.models[0].attributes.elements[0].tab[idx].key.split('_')[0];
							break;
						}
					}
				}

				if (real_pgm == "pgm144") {
					send_msg = packet.msg.replace(/\}$/,"") + ",\"NEXT\":\"" + system_msg["NEXT"][0].V + "\"}";
					sendMsg(packet.main, real_pgm, packet.type, packet.range, send_msg);
					break;
				}
         } else if (system_msg["LANG_SAV_RESULT"]) {
            location.href = location.href.replace(/#$/, '');
            break;
         } else if (system_msg["CHECKOUT"]) {
				$('<div />').html(langs.getText("p3132","chkout_success")).dialog({
               modal: true,
               closeOnEscape: false,
               title: langs.getText(lang_common_type,"notification"),
               open: function (event, ui) {
                  $(".ui-dialog-titlebar-close").hide();
               },
               buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								pgm_models.get_model(ap.render_pgm, true);
								$(this).dialog("destroy");
							}
						}
					]
            });
            break;
         } else if (system_msg["FAV_SAV_RESULT"]) {
				if(system_msg["FAV_SAV_RESULT"][0].V == "1") {
					$('<div />').html(langs.getText(lang_common_type,"favsave_success")).dialog({
						modal: true,
						closeOnEscape: false,
						title: langs.getText(lang_common_type,"notification"),
						open: function (event, ui) {
							$(".ui-dialog-titlebar-close").hide();
						},
						buttons: [
							{
								text: langs.getText(lang_common_type,"simple_okay"),
								click: function () {
									requirejs.undef('user/user.profile');
									require(['user/user.profile'], function (k) {
										debug_mode.flag && console.log("user/user.profile reloaded");
										$(document).trigger("user_func_loaded");
									});

									$(document).unbind("user_func_loaded");
									$(document).bind("user_func_loaded", function () {
										debug_mode.flag && console.log("user func reloaded");

										_.each(pgm_menuList_view.collection.models, function (item) {
											_.each(item.attributes.children, function (child) {
												try {
													child.fav = 0;
													if (favorite_pgmlist[child.num]) {
														child.fav = favorite_pgmlist[child.num];
													}
												} catch (e) {
													debug_mode.flag && console.log("user.profile.js read error!!");
												}
											}, this);
										}, this);

										_.each(func_menuList_view.collection.models, function (item) {
											_.each(item.attributes.children, function (child) {
												try {
													child.fav = 0;
													if (favorite_funclist[child.num]) {
														child.fav = favorite_funclist[child.num];
													}
												} catch (e) {
													debug_mode.flag && console.log("user.profile.js read error!!");
												}
											}, this);
										}, this);

										make_favorite_pgm();
										$('.loadingPane').hide();
										$(document).trigger("Resize_pane");
									});
									$(this).dialog("destroy");
								}
							}
						]
					});
					break;
				} else if(system_msg["FAV_SAV_RESULT"][0].V == "2") {
					$('<div />').html(langs.getText(lang_common_type,"save_fail")).dialog({
						modal: true,
						closeOnEscape: false,
						title: langs.getText(lang_common_type,"notification"),
						open: function (event, ui) {
							$(".ui-dialog-titlebar-close").hide();
						},
						buttons: [
							{
								text: langs.getText(lang_common_type,"simple_okay"),
								click: function () {
									$('.loadingPane').hide();
									$(this).dialog("destroy");
								}
							}
						]
					});
					break;
				}
         } else if (system_msg["FUNC_SAV_RESULT"]) {
				if(system_msg["FUNC_SAV_RESULT"][0].V == "1") {
					$('<div />').html(langs.getText(lang_common_type,"funcsave_success")).dialog({
						modal: true,
						closeOnEscape: false,
						title: langs.getText(lang_common_type,"notification"),
						open: function (event, ui) {
							$(".ui-dialog-titlebar-close").hide();
						},
						buttons: [
							{
								text: langs.getText(lang_common_type,"simple_okay"),
								click: function () {
									var this_index = 0;
									var new_index = 0;

									this_index = $('#' + active_base + ' .nav-tabs-main .active').index();
									_.each($('#' + active_base + ' .nav-tabs-main li'), function (item, i) {
										if ($('#' + active_base + ' .nav-tabs-main li:eq(' + i + ') a').text() == langs.getText("mnt_menu","pgm99")) {
											new_index = i;
										}
									});

									if (new_index == 0) {
										if ($('#' + active_base + ' .nav-tabs-main .active').text() == $('#' + active_base + ' .nav-tabs-main li:last a').text()) {
											new_index = this_index - 1;
										} else {
											new_index = this_index + 1;
										}
									}

									$('#' + active_base + ' .nav-tabs-main li:eq(' + new_index + ')').addClass("active").children('a').append("<img src='img/refresh_icon.png' class='icon_refresh' title='" + langs.getText("toolTip","tip_refreshtab") + "' />");
									$('#' + active_base + ' .tab-content-main .tab-pane-main:eq(' + new_index + ')').addClass("active");
									$('#' + active_base + ' .nav-tabs-main li:eq(' + this_index + ')').remove();
									$('#' + active_base + ' .tab-content-main .tab-pane-main:eq(' + this_index + ')').remove();

									moveTab();

									requirejs.undef('user/user.profile');
									requirejs.undef('models/left_menu');
									require(['user/user.profile'], function (k) {
										debug_mode.flag && console.log("user/user.profile reloaded");
										require(['models/left_menu'], function (k) {
											debug_mode.flag && console.log("models/left_menu reloaded");
											$(document).trigger("user_func_loaded");
										});
									});

									$(document).unbind("user_func_loaded");
									$(document).bind("user_func_loaded", function () {
										debug_mode.flag && console.log("user func reloaded");

										func_dir_view.initialize();
										func_menuList_view.initialize();

										_.each(func_menuList_view.collection.models, function (item) {
											_.each(item.attributes.children, function (child) {
												try {
													child.fav = 0;
													if (favorite_funclist[child.num]) {
														child.fav = favorite_funclist[child.num];
													}
												} catch (e) {
													debug_mode.flag && console.log("user.profile.js read error!!");
												}
											}, this);
										}, this);

										if (ap.render_pgm == "pgm99") {
											var range_type = [];
											var range = [];
											packet.setPacket(0, range_type, range, "{}");
											$('#' + ap.render_pgm).html("");
											pgm_models.get_model(ap.render_pgm, true, packet);
										} else {
											$('.loadingPane').hide();
										}
										$(document).trigger("Resize_pane");
									});
									$(this).dialog("destroy");
								}
							}
						]
					});
					break;
				} else if (system_msg["FUNC_SAV_RESULT"][0].V == "2") {
					$('<div />').html(langs.getText(lang_common_type,"save_fail")).dialog({
						modal: true,
						closeOnEscape: false,
						title: langs.getText(lang_common_type,"notification"),
						open: function (event, ui) {
							$(".ui-dialog-titlebar-close").hide();
						},
						buttons: [
							{
								text: langs.getText(lang_common_type,"simple_okay"),
								click: function () {
									$('.loadingPane').hide();
									$(this).dialog("destroy");
								}
							}
						]
					});
					break;
				} else if (system_msg["FUNC_SAV_RESULT"][0].V == "3") {
					requirejs.undef('user/user.profile');
					requirejs.undef('models/left_menu');
					require(['user/user.profile'], function (k) {
						debug_mode.flag && console.log("user/user.profile reloaded");
						require(['models/left_menu'], function (k) {
							debug_mode.flag && console.log("models/left_menu reloaded");
							$(document).trigger("user_func_loaded");
						});
					});

					$(document).unbind("user_func_loaded");
					$(document).bind("user_func_loaded", function () {
						debug_mode.flag && console.log("user func reloaded");

						func_dir_view.initialize();
						func_menuList_view.initialize();

						_.each(func_menuList_view.collection.models, function (item) {
							_.each(item.attributes.children, function (child) {
								try {
									child.fav = 0;
									if (favorite_funclist[child.num]) {
										child.fav = favorite_funclist[child.num];
									}
								} catch (e) {
									debug_mode.flag && console.log("user.profile.js read error!!");
								}
							}, this);
						}, this);
					});
				}
			} else if (system_msg["SETMAINT"]) {
				$('<div />').html(langs.getText("iw_common","setmaint")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
			} else if (system_msg["EXISTMAINT"]) {
				var this_index = $('#' + active_base + ' .nav-tabs-main .active').index();

				$('#' + active_base + ' .nav-tabs-main .active').removeClass('active').children().children('img').remove();
				$('#' + active_base + ' .tab-content-main .active').removeClass('active');
				$('#' + active_base + ' .nav-tabs-main li:eq(' + (this_index + 1) + ')').addClass('active').children().css('color', '').append("<img src='img/refresh_icon.png' class='icon_refresh' title='" + langs.getText("toolTip","tip_refreshtab") + "' />");
				$('#' + active_base + ' .tab-content-main .tab-pane-main:eq(' + (this_index + 1) + ')').addClass('active');

				ap.render_pgm = $('#' + active_base + ' .tab-content-main .active').attr('id');
				$('#' + ap.render_pgm).html("");
				pgm_models.get_func_model(ap.render_pgm, true);
				break;
			} else if (system_msg["ACTSTB_CHANGE_FAIL"]) {
				$('.loadingPane').hide();
				$('<div />').html(langs.getText(lang_error_msg_type,"change_fail")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
				break;
			} else if (system_msg["SEND_MAIL_RESULT"]) {
				$('.loadingPane').hide();
				$('<div />').html(langs.getText(lang_common_type,system_msg["SEND_MAIL_RESULT"][0].V) + "<br>" + system_msg["SEND_MAIL_RESULT"][0].C).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
				break;
			} else if (system_msg["CONTINUE_STAT"]) {
				if (devmonitor_popup && !devmonitor_popup.closed) {
					render_cancel_flag = true;
					mappingToModel(operationCode, rangeType, range, operationValue, render_cancel_flag);
				}
				break;
			} else if (system_msg["SET_SPD_TYPE"]) {
				$('<div />').html(langs.getText("p100","popup_ch_spdtype_1") + "<br>" + langs.getText("p100","popup_ch_spdtype_2")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"refresh"),
							click: function () {
								location.href = location.href.replace(/#$/, '')
								$(this).dialog("destroy");
							}
						}
					]
				});
				break;
			} else if (system_msg["REQUEST_LDAP_SEARCH"]) {
				$('<div />').html(langs.getText("up005","request_ldapsearch")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								var send_msg = "{\"LDAP_SEARCH\":\"" + system_msg["REQUEST_LDAP_SEARCH"][0].V + "\"}";
								debug_mode.flag && console.log(send_msg);
								var range_type = [];
								var range_val = [];
								packet.setPacket(1, range_type, range_val, send_msg);
								sendMsg(packet.main, "pgmup005", packet.type, packet.range, packet.msg);
								$(this).dialog("destroy");
							}
						},
						{
							text: langs.getText(lang_common_type,"cancel"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
			} else if (system_msg["NO_RESULTS_FOUND"]) {
				$('<div />').html(langs.getText("up005","no_results_found")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
			} else if (system_msg["CLICKCALL_FAIL"]) {
				var clickcall_fail_reason = "";
				if (system_msg["CLICKCALL_FAIL"][0].V == "1") {
					clickcall_fail_reason = langs.getText("up005","clickcall_fail_reason1");
				} else if (system_msg["CLICKCALL_FAIL"][0].V == "2") {
					clickcall_fail_reason = langs.getText("up005","clickcall_fail_reason2");
				} else if (system_msg["CLICKCALL_FAIL"][0].V == "3") {
					clickcall_fail_reason = langs.getText("up005","clickcall_fail_reason3");
				} else if (system_msg["CLICKCALL_FAIL"][0].V == "4") {
					clickcall_fail_reason = langs.getText("up005","clickcall_fail_reason4");
				}
				
				$('<div />').html(langs.getText("up005","clickcall_fail")+" "+clickcall_fail_reason).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"simple_okay"),
							click: function () {
								$(this).dialog("destroy");
							}
						}
					]
				});
			} else if (system_msg["CRRCHANGE"]) {
				$('<div />').html(langs.getText("common2","sys_con_changed")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"refresh"),
							click: function () {
								location.href = location.href.replace(/#$/, '')
								$(this).dialog("destroy");
							}
						}
					]
				});
			} else if (system_msg["SVUVM_CHANGED"]) {
				$('<div />').html(langs.getText("common2","sys_con_changed")).dialog({
					modal: true,
					closeOnEscape: false,
					title: langs.getText(lang_common_type,"notification"),
					open: function (event, ui) {
						$(".ui-dialog-titlebar-close").hide();
					},
					buttons: [
						{
							text: langs.getText(lang_common_type,"refresh"),
							click: function () {
								location.href = location.href.replace(/#$/, '')
								$(this).dialog("destroy");
							}
						}
					]
				});
         }
         
         if (ap.render_pgm == "pgm86") {
				var req_model_name = "";
				var req_model_names = new Array();
         
				for (var tmp_keys in system_msg) {
					if (tmp_keys.match("WADLOG_PGMNUM")) {
						req_model_name = $.trim(system_msg[tmp_keys][0].V);
					} else if (tmp_keys.match("WADLOG_ATTR") && $.trim(system_msg[tmp_keys][0].V).length && !pgm_views[req_model_name]) {
						if (req_model_names.length > 0) {
							for (var idx=0; idx<req_model_names.length; idx++) {
								if (!req_model_names[idx].match(req_model_name)) {
									req_model_names.push("models/" + req_model_name + "_model");
								}
							}
						} else {
							req_model_names.push("models/" + req_model_name + "_model");
						}
					}
				}
				
				if (req_model_names.length > 0) {
					require(req_model_names, function () {
						var tmp_model_name = "";
						
						for (var idx=0; idx<req_model_names.length; idx++) {
							tmp_model_name = req_model_names[idx].replace("models/","").replace("_model","");
						
							debug_mode.flag && console.log(tmp_model_name + " required...");
							pgm_models[tmp_model_name] = arguments[idx];
							var tmp_pgm_model = $.extend(true, {}, pgm_models[tmp_model_name]);

							pgm_views[tmp_model_name] = new pgm_ModelsView(tmp_pgm_model);

							pgm_name_maps.make_map(tmp_model_name);
							pgm_key_maps.make_map(tmp_model_name);
						}
						
						mappingToModel(operationCode, rangeType, range, operationValue, render_cancel_flag);
					});
				} else {
					mappingToModel(operationCode, rangeType, range, operationValue, render_cancel_flag);
				}
			} else if (ap.render_pgm == "iw001") {
				// Unified R4.0.8 MP QV 72705 - Install Wizard Step 2에서 Prev Button으로 Step 1로 돌아올때 Step 체크를 위해 보낸 Websocket Message가 돌아오면서 Step 2가 같이 Render 되던 부분을 Skip하도록 수정
         } else {
				mappingToModel(operationCode, rangeType, range, operationValue, render_cancel_flag);
			}
      }
   } else {
      // size가 일치 하지 않음.
      //alert("invalid message size");
   }
}

function utf8CharByteSize(ch) {
   if (ch == null || ch.length == 0) {
      return 0;
   }

   var charCode = ch.charCodeAt(0);

   if (charCode <= 0x00007F) {
      return 1;
   } else if (charCode <= 0x0007FF) {
      return 2;
   } else if (charCode <= 0x00FFFF) {
      return 3;
   } else {
      return 4;
   }
}

function utf8StringByteSize(str) {
   if (str == null || str.length == 0) {
      return 0;
   }

   var size = 0;
   for (var i = 0; i < str.length; i++) {
      size += utf8CharByteSize(str.charAt(i));
   }

   return size;
}

function utf8ByteStringLength(str, operationValueSize) {
   if (str == null || str.length == 0) {
      return 0;
   }

   var size = 0;
   var length = 0;
   for (var i = 0; i < str.length; i++) {
      size += utf8CharByteSize(str.charAt(i));
      if (size == operationValueSize) {
         length = i + 1;
         break;
      }
   }

   return length;
}

function makeRandomSyncCode() {
   var characters = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var code = "";
   var ran = 0;

   for (var x = 0; x < 8; x++) {
      ran = Math.floor(Math.random() * characters.length);
      code += characters.charAt(ran);
   }

   return code;
}

function mappingToModel(pgm, rangeType, range, msg, render_cancel_flag) {
   var get_num = null;
   var rcv_msg = null;
   var col_history = [];
   col_history[0] = null;
   col_history[1] = null;
   var new_form = null;
   var form_name_maps = new Object;

   pgm = pgm.replace(/\s/g, "");

   debug_mode.flag && console.log(pgm);
   debug_mode.flag && console.log(msg);

   //msg = msg.replace(/^\{|\}$/g,"");
   //debug_mode.flag && console.log(msg);
   try {
      rcv_msg = JSON.parse(msg);
   } catch (e) {
      debug_mode.flag && console.log(e);
      $('.loadingPane').hide();
      $('<div />').html(langs.getText(lang_error_msg_type,"error_parsemsg")).dialog({
         modal: true,
         closeOnEscape: false,
         title: langs.getText(lang_common_type,"notification"),
         open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
         },
         buttons: [
				{
					text: langs.getText(lang_common_type,"refresh"),
					click: function () {
						location.href = location.href.replace(/#$/, '')
						$(this).dialog("destroy");
					}
				}
			]
      });
      return false;
   }

   debug_mode.flag && console.log(rcv_msg);

   if (rcv_msg["RANGE_ERROR"]) {
      if (rcv_msg["RANGE_ERROR"][0].V) {
         pgm_name_maps[pgm]["RANGE_ERROR"].value = rcv_msg["RANGE_ERROR"][0].V;
         if (ap.render_pgm == "pgm58") {
            pgm_views[ap.render_pgm].render();
         } else {
            pgm_models.get_model(ap.render_pgm, true, packet);
         }
         return false;
      }
   }

   if (range) {
      for (var rangeIndex = 0; rangeIndex < range.length; rangeIndex++) {
			if(pgm_name_maps[pgm]["RANGE_VIEW_" + (rangeIndex + 1)]) {
				pgm_name_maps[pgm]["RANGE_VIEW_" + (rangeIndex + 1)].value = range[rangeIndex];
         }
      }
   }
   
   if (rangeType) {
      for (var rangeIndex = 0; rangeIndex < rangeType.length; rangeIndex++) {
			if(pgm_name_maps[pgm]["RANGE_TYPE_" + (rangeIndex + 1)]) {
				pgm_name_maps[pgm]["RANGE_TYPE_" + (rangeIndex + 1)].range_type = rangeType[rangeIndex];
         }
      }
   }

   for (var key in rcv_msg) {
      if (pgm_name_maps[pgm][key]) {
         debug_mode.flag && console.log(key + " is exist!!");

         pgm_name_maps[pgm][key].value = rcv_msg[key][0].V;
         pgm_name_maps[pgm][key].message = rcv_msg[key][0].C;
         pgm_name_maps[pgm][key].error = rcv_msg[key][0].E;
      } else {
         if (pgm_views[pgm]) {
            if (nameInDataform(pgm, key)) {
               col_history[0] = col_history[1];
               get_num = key.split("_");
               col_history[1] = get_num[get_num.length - 1];

               if (col_history[0] != col_history[1]) {
                  if (col_history[0] != null) {
                     debug_mode.flag && console.log(new_form);
                     _.each(pgm_views[pgm].collection.models[0].attributes.elements[0].tab, function (tabs, i) {
                        if (tabs.variable_data) {
                           pgm_views[pgm].collection.models[0].attributes.elements[0].tab[i].variable_data.push(new_form);
                        }
                     });
                  }

                  _.each(pgm_views[pgm].collection.models[0].attributes.elements[0].tab, function (items) {
                     if (items.data_form) {
                        new_form = $.extend(true, {}, items.data_form[0]);

                        if (new_form.struct) {
                           _.each(new_form.struct, function (item) {
										if(item.tr) {
											_.each(item.tr, function (td) {
												if (td.name) {
													form_name_maps[td.name] = td;
												}
											});
                              } else if(item.th) {
											_.each(item.th, function (th) {
												if (th.name) {
													form_name_maps[th.name] = th;
												}
											});
                              }
                           });
                        } else if (new_form.tr) {
                           _.each(new_form.tr, function (item) {
                              if (item.name) {
                                 form_name_maps[item.name] = item;
                              }
                           });
                        } else if (new_form.th) {
                           _.each(new_form.th, function (item) {
                              if (item.name) {
                                 form_name_maps[item.name] = item;
                              }
                           });
                        }
                        debug_mode.flag && console.log(form_name_maps);
                     }
                  });

                  if (form_name_maps["CHECKLIST"]) {
                     form_name_maps["CHECKLIST"].radio[0].value = col_history[1];
                  }
               }
               pushToModel(pgm, key, rcv_msg[key][0], form_name_maps);
            }
         } else {
            debug_mode.flag && console.log("This PGM don't have a view!!");
         }
      }
   }
   if (new_form != null) {
      _.each(pgm_views[pgm].collection.models[0].attributes.elements[0].tab, function (tabs, i) {
         if (tabs.variable_data) {
            pgm_views[pgm].collection.models[0].attributes.elements[0].tab[i].variable_data.push(new_form);
         }
      });
   }
   
   if ( (pgm == "pgm110") || (pgm == "pgm1131") || (pgm == "pgm124") || (pgm == "pgm1272") || (pgm == "pgm227") ) {		
      _.each(pgm_views[pgm].collection.models[0].attributes.elements[0].tab, function (tabs, i) {
         if (tabs.variable_data) {
			pgm_views[pgm].collection.models[0].attributes.elements[0].tab[i].variable_data.sort(function (a, b) { 
				if (a.tr && b.tr) {
					if (a.tr[0].value && b.tr[0].value) {
						return a.tr[0].value < b.tr[0].value ? -1 : a.tr[0].value > b.tr[0].value ? 1 : 0;
					}
				}
			});
         }
      });
   }

	if (render_cancel_flag) {
		if (pgm == "pgm98") {
			$(document).trigger("cont_msg_recieved");
		}
	} else {
		$(document).trigger("Stand_by");
	}
}

function pushToModel(pgm, name, rcv_msg, form_name_maps) {
   var tmp_name = name.replace(/\_\d*$/, "");

   if (form_name_maps[tmp_name]) {
      debug_mode.flag && console.log(tmp_name);
      form_name_maps[tmp_name].name = name;
      form_name_maps[tmp_name].value = rcv_msg.V;
      if (rcv_msg.C) {
         debug_mode.flag && console.log("have message");
         form_name_maps[tmp_name].message = rcv_msg.C;
      }
      if (rcv_msg.E) {
         debug_mode.flag && console.log("have error message");
         form_name_maps[tmp_name].error = rcv_msg.E;
      }
      debug_mode.flag && console.log(form_name_maps[tmp_name]);
   }
}

function nameInDataform(pgm, name) {
   var tmp_name = name.replace(/\_\d*$/, "");
   var ex_flag = false;

   _.each(pgm_views[pgm].collection.models[0].attributes.elements[0].tab, function (items) {
      if (items.data_form) {
         if (items.data_form[0].struct) {
            _.each(items.data_form[0].struct, function (item) {
					if(item.tr) {
						_.each(item.tr, function (td) {
							if (td.name) {
								if (td.name == tmp_name) {
									ex_flag = true;
								}
							}
						});
               } else if(item.th) {
						_.each(item.th, function (th) {
							if (th.name) {
								if (th.name == tmp_name) {
									ex_flag = true;
								}
							}
						});
               }
            });
         } else if (items.data_form[0].tr) {
            _.each(items.data_form[0].tr, function (item) {
               if (item.name) {
                  if (item.name == tmp_name) {
                     ex_flag = true;
                  }
               }
            });
         } else if(items.data_form[0].th) {
            _.each(items.data_form[0].th, function (item) {
               if (item.name) {
                  if (item.name == tmp_name) {
                     ex_flag = true;
                  }
               }
            });
         }
      }
   });

   if (ex_flag) {
      debug_mode.flag && console.log(name + " is exist in dataform!!");
      return true;
   } else {
      debug_mode.flag && console.log(name + " is not in dataform!!");
      return false;
   }
}
