Ext.onReady(function(){
  var selectedRow, selectedIndent;

  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['mnu005l']+'/mnu005l.asp'
      ,id:'MNUID'
		  ,fields:[
        {name:'MNUSYSID'}
        ,{name:'INDENT', type:'int'}
        ,{name:'MTXTXT'}
        ,{name:'MNULNK'}
		  ]
		  ,remoteSort: true
	  });

  function renderText(value, p, record) {
    var string = String.format('<img src="/menu/images/space.gif" width="{0}" height="1" />{1}', record.data['INDENT'] * 20, value);
    return string;
  }

  var grid = new Ext.grid.GridPanel({
    renderTo:Ext.getBody()
    ,autoScroll : true
    ,enableDragDrop: true
    ,ddGroup:'grid'
    ,store: ds
    ,columns:
      [
        {header: menu.I18N['description'], width:300, sortable:false, dataIndex: 'MTXTXT', renderer: renderText}
        ,{header: menu.I18N['link'], width:300, sortable:false, dataIndex: 'MNULNK'}
      ]
    ,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-menu-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 source = ds.data.items[data.rowIndex];
      var sourceMenuID = source.id;
      var target = ds.data.items[ddSource.getDragData(e).rowIndex];
      var targetMenuID = target.id;
      if (ddSource.getDragData(e).rowIndex == 0 || typeof(ds.data.items[ddSource.getDragData(e).rowIndex-1]) == 'undefined') {
        var beforeMenuID = 0;
      } else {
        beforeMenuID = ds.data.items[ddSource.getDragData(e).rowIndex-1].id;
      }

      if (source.data.MNUSYSID != target.data.MNUSYSID) {
        Ext.Msg.alert(menu.I18N['message'], menu.I18N['invalidDropZone4menuItem']);
        return;
      }

      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['mnu005s2']+'/mnu005s2.asp?dropBorA=before&sourceMenuID='+sourceMenuID+'&targetMenuID='+targetMenuID+'&beforeMenuID='+beforeMenuID
              });
              conn.on('requestcomplete', function () {
                ds.load();
                dropWin.hide()
              });
            }
          },{
            text: menu.I18N['after']
            ,handler: function() {
              var conn = new Ext.data.Connection();
              conn.request({
                url: '/'+hive['mnu005s2']+'/mnu005s2.asp?dropBorA=after&sourceMenuID='+sourceMenuID+'&targetMenuID='+targetMenuID+'&beforeMenuID='+beforeMenuID
              });
              conn.on('requestcomplete', function () {
                ds.load();
                dropWin.hide()
              });
            }
          },{
            text: menu.I18N['cancel']
            ,handler: function() {
              dropWin.hide();
            }
          }
        ]
      });
      dropWin.show();
    }
  }); 	

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

  grid.on('rowcontextmenu', onRowMenu);
  grid.on('rowclick', function(grid, rowIndex, e) {
    selectedRow    = ds.data.items[rowIndex].id;
    selectedIndent = ds.data.items[rowIndex].INDENT;
  });
  grid.on('rowdblclick', function(grid, rowIndex, e) {
    selectedRow   = ds.data.items[rowIndex].id;
    if (ds.getById(selectedRow).get('INDENT') > 0) {
      processMenuRow(selectedRow, 'update');
    }
  });

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

  ds.on('load', function(store, records, options) {
    if(!store.reader.jsonData.success) {
      ds.removeAll();
      Ext.Msg.alert(menu.I18N['message'], store.reader.jsonData.message);
    }
  });

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

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

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

  var windowCount = 0;
  function processMenuRow(menuID, func) {
    // Loading store with detail data
    var action = (func == 'create') ? 'init' : 'get';
    var menuRowData = new Ext.data.JsonStore({
      url:'/'+hive['mnu005s']+'/mnu005s.asp?action='+action+'&MNUID='+menuID
    });
    if (func == 'copy') {
      rrn = 0;
      func = 'create';
    }
    menuRowData.on('load', function() {
      var data = menuRowData.getAt(0).data;
      var dsMnuGrp = new Ext.data.JsonStore({
        totalProperty:'totalRows'
        ,root:'rows'
        ,url:'/'+hive['mnu005l']+'/mnu005l.asp?thisMenu='+menuID
        ,id:'MNUID'
        ,fields:[
                  'MNUID'
                  ,'MTXTXT'
        ]
        ,remoteSort:false
        ,baseParams: {
          system: (data['MNUSYSID'] == 0) ? -1 : data['MNUSYSID']
        }
      });
      dsMnuGrp.load()

      var dsUsrGrp = new Ext.data.JsonStore({
        totalProperty:'totalRows'
        ,root:'rows'
        ,url:'/'+hive['mnu006l']+'/mnu006l.asp?GMRMNUID='+data['MNUID']
        ,id:'UGRID'
        ,fields:[
                  'UGRID'
                  ,'UGRTXT'
                  ,'CHECKED'
        ]
        ,remoteSort:false
      });
      dsUsrGrp.on('load', function() {
        var dsMnuTxt = new Ext.data.JsonStore({
          totalProperty:'totalRows'
          ,root:'rows'
          ,url:'/'+hive['mnu008l']+'/mnu008l.asp?MTXMNUID='+data['MNUID']
          ,id:'LNGID'
          ,fields:[
                    'LNGID'
                    ,'LNGTXT'
                    ,'MTXTXT'
          ]
          ,remoteSort:false
        });
        var dsMetaform = new Ext.data.JsonStore({
          url:'/menu/metaform02.aspx?form=menu'
        });
        dsMetaform.on('load', function() {
          dsMnuTxt.on('load', function() {
            windowCount++

            var UsrGrpArray = new Array();
            var maxi = dsUsrGrp.getTotalCount();
            for (i=0; i<=maxi-1; i++) {
              var usrGrp = new Object();
              usrGrp.xtype='checkbox';
              usrGrp.hideLabel = true;
              usrGrp.boxLabel=dsUsrGrp.getAt(i).data['UGRTXT'];
              usrGrp.name = 'group.' + dsUsrGrp.getAt(i).data['UGRID'];
              if (dsUsrGrp.getAt(i).data['CHECKED'] == 'true') {
                usrGrp.checked = true;
              } else {
                usrGrp.checked = false;
              }
              UsrGrpArray[i] = usrGrp;
            };
            var mnuTxtArray = new Array();
            var maxi = dsMnuTxt.getTotalCount();
            for (i=0; i<=maxi-1; i++) {
              var mnuTxt = new Object();
              mnuTxt.xtype='textfield';
              mnuTxt.fieldLabel = dsMnuTxt.getAt(i).data['LNGTXT'];
              mnuTxt.name = 'txt.' + dsMnuTxt.getAt(i).data['LNGID'];
              mnuTxt.value = dsMnuTxt.getAt(i).data['MTXTXT'];
              mnuTxt.width = 400;
              mnuTxtArray[i] = mnuTxt;
            };

            var MNUSYSID = new menu.ddSystem({
              hiddenName:'MNUSYSID'
              ,value:data['MNUSYSID']
              ,displayValue:data['STXTXT']
              ,hive:hive['mnu007l']
              ,valueNotFoundText:menu.I18N['selectSystem']
              ,emptyText:menu.I18N['selectSystem']
            });

            var MNUGRPID = new Ext.form.ComboBox({
              fieldLabel:menu.I18N['menuGroup']
              ,hiddenName:'MNUGRPID'
              ,value:data['MNUGRPID']
              ,store:dsMnuGrp
              ,displayField:'MTXTXT'
              ,valueField:'MNUID'
              ,allowBlank:false
              ,editable:true
              ,mode:'local'
              ,forceSelection:true
              ,triggerAction:'all'
              ,typeAhead:false
              ,selectOnFocus:true
              ,valueNotFoundText:menu.I18N['selectMenuGroup']
              ,emptyText:menu.I18N['selectMenuGroup']
            });

            // tabs
            var tabs = [];

            var tab = {
              title: menu.I18N['linkInformation'],
              xtype: 'form',
              id: 'menuform0',
              defaults: {
                  width:400
              },
              height: 250,
              autoScroll: true,
              items: [
                {xtype:'hidden',name:'MNUSELICO',value:data['MNUSELICO']}
                ,MNUSYSID
                ,MNUGRPID
                ,{xtype:'textfield',fieldLabel:menu.I18N['description'],name:'MTXTXT',value:data['MTXTXT'],allowBlank:false,listeners:{blur:function(o){ setLanguageText(o) }}}
                ,{xtype:'textfield',fieldLabel:menu.I18N['link'],name:'MNULNK',value:data['MNULNK']}
                ,{xtype:'ddHives',hiddenName:'MNUPTH',value:data['MNUPTH'],displayValue:data['MNUPTHTXT'],hive:hive['mnu920l'],extraRecord:menu.I18N['useSystemPath']}
                ,{xtype:'ddIcon',hiddenName:'searchIcon',value:data['MNUSELICO']
                  ,listeners:{
                    blur:function(f){ 
                      winMnu.key.enable();
                      changeIcon(f.getValue()) 
                    }
                    ,focus:function(f){ 
                      winMnu.key.disable();
                    }
                    ,selectIcon: function(f) {
                      changeIcon(f.getValue());
                    }
                    ,hideIcon: function() {
                      changeIcon('');
                    }
                  }
                }
                ,{xtype:'label',html:formatIcon(data['MNUSELICO'])}
                ,{
                  layout:'column'
                  ,border:false
                  ,width:720
                  ,items:[
                    {
                      width:300
                      ,layout: 'form'
                      ,border:false
                      ,items: [
                        {xtype:'checkbox',fieldLabel:menu.I18N['openInWindow'],name:'openInWindow',checked:(data['openInWindow'] == 'on') ? true : false,allowBlank:true
                          ,listeners:{
                            'check':{
                              fn:function(box, checked) {
                                var form = box.findParentByType('form');
                                var fld = form.getForm().findField('MNULNK');
                                if (fld.getValue().toLowerCase().indexOf('icecap.aspx') != -1)  {
                                  checked = false;
                                  box.setValue(checked);
                                  Ext.MessageBox.alert(menu.I18N['message'], menu.I18N['notAllow4icecap']);
                                }
                                var fld = form.getForm().findField('windowWidth');
                                if (checked) {
                                  fld.enable();
                                } else {
                                  fld.disable();
                                }
                                var fld = form.getForm().findField('windowHeight');
                                if (checked) {
                                  fld.enable();
                                } else {
                                  fld.disable();
                                }
                              }
                            }
                          }
                        }
                      ]
                    },{
                      width:190
                      ,layout: 'form'
                      ,border:false
                      ,labelWidth:135
                      ,items: [
                        {xtype:'numberfield',fieldLabel:menu.I18N['windowWidth'],name:'windowWidth',value:data['windowWidth'],width:40,disabled:(data['openInWindow'] == 'on') ? false : true}
                      ]
                    },{
                      width:95
                      ,layout: 'form'
                      ,border:false
                      ,labelWidth:50
                      ,items: [
                        {xtype:'numberfield',fieldLabel:menu.I18N['windowHeight'],name:'windowHeight',value:data['windowHeight'],width:40,disabled:(data['openInWindow'] == 'on') ? false : true}
                      ]
                    }
                  ]
                }
                ,{xtype:'checkbox',fieldLabel:menu.I18N['startInNewBrowserWindow'],name:'openInNewWindow',checked:(data['openInNewWindow'] == 'on') ? true : false,allowBlank:true}
              ]
            }
            tabs.push(tab);

            var tab = {
              title: menu.I18N['authority'],
              xtype: 'form',
              id: 'menuform1',
              defaults: {width:380},
              height: 250,
              autoScroll: true,
              items: [
                {xtype:'ddUserClass',fieldLabel:menu.I18N['requireUserClass'],hiddenName:'MNUUCLID',value:data['MNUUCLID'],displayValue:data['UCLTXT'],hive:hive['mnu009l']}
                ,{xtype:'fieldset',title:menu.I18N['userGroupAccess'],autoHeight:true,width:572,labelWidth:500
                  ,items:UsrGrpArray
                }
              ]
            }
            tabs.push(tab);

            var tab = {
              title: menu.I18N['descriptionInDiffenrenceLanguage'],
              xtype: 'form',
              id: 'menuform2',
              defaults: {width:400},
              height: 250,
              autoScroll: true,
              items: mnuTxtArray
            }
            tabs.push(tab);

            var tab = {
              title: menu.I18N['advanced'],
              xtype: 'form',
              id: 'menuform3',
              defaults: {width:400},
              height: 250,
              autoScroll: true,
              items: [
                {xtype:'checkbox',hideLabel:true,boxLabel:menu.I18N['criticalApplication'],name:'criticalAppl',checked:(data['criticalAppl'] == 'on') ? true: false,allowBlank:true}
                ,{xtype:'fieldset',title:menu.I18N['menuGroup'],autoHeight:true,width:572,labelWidth:500
                  ,items:[
                    {xtype:'checkbox',hideLabel:true,boxLabel:menu.I18N['startTogether'],name:'menuGroup',checked:(data['menuGroup'] == 'on') ? true: false,allowBlank:true}
                    ,{xtype:'checkbox',hideLabel:true,boxLabel:menu.I18N['hideChildrenInMenuGroup'],name:'hideChildrenInGroup',checked:(data['hideChildrenInGroup'] == 'on') ? true: false,allowBlank:true}
                    ,{xtype:'checkbox',hideLabel:true,boxLabel:menu.I18N['closeAllChildrenInMenuGroup'],name:'closeAllChildrenInGroup',checked:(data['closeAllChildrenInGroup'] == 'on') ? true: false,allowBlank:true}
                  ]
                }
              ]
            }
            tabs.push(tab);

            var maxi = dsMetaform.getTotalCount();
            for (i=0; i<=maxi-1; i++) {
              var tab = {
                title: dsMetaform.getAt(i).data['caption'],
                xtype: 'panel',
                layout: 'form',
                height: 250,
                autoScroll: true,
                items: {
                  xtype:'iceMetaForm'
                  ,url:'/menu/metaForm.aspx?xml='+dsMetaform.getAt(i).data['xml']+'&form=menu&key='+data['MNUID']
                }
              }
              tabs.push(tab);
            }          

            var windowID = 'mnu005-window-' + windowCount;
            var title = (func == 'create') ? menu.I18N['addNew'] : menu.I18N['update'] + ': ' + data['MTXTXT'];
            if (!winMnu) {
              var winMnu = new Ice.Window({
                id: windowID
                ,title: title
                ,width: 740
                ,height: 390
                ,minWidth: 50
                ,minHeight: 50
                ,autoScroll : true
                ,bodyStyle:'padding:5px;'
                ,buttonAlign:'left'
                ,layout: 'fit'
                ,plain:true
                ,modal: false
                ,items:{
                  xtype:'tabpanel'
                  ,id:'tabs'
                  ,activeTab: 0
                  ,frame:false
                  ,defaults:{bodyStyle:'padding:5px 5px 0',labelWidth:200}
                  ,deferredRender:false
                  ,items:tabs
                }
                ,buttons: [{
                  text: menu.I18N['save']
                  ,type: 'submit'
                  ,handler: function() {	
                    var isValid = true;

                    var i=0;
                    var params = {};
                    for (i=0;i<=3;i++) {
                      var form = Ext.getCmp('menuform'+i);
                      if (form.getForm().isValid()) {
                        var p = form.getForm().getValues()
                        for (var o in p) {
                          params[o] = p[o];
                        }
                      } else {
                        isValid = false;
                        break;
                      }
                    }

                    if (isValid) {
                      Ext.Ajax.request({
                        url:'/'+hive['mnu005s']+'/mnu005s.asp?MNUID='+menuID+'&action='+func
			                  ,method:'POST'
                        ,params:params
			                  ,success: function (response,request) {
                          winMnu.hide();
                          ds.load();
                          iceSaveMetaForm(winMnu);
                        }
                      });
                    }
                  }
                  ,key:'ENTER'
                },{
                  text: menu.I18N['delete'],
                  handler: function(){
                    Ext.MessageBox.confirm(menu.I18N['message'], menu.I18N['confirmDelete'] , doMenuDelete);
                  }
                },{
                  text: menu.I18N['cancel']
                  ,handler: function() {
                    winMnu.hide();
                  }
                }]
              })
            }
            winMnu.show();

            if (func == 'create' || data['hasChildren'] == 'true') {
              winMnu.buttons[1].disable();
            }

            MNUSYSID.on('select', function(){
              dsMnuGrp.baseParams = {
                system: MNUSYSID.getValue()
              }
              dsMnuGrp.load()
              dsMnuGrp.on('load', function() {
                MNUGRPID.setValue('0')
              })
            })

            MNUSYSID.focus(true,10);

            function formatIcon(icon) {
              var img = (icon.length == 0) ? Ext.BLANK_IMAGE_URL : icon;
              var string = '';
              var id = 'icon'+windowCount;
              string =  '<div tabindex="-1" class="x-form-item ">';
              string += '<label class="x-form-item-label" style="width: 170px;">{0}:</label>';
              string += '<div style="padding-left: 175px;" class="x-form-element">';
              string += '<img src="{1}" id="{2}" style="width:16px; height:16px;" />';
              string += '</div><div class="x-form-clear-left"></div></div>';
              return String.format(string, menu.I18N['icon'], img, id);
            }
            function changeIcon(icon) {
              var img = (icon.length == 0) ? Ext.BLANK_IMAGE_URL : icon;
              var v = img.toLowerCase();
              if (v.indexOf('.png') > 0 || v.indexOf('.gif') > 0 || v.indexOf('.ico') > 0) {
                var form = Ext.getCmp('menuform0').getForm();
                var field = form.findField('MNUSELICO');
                field.setValue(icon);
                document.getElementById('icon'+windowCount).src = img;
              }
            }
            function setLanguageText(descField) {
              if (func == 'create') {
                var newValue = descField.getValue();
                
                var form = Ext.getCmp('menuform0').getForm();
                var field = form.findField('searchIcon');
                field.setValue(newValue);

                var form = Ext.getCmp('menuform2').getForm();
                var i;
                var maxi = dsMnuTxt.getTotalCount();
                for (i=0; i<=maxi-1; i++) {
                  var name = 'txt.' + dsMnuTxt.getAt(i).data['LNGID'];
                  var field = form.findField(name);
                  if (field.getValue().length === 0) {
                    field.setValue(newValue);
                  }

                }
              }
            }
            function doMenuDelete(btn) {
              if (btn == 'yes') {
                Ext.Ajax.request({
                  url:'/'+hive['mnu005s']+'/mnu005s.asp?MNUID='+menuID+'&action=delete'
			            ,method:'POST'
			            ,success: function (response,request) {
                    winMnu.hide();
                    ds.load();
                  }
                });
              }
            }
          })
          dsMnuTxt.load()
        })
        dsMetaform.load()
      })
      dsUsrGrp.load()
    })
    menuRowData.load()
  }
});