var pgm_Model = Backbone.Model.extend({
   defaults: {
      name: ""
   }
});

var pgm_Collection = Backbone.Collection.extend({
   model: pgm_Model
});

/*
var tmp_str = "";

var pgm_ModelView = Backbone.View.extend({
    template: Handlebars.compile($("#pgmTemplate").html()),

    render: function () {
        var pgm111_tmp = this.template;

        if(this.model.attributes.cont === 1) {
            tmp_str = pgm111_tmp(this.model.toJSON());

            $('#'+active_pgm+' td').last().append(tmp_str);
        } else {
            $(this.el).html(pgm111_tmp(this.model.toJSON()));
        }

        return this;
    }
});
*/

var pgm_ModelsView = Backbone.View.extend({
   template: Handlebars.compile($("#pgmTemplate").html()),
   attr_template: Handlebars.compile($("#make_attrTemplate").html()),
   func_template: Handlebars.compile($("#make_funcTemplate").html()),

   initialize: function (col) {
      this.collection = new pgm_Collection(col);
   },

   render: function (sel) {
		//var start_time = new Date;
		//console.log("[0.000] Start Time : "+start_time);
      var that = this;
      var mytab = this.collection.models[0].attributes.elements[0].tab;
      type_history[0] = null;
      type_history[1] = null;
      variable_order[ap.render_pgm] = 0;

      debug_mode.flag && console.log(" pgm_view.collection.models[0].attributes.elements[0].tab render_pgm:" + ap.render_pgm + " mytab.length:" + mytab.length);

      _.each(this.collection.models[0].attributes.elements, function (items) {
         _.each(items.tab, function (item, i) {
            if (item.preload) {
               no_margin_flag = false;
            }
         }, this);
      }, this);

      _.each(this.collection.models[0].attributes.elements, function (items) {
			var tbl_name = null;

         _.each(items.tab, function (item, i) {
            if (sel) {
					if(i == 0) {
						var attr_pgm = item.key.split("_");
						$("#" + ap.render_pgm + "_attrs").append("<div style='text-align:center'><input type='button' value='"+langs.getText("common","btn_chkall")+"' class='btn_checkall_attr'><input type='button' name='"+attr_pgm[0]+"' value='"+langs.getText("common","btn_save")+"' class='btn_save_attr' style='margin-left:10px'><input type='button' name='"+attr_pgm[0]+"' value='"+langs.getText("common","btn_init")+"' class='btn_init_attr' style='margin-left:10px'></div>");
					}
               that.render_attrs(item);
               if(item.table && item.title) {
						$("#" + ap.render_pgm + "_attrs div input:checkbox:last").addClass("mktbl");
						tbl_name = item.key;
               } else if((item.th || item.tr || item.struct) && item.title) {
						$("#" + ap.render_pgm + "_attrs div input:checkbox:last").addClass("tbl_tr");
						$("#" + ap.render_pgm + "_attrs div input:checkbox:last").attr("name",tbl_name);
						$("#" + ap.render_pgm + "_attrs div input:checkbox:last").attr("disabled","disabled");
               }
            } else {
					if ((active_base == "tab_function_base") && (pgm_models[ap.active_pgm].elements.length > 1) && (i == 0)) {
						if($('#'+ap.render_pgm).index() == 0) {
							$('#'+ap.render_pgm).append("<div class='top_button'><input type='button' class='btn-image btn_next' value=' "+langs.getText("common","btn_next")+" '><br></div>");
						} else if($('#'+ap.render_pgm).index() == pgm_models[ap.active_pgm].elements.length - 1) {
							$('#'+ap.render_pgm).append("<div class='top_button'><input type='button' class='btn-image btn_prev' value=' "+langs.getText("common","btn_prev")+" '><br></div>");
						} else {
							$('#'+ap.render_pgm).append("<div class='top_button'><input type='button' class='btn-image btn_prev' value=' "+langs.getText("common","btn_prev")+" '><input type='button' class='btn-image btn_next' value=' "+langs.getText("common","btn_next")+" '><br></div>");
						}
					}

					if ((active_base == "tab_install_wizard") && (i == 0)) {
						if($('#'+ap.render_pgm).index() == 0) {
							$('#'+ap.render_pgm).append("<div class='button'><input type='button' class='btn_next' value=' "+langs.getText("common","btn_next")+" '><br></div>");
						} else if($('#'+ap.render_pgm).index() == (info.NO_OF_INSTALL_WIZARD_STEP - 1)) {
							$('#'+ap.render_pgm).append("<div class='button'><input type='button' class='btn_prev' value=' "+langs.getText("common","btn_prev")+" '><input type='button' class='btn_finish' value=' "+langs.getText("common","btn_finish")+" '><br></div>");
						} else {
							$('#'+ap.render_pgm).append("<div class='button'><input type='button' class='btn_prev' value=' "+langs.getText("common","btn_prev")+" '><input type='button' class='btn_next' value=' "+langs.getText("common","btn_next")+" '><br></div>");
						}
					}

               if (item.table) {
                  if (item.table[0] && item.table[0].tbl_show_flag) {
                     if (item.table[0].value == "1") {
                        tbl_render_flag = true;
                        $("#" + ap.render_pgm).append("<div style='display:none'><input type='hidden' name='" + item.table[0].name + "' value='" + item.table[0].value + "'></div>");
                     } else {
                        tbl_render_flag = false;
                     }
                  }
               }
               that.renderModel(item);
            }
         }, this);
      }, this);

      if(sel && ($("#" + ap.render_pgm + "_attrs div").length == 1)) {
			$("#" + ap.render_pgm + "_attrs .btn_checkall_attr").hide();
			$("#" + ap.render_pgm + "_attrs .btn_save_attr").css("margin-left","0");
			$("#"+ap.render_pgm+"_attrs").append("<div class='all_attr' style='margin-bottom:0px'>"+ langs.getText("common","no_attr") + "</div>");
			$("#" + ap.render_pgm + "_attrs div:last").css("background-color", "#D9EDF7");
      }

      if (active_base == "tab_pgm_base" || active_base == "tab_function_base" || active_base == "tab_maintenance" || active_base == "tab_stn_base") {
			$('#' + ap.render_pgm).css('height', $('.row-fluid .custom_span_pgm ').height() - $('#' + active_base + ' .nav-tabs-main').height() - eval($('#' + active_base + ' .nav-tabs-main').css('margin-top').replace('px', '')) - eval($('#' + active_base + ' .nav-tabs-main').css('margin-bottom').replace('px', '')) - eval($('#' + active_base + ' .tab-pane-main').css('padding-bottom').replace('px', '')));
      } else if (active_base == "tab_install_wizard") {
			$('#' + ap.render_pgm).css('height', $('.row-fluid .custom_span_iwpgm ').height() - $('#' + active_base + ' .nav-tabs-main').height() - eval($('#' + active_base + ' .nav-tabs-main').css('margin-top').replace('px', '')) - eval($('#' + active_base + ' .nav-tabs-main').css('margin-bottom').replace('px', '')) - eval($('#' + active_base + ' .tab-pane-main').css('padding-bottom').replace('px', '')));
      }
      if((active_base == "tab_function_base") && (ap.active_pgm != "favorite_func") && (pgm_models[ap.active_pgm].elements.length > 1)) {
			$('#' + ap.render_pgm).css('height', $('#' + ap.render_pgm).height() - $('#' + ap.active_pgm+' .nav-tabs-sub').height() - eval($('#' + ap.active_pgm+' .tab-pane-sub').css('padding-top').replace('px', '')) - eval($('#' + ap.active_pgm+' .tab-pane-sub').css('padding-bottom').replace('px', '')) - eval($('#' + ap.active_pgm+' .tab-content-sub').css('margin-bottom').replace('px', '')) - eval($('#' + ap.active_pgm+' .nav-tabs-sub').css('border-bottom-width').replace('px', '')) - eval($('#' + ap.active_pgm+' .tab-content-sub').css('border-bottom-width').replace('px', '')));
      }
      /*
      if ($("#" + ap.render_pgm)[0].scrollHeight > ($('.tab-pane-main').height() * 2)) {
         $("#" + ap.render_pgm).append("<div class='btn_scroll'><i class='icon-chevron-up btn_top'></i><br><i class='icon-align-justify'></i><br><i class='icon-chevron-down btn_bottom'></i></div>");
      }
      */
      if((active_base == "tab_function_base") && (ap.active_pgm != "favorite_func") && (pgm_models[ap.active_pgm].elements.length > 1)) {
			$('#' + ap.render_pgm + ' .button').css('right', 40 - $('#' + ap.render_pgm).scrollLeft());
         $('#' + ap.render_pgm + ' .btn_scroll').css('top', 170 + $('#' + ap.render_pgm).scrollTop()).css('right', 40 - $('#' + ap.render_pgm).scrollLeft());
      }

      $('.tab-pane-main, .fav_list, .fav_edit').scroll(function () {
			if((active_base == "tab_function_base") && (ap.active_pgm != "favorite_func") && (pgm_models[ap.active_pgm].elements.length > 1)) {
				$('#' + ap.render_pgm + ' .button').css('top', $('#' + ap.active_pgm+' .tab-content-sub').scrollTop()).css('right', 40 - $('#' + ap.active_pgm+' .tab-content-sub').scrollLeft());
				$('#' + ap.render_pgm + ' .btn_scroll').css('top', 100 + $('#' + ap.active_pgm+' .tab-content-sub').scrollTop()).css('right', 40 - $('#' + ap.active_pgm+' .tab-content-sub').scrollLeft());
			} else {
				$('#' + ap.render_pgm + ' .button').css('top', $('#' + ap.render_pgm).scrollTop()).css('right', 20 - $('#' + ap.render_pgm).scrollLeft());
				$('#' + ap.render_pgm + ' .btn_scroll').css('top', 100 + $('#' + ap.render_pgm).scrollTop()).css('right', 20 - $('#' + ap.render_pgm).scrollLeft());
         }
      });

      if ($("#" + ap.render_pgm + " input[name='CHKFLAG']").val() == "1") {
         $('#' + ap.render_pgm + ' .btn_checkall').attr('value', langs.getText("common","btn_unchkall"));
         $('#' + ap.render_pgm + ' .chk_checkall').attr('checked', 'checked');
      }

      $('#' + ap.render_pgm + ' .btn_selectall').attr('value', langs.getText("common","btn_unselectall"));
      _.each($('#' + ap.render_pgm + ' .chk_selectall'), function (item) {
         //debug_mode.flag && console.log(item);
         if (!item.checked && !item.disabled) {
            $('#' + ap.render_pgm + ' .btn_selectall').attr('value', langs.getText("common","btn_selectall"));
            return false;
         }
      });

      if (!sel) {
         $("#" + ap.render_pgm).append("<br>");
      }

      if ($("#" + ap.render_pgm + " .preload").length) {
         $("#" + ap.render_pgm + " .preload input:eq(1)").focus();
      } else {
         $('#' + ap.render_pgm).scrollTop(0);
      }

      if ($('#'+ap.render_pgm).children().not('.preload').children().find('.error').length) {
			$('#'+ap.render_pgm).children().not('.preload').children().find('.error:eq(0)').prev().focus();
      }

		if (active_base != "tab_user_guide") {
			if ((info.AUTH == 1) || ((pgm_info[ap.render_pgm.replace("pgm","")]) && (pgm_info[ap.render_pgm.replace("pgm","")].auth == 1))) {
				$("#" + ap.render_pgm + " .auth_write").attr('disabled','disabled').css('cursor','default');
			}
      }
      
      if ((info.SYSTEM_ID == "iPECS eMG80" || info.SYSTEM_ID == "iPECS eMG800") && offline_mode) {
			var real_pgm = ap.render_pgm;

			if (active_base == "tab_function_base") {
				ap.render_pgm = $(this).parents('.tab-pane-sub').attr("id");
				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 ($('#'+ap.render_pgm+' .edit_table').length) {
			render_editTable();
      }

      tbl_render_flag = true;
      no_margin_flag = true;
      $('.loadingPane').hide();
		//var end_time = new Date;
		//console.log("["+((end_time.getTime() - start_time.getTime())/1000)+"] End Time : "+end_time);
   },

   renderModel: function (item) {
      var pgm_tmp = this.template;

      pgm_tmp(eval(item));
   },
   render_attrs: function (item) {
      var pgm_attr_tmp = this.attr_template;
      //debug_mode.flag && console.log("item.length:"+item.table.length);
      //debug_mode.flag && console.log("render_pgm : " + ap.render_pgm);
      $("#" + ap.render_pgm + "_attrs").append(pgm_attr_tmp(eval(item)));
      if ((item.table || item.th) && item.title) {
         $("#" + ap.render_pgm + "_attrs div:last").css("background-color", "#D9EDF7");
      } else {
         if (($("#" + ap.render_pgm + "_attrs div").length % 2) == 0) {
            if ($("#" + ap.render_pgm + "_attrs div:last").css("background-color") != "rgb(217, 237, 247)") {
               $("#" + ap.render_pgm + "_attrs div:last").css("background-color", "#eaeaea");
            }
         }
      }
   },
   render_item: function (id) {
      var make_func_tmp = this.func_template;
      // debug_mode.flag && console.log("this.collection.models.length:"+this.collection.models.length);
      debug_mode.flag && console.log(" this.collection.models[0].attributes.elements[0].tab.length:" + this.collection.models[0].attributes.elements[0].tab.length + " id:" + id);

      for (var i in this.collection.models[0].attributes.elements[0].tab) {
         var model = this.collection.models[0].attributes.elements[0].tab[i];
         tcol = model;
         //debug_mode.flag && console.log("model.key:"+model.key+" active_pgm:"+ap.active_pgm+" active_tab:"+active_tab);
         if (model.key == id) {
            debug_mode.flag && console.log("key:" + model.key + " added!! render_pgm:" + ap.render_pgm + " active_tab:" + active_tab);
            make_func_tmp(eval(model));
            break;
         }
      }

      debug_mode.flag && console.log(" render_item:" + id);
   }
});

function render_editTable () {
	var table_headers = new Array();
	var table_data = new Array();
	var tmp_row_data = null;
	var set_column_config = new Array();
	var data_index = 0;
   var real_pgm = ap.render_pgm;

   if (active_base == "tab_function_base" || active_base == "tab_install_wizard") {
      ap.render_pgm = $(this).parent().parent().attr("id");
      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;
			}
		}
   }

	_.each(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab, function(item, i) {
		if (item.edit_table) {
			data_index = i;
		}
	});

	_.each($('#'+ap.render_pgm+' .edit_table th'), function(item) {
		table_headers.push($.trim($(item).text()));
	});

	_.each($('#'+ap.render_pgm+' .edit_table tr'), function(items, i) {
		tmp_row_data = new Array();
		_.each($('#'+ap.render_pgm+' .edit_table tr:eq('+i+') td'), function(item, j) {
			tmp_row_data.push($.trim(item.firstChild.data));
		});
		if ($('#'+ap.render_pgm+' .edit_table tr:eq('+i+') td').length) {
			table_data.push(tmp_row_data);
		}
	});

   if (column_config[real_pgm]) {
		set_column_config = column_config[real_pgm];
   } else {
		var tmp_object = new Object;
		for (var i=0; i<table_headers.length; i++) {
			set_column_config.push(tmp_object);
		}
   }

	$('#'+ap.render_pgm).append('<div name=spreadsheet_table></div>')
	$('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable({
		data: table_data,
		currentRowClassName: 'currentRow',
		currentColClassName: 'currentCol',
		colHeaders: table_headers,
		columns: set_column_config,
		outsideChkboxPlugin: true,
		beforeChange: function (changes, source) {
			for (var i=0; i<changes.length; i++) {
				//debug_mode.flag && console.log("[changes] row : "+changes[i][0]+", col : "+changes[i][1]+", old_data : "+changes[i][2]+", new_data : "+changes[i][3]);
				if (real_pgm == "pgm446" || real_pgm == "pgm4461") {
					if ((changes[i][1] == 11) || (changes[i][1] == 13)) {
						if ((changes[i][3] == langs.getText("common","opt_off").toLowerCase())) {
							changes[i][3] = langs.getText("common","opt_off");
						} else if ((changes[i][3] == langs.getText("common","opt_on").toLowerCase())) {
							changes[i][3] = langs.getText("common","opt_on");
						} else if ((changes[i][3] != langs.getText("common","opt_off")) && (changes[i][3] != langs.getText("common","opt_on"))) {
							changes[i][3] = langs.getText("common","opt_off");
						}
					}
					else if (changes[i][1] == 14) {
						if ((changes[i][3] == langs.getText("p446","ucs_vstd").toLowerCase())) {
							changes[i][3] = langs.getText("p446","ucs_vstd");
						} else if ((changes[i][3] == langs.getText("p446","ucs_nvstd").toLowerCase())) {
							changes[i][3] = langs.getText("p446","ucs_nvstd");
						} else if ((changes[i][3] == langs.getText("p446","ucs_vprem").toLowerCase())) {
							changes[i][3] = langs.getText("p446","ucs_vprem");
						} else if ((changes[i][3] == langs.getText("p446","ucs_nvprem").toLowerCase())) {
							changes[i][3] = langs.getText("p446","ucs_nvprem");
						} else if ((changes[i][3] == langs.getText("p446","ucs_mobile").toLowerCase())) {
							changes[i][3] = langs.getText("p446","ucs_mobile");
						} else if ((changes[i][3] != langs.getText("p446","ucs_vstd")) && (changes[i][3] != langs.getText("p446","ucs_nvstd"))
								&& (changes[i][3] != langs.getText("p446","ucs_vprem"))&& (changes[i][3] != langs.getText("p446","ucs_nvprem"))
								&& (changes[i][3] != langs.getText("p446","ucs_mobile"))) {
							changes[i][3] = langs.getText("p446","ucs_vstd");
						}
					}
				} else {
					break;
				}
			}
		},
		cells: function (row, col, prop) {
			//debug_mode.flag && console.log("row : "+row+", col : "+col+", prop : "+prop);
			if (pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data && pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row] && pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col]) {
				var cellProperties = {};
				cellProperties.readOnly = false;
				cellProperties.valid = true;
				cellProperties.modified = false;
				cellProperties.comment = "";
				if (col === 0) {
					cellProperties.readOnly = true;
				}
				if (real_pgm == "pgm446") {
					if ((col == 1) || (col == 2)) {
						if ($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value).length != 0) {
							cellProperties.readOnly = true;
						}
					}
				}

				if ($('#'+ap.render_pgm+' [name=spreadsheet_table]').length && ($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) != $('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col])) {
					if (real_pgm == "pgm446" || real_pgm == "pgm4461") {
						if ((col == 11) || (col == 13)) {
							if (!(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "0") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("common","opt_off"))) && !(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "1") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("common","opt_on")))) {
								cellProperties.modified = true;
							}
						}
						else if (col == 14) {
							if (!(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "0") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("p446","ucs_vstd")))
							&& !(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "1") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("p446","ucs_nvstd")))
							&& !(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "2") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("p446","ucs_vprem")))
							&& !(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "3") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("p446","ucs_nvprem")))
							&& !(($.trim(pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].value) == "4") && ($('#'+ap.render_pgm+' [name=spreadsheet_table]').handsontable('getData')[row][col] == langs.getText("p446","ucs_mobile")))) {
								cellProperties.modified = true;
							}
						} else {
							cellProperties.modified = true;
						}
					} else {
						cellProperties.modified = true;
					}
				} else {
					if (pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].error) {
						cellProperties.valid = false;
						cellProperties.comment = langs.getText("error_msg",pgm_views[real_pgm].collection.models[0].attributes.elements[0].tab[data_index].variable_data[row].tr[col].error);
					}
				}
				return cellProperties;
			}
		}
	});
}
