pgm_models.get_model = function (pgm, p) {
	var real_pgm = ap.render_pgm;

   if (pgm_views[pgm]) {
      debug_mode.flag && console.log(pgm + " exist...");

      _.each(pgm_views[pgm].collection.models[0].attributes.elements, function (tabs, i) {
			_.each(tabs.tab, function (tab, j) {
				if (tab.variable_data) {
					debug_mode.flag && console.log(pgm + " has variable data!!");
					pgm_views[pgm].collection.models[0].attributes.elements[i].tab[j].variable_data.splice(1, pgm_views[pgm].collection.models[0].attributes.elements[i].tab[j].variable_data.length);
					// 특정한 Table 형태 구성을 위해 Dataform과 Variable Data가 따로 떨어져 있을 경우 Funtion Base Program에 이 Variable Data를 삽입하기 위해 Variable Data의 첫번째 자리는 항상 빈 오브젝트로 채우도록 수정
					// 이에 따라 Variable Data 초기화 시에서 1부터 Variable Data의 Length 만큼 초기화 함 (빈 오브젝트는 Render 시에 아무런 영향을 주지 않음)
				}
         });
      });

      pgm_views["selected_pgm"] = pgm_views[pgm];

      sendMsg(p.main, pgm, p.type, p.range, p.msg);

      $(document).unbind("Stand_by");
      $(document).bind("Stand_by", function () {
         pgm_views[pgm].render();
         debug_mode.flag && console.log("this pgm : " + pgm + " render event received");
      });
   } else {
      require(['models/' + pgm + "_model"], function (model) {
         debug_mode.flag && console.log(pgm + " required...");
         pgm_models[pgm] = model;
         var tmp_pgm_model = $.extend(true, {}, pgm_models[pgm]);

         pgm_views[pgm] = new pgmup_ModelsView(tmp_pgm_model);

         pgm_name_maps.make_map(pgm);
         pgm_key_maps.make_map(pgm);

         pgm_views["selected_pgm"] = pgm_views[pgm];

         if (pgm_views[pgm]) {
            sendMsg(p.main, pgm, p.type, p.range, p.msg);

            $(document).unbind("Stand_by");
            $(document).bind("Stand_by", function () {
               pgm_views[pgm].render();
               debug_mode.flag && console.log("this pgm : " + pgm + " render event received");
            });
         }
      });
   }
}

pgm_name_maps.make_map = function (pgm) {
   var tmpobj = [];

   _.each(pgm_views[pgm].collection.models[0].attributes.elements, function (col) {
      $.map(col.tab, function (item) {
         if (item.tr) {
            _.each(item.tr, function (v) {
               if (v.name) {
                  tmpobj[v.name] = v;
               }
            });
         } else if (item.contents) {
            _.each(item.contents, function (v) {
               if (v.name) {
                  tmpobj[v.name] = v;
               }
            });
         } else if (item.struct) {
            _.each(item.struct, function (s) {
               if (s.tr) {
                  _.each(s.tr, function (v) {
                     if (v.name) {
                        tmpobj[v.name] = v;
                     }
                  });
               } else if(s.th) {
                  _.each(s.th, function (v) {
                     if (v.name) {
                        tmpobj[v.name] = v;
                     }
                  });
               }
            });
         } else if (item.table) {
            _.each(item.table, function (v) {
               if (v.name) {
                  tmpobj[v.name] = v;
               }
            });
         } else if (item.table_striped) {
            _.each(item.table_striped, function (v) {
               if (v.name) {
                  tmpobj[v.name] = v;
               }
            });
         } else if (item.th) {
            _.each(item.th, function (v) {
               if (v.name) {
                  tmpobj[v.name] = v;
               }
            });
         }

      });
   });
   pgm_name_maps[pgm] = tmpobj;
}

pgm_key_maps.make_map = function (pgm) {
   var tmpkey = [];

   _.each(pgm_views[pgm].collection.models[0].attributes.elements, function (col) {
      $.map(col.tab, function (item) {
         if (item.key) {
            tmpkey[item.key] = item;
         }
      });
   });
   pgm_key_maps[pgm] = tmpkey;
}

$(document).on('click', '.pgm a', function (e) {
	e.preventDefault();
});

var isTouchDevice = ("ontouchstart" in document.documentElement);

$(function() {
	if (offline_mode) {
		$('<div />').html(langs.getText("up_error_msg","alert_owadisable")).dialog({
			modal: true,
			closeOnEscape: false,
			title: langs.getText("up_common","notification"),
			open: function (event, ui) {
				$(".ui-dialog-titlebar-close").hide();
			},
			buttons: [
				{
					text: langs.getText("up_common","simple_okay"),
					click: function () {
						$(this).dialog("destroy");
					}
				}
			]
		});
		return false;	
	}
	$('html, body').css('font-family','arial');
	
	$(".up_main_menu").niceScroll();
	
	if (!isTouchDevice) {
		$('.pgm').addClass('hover_allowed');
	}
	
	$('.pgm:eq(0)').addClass('active');
	packet.setPacket(1, [], [], "{\"AD_STAGRP\":\"" + localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]") + "\", \"AD_REASON\":\"" + localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]") + "\"}");
	debug_mode.flag && console.log("g_acdstngrpnum["+info.STN_NUM+"] = "+localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]")+", g_acdoffreason["+info.STN_NUM+"] = "+localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]"));
	pgm_models.get_model("pgmup001", packet);
});

$(window).resize(function () {
	$(".up_main_menu").getNiceScroll().resize();
	$(".up_main_menu").getNiceScroll(0).doScrollLeft(0);

	if ($('.ui-dialog').is(':visible')) {
		$('.ui-dialog').position({my: "center", at: "center", of: window});
	}
	
	if ($('.up_hotkey_pane').is(':visible')) {
		$('.up_hotkey_pane').css('top','').css('left',($(window).width()/2) - 161);
	}
	
	if ($('.pgm.active a').attr('href').replace("#", "").trim() == "pgmup005") {
		if ($(window).width() >= 568) {
			if ($('.up_sel_search_priority').hasClass('ldap')) {
				$('.up_sel_search_priority .btn_txt').text(langs.getText("up005","ldap"));
			} else {
				$('.up_sel_search_priority .btn_txt').text(langs.getText("up005","system"));
			}
		} else {
			if ($('.up_sel_search_priority').hasClass('ldap')) {
				$('.up_sel_search_priority .btn_txt').text("L");
			} else {
				$('.up_sel_search_priority .btn_txt').text("S");
			}
		}
	}
});

$(document).on('click', '.pgm', function (e) {
	var pgm = $(this).children().attr("href").replace("#", "");
   var range_type = [];
   var range = [];
   
	if (offline_mode) {
		$('<div />').html(langs.getText("up_error_msg","alert_owadisable")).dialog({
			modal: true,
			closeOnEscape: false,
			title: langs.getText("up_common","notification"),
			open: function (event, ui) {
				$(".ui-dialog-titlebar-close").hide();
			},
			buttons: [
				{
					text: langs.getText("up_common","simple_okay"),
					click: function () {
						$(this).dialog("destroy");
					}
				}
			]
		});
		return false;
	}

	$('.pgm').removeClass('active');
	$(this).addClass('active');
	
	if (pgm == "pgmup001") {
		packet.setPacket(1, range_type, range, "{\"AD_STAGRP\":\"" + localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]") + "\", \"AD_REASON\":\"" + localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]") + "\"}");
		debug_mode.flag && console.log("g_acdstngrpnum["+info.STN_NUM+"] = "+localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]")+", g_acdoffreason["+info.STN_NUM+"] = "+localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]"));
	} else {
		packet.setPacket(0, range_type, range, "{}");
	}
	pgm_models.get_model(pgm, packet);
});

$(document).on('click', '.btn.up_save', function (e) {
	var pgm = $('.up_main_menu .pgm.active').children().attr("href").replace("#", "");
   var range_type = [];
   var range = [];
   var pre_msg = [];
   var tmp_name = "";
   var tmp_value = "";
   var dont_save_flag = false;
   
   $('.up_pgm_pane .error_txt').remove();

	_.each($('.up_pgm_pane').find('input, select'), function (elem) {
		if (!elem.disabled && elem.name && (elem.name != "undefined") && ($(elem).is(':visible') || (elem.type == "hidden")) && (elem.name != "CHKFLAG") && !$(elem).hasClass('dont_save')) {
			if ((elem.type == "radio") && (elem.checked == false)) {
				return true;
			}
		
         tmp_name = "";
         tmp_value = "";
		
			tmp_name = "\"" + elem.name + "\"";
			
			if (elem.name) {
				if (elem.name == "AD_STAGRP") {
					localStorage.setItem("g_acdstngrpnum["+info.STN_NUM+"]", elem.value);
					debug_mode.flag && console.log("g_acdstngrpnum["+info.STN_NUM+"] = "+localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]"));
				} else if (elem.name == "AD_REASON") {
					localStorage.setItem("g_acdoffreason["+info.STN_NUM+"]", elem.value);
					debug_mode.flag && console.log("g_acdoffreason["+info.STN_NUM+"] = "+localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]"));
				}
			}
			
			if (elem.value) {
				if (!elem.className.match('enable_mullang')) {
					if (elem.value.match(/[^a-zA-Z0-9\s\{\}\[\]\/?.,;:|\)*~`!^\-_+┼<>@\#$%&\'\(\=\\]/g)) {
						dont_save_flag = true;
						$(elem).addClass('error');
						$(elem).after("<div class='error_txt'>"+langs.getText("error_msg","error_mullang")+"</div>");
						return false;
               }
            }
            
            if (elem.value.match(/[\f\r\t\v\n\"]/g)) {
					dont_save_flag = true;
					$(elem).addClass('error');
					$(elem).after("<div class='error_txt'>"+langs.getText("error_msg","error_mullang")+"</div>");
					return false;
            }
            
            if (elem.type && (elem.type == "password")) {
					if(!offline_mode) {
						tmp_value = "\"" + RSA.encrypt(elem.value, $key) + "\"";
					} else {
						tmp_value = "\"" + elem.value + "\"";
					}
            } else {
				tmp_value = "\"" + elem.value + "\"";
            }
			} else {
				tmp_value = "\"\"";
			}
			
         pre_msg.push({
            name: tmp_name,
            value: tmp_value
         });
		}
	});
	
	if (dont_save_flag) {
		return false;
	}
	
   send_msg = "{";
   _.each(pre_msg, function (item, i) {
      send_msg += item.name + ":" + item.value;
      if (i !== pre_msg.length - 1) {
         send_msg += ",";
      }
   });
   send_msg += "}";
   
   packet.setPacket(1, range_type, range, send_msg);
	pgm_models.get_model(pgm, packet);
});

$(document).on('click', '.up_btn_dir_search', function (e) {
	up_dir_search_func();
});

$(document).on('keypress', '.up_txt_dir_search', function (e) {
	if (event.keyCode === 13) {
		up_dir_search_func();
	}
});

function up_dir_search_func () {
	var pgm = $('.up_main_menu .pgm.active').children().attr("href").replace("#", "");
	var send_msg = "";
	var search_name = "";
	
	if ($('.up_sel_search_priority').hasClass('system')) {
		search_name = "SYS_SEARCH";
	} else if ($('.up_sel_search_priority').hasClass('ldap')) {
		search_name = "LDAP_SEARCH";
	}
	
	send_msg = "{\"" + search_name + "\":\"" + $('.up_txt_dir_search').val() + "\"}";
	packet.setPacket(1, [], [], send_msg);
	pgm_models.get_model(pgm, packet);
}

$(document).on('click', '.btn_clickcall', function (e) {
	var pgm = $('.up_main_menu .pgm.active').children().attr("href").replace("#", "");
	var send_msg = "";
	
	send_msg = "{\"CLICKCALL\":\"" + $(this).siblings('input:hidden').val().trim() + "\"}";
	sendMsg(1, pgm, [], [], send_msg);
   $(document).unbind("Stand_by");
   $(document).bind("Stand_by", function () {
   });
});

$(document).on('click', '.btn_hotkey_save', function (e) {
	if ($(this).attr('name') && $(e.target).attr('value') && ($(e.target).attr('value') != $(this).children('.active').attr('value'))) {
		var send_msg = "";
	
		if ($(this).attr('name') == "CFW_ENABLE") {
			send_msg += "{\"CFW_COND\":\"" + pgm_name_maps["pgmup001"]["CFW_COND"].value + "\", \"CFW_DESTTYPE\":\"" + pgm_name_maps["pgmup001"]["CFW_DESTTYPE"].value + "\", \"CFW_DEST\":\"" + pgm_name_maps["pgmup001"]["CFW_DEST"].value + "\", \"" + $(this).attr('name') + "\":\"" + $(e.target).attr('value') + "\", ";
		} else {
			send_msg += "{\"" + $(this).attr('name') + "\":\"" + $(e.target).attr('value') + "\", ";
		}
		
		send_msg += "\"AD_STAGRP\":\"" + localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]") + "\", \"AD_REASON\":\"" + localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]") + "\"}";
		debug_mode.flag && console.log("g_acdstngrpnum["+info.STN_NUM+"] = "+localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]")+", g_acdoffreason["+info.STN_NUM+"] = "+localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]"));

		packet.setPacket(1, [], [], send_msg);
		make_hotkey_list(packet);
	}
});


$(document).on('click', '.up_hotkey_btn', function (e) {
	if (offline_mode) {
		$('<div />').html(langs.getText("up_error_msg","alert_owadisable")).dialog({
			modal: true,
			closeOnEscape: false,
			title: langs.getText("up_common","notification"),
			open: function (event, ui) {
				$(".ui-dialog-titlebar-close").hide();
			},
			buttons: [
				{
					text: langs.getText("up_common","simple_okay"),
					click: function () {
						$(this).dialog("destroy");
					}
				}
			]
		});
		return false;	
	}
	
	packet.setPacket(1, [], [], "{\"AD_STAGRP\":\"" + localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]") + "\", \"AD_REASON\":\"" + localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]") + "\"}");
	debug_mode.flag && console.log("g_acdstngrpnum["+info.STN_NUM+"] = "+localStorage.getItem("g_acdstngrpnum["+info.STN_NUM+"]")+", g_acdoffreason["+info.STN_NUM+"] = "+localStorage.getItem("g_acdoffreason["+info.STN_NUM+"]"));
	make_hotkey_list(packet);
	
	$('.up_hotkey_pane').css('top','').css('left',($(window).width()/2) - 161);
	$('.up_hotkey_overlay').css('display','table');
	$('.up_hotkey_btn').addClass('active');
});

$(document).on('click', '.up_hotkey_close_btn', function (e) {
	$('.up_hotkey_overlay').css('display','none');
	$('.up_hotkey_btn').removeClass('active');
});

$(document).on('click', '.up_more_btn', function (e) {
	if($('.up_more_btn').hasClass('active')) {
		$('.up_more_btn').removeClass('active');
		$('.up_more_btn .up_more_list').hide();
	} else {
		$('.up_more_btn').addClass('active');
		$('.up_more_btn .up_more_list').show();
	}
	e.stopPropagation();
});

function onRefresh() {
   skipConfirm_flag = true;
}

window.onbeforeunload = onRefresh;

$(document).click(function(e) {
	if($('.up_more_btn').hasClass('active')) {
		$('.up_more_btn').removeClass('active');
		$('.up_more_btn .up_more_list').hide();
	}
});

$(document).on('click', '.up_more_list', function (e) {
   var send_msg = "";
   var range_type = [];
   var range = [];

	if (e.target.className.match("item_oldweb")) {
		location.href = location.origin + "/s_index.html";
	} else if (e.target.className.match("item_chlang")) {
		if (e.target.className.match("ch_local")) {
			$(".up_more_list .item_chlang").removeClass("ch_local").addClass("ch_eng").text(langs.getText("common","top_menu_chlang") + " (" + langs.getText("common","simple_eng") + ")");
			send_msg = "{\"CH_LANG\":\"1\"}";
		} else if (e.target.className.match("ch_eng")) {
			$(".up_more_list .item_chlang").removeClass("ch_eng").addClass("ch_local").text(langs.getText("common","top_menu_chlang") + " (" + langs.getText("common","local") + ")");
			send_msg = "{\"CH_LANG\":\"0\"}";
		}
		packet.setPacket(1, range_type, range, send_msg);
		sendMsg(packet.main, "pgm97", packet.type, packet.range, packet.msg);
	} else if (e.target.className.match("item_logout")) {
		send_msg = "{\"LOGOUT\":\"\"}";
		debug_mode.flag && console.log(send_msg);
		
		skipConfirm_flag = true;
		logout_flag = true;
		
		packet.setPacket(1, range_type, range, send_msg);
		sendMsg(packet.main, "pgm50", packet.type, packet.range, packet.msg);

		$(document).unbind("Log_out");
		$(document).bind("Log_out", function () {
			debug_mode.flag && console.log("Log Out");
			location.href = location.origin;
		});
	}
});

$(document).on('focusin', 'input:text, input:password, input:radio, select', function (e) {
	if($(this).parents('td, th').find('.note') && !$(this).parents('td, th').find('.note').hasClass('active') && $(this).is(':enabled')) {
		$(this).parents('td, th').find('.note').addClass('active');
	}
});

$(document).on('focusout', 'input:text, input:password, input:radio, select', function (e) {
	if($(this).parents('td, th').find('.note') && $(this).parents('td, th').find('.note').hasClass('active')) {
		$(this).parents('td, th').find('.note').removeClass('active');
	}
});

if (!isTouchDevice) {
	$(document).on('mouseenter', 'input:text, input:password, input:radio, select', function (e) {
		if($(this).parents('td, th').find('.note') && !$(this).parents('td, th').find('.note').hasClass('active') && $(this).is(':enabled')) {
			$(this).parents('td, th').find('.note').addClass('active');
		}
	});

	$(document).on('mouseleave', 'input:text, input:password, input:radio, select', function (e) {
		if($(this).parents('td, th').find('.note') && $(this).parents('td, th').find('.note').hasClass('active') && !$(this).is(':focus')) {
			$(this).parents('td, th').find('.note').removeClass('active');
		}
	});
}

$(document).on('click', '.chk_checkall', function (e) {
	var end_idx = 0;

	if (e.target.checked) {
		$(this).parents('tr').find('input.dont_save, select.dont_save').not(this).removeClass('dont_save');
		
		if ($(this).parents('td').attr('rowspan')) {
			end_idx = eval($(this).parents('td').attr('rowspan'));
		
			for (var i=0; i<end_idx-1; i++) {
				$(this).parents('tr').nextAll().eq(i).find('input.dont_save, select.dont_save').not(this).removeClass('dont_save');
			}
		}
	} else {
		$(this).parents('tr').find('input, select').not('.dont_save').not(this).addClass('dont_save');
		
		if ($(this).parents('td').attr('rowspan')) {
			end_idx = eval($(this).parents('td').attr('rowspan'));
		
			for (var i=0; i<end_idx-1; i++) {
				$(this).parents('tr').nextAll().eq(i).find('input, select').not('.dont_save').not(this).addClass('dont_save');
			}
		}
	}
});

$(document).on('change', '.up001_psm_sel', function (e) {
	if ($(this).parents('tr').next().children('td').length > 2) {
		for (var i=1; i<$(this).parents('tr').next().children('td').length; i++) {
			$(this).parents('tr').next().children('td').eq(i).hide();
		}
	}
	
	switch ($(this).val()) {
		case "2":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_time"));
			$('.up_pgm_pane [name=PSM_VAL_2]').parents('td').show();
			break;
		case "3":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_date"));
			$('.up_pgm_pane [name=PSM_VAL_3]').parents('td').show();
			break;
		case "4":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_time"));
			$('.up_pgm_pane [name=PSM_VAL_4]').parents('td').show();
			break;
		case "5":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_date"));
			$('.up_pgm_pane [name=PSM_VAL_5]').parents('td').show();
			break;
		case "7":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_num"));
			$('.up_pgm_pane [name=PSM_VAL_7]').parents('td').show();
			break;
		case "8":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_num"));
			$('.up_pgm_pane [name=PSM_VAL_8]').parents('td').show();
			break;
		case "9":
			$(this).parents('tr').next().show().children('td').eq(0).text(langs.getText("up001","psm_val_time"));
			$('.up_pgm_pane [name=PSM_VAL_9]').parents('td').show();
			break;
		default:
			$(this).parents('tr').next().hide().children('td').eq(0).text("");
			$(this).parents('tr').next().children('td').eq(1).show();
			break;
	}
});

$(document).on('change', '.up001_arm_sel', function (e) {
	if ($(this).val() == "4") {
		$(this).parents('tr').next().show();
	} else {
		$(this).parents('tr').next().hide();
	}
});

$(document).on('click', '.up_sel_search_priority', function (e) {
	var txt_system = "";
	var txt_ldap = "";
	if ($(window).width() >= 568) {
		txt_system = langs.getText("up005","system");
		txt_ldap = langs.getText("up005","ldap");
	} else {
		txt_system = "S";
		txt_ldap = "L";
	}

	if ($(this).hasClass('system')) {
		$(this).removeClass('system');
		$(this).addClass('ldap');
		$(this).children('.btn_txt').text(txt_ldap);
	} else if ($(this).hasClass('ldap')) {
		$(this).removeClass('ldap');
		$(this).addClass('system');
		$(this).children('.btn_txt').text(txt_system);
	} else {
	
	}
});
