Ext.ns('IceCap');  // Name space

// ===============================================================
IceCap.AdvancedComboBox = Ext.extend(Ext.form.ComboBox, {
  minChars : 3  // character needed to start server search
  ,maxLength : 10
  ,displayField:'key'
  ,forceSelection: false
  ,valueField:'key'
  ,typeAhead: false
  ,pageSize: 10
  ,hideTrigger:true
  ,fieldClass: 'x-form-field'
  ,triggerField:true
  ,tpl: new Ext.XTemplate(
  '<tpl for="."><div class="x-form-field">',
    '<b>{key} - </b>',
    '{value}',
    '</div></tpl>'
  )
  ,itemSelector: 'div.x-form-field'
  ,initComponent:function() {
    Ext.apply(this, {
      store: new Ext.data.JsonStore({
        url: '/icebreak/ddlibs.aspx?func=getRows'
      })
    });
    this.on("beforerender", function(){
      if (!this.readOnly) {
        this.fieldClass += ' iceCap-trigger-field';
      }
    });
    this.on("beforequery", function(){
      //this.syncSize();
    });
    IceCap.AdvancedComboBox.superclass.initComponent.call(this);
  }
});
Ext.reg('DDLIB', IceCap.AdvancedComboBox); // register xtype

// ===============================================================
// Used sqlComboBox to place SQL response directly in a dropdown
IceCap.sqlComboBox = Ext.extend(Ext.form.ComboBox, {
  valueField: 'KEY',
  displayField:'VALUE',
  hiddenName: 'KEY',
  typeAhead: true,
  mode: 'remote',
  triggerAction: 'all',
  selectOnFocus:true,
  editable: true, // false=Dropdown like, true=ComboBox
  listWidth: this.width,
  displayValue:this.displayValue,
  initComponent:function() {
    Ext.apply(this, {
      store: new Ext.data.JsonStore({
        url: '/menu/DDSQL.aspx?runSql=runsql&sqlVoucher=' + this.sqlVoucher
      })
    });
    if (this.displayValue && this.displayValue.length > 0) {
      var recordFormat = Ext.data.Record.create(['KEY','VALUE']);
      var record = new recordFormat({KEY: this.value, VALUE:this.displayValue});
      this.store.add(record);
    }
  }
});
Ext.reg('DDSQL', IceCap.sqlComboBox); // register xtype

// ===============================================================
// Used sqlSearchBox to place SQL response directly in a advanced Search combobox
var searchMode = false;
IceCap.sqlSearchBox = Ext.extend(Ext.form.ComboBox, {
  minChars : 3,  // character needed to start server search
  maxLength : 10,
  valueField: 'KEY',
  displayField:'VALUE',
  hiddenName: 'KEY',
  forceSelection: false,
  typeAhead: false,
  pageSize: 10,
  listWidth: this.width,
  triggerField:true,
  listeners: {
// CRL (2013.05.22)
// Removed, do not known why this code !!!
// Cause that the client can not press a f-key, when ex. typing a "?"
//    keypress: function(fld, e){
//      if (e.getKey() >=e.ONE && (e.getKey() <= e.NINE)){
//        IceCap.activeSession.map.enable();
//      } else if (e.getKey() != e.ENTER){
//        IceCap.activeSession.map.disable();
//      }
//    },
    keydown: function(fld, e){
      if (searchMode && e.getKey() == e.UP){
        e.stopEvent();
      }
    },
    focus: function(fld, e){
      searchMode = false;
      IceCap.activeSession.map.enable();
    },
    blur: function(fld, e){
      searchMode = false;
      IceCap.activeSession.map.enable();
    },
    beforequery: function(box, rec, num){
      searchMode = true;
    },
    select: function(box, rec, num){
      IceCap.activeSession.map.enable();
      searchMode = false;
      var flds = rec.fields.items;
      for (i = 0; i < flds.length; i++){
        var fname = flds[i].name;
          var f = document.getElementsByName(fname);
          if (f.length > 0){
            eval ("var d = rec.data." + fname);
            f[0].value = d;
          }
      }
    }
  },
  hideTrigger: true,
  tpl: new Ext.XTemplate(
  '<tpl for="."><div class="x-form-field">',
    '{VALUE}',
    '</div></tpl>'
  ),
  itemSelector: 'div.x-form-field',
  initComponent:function() {
    if (this.initialConfig && this.initialConfig.displayField) {
      this.displayField = this.initialConfig.displayField;
    }
    Ext.apply(this, {
      store: new Ext.data.JsonStore({
        url: '/menu/DDSQL.aspx?runSql=runsql&sqlVoucher=' + this.sqlVoucher
      })
    });
    this.on("beforerender", function(){
      if (!this.readOnly) {
        this.fieldClass += ' iceCap-trigger-field';
      }
    });
    IceCap.sqlSearchBox.superclass.initComponent.call(this);
  }

});

Ext.reg('DDSEARCH', IceCap.sqlSearchBox); // register xtype

// ===============================================================
// Link Field, Link to a external URL
IceCap.LINKFIELD = Ext.extend(Ext.form.TriggerField, {
  validationEvent:false
  ,validateOnBlur:false
  ,triggerClass:'icecap-form-link-trigger'
  ,onTriggerClick : function() {
    if (this.getValue().length == 0) {
      Ext.MessageBox.alert('Message', 'Url required');
    } else {
      if (parent.Ext.getCmp('portfolio-tabpanel')) {
        parent.Ext.getCmp('portfolio-tabpanel').fireEvent('addTab',this.tabName,'',this.getValue(),'');
      }
    }
  }
});
Ext.reg('LINKFIELD', IceCap.LINKFIELD); // register xtype

// ===============================================================
// Link Field, Link to a external URL
IceCap.COMBOBOX = Ext.extend(Ext.form.ComboBox, {
  valueField: 'key'
  ,displayField:'value'
  ,typeAhead: true
  ,mode:'local'
  ,forceSelection: true
  ,triggerAction: 'all'
  ,selectOnFocus:true
  ,initComponent:function() {
    this.store = new Ext.data.SimpleStore({
      fields:['key', 'value']
      ,data:this.valueMap
    });
    IceCap.COMBOBOX.superclass.initComponent.call(this);
  }
});
Ext.reg('COMBOBOX', IceCap.COMBOBOX); // register xtype

/** ===============================================================
 * iceCap class to make Fusion chart
 * @xtype FUSIONCHART
 *
 * config option:
 * width:             Default: 500
 * height:            Default: 500
 * chartType:         chart type. See system/components/FusionCharts/Charts for posiablies. Default: "Column2D"
 * decimalSeparator:  Default: ','
 * thousandSeparator: Default: '.'
 * xmlData:           String - Raw xml data
 * data:              Array - Data as json array
 *
 * <p>Ex. with xml data:<pre><code>
var chart = new IceCap.fusionChart({
    chartType: 'Pie3D'
    ,xmlData: '<chart><set label='A' value='111' /><set label='B' value='222' /></chart>'
});
 * </code></pre></p>
 *
 * <p>Ex. with data:<pre><code>
var chart = new IceCap.fusionChart({
    chartType: 'Column3D'
    ,data:[['A', '111'],['B', '222']]
});
 * </code></pre></p>
 */
IceCap.fusionChart = Ext.extend(Ext.Panel,{
  // defaults - can be changed from outside
  border:false
  ,bodyBorder:false
  ,id:'fusionChart'
  ,header:false
  ,width:500
  ,height:500
  ,bodyStyle: { padding: 5 }
  // defaults for fusion chart
  ,chartType:'Column2D'
  ,decimalSeparator:','
  ,thousandSeparator:'.'
  ,initComponent: function() {
    dsCharttype = new Ext.data.SimpleStore({
      fields:['type', 'description']
      ,data :[
        ['Area2D','Area 2D']
        ,['Bar2D','Bar 2D']
        ,['Column2D','Column 2D']
        ,['Column3D','Column 3D']
        ,['Doughnut2D','Doughnut 2D']
        ,['Funnel','Funnel']
        ,['Line','Line']
        ,['Pie2D','Pie 2D']
        ,['Pie3D','Pie 3D']
      ]
    });
    var width = this.width;
    this.width = width + 300;
    this.items = [{
      layout:'column'
      ,border:false
      ,items:[{
        width:width
        ,border:false
        ,items:[{
          xtype:'box'
          ,autoEl:'div'
          ,id:'chart'
          ,listeners:({
            'render' : {
              fn: function() {
                this.buildChart(Ext.getCmp('fusionChart'), this.chartType)
              }
              ,scope: this
            }
          })
        }]
      },{
        width:280
        ,height:this.height
        ,border:false
        ,style:'{padding-left:20px; margin-top:4px;}'
        ,items:[{
          xtype:'combo'
          ,fieldLabel:menu.I18N['chartType']
          ,hiddenName:'charttype'
          ,store:dsCharttype
          ,displayField:'type'
          ,valueField:'description'
          ,value:this.chartType
          ,fieldClass:'x-form-text'
          ,width:160
          ,listWidth:160
          ,allowBlank:false
          ,editable:true
          ,mode:'local'
          ,forceSelection:true
          ,triggerAction:'all'
          ,typeAhead:false
          ,selectOnFocus:true
          ,valueNotFoundText:menu.I18N['selectChartType']
          ,emptyText:menu.I18N['selectChartType']
          ,listeners:({
            'select' : {
              fn: function(combo, record, index, e) {
                this.buildChart( Ext.getCmp('fusionChart'), record.data.type)
              }
              ,scope: this
            }
          })
        }]
      }]
    }]

    IceCap.fusionChart.superclass.initComponent.apply(this,arguments);
  }
  ,buildChart: function(chart, type) {
    var code = '';
    code = 'var chart = new FusionCharts("/menu/system/components/FusionCharts/Charts/FCF_' + type + '.swf",';
    code += ' "ChartId",';
    code += ' "' + (chart.width - 300) + '",';
    code += ' "' + chart.height + '",';
    code += ' "0", "0");';
    code += ' chart.setDataXML("';
    // json data
    if (chart.data) {
      code += '<graph';
      code += ' decimalSeparator=\'' + chart.decimalSeparator + '\'';
      code += ' thousandSeparator=\'' + chart.thousandSeparator + '\'';
      code += ' formatNumberScale=\'0\'';
      code += '>';
      data = new Ext.data.SimpleStore({
        fields:['label', 'value']
        ,data:chart.data
      });
      for (i=0; i<=data.getTotalCount()-1; i++) {
        // remove/replace thousand separator -& decimal point
        var value = iceCapFormatNumeric(data.getAt(i).data['value'], chart.decimalSeparator);
        code += '<set';
        code += ' name=\'' + data.getAt(i).data['label'] + '\'';
        code += ' value=\'' + value + '\'';
        code += ' />';
      }
      code += '</graph>';
    } else if (chart.xmlData) {
      code += chart.xmlData;
    }
    code += '");';
    code += 'chart.render("chart");'

    eval(code);
  }
});
Ext.reg('FUSIONCHART', IceCap.fusionChart); // register xtype

// ===============================================================
// Library field with dependency to file combobox
IceCap.LibraryFileDependency = Ext.extend(Ext.form.TextField, {
  fieldLabel:'Library'
  ,name:'lib'
  ,fileClass:'file'
  ,listeners: {
    blur: function(o) {
      var parentObj = Ext.getCmp(this.ownerCt.id);
      var objs = iceCapGetElementsByClass(this.fileClass, parentObj, 'input');
      var ddFileStore = objs[0].getStore();
      ddFileStore.baseParams = {
        lib: o.getValue()
      }
      ddFileStore.load()
    }
  }
  ,initComponent:function() {
    IceCap.LibraryFileDependency.superclass.initComponent.call(this);
  }
});
Ext.reg('LibraryFileDependency', IceCap.LibraryFileDependency); // register xtype

// ===============================================================
// File field with dependency to library text field
IceCap.FileLibraryDependency = Ext.extend(Ext.form.ComboBox, {
  hiddenName:'DD.obj' // must be named DD.xxxxx so icecap known it a dropdown, and value must be pick from hidden field
  ,valueField:'obj'
  ,displayField:'txt'
  ,fieldLabel:'File'
  ,width:300
  ,lib:'qtemp'
  ,obj:'*all'
  ,typ:'*all'
  ,atr:'*all'
  ,store:new Ext.data.JsonStore({
    url:'/menu/objlst.aspx'
  })
  ,mode:'remote'
  ,typeAhead:true
  ,triggerAction:'all'
  ,selectOnFocus:true
  ,editable:true
  ,initComponent:function() {
    this.listWidth = (this.listWidth) ? this.listWidth : this.width;
    this.emptyText = (this.emptyText) ? this.emptyText : 'Select ' + this.fieldLabel;

    // first time load
    this.store.baseParams = {
      lib:this.lib
      ,obj:this.obj
      ,typ:this.typ
      ,atr:this.atr
    }
    this.store.load();

    IceCap.FileLibraryDependency.superclass.initComponent.call(this);
  }

});
Ext.reg('FileLibraryDependency', IceCap.FileLibraryDependency);

// ===============================================================
// as/400 command dropdown
IceCap.CommandPanel = Ext.extend(Ext.Panel,{
  // defaults - can be changed from outside
  border:false
  ,bodyBorder:true
  ,header:false
  ,width:280
  ,height:24
  ,bodyStyle: { padding: 5 }
  ,buttonAlign:'right'
  ,initComponent: function() {
    var dsCmds = new Ext.data.SimpleStore({
      fields:['cmd', 'description']
      ,data :[
        ['wrksplf','Work with spooled files']
        ,['wrkusrjob','Work with user jobs']
        ,['dspjob', 'Display job']
      ]
    });
    this.items = [{
      xtype:'combo'
      ,hideLabel:true
      ,hiddenName:'cmd'
      ,store:dsCmds
      ,displayField:'description'
      ,valueField:'cmd'
      ,width:250
      ,listWidth:250
      ,allowBlank:true
      ,editable:true
      ,mode:'local'
      ,forceSelection:true
      ,triggerAction:'all'
      ,typeAhead:false
      ,selectOnFocus:true
      ,emptyText:'Select a command and click OK...'
    }];
    this.buttons=[{
      xtype:'button'
      ,text: 'OK'
      ,handler: function() {
        var cmd = this.ownerCt.items.items[0].getValue();
        if (cmd.length > 0) {
          if (parent.Ext && parent.Ext.getCmp('portfolio-tabpanel')) {
            var url = '/menu/icecap.aspx?func='+cmd;
            parent.Ext.getCmp('portfolio-tabpanel').fireEvent('addTab',cmd,'',url);
          }
        }
      }
    }];

    IceCap.CommandPanel.superclass.initComponent.apply(this,arguments);
  }
});
Ext.reg('COMMANDPANEL', IceCap.CommandPanel); // register xtype

// ===============================================================
IceCap.InlineGrid = Ext.extend(Ext.grid.GridPanel, {
  initComponent:function() {
    function cols(d) {
      var c = [];
      for  (i=0; i<d.length; i++) {
        c.push({name: 'c' + i});
        d[i].dataIndex = 'c' + i;
      }
      return c;
    }
    var r = Ext.data.Record.create( cols(this.columns));

    var myReader = new Ext.data.ArrayReader({
    }, r);

      Ext.apply(this, {
      viewConfig: {
        forceFit: true
      },
      store: new Ext.data.Store({
        reader: myReader,
        data: this.dataArray
      })
    });
    IceCap.InlineGrid.superclass.initComponent.call(this);
  }
});
Ext.reg('INLINEGRID', IceCap.InlineGrid); // register xtype

IceCap.RadioGroup = Ext.extend(Ext.form.RadioGroup, {

  initComponent:function() {

    var i_self = this;
    var a_class = (i_self.cls || "").split(" ");
    a_class.push("iceCap-radio");
    i_self.cls = a_class.join(" ");
    var a_split = i_self.fieldClass.split(" ");
    a_split.pop();
    i_self.fieldClass = a_split.join(" ");
    var a_values = i_self.valueMap;
    i_self.items = i_self.getItems(a_values);
    IceCap.RadioGroup.superclass.initComponent.call(i_self);
    i_self.on({
      render: function(item) {
        var value = item.value;
        if (value) {
          item.setValue(value);
          var a_items = item.items.items;
          if(a_items.length > 0) {
            for(var i = 0; i <  a_items.length; i++) {
              var i_radio = a_items[i];
              i_radio.wrap.setStyle("padding", 0);

            }
          }
        }
      },
      specialkey: function(i_field, e) {
        if (e.keyCode == 39 || e.keyCode == 37) {
            var n_index = 0;
            var b_found = false;
            var n_len = i_field.items.length;
            i_field.items.each(function(i_radio) {
              if (i_radio.innerWrap.id == e.target.id) {
                b_found = true;
              }
              if (!b_found) {
                n_index++;
              }
            });
            if (e.keyCode == 39) {
              n_index++;
            }
            else if(e.keyCode == 37) {
              n_index--;
            }
            if (b_found) {
              var i_radio;
              if (n_index == n_len) {
                i_radio = i_field.items.get(0);
              }
              else {
                if (n_index < 0) {
                  i_radio = i_field.items.get(n_len-1);
                }
                else {
                  i_radio = i_field.items.get(n_index);
                }
              }
              i_radio.innerWrap.focus();
              i_field.setValue(i_radio.inputValue);
            }
        }
      }
    });
    return i_self;
  },

  getItems: function(a_values) {

    var i_self = this;
    var a_return = [];

    for(var i = 0; i < a_values.length; i++) {

      var o_input = a_values[i];
      var o_radio = {
        inputValue: o_input.key,
        boxLabel: o_input.value,
        name: i_self.id + "_group"
      };
      a_return.push(o_radio);
    }
    return a_return;
  },

  getValue: function() {

    var i_self = this;
    var value = i_self.value;

    if (i_self.items) {
      i_self.items.each(function(i_radio) {
        if (i_radio.inputValue == value) {
          value = i_radio.getGroupValue();
        }
      });
    }

    return value;
  },

  setValue: function(value) {

    var i_self = this;
    if (i_self.items) {
      i_self.items.each(function(i_radio) {
        if (i_radio.inputValue ==  value) {
          i_radio.setValue(true);
        }
        else {
          i_radio.setValue(false);
        }
      });
    }
    i_self.value = value;
  },
  setFocus: function() {

    var i_self = this;
    var b_found = false;
    if (i_self.items) {
      i_self.items.each(function(i_radio) {
        if (i_radio.checked) {
          b_found = true;
          i_radio.innerWrap.focus();
          i_self.setValue(i_radio.inputValue);
        }
      });
      if (!b_found) {
        var i_radio = i_self.items.get(0);
        i_radio.innerWrap.focus(true);
        i_self.setValue(i_radio.inputValue);
      }
    }
  }

});

Ext.reg('RADIOGROUP', IceCap.RadioGroup);

