Ext.onReady(function(){
  var selectedRow;

  Ext.BLANK_IMAGE_URL = '/system/Components/ext-2/resources/images/default/s.gif';

  Ext.QuickTips.init();
  Ext.form.Field.prototype.msgTarget = 'under';
  Ext.form.Field.prototype.height = 20;

  var ds = new Ext.data.JsonStore({
		totalProperty:'totalRows'
		,root:'rows'
		,url:'/'+hive['mnu007l']+'/mnu007l.asp'
		,remoteSort: true
	});

  var grid = new Ext.grid.GridPanel({
    renderTo:Ext.getBody()
    ,autoScroll : true
    ,enableDragDrop: true
    ,ddGroup:'grid'
    ,store: ds
    ,columns:
      [
        {header: menu.I18N['sequence'], width:60, sortable:true, dataIndex: 'SYSSEQ'}
        ,{header: menu.I18N['systemID'], width:60, sortable:true, dataIndex: 'SYSID'}
        ,{header: menu.I18N['description'], width:300, sortable:true, dataIndex: 'STXTXT'}
        ,{header: menu.I18N['systemHives'], width:100, sortable:true, dataIndex: 'SYSPTH'}
        ,{header: menu.I18N['program4LoadingMenu'], width:200, sortable:true, dataIndex: 'SYSPGM'}
        ,{header: menu.I18N['icon'], width:200, sortable:true, dataIndex: 'SYSICO'}
      ]
    ,sm: new Ext.grid.RowSelectionModel({singleSelect:true})
    ,loadMask:false
		,tbar:
			[
        {
          id:'addNew'
          ,text: menu.I18N['addNew']
          ,tooltip: menu.I18N['addNew']
          ,cls:'x-btn-text-icon mnu-tb-add'
          ,handler: onButtonClick
        }
			]
    ,autoHeight:true
  });

	var gridDropTarget = new Ext.dd.DropTarget(grid.getView().el.dom.childNodes[0].childNodes[1], {
    ddGroup    : 'grid',
    copy       : true,
    notifyDrop : function(ddSource, e, data) {
      var sourceSystemID = ds.data.items[data.rowIndex].id;
      var targetSystemID = ds.data.items[ddSource.getDragData(e).rowIndex].id;
      if (ddSource.getDragData(e).rowIndex == 0) {
        var beforeSystemID = 0;
      } else {
        beforeSystemID = ds.data.items[ddSource.getDragData(e).rowIndex-1].id;
      }

      var coords = e.getXY();
      dropWin = new Ext.Window({
        title:menu.I18N['whereToDrop']
        ,html:menu.I18N['DropBeforeOrAfter']
        ,width: 300
        ,height: 100
        ,minWidth: 60
        ,minHeight: 50
        ,buttonAlign:'center'
        ,bodyStyle:'padding:5px;'
        ,x:coords[0]
        ,y:coords[1]
        ,buttons:[
          {
            text: menu.I18N['before']
            ,handler: function() {
              var conn = new Ext.data.Connection();
              conn.request({
                url:'/'+hive['mnu007s2']+'/mnu007s2.asp?dropBorA=before&sourceSystemID='+sourceSystemID+'&targetSystemID='+targetSystemID+'&beforeSystemID='+beforeSystemID
              });
              conn.on('requestcomplete', function () {
                ds.load();
                dropWin.hide()
              });
            }
          },{
            text: menu.I18N['after']
            ,handler: function() {
              var conn = new Ext.data.Connection();
              conn.request({
                url:'/'+hive['mnu007s2']+'/mnu007s2.asp?dropBorA=after&sourceSystemID='+sourceSystemID+'&targetSystemID='+targetSystemID+'&beforeSystemID='+beforeSystemID
              });
              conn.on('requestcomplete', function () {
                ds.load();
                dropWin.hide()
              });
            }
          },{
            text: menu.I18N['cancel']
            ,handler: function() {
              dropWin.hide();
            }
          }
        ]
      });
      dropWin.show();
    }
  }); 	

  // Row system
  var rowMenu = new Ext.menu.Menu({
    id: 'rowMenu',
    items: [
      {id: 'edit', text: menu.I18N['edit'], cls:'mnu-icon-edit smd-default', handler:onRowRightClick}
    ]
  });

  grid.on('rowcontextmenu', onRowMenu);
  grid.on('rowclick', function(grid, rowIndex, e) {
    selectedRow = ds.data.items[rowIndex].id;
  });
  grid.on('rowdblclick', function(grid, rowIndex, e) {
    selectedRow = ds.data.items[rowIndex].id;
    processSystemRow(selectedRow, 'update');
  });

  ds.load({
    params: {}
  });

  // handler for grid toolbar
  function onButtonClick(btn){
    switch (btn.id) {
    case 'addNew':
      processSystemRow(0, 'create');
      break;
    }
  }

  function onRowMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    rowMenu.showAt([coords[0], coords[1]]);
    selectedRow = ds.data.items[rowIndex].id;
  }

  function onRowRightClick(item) {
    switch (item.id) {
    case 'edit':
      processSystemRow(selectedRow, 'update');
      break;
    }
  }

  var windowCount = 0;
  function processSystemRow(systemID, func) {
    // Loading store with detail data
    var action = (func == 'create') ? 'init' : 'get';
    var systemRowData = new Ext.data.JsonStore({
      url:'/'+hive['mnu007s']+'/mnu007s.asp?action='+action+'&SYSID='+systemID
    });			
    systemRowData.on('load', function() {
      var data = systemRowData.getAt(0).data;
      if (data['SYSSRHOPT'] == 'on') {
        searchOption = true;
      } else {
        searchOption = false;
      }

      var dsSysTxt = new Ext.data.JsonStore({
        totalProperty:'totalRows'
        ,root:'rows'
        ,url:'/'+hive['mnu011l']+'/mnu011l.asp?STXSYSID='+systemID
        ,id:'LNGID'
        ,fields:[
                  'LNGID'
                  ,'LNGTXT'
                  ,'STXTXT'
        ]
        ,remoteSort:false
      });
      dsSysTxt.on('load', function() {
        var sysTxtArray = new Array();
        var maxi = dsSysTxt.getTotalCount();
        for (i=0; i<=maxi-1; i++) {
          var sysTxt = new Object();
          sysTxt.xtype='textfield';
          sysTxt.fieldLabel = dsSysTxt.getAt(i).data['LNGTXT'];
          sysTxt.name = 'txt.' + dsSysTxt.getAt(i).data['LNGID'];
          sysTxt.value = dsSysTxt.getAt(i).data['STXTXT'];
          sysTxt.width = 280;
          sysTxtArray[i] = sysTxt;
        };
      // Building window & form
        var frm = new Ext.form.FormPanel({
          labelAlign: 'left'
          ,labelWidth:270
          ,border:false
          ,bodyStyle:'padding:5px 5px 0'
          ,defaults:{width:300}
          ,layout:'form'
          ,items:[
            {xtype:'textfield',fieldLabel:menu.I18N['description'],name:'STXTXT',value:data['STXTXT'],allowBlank:false}
            ,{xtype:'fieldset',title:menu.I18N['descriptionInDiffenrenceLanguage'],autoHeight:true,autoScroll:true,autoWidth:false,width:575,labelWidth:260
              ,items:sysTxtArray
            }
            ,{xtype:'textfield',fieldLabel:menu.I18N['icon'],name:'SYSICO',value:data['SYSICO']}
            ,{xtype:'ddHives',hiddenName:'SYSPTH',value:data['SYSPTH'],displayValue:data['SYSPTHTXT'],hive:hive['mnu920l'],extraRecord:menu.I18N['doNotUseHives']}
            ,{xtype:'ddHives',fieldLabel:menu.I18N['Hive4LoadingProgram'],hiddenName:'SYSBLDPTH',value:data['SYSBLDPTH'],displayValue:data['SYSBLDPTHTXT'],hive:hive['mnu920l'],extraRecord:menu.I18N['useSystemPath']}
            ,{xtype:'textfield',fieldLabel:menu.I18N['program4LoadingMenu'],name:'SYSPGM',value:data['SYSPGM']}
            ,{xtype:'checkbox',fieldLabel:menu.I18N['searchOption'],name:'SYSSRHOPT',checked:searchOption}
            ,{xtype:'textfield',fieldLabel:menu.I18N['initialCommand4IceCap'],name:'INITCMD',value:data['INITCMD']}
            ,{xtype:'textfield',fieldLabel:menu.I18N['metaFormXML'],name:'metaFormXML',value:data['metaFormXML']}
          ]
        });

        var windowID = 'mnu007-window-' + windowCount++;
        var title = (func == 'create') ? menu.I18N['addNew'] : menu.I18N['update'];
        if (!winSys) {
          var winSys = new Ice.Window({
            id: windowID
            ,title: title
            ,width: 620
            ,height: 420
            ,minWidth: 50
            ,minHeight: 50
            ,autoScroll : true
            ,bodyStyle:'padding:5px;'
            ,buttonAlign:'left'
            ,layout: 'fit'
            ,plain:true
            ,modal: false
            ,items: frm
            ,buttons: [{
              text: menu.I18N['save']
              ,type: 'submit'
              ,handler: function() {	
                if (frm.form.isValid()) {
                  frm.form.submit({
                    url:'/'+hive['mnu007s']+'/mnu007s.asp?SYSID='+systemID+'&action='+func
                    ,success: function() {
                      winSys.hide();
                      ds.load();
                    }
                  });
                }
              }
              ,key:'ENTER'
            },{
              text: menu.I18N['delete'],
              handler: function(){
                Ext.MessageBox.confirm(menu.I18N['message'], menu.I18N['confirmDelete'] , doSystemDelete);
              }
            },{
              text: menu.I18N['cancel']
              ,handler: function() {
                winSys.hide();
              }
            }]
          })
        }
        winSys.show();

        if (func == 'create') {
          winSys.buttons[1].disable();
        }

        frm.form.findField('STXTXT').focus();

        function doSystemDelete(btn) {
          if (btn == 'yes') {
            frm.form.submit({
              url:'/'+hive['mnu007s']+'/mnu007s.asp?SYSID='+systemID+'&action=delete'
              ,success: function() {
                winSys.hide();
                ds.load();
              }
              ,waitMsg:menu.I18N['deletingData']
            });
          }
        }
      })
      dsSysTxt.load()
    })
    systemRowData.load()
  }
});