Ext.onReady(function() {
  var windowCount = 0;
  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;
 	Ext.form.Field.prototype.width = 300;

  var settingData = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url:'/'+hive['syssets']+'/sysSetS.aspx?action=get'
    }),
    reader: new Ext.data.JsonReader({}),
    remoteSort: true
  });
  settingData.on('load', function() {
    var data = settingData.getAt(0).data;
          
    // open new tab on
    var ontDta = [['double', menu.I18N['doubleClick']], ['single', menu.I18N['singleClick']]];
    var ontDs = new Ext.data.SimpleStore({
        fields: ['click', 'text']
        ,data : ontDta
    });
    var ont = new Ext.form.ComboBox({
        store: ontDs
        ,displayField:'text'
        ,valueField:'click'
        ,hiddenName:'portfolioOpenNewTab'
        ,fieldLabel:menu.I18N['portfolioOpenNewTab']
        ,typeAhead: true
        ,mode: 'local'
        ,forceSelection: true
        ,triggerAction: 'all'
        ,selectOnFocus:true
        ,value:data['portfolioOpenNewTab']
    });          
        
    // create new user at login
    var cnuDta = [['yes', menu.I18N['yes']], ['no', menu.I18N['no']]];
    var cnuDs = new Ext.data.SimpleStore({
        fields: ['yesno', 'text']
        ,data : cnuDta
    });
    var cnu = new Ext.form.ComboBox({
        store: cnuDs
        ,displayField:'text'
        ,valueField:'yesno'
        ,hiddenName:'autoCreateNewUser'
        ,fieldLabel:menu.I18N['autoCreateNewUser']
        ,typeAhead: true
        ,mode: 'local'
        ,forceSelection: true
        ,triggerAction: 'all'
        ,selectOnFocus:true
        ,value:data['autoCreateNewUser']
    });

    // login css path
    var lcpDta = [
      ['', 'Standard']
      ,['/menu/styles/login/bright-blue-turquoise.css', 'Bright blue turquoise']
      ,['/menu/styles/login/bright-green.css', 'Bright green']
      ,['/menu/styles/login/bright-orange.css', 'Bright orange']
      ,['/menu/styles/login/grey.css', 'Grey']
      ,['/menu/styles/login/matte-blue.css', 'Matte blue']
      ,['/menu/styles/login/matte-green.css', 'Matte green']
      ,['/menu/styles/login/matte-purple.css', 'Matte purple']
      ,['/menu/styles/login/regular-blue.css', 'Regular blue']
      ,['/menu/styles/login/regular-green.css', 'Regular green']
      ,['/menu/styles/login/regular-purple.css', 'Regular purple']
    ];
    var lcpDs = new Ext.data.SimpleStore({
        fields: ['css', 'text']
        ,data : lcpDta
    });
    var lcp = new Ext.form.ComboBox({
        store: lcpDs
        ,displayField:'text'
        ,valueField:'css'
        ,hiddenName:'loginCSSPath'
        ,fieldLabel:menu.I18N['loginLayout']
        ,listWidth:300
        ,typeAhead: true
        ,mode: 'local'
        ,forceSelection: true
        ,triggerAction: 'all'
        ,selectOnFocus:true
        ,value:data['loginCSSPath']
    });          

    // create new user at login
    var useLangaugeCodeFrom = {};
    useLangaugeCodeFrom.data = [['browser', menu.I18N['browser']], ['user', menu.I18N['user']]];
    useLangaugeCodeFrom.store = new Ext.data.SimpleStore({
        fields: ['from', 'text']
        ,data : useLangaugeCodeFrom.data
    });
    useLangaugeCodeFrom.combo = new Ext.form.ComboBox({
        store: useLangaugeCodeFrom.store
        ,displayField:'text'
        ,valueField:'from'
        ,hiddenName:'useLangaugeCodeFrom'
        ,fieldLabel:menu.I18N['useLangaugeCodeFrom']
        ,typeAhead: true
        ,mode: 'local'
        ,forceSelection: true
        ,triggerAction: 'all'
        ,selectOnFocus:true
        ,value:data['useLangaugeCodeFrom']
    });

    // login css path
    var keysDta = [
      ['ATTN', 'Standard (attention)']
      ,['ENTER', 'Enter']
      ,['F1', 'F1']
      ,['F2', 'F2']
      ,['F3', 'F3']
      ,['F4', 'F4']
      ,['F5', 'F5']
      ,['F6', 'F6']
      ,['F7', 'F7']
      ,['F8', 'F8']
      ,['F9', 'F9']
      ,['F10', 'F10']
      ,['F11', 'F11']
      ,['F12', 'F12']
      ,['F13', 'F13']
      ,['F14', 'F14']
      ,['F15', 'F15']
      ,['F16', 'F16']
      ,['F17', 'F17']
      ,['F18', 'F18']
      ,['F19', 'F19']
      ,['F20', 'F20']
      ,['F21', 'F21']
      ,['F22', 'F22']
      ,['F23', 'F23']
      ,['F24', 'F24']
      ,['ROLLUP', 'Roll up']
      ,['ROLLDOWN', 'Roll down']
      ,['PRINT', 'Print']
    ];
    var keysDs = new Ext.data.SimpleStore({
        fields: ['key', 'text']
        ,data : keysDta
    });
    var keys = new Ext.form.ComboBox({
        store: keysDs
        ,displayField:'text'
        ,valueField:'key'
        ,hiddenName:'mapEscAs'
        ,fieldLabel:menu.I18N['mapEscAs']
        ,listWidth:300
        ,typeAhead: true
        ,mode: 'local'
        ,forceSelection: true
        ,triggerAction: 'all'
        ,selectOnFocus:true
        ,value:data['mapEscAs']
    });          
    
    // tabs
    var tabs = [];

    tabs[0] = new Object();
    tabs[0].title = menu.I18N['generel'];
    tabs[0].xtype = 'form';
    tabs[0].id = 'settingForm0';
    tabs[0].labelWidth = 320;
    tabs[0].height = 230;
    tabs[0].autoScroll = true;
    tabs[0].items = [
      ont
      ,cnu
      ,{xtype:'numberfield',fieldLabel:menu.I18N['serverRequestTimeout'],name:'serverRequestTimeout',value:data['serverRequestTimeout'],width:60,maxLength:10}
      ,{xtype:'numberfield',fieldLabel:menu.I18N['days4warningBeforePasswordExpires'],name:'days4warningBeforePasswordExpires',value:data['days4warningBeforePasswordExpires'],width:60,maxLength:5}
      ,{xtype:'numberfield',fieldLabel:menu.I18N['days4newPasswordExpiration'],name:'days4newPasswordExpiration',value:data['days4newPasswordExpiration'],width:60,maxLength:5}
      ,useLangaugeCodeFrom.combo
    ];

    tabs[1] = new Object();
    tabs[1].title = menu.I18N['startPage'];
    tabs[1].xtype = 'form';
    tabs[1].id = 'settingForm1';
    tabs[1].labelWidth = 150;
    tabs[1].height = 200;
    tabs[1].autoScroll = true;
    tabs[1].items = [
      {xtype:'radio',fieldLabel:menu.I18N['portalStartPage'],name:'portalStartPage',checked:(data['portalStartPage'] == 'portal') ? true: false,inputValue:'portal',boxLabel:menu.I18N['portalStartPagePortal']
        ,listeners: {
          check:function(box,checked){
            if (checked) {
              var obj = Ext.getCmp('portalStartPageTitle');
              if (obj.getValue() == '') {
                obj.setValue('Portal');
              }
            }
          }
        }
      }
      ,{xtype:'radio',fieldLabel:'',labelSeparator: '',name:'portalStartPage',checked:(data['portalStartPage'] == 'initialmenu') ? true: false,inputValue:'initialmenu',boxLabel:menu.I18N['portalStartPageInitalMenu']
        ,listeners: {
          check:function(box,checked){
            if (checked) {
              var obj = Ext.getCmp('portalStartPageTitle');
              if (obj.getValue() == '') {
                obj.setValue('Initial Menu');
              }
            }
          }
        }
      }
      ,{xtype:'radio',fieldLabel:'',labelSeparator: '',name:'portalStartPage',checked:(data['portalStartPage'] == 'customized') ? true: false,inputValue:'customized',boxLabel:menu.I18N['portalStartPageCustomized']
        ,listeners: {
          check:function(box,checked){
            var obj = Ext.getCmp('portalStartPageUrl');
            if (checked) {
              obj.enable();
              var obj = Ext.getCmp('portalStartPageTitle');
              if (obj.getValue() == '') {
                obj.setValue('Customized');
              }
            } else {
              obj.disable();
            }
          }
        }
      }
      ,{xtype:'textfield',fieldLabel:menu.I18N['portalStartPageUrl'],name:'portalStartPageUrl',id:'portalStartPageUrl',value:data['portalStartPageUrl'],disabled:(data['portalStartPage'] == 'customized') ? false: true}
      ,{xtype:'textfield',fieldLabel:menu.I18N['portalStartPageTitle'],name:'portalStartPageTitle',id:'portalStartPageTitle',value:data['portalStartPageTitle'],width:300}
    ];

    tabs[2] = new Object();
    tabs[2].title = 'IceCap'
    tabs[2].xtype = 'form';
    tabs[2].id = 'settingForm2';
    tabs[2].labelWidth = 320;
    tabs[2].height = 220;
    tabs[2].autoScroll = true;
    tabs[2].items = [
      {xtype:'checkbox',fieldLabel:menu.I18N['mapCtrlAsEnter'],name:'mapCtrlAsEnter',checked:(data['mapCtrlAsEnter'] == 'on') ? true: false}
      ,keys
      ,{xtype:'checkbox',fieldLabel:menu.I18N['ignoreLimitCapaWarning'],name:'ignoreLimitCapaWarning',checked:(data['ignoreLimitCapaWarning'] == 'on') ? true: false}
      ,{xtype:'fieldset',title:menu.I18N['attention'],height:70
        ,items:[
          {xtype:'textfield',fieldLabel:menu.I18N['program'],name:'attentionProgram',id:'attentionProgram',value:data['attentionProgram'],width:100,maxLength:10}
          ,{xtype:'textfield',fieldLabel:menu.I18N['library'],labelStyle:'padding-left:15px;',name:'attentionProgramLibrary',id:'attentionProgramLibrary',value:data['attentionProgramLibrary'],width:100,maxLength:10}
        ]
      }
      ,{xtype:'numberfield',fieldLabel:menu.I18N['maxNumberOfIceCapSessionPerUser'],name:'maxNumberOfIceCapSessionPerUser',value:data['maxNumberOfIceCapSessionPerUser'],width:60,maxLength:5}
    ];

    tabs[3] = new Object();
    tabs[3].title = menu.I18N['loginLayout'];
    tabs[3].xtype = 'form';
    tabs[3].id = 'settingForm3';
    tabs[3].labelWidth = 270;
    tabs[3].height = 200;
    tabs[3].autoScroll = true;
    tabs[3].items = [
      lcp
      ,{xtype:'textfield',fieldLabel:menu.I18N['systemCSSPath'],name:'systemCSSPath',id:'systemCSSPath',value:data['systemCSSPath']}
    ];

    var queryString = window.location.href.substring(window.location.href.indexOf('?') + 1);
    var windowId = IceCap.getQueryString(queryString,'portfolioWindowID');
              
    var panel = new Ext.Panel({
      renderTo:Ext.getBody()
      ,autoScroll:true
      ,bodyStyle:'padding:5px;'
      ,buttonAlign:'left'
      ,border:false
      ,items:{
        xtype:'tabpanel'
        ,id:'tabs'
        ,activeTab: 0
        ,frame:false
        ,defaults:{bodyStyle:'padding:5px 5px 0',labelWidth:170}
        ,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<tabs.length;i++) {
            var form = Ext.getCmp('settingForm'+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['syssets']+'/sysSetS.asp?action=update'
			        ,method:'POST'
              ,params:params
			        ,success: function (response,request) {
                if (parent.Ext && parent.Ext.getCmp(windowId)) {
                  parent.Ext.getCmp(windowId).fireEvent('closeWindow'); 
                }
              }
            });
          }
        }
        ,key:'ENTER'
      },{
        text: menu.I18N['cancel']
        ,handler: function() {
          if (parent.Ext && parent.Ext.getCmp(windowId)) {
            parent.Ext.getCmp(windowId).fireEvent('closeWindow'); 
          }
        }
      }]
    })
  });
  settingData.load();
});