// Override events, etc. for touch devices
// =======================================
Ext.isiPad = navigator.userAgent.match(/iPad/i) != null;
Ext.isiPhone = navigator.userAgent.match(/iPhone/i) != null;
Ext.isMobileDevice = Ext.isiPad || Ext.isiPhone;

if (Ext.isMobileDevice) {
  Ext.ns('touch');
  touch.scripts = {};
  touch.styles = {};
  // Load script dynamic
  // -------------------
  touch.loadScript = function(src) {
    if (src.indexOf('.js') == -1) src += '.js';
    if (touch.scripts[src]) return;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.getElementsByTagName('head')[0].appendChild(script);
    touch.scripts[src] = true;
  }
  touch.loadScript('/menu/touch/iscroll.js');
  touch.loadScript('/menu/touch/touch.js');
}

var yScaleCorrection = 3;
var winCnt = 0;
var win = '';
var blank = '';
for(x=1;x<=25;x++) {
  blank += '           ';
}
var panelNo = 0, columnNumber = 0;
var saved = {};
var input = {};
var output = {};
var adjustLine;
var keyCount = 0;

Ext.isWebKit = true;

Ext.ns('IceCap');

IceCap.focus = 0;
IceCap.fieldNo = 0;

var conn = new Ext.data.Connection;
conn.request({
  url: '/menu/icecap_config.xml',
  callback: function(options, success, response) {
    if (success) {
      IceCap.configXml = response.responseXML;
    }
  }
});

// override mouse event
var cursorPosition = {x:0, y:0, element:{}, offset:0, clicks:0};
if (window.Event && document.captureEvents) {
  document.captureEvents(Event.MOUSEDOWN | Event.KEYUP);
}
var doubleClick = false;
document.ondblclick = IceCapSaveDoubleClick;
document.onmousedown = IceCapSaveCursorPosition;
document.onkeyup = IceCapClearCursorPosition;

// Capture key down event and get key code.
// This for getting the correct key code for + and field+ (Extjs returns the same key code for this two keys and others)
var keyunicode = '';

document.onkeydown = function (e) {
  if (!e) var e = window.event;
  keyunicode = e.keyCode ? e.keyCode : e.charCode
}

IceCap.serverRequest = function(me, key, inputData) {
    var async = true,
        url = '',
        doRequest,
        doMask;

    doMask = function( obj ) {
      var obj = obj || {},
          what = obj.todo || 'show',
          msg = obj.msg || me.statusMask.msg;
      if ( what === 'show' ) {
        $('body').mask(msg);
        //me.statusMask.msg = msg;
        //me.statusMask.show();
        //IceCap.addClass(document.body, 'wait');
      }
      if ( what === 'close' ) {
        $('body').unmask();
        //me.statusMask.hide();
        //IceCap.removeClass(document.body, 'wait');
      }
    };

    doRequest = function( isLooped ) {

      Ext.Ajax.request({
        url             : url
        ,method         : 'POST'
        ,params         : me.params
        ,async          : async
        ,serviceProgram : ( typeof this.serviceProgram != 'undefined' && this.serviceProgram.length > 0 ) ? true : false
        ,success        : function ( response, request ) {

          var iceCapWindow,
              result,
              msg = '',
              sep = '',
              i = 0;

          if ( request.serviceProgram && response.responseText.length == 0 ) {
            iceCapWindow = IceCap.activeSession.window[0];
            iceCapWindow.close();
            IceCap.activeSession.windowNumber--;
            return;
          }

          result = IceCap.ServerResponse(response);

          if ( result.statusUpdate ) {

            for (i; i < result.text.length; i++) {
              msg += sep + result.text[i];
              sep = '<br/>';
            }

            doMask({
              msg: msg
            });

            if (!me.params.key) {
              me.params.key = 'ENTER';
            }

            setTimeout(function() {
              doRequest(true);
            }, 500);

            return;

          }

          if ( result.window ) {
            if (request.serviceProgram) {
              result.window.level = 1;
            }
            IceCap.ShowPanel(result);
          }

          doMask({
            todo: 'close'
          });

          return;
        }

      });

    };

    doMask({
      todo: 'show',
      msg: me.statusMask.msg
    });

    if (!me.params) me.params = {};

    if (typeof key != 'undefined') {
      if (key == 'reload') {
        me.params['reloadEmlXml'] = 'true';
      } else {
        async = false;
        var result = IceCap.Form2Parm(key, inputData);
        if (!result.isValid) {
          doMask({
            todo: 'close'
          });
          return;
        };
        me.params = result.params;
      }
    }

    if (me.example.length > 0) {
      url = 'examples/' + me.example;
    } else if (typeof(me.serviceProgram) != 'undefined' && me.serviceProgram.length > 0) {
      url = me.serviceProgram;
    } else {
      url = me.href;
    }

    me.params.i18nLearning = me.i18nLearningMode;

    doRequest();
};

IceCap.session = Ext.extend(Ext.Component,{
  autoEl: 'div'
  ,windowNumber: 0
  ,initComponent: function () {
    var me = this;
    // change prototype attributes
    Ext.data.Connection.prototype.timeout = IceCap.systemSetting.serverRequestTimeout;
    Ext.Msg.minWidth = 200;

    IceCap.Scale();

    me.sessionNumber = parseInt(location.pathname.substring(23,24),10);
    me.id = 'ses' + me.sessionNumber;

    // set event handler for request from parent
    if (window.addEventListener) {
      window.addEventListener("message", IceCap.requestFromParent, false);
    } else {
      window.attachEvent("onmessage", IceCap.requestFromParent);
    }

    me.href = location.href;
    me.href += (me.href.indexOf('?') == -1) ? '?' : '&';
    me.href += 'xscale=' + IceCap.xScale;
    me.href += '&yscale=' + IceCap.yScale;

    // get query string
    var queryString = me.href.substring(me.href.indexOf('?') + 1);
    me.example = IceCap.getQueryString(queryString,'example');
    me.portalWindowID = IceCap.getQueryString(queryString,'portalWindowID');
    me.portalWindow = (me.portalWindowID.length == 0) ? false : true;
    me.portfolioWindowID = IceCap.getQueryString(queryString,'portfolioWindowID');
    me.portfolioWindow = (me.portfolioWindowID.length == 0) ? false : true;

    // tell portfolio to make extra call, when tab is closed
    try {
      if (!me.portalWindow && !me.portfolioWindowID) {
        var portfolio = iceCapGetPortfolio();
        if (portfolio != null) {
          portfolio.fireEvent('setChildAttribute','icecap', location.pathname);
        }
      }
    } catch (err) {
    }

    me.level = 0;
    me.items = [];
    me.viewport = [];
    me.window = [];

    me.i18nLearningMode = false;

    me.statusMask = new Ext.LoadMask(Ext.getBody());
    me.statusMask.msg = 'Please wait...';

    // if internet explorer - disabled F1 help
    if (Ext.isIE) {
      document.onhelp = new Function("return false;");
      window.onhelp = new Function("return false;");
    }

    // key map for icecap (5250 keys)
    me.map = new Ext.KeyMap(document,[{}]);

    // Map ctrl key as enter ?
    if (IceCap.systemSetting.mapCtrlAsEnter) {
      var recordFormat = Ext.data.Record.create(['eventObject','keyValue','shiftRequired']);
      var record = new recordFormat({ eventObject:Ext.EventObject.CTRL,keyValue:'ENTER',shiftRequired:false });
      IceCap.keys.add(record);
    }
    // Map ESC key as !!!
    if (IceCap.systemSetting.mapEscAs != 'ATTN') {
      IceCap.keys.each(function (k) {
        if (k.data.eventObject == Ext.EventObject.ESC) {
          k.data.keyValue = IceCap.systemSetting.mapEscAs;
        }
      })
    }

    // map all keys in iceCap key array
    IceCap.keys.each(function (k) {
      Ext.EventObject.ESC
      k.data.eventObject
      me.map.addBinding({
        key: k.data.eventObject
				,shift: k.data.shiftRequired
				,fn: function (keyCode,e) {
				  e.stopEvent();
				  if (Ext.isIE) {
				    e.browserEvent.keyCode = 0; // Cheat IE to believe that another key was pressed.
				  }
          IceCap.keyPressed = keyCode;

          for(dk in IceCap.activeSession.scn.disabledKeys) {
            var disabledKey = IceCap.activeSession.scn.disabledKeys[dk];
            if (disabledKey.id == this.data.keyValue) {
              IceCap.activeSession.map.disable();
              if (disabledKey.message && disabledKey.message.length > 0) {
                Ext.Msg.alert(menu.I18N['message'], disabledKey.message, IceCap.enableKeymap);
              }
              return;
            }
          }

          IceCap.serverRequest(me, this.data.keyValue);
				}
        ,scope:this
        ,stopEvent:true
      })
    });

    // tab forward (tab only inside icecap)
    me.map.addBinding({
      key: Ext.EventObject.TAB
		  ,shift: false
		  ,fn: function (keyCode,e) {
			  e.preventDefault();
			  if (Ext.isIE) {
				  e.browserEvent.keyCode = 0; // Cheat IE to believe that another key was pressed.
			  }
        IceCap.moveCursorRight();
		  }
      ,scope:this
    });

    // tab backward (tab only inside icecap)
     me.map.addBinding({
      key: Ext.EventObject.TAB
		  ,shift: true
		  ,fn: function (keyCode,e) {
			  e.preventDefault();
			  if (Ext.isIE) {
				  e.browserEvent.keyCode = 0; // Cheat IE to believe that another key was pressed.
			  }
        IceCap.moveCursorLeft();
		  }
      ,scope:this
    });

    // key nav for icecap
    me.nav = new Ext.KeyNav(document,{
      "up" : function(e) {
        IceCap.moveCursorUp();
      }
      ,"down" : function(e) {
        IceCap.moveCursorDown();
      }
      ,scope:this
    });

    // source reference in tab object
    try {
      var portfolio = iceCapGetPortfolio();
      if (portfolio != null) {
        if (!me.portfolioWindowID) {
          portfolio.activeTab.src = me.href;
        }
      }
    } catch (err) {
    }

    IceCap.session.superclass.initComponent.apply(me,arguments);
  }
  ,afterRender: function () {
    IceCap.activeSession = this;
    IceCap.serverRequest(this);
    IceCap.session.superclass.afterRender.apply(this, arguments);
  }
  ,listeners: {
    sendServerRequest: function(key, inputData) {
      IceCap.serverRequest(this, key, inputData);
    }
  }
});
Ext.reg('iceCapSession', IceCap.session);

/** -----------------------------------------------------------------
* iceCap build and show panel
*/
IceCap.ShowPanel = function(scn) {

  scn.disabledKeys = (scn.disabledKeys) ? scn.disabledKeys : [];

	IceCap.activeSession.scn = scn;

  if (scn.onShow && scn.onShow.call) {
    scn.onShow.call(scn,this);
  }

  // open new tab with command (pco command)
  if (scn.cmd) {
    IceCap.runPco(scn);
  }

  // get layout mode, panel/window size
  var layout = IceCap.getObjectLayout(scn);

  IceCap.layout = 'absolute';
  var iceCapObj = new IceCap.Form({
    header:layout.header
    ,region:'center'
    ,autoScroll:true
    ,listeners:{
      resize:function(panel, adjWidth, adjHeight, rawWidth, rawHeight) {
        var grids = iceCapObj.findByType('iceCapEditorGrid');
        for (g=0;g<grids.length;g++) {
          var grid = grids[g];
          if (grid.rendered) {
            grid.fireEvent('setGridHeight', grid, adjHeight);
            grid.doLayout();
          }
        }
      }
    }
  });

  iceCapObj.layout = IceCap.layout;

  var buttonPanel = {};
  if (scn.window.level == 0) {
    iceCapObj.renderTo = IceCap.activeSession.id;
    if (!IceCap.activeSession.portalWindow) {
      iceCapObj.setTitle(scn.window.title);
    }
    var response = IceCap.buildFormBottom(iceCapObj, scn, IceCap.getBodyWidth());
    buttonPanel = response.panel;
    var iceCapViewport = new Ext.Viewport({
      layout: 'border'
      ,id:'iceCapViewport' + IceCap.activeSession.windowNumber
      ,border:false
      ,frame:false
      ,items:[
        iceCapObj
        ,buttonPanel
      ]
    });
    iceCapObj.show();
    iceCapObj.doLayout();
    IceCap.addMessage(scn);
    iceCapObj = IceCap.afterRender(iceCapObj, scn, iceCapViewport);
  } else {
    var response = IceCap.buildFormBottom(iceCapObj, scn, layout.width);
    buttonPanel = response.panel;
    winCnt++;

    // get size from child
    var item = (iceCapObj.items) ? iceCapObj.items.items[0] : {};
    if (item.width) {
      if (item.width > layout.width) {
        layout.width = item.width + 48;
      }
    }
    if (typeof (item.height) != 'undefined') {
      if (item.height > layout.height) {
        layout.height = item.height + 16;
      }
    }

    var items = [], layoutMethod, modal;
    if (response.config.navigationPanel) {
      layoutMethod = 'fit';
      modal = false;
      items = [
        iceCapObj
      ];
    } else {
      layoutMethod = 'border';
      modal = true;
      items = [
        iceCapObj
        ,buttonPanel
      ]
    }

    var iceCapWindow = new IceCap.Window({
      id:'iceCapWindow' + winCnt
      ,title:scn.window.title
      ,width:layout.width
      ,height:layout.height
      ,layout:layoutMethod
      ,modal: modal
      ,items: items
    });

    if (IceCap.systemSetting.openSubPgmInWindow) {
      var left = (scn.window.level * 20);
      var top  = (scn.window.level * 20);
      iceCapWindow.setPosition(left, top);
    }

    iceCapWindow.show();

    iceCapObj.show(null, function() {
      iceCapObj = IceCap.afterRender(iceCapObj, scn, iceCapWindow);
    });
    iceCapObj.doLayout();
    IceCap.addMessage(scn);
    iceCapObj = IceCap.afterRender(iceCapObj, scn, iceCapWindow);
  }

  // stack iceCap object into session stack
  IceCap.activeSession.items[IceCap.activeSession.level] = iceCapObj;
  if (scn.window.level == 0) {
    IceCap.activeSession.viewport[IceCap.activeSession.level] = iceCapViewport;
  } else {
    IceCap.activeSession.window[IceCap.activeSession.level] = iceCapWindow;
  }
}

/** -----------------------------------------------------------------
* Move input data from form to parmeter object
*/
IceCap.Form2Parm = function(key, inputData) {
  var isValid = true;
  var parm={};

  // Find current iceCap Object in session stack
  var iceCapObj = IceCap.activeSession.items[IceCap.activeSession.level];

  // giving field name and input value
  if (Ext.isArray(inputData)) {
    for (var i = 0; i < inputData.length; i++) {
      var field  = inputData[i].field;
      var option = inputData[i].option;
      var f = (field.substring(0,2) == 'g.') ? field.substring(2) : field;
      parm[f]=option;
    }
  }

  key = (key.indexOf('.') > -1) ? key.substring(0,key.indexOf('.')) : key;
	if (key == 'toggle') {
    parm['toggle']='true';
	  if (iceCapObj.scn.emulator == 'advanced') {
	    parm['repositionSubfile']='true';
      IceCap.activeSession.href = IceCap.changeQueryString(IceCap.activeSession.href, 'config', '*DFT');
	  } else {
      IceCap.activeSession.href = IceCap.changeQueryString(IceCap.activeSession.href, 'config', iceCapObj.scn.config);
	  }
	} else {
    if (key=='ENTER' && input.activeObj.type == 'button') {
      key = (input.activeObj.id.indexOf('.') > -1) ? input.activeObj.id.substring(0,input.activeObj.id.indexOf('.')) : key;
      input.activeObj.focus();

      for(dk in IceCap.activeSession.scn.disabledKeys) {
        var disabledKey = IceCap.activeSession.scn.disabledKeys[dk];
        if (disabledKey.id == key) {
          IceCap.activeSession.map.disable();
          if (disabledKey.message && disabledKey.message.length > 0) {
            Ext.Msg.alert(menu.I18N['message'], disabledKey.message, IceCap.enableKeymap);
          }
          var result = {};
          result.isValid = false;
          return result;
        }
      }
    }
    parm['key']=key;
  }

  if (iceCapObj.panelType) {
    parm['panelType'] = iceCapObj.panelType;
    // set active page (tab)
    if (iceCapObj.panelType == 'tabpanel' && typeof(input.activeTab) != 'undefined') {
      parm['activePage'] = input.activeTab + 1;
    } else if (iceCapObj.panelType == 'grid') {
      parm['activePage'] = 1;
    }
  }
  if (iceCapObj.gridPages) {
    parm['gridPages'] = iceCapObj.gridPages;
  }

  // set cursor position
  var obj = (cursorPosition.element.id === undefined) ? undefined : IceCap.getComponent(cursorPosition.element.id);
	if (obj) {
    parm['csrLin'] = obj.lin;
    if (Ext.isIE) {
      if (cursorPosition.x > 0) {
        var x = cursorPosition.x;
      } else {
        var x = obj.col;
      }
      parm['csrCol'] = Math.ceil(x / IceCap.xScale);
      if (parm['csrCol'] < obj.col) {
        parm['csrCol'] = obj.col;
      }
    } else{
      parm['csrCol'] = obj.col + ((cursorPosition.offset) ? cursorPosition.offset : 0);
    }
	} else {
    // obj.y=(fld.lin - adjustLine) * IceCap.yScale - yScaleCorrection;
    parm['csrLin'] = Math.ceil((cursorPosition.y + 30 / (IceCap.yScale - yScaleCorrection))) - adjustLine;
    parm['csrCol'] = Math.ceil(cursorPosition.x / IceCap.xScale);
	}

  if (inputData == 'pcowait') {
    var result = {};
    result.isValid = isValid;
    result.params = parm;
    return result;
  }

  // build parm string of all input fields and then destroy them
  if (iceCapObj.rendered) {
    for(var t=0;t<input.items.length;t++) {
      var items = input.items[t].items;
      for(var i=0;i<=items.length;i++) {
        var f = items[i];
        if(f != undefined) {
          if (f.type == 'button') { continue; }
          if (!f.isValid) { isValid = false } // check if the input value is valid
          if (f.invalid && key == 'ENTER') { isValid = false } // check if the input value is valid. Set in message handler
          if (f.id.substr(f.id.length - 1) == '.') {
            f.id = f.id.substr(0, f.id.length - 1);
          }

          var value = '';
          if (f.hiddenName && f.hiddenName.substring(0,3) == 'DD.') { // dd xtype - take value from hidden field
            if (document.getElementById(f.hiddenName)) {
              value = document.getElementById(f.hiddenName).value;
              document.getElementById(f.hiddenName).value = '';
            }
            if (value.length == 0 && f.xtype != 'DDSQL') {
              value = document.getElementById(f.id).value;
            } else if (value.length == 0) {
              value = f.getValue();
            }
          } else {
            // if combobox and list is visible, fire click event, so value is updated
            if (f.list && f.list.visible) {
              f.view.fireEvent('click',f);
            }
            value = (f.xtype == 'textarea') ? '' : f.getValue();
            if (value.length == 0) {
              value = (document.getElementById(f.id)) ? document.getElementById(f.id).value : '';
            }
          }

          if (value == undefined) {
            value = '';
          }

          value = IceCap.convertInputValue(f, value);
          if (typeof(f.xtype == "string")) {
            if (f.isXType("datefield")) {
              if (f.initialConfig.value && f.initialConfig.value.format) {
                f.initialConfig.value = f.initialConfig.value.format(f.format);
              }
            }
          }

          if (f.initialConfig.value == undefined) {
            f.initialConfig.value = '';
          }
	        if (f.emptyText == undefined || f.emptyText == null) {
            f.emptyText = 'icecap is cooooooooool';
          }

          var valueChanged = false;
          if (value != f.initialConfig.value && value != f.emptyText) {   // modified data tag :-)
            valueChanged = true;
          } else if (f.mandatory) {
            valueChanged = true;
          } else if (f.modifiedDataTag) {
            valueChanged = true;
          }

          if (valueChanged) {
            f.initialConfig.value = value;

            var elmId = f.id;
            if (elmId.substr(elmId.length - 1) == '.') {
              elmId = elmId.substr(0, elmId.length - 1);
            }
            if (elmId.substr(0, 3) == 'win') {
              elmId = elmId.substr(5);
            }
            parm[elmId] = value;
  	      }
        }
      }
    }
  }

  var result = {};
  result.isValid = isValid;
  result.params = parm;
  return result;
}

/** -----------------------------------------------------------------
* Handler response from server (check and cleanup from previous panel)
*/
IceCap.convertInputValue = function(field, value) {
  var newValue = value;
  if (field.convertToUpperCase) {
    newValue = Ext.util.Format.uppercase(value);
  }
  if (typeof(field.xtype == "string")) {
    if (field.isXType("datefield")) {
      if (value.format) {
        newValue = value.format(field.format);
      }
    } else if (field.isXType("numberfield")) {
    } else if (field.isXType("checkbox")) {
      if (value) {
        newValue = field.trueValue;
      } else {
        newValue = field.falseValue;
      }
    }
  }
  return newValue;
}

/** -----------------------------------------------------------------
* Handler response from server (check and cleanup from previous panel)
*/
IceCap.ServerResponse = function(response) {
  IceCap.removeClass(document.body, 'wait');

  var result = {};

  try {
    eval("result = " + response.responseText); // materialize the JSON object;
  } catch (err) {
    Ext.Ajax.request({
      url: '/menu/icecaplog.aspx'
      ,method: 'POST'
      ,params: { text: response.responseText }
    });
    IceCap.activeSession.map.disable();
    Ext.Msg.alert(menu.I18N['message'],'Invalid server response : ' + err + '<br/> An error log is written.',IceCap.enableKeymap);
    return 'error';
  }


  if (result.close) {
    IceCap.closeTab();
    return 'close';
  } else {
    // check error
    if (!IceCap.Monitor(result) && !result.statusUpdate) {
      IceCap.cleanUp(result);
    }
  }
  return result;
}

/** -----------------------------------------------------------------
* DOM clean up depending on icecap window level
* if response level = current level then same window
* if response level > current level then new window
* if response level < current level then delete DOM object
*/

IceCap.cleanUp = function(scn) {
  // destroy message status bar
  var msg = Ext.getCmp('iceCap-message-bar');
  if (msg) {
    msg.plugins.hideErrors();
    msg.plugins.onDestroy();
  }
  // check window level
  if (scn.window.level > IceCap.activeSession.level) { // higher level = new window
    IceCap.activeSession.level++;
    IceCap.activeSession.windowNumber++;
  } else if (scn.window.level < IceCap.activeSession.level) { // lower level = window closed, then cleanup after window
    for (i = IceCap.activeSession.level;i >= scn.window.level;i--) {
      var iceCapObj = IceCap.activeSession.items[i];
      if (i > scn.window.level) {
        var iceCapWindow = IceCap.activeSession.window[i];
        iceCapWindow.close();
        IceCap.activeSession.windowNumber--;
      }
      if (typeof (iceCapObj) != "undefined") {
        iceCapObj.destroy();
        IceCap.activeSession.items[i].remove();
      }

      if (i == 0) {
        var iceCapViewport = IceCap.activeSession.viewport[i];
        if (typeof (iceCapViewport) != "undefined") {
          iceCapViewport.destroy();
          IceCap.activeSession.viewport[i].remove();
        } else {
          var iceCapWindow = IceCap.activeSession.window[i];
          if (typeof (iceCapWindow) != "undefined") {
            iceCapWindow.destroy();
            IceCap.activeSession.window[i].remove();
          }
        }
      } else {
        var iceCapWindow = IceCap.activeSession.window[i];
        iceCapWindow.destroy();
        IceCap.activeSession.window[i].remove();
      }
    }
    IceCap.activeSession.level = scn.window.level;
  } else if (IceCap.activeSession.items.length > 0) { // same level = same window, cleanup for new render
    var iceCapObj = IceCap.activeSession.items[IceCap.activeSession.level];
    iceCapObj.destroy();
    IceCap.activeSession.items[IceCap.activeSession.level].remove();

    if (IceCap.activeSession.level == 0) {
      var iceCapViewport = IceCap.activeSession.viewport[IceCap.activeSession.level];
      if (typeof (iceCapViewport) != "undefined") {
        iceCapViewport.destroy();
        IceCap.activeSession.viewport[IceCap.activeSession.level].remove();
      } else {
        var iceCapWindow = IceCap.activeSession.window[IceCap.activeSession.level];
        if (typeof (iceCapWindow) != "undefined") {
          iceCapWindow.destroy();
          IceCap.activeSession.window[IceCap.activeSession.level].remove();
        }
      }
    } else {
      var iceCapWindow = IceCap.activeSession.window[IceCap.activeSession.level];
      if (typeof (iceCapWindow) != "undefined") {
        iceCapWindow.destroy();
        IceCap.activeSession.window[IceCap.activeSession.level].remove();
      }
    }
  }
}


/** -----------------------------------------------------------------
* Check response for error
*/
IceCap.Monitor = function(scn) {
  var error = false;
  if (scn.status == -1) { // -1 = Status update
    return error;
  }

  // check status
  if (scn.status < 0 ) { // -1 = Status update
    if (scn.status == -1) {
      Ext.Msg.buttonText.yes = "Retry";
      Ext.Msg.buttonText.no = "Signoff";
      Ext.Msg.show({
        title: 'Message'
        ,msg: 'Your job encounted a lock'
        ,buttons: Ext.Msg.YESNO
        ,fn: IceCap.retryJob
      });
      error = true;
    } else {
      IceCap.activeSession.map.disable();
      Ext.Msg.confirm('Message', 'Your job encounted a serious error: ' +scn.status, IceCap.closeTab);
      error = true;
    }
  }

  // error message
  if (scn.messageText && scn.messageText.length > 0) {
    if (scn.messageID == 'ICE9999') {
      IceCap.signOn();
      error = true;
    } else if (scn.messageID == 'ICE9998') {
      IceCap.limitCapabilitiesUser(scn.messageHeader, scn.messageText);
      error = true;
    } else if (scn.messageID == 'ICE0001') {
      IceCap.invalidProfile(scn.messageHeader, scn.messageText);
      error = true;
    } else {
      IceCap.activeSession.map.disable();
      // disable tab closable
      var portfolio = iceCapGetPortfolio();
      if (portfolio != null) {
        portfolio.fireEvent('setTabClosable', false);
      }
      if (scn.messageID == 'ICE0002') {
        Ext.Msg.show({
          title:menu.I18N['message']
          ,msg:scn.messageText
          ,buttons: Ext.Msg.OK
          ,fn: function() {
            IceCap.closeTab();
          }
          ,icon: Ext.MessageBox.WARNING
        });
      } else {
        var header = (scn.messageHeader && scn.messageHeader.length > 0) ? scn.messageHeader : menu.I18N['message'];
        Ext.Msg.buttonText.yes = "OK";
        Ext.Msg.buttonText.no = menu.I18N['displayJoblog'];
        Ext.Msg.show({
          title:header
          ,msg:scn.messageText
          ,buttons: Ext.Msg.YESNO
          ,fn: IceCap.displayLog
          ,icon: Ext.MessageBox.WARNING
        });
      }
      error = true;
    }
  }
  return error;
}

/** -----------------------------------------------------------------
* Signon required - prompt for user id & password
*/
IceCap.signOn = function() {
  IceCap.activeSession.map.disable();

  var signon = new Ext.FormPanel({
    labelWidth:75
    ,frame:true
    ,title: 'Sign on'
    ,width: 350
    ,hidden:true
    ,defaults: {width: 230}
    ,style:'margin: 200px 0px 0px -150px;'
    ,defaultType: 'textfield'
    ,items:[{
      fieldLabel: menu.I18N['userId']
      ,name:'user'
      ,id:'user'
      ,maxLength:128
      ,height:IceCap.yScale - 3
      ,allowBlank:false
      ,msgTarget:'under'
    },{
      fieldLabel: menu.I18N['password']
      ,name: 'password'
      ,id: 'password'
      ,maxLength:128
      ,height:IceCap.yScale - 3
      ,inputType:'password'
      ,allowBlank:false
      ,msgTarget:'under'
    }]
    ,buttons: [{
      text: 'Login'
      ,type: 'submit'
      ,handler: function(){
        if (signon.getForm().isValid()) {
          signon.getForm().submit({
            url:'/menu/MNU001S.asp'
            ,success: function() {
              IceCap.activeSession.map.enable();
              window.location = IceCap.activeSession.href;
            }
          })
        }
      }
    },{
      text: 'Cancel'
      ,handler: function(){
        signon.hide();
        IceCap.closeTab();
      }
    }]
  });

  signon.render('ses'+IceCap.activeSession.sessionNumber);

  signon.getEl().alignTo('ses'+IceCap.activeSession.sessionNumber, 'c');
  signon.show();
  Ext.getCmp('user').focus(true,10);
}

/** -----------------------------------------------------------------
* Retry or Close Virtual Terminal job, if status < 0
*/
IceCap.retryJob = function(btn) {
  if (btn == 'yes') {
    this.fireEvent('sendServerRequest','ENTER');
  } else if (typeof (iceCapCloseBreakout) == 'function') {
    iceCapCloseBreakout(IceCap.activeSession, true);
  }
}

/** -----------------------------------------------------------------
* icecap message alert
*/
IceCap.invalidProfile = function(title, msg) {
  IceCap.activeSession.map.disable();

  var win = new Ext.Window({
    frame:true
    ,layout:'form'
    ,title: title
    ,bodyStyle:'padding:5px 5px 0'
    ,width: 350
    ,html:msg
    ,buttons: [{
      text: 'OK'
      ,id:'OK'
      ,handler:function() {
        win.hide();
        IceCap.closeTab();
      }
    },{
      text: 'Signon display'
      ,handler:function() {
        win.hide();
        IceCap.activeSession.map.enable();
        window.location = 'icecap.aspx';
      }
    }]
  });

  win.show();

  Ext.getCmp('OK').focus();
}

/** -----------------------------------------------------------------
* User with limit capabilities, send warning
*/
IceCap.limitCapabilitiesUser = function(title, msg) {
  IceCap.activeSession.map.disable();

  var win = new Ext.Window({
    frame:true
    ,layout:'form'
    ,title: title
    ,bodyStyle:'padding:5px 5px 0'
    ,width: 500
    ,labelWidth:200
    ,items:[{
      xtype:'label'
      ,html:msg
    },{
      xtype:'label'
      ,html:'<div style="height:40px;">&nbsp;</div>'
    },{
      xtype:'checkbox'
      ,fieldLabel:menu.I18N['showWindowAgain']
      ,listeners: {
        check: function(box) {
          Ext.Ajax.request({
            method:'POST'
            ,url:'/menu/setsgv.aspx?name=limitCapabilitiesMessage&value=' + box.checked
          })
        }
      }
    }]
    ,buttons:[{
      text:menu.I18N['continue']
      ,handler:function() {
        win.hide();
        IceCap.activeSession.map.enable();
        IceCap.activeSession.href += (IceCap.activeSession.href.indexOf('?') == -1) ? '?' : '&';
        IceCap.activeSession.href += 'bypassLimituser=true';
        window.location = IceCap.activeSession.href;
      }
    },{
      text:menu.I18N['exit']
      ,id:'OK'
      ,handler:function() {
        win.hide();
        IceCap.closeTab();
      }
    }]
  });

  win.show();

  Ext.getCmp('OK').focus();
}

/** -----------------------------------------------------------------
* Display job log
*/
IceCap.displayLog = function(btn) {
  if (btn == 'no') {
    var ds = new Ext.data.JsonStore({
      autoLoad:true
		  ,totalProperty:'totalRows'
		  ,root:'rows'
		  ,url:'/menu/mnu014l.asp'
		  ,remoteSort: true
	  });

    var grid = new Ext.grid.GridPanel({
      store: ds
      ,anchor:'100% 100%'
      ,columns:
        [
          {header: menu.I18N['text'], sortable:false, dataIndex: 'text'}
        ]
      ,viewConfig: {
        forceFit:true
      }
      ,loadMask:false
    });

    var windowCount = 0;
    var win = new Ext.Window({
      title:menu.I18N['displayJoblog']
      ,id:'logWindow' + windowCount++
      ,layout: 'fit'
      ,width: 720
      ,height: 500
      ,minWidth: 60
      ,minHeight: 50
      ,buttonAlign:'right'
      ,bodyStyle:'padding:5px;'
      ,items:grid
      ,buttons:[{
        text: menu.I18N['closeWindow']
        ,handler: function() {
          win.hide()
        }
      }]
    });
    win.show();
  }
  IceCap.enableKeymap();
}

/** -----------------------------------------------------------------
* Enable key map again after ex. message box with OK button
*/
IceCap.enableKeymap = function() {
  IceCap.activeSession.map.enable();
  // enable tab closable again
  var portfolio = iceCapGetPortfolio();
  if (portfolio != null) {
    portfolio.fireEvent('setTabClosable', true);
  }

  // set focus
  if (typeof(IceCap.activeSession.scn) != 'undefined') {
    var obj = IceCap.getComponent('i'+(IceCap.activeSession.scn.focus-1));
    if (obj) {
      IceCap.setFocus(obj, 10);
    } else {
      IceCap.focusOnFirstField();
    }
  }
}

/** -----------------------------------------------------------------
* Set iceCap Object attribute after render
*/
IceCap.afterRender = function(iceCapObj, scn, parent) {
  // resize border layout to force new render (to fix scrollbars)
  var center = parent.getLayout().center;;
  if (center) {
    var size = center.panel.getSize();
    center.panel.setHeight(size.height-1);
  }
  parent.doLayout();

	// Add marking tool for copy to clipboard
  $(iceCapObj.el.dom).smClipboardCopy({
    plugins       : ['allerinputfields', 'allergrids'],
    threshold     : 1
  });

  // add option field for editor grid
  var g = 0, r = 0, c = 0;
  var grids = iceCapObj.findByType('iceCapEditorGrid');
  for (g=0;g<grids.length;g++) {
    if (grids[g].windowNumber == iceCapObj.windowNumber) {
      var gridConfig = grids[g].gridConfig;

      iceCapObj.panelType = 'grid';
      iceCapObj.gridPages = grids[g].gridConfig.gridPages;

      var cm = grids[g].getColumnModel();
      var numberOfColumns = cm.getColumnCount();

      var store = grids[g].getStore();
      var numberOfRows = store.getCount();

      // Loop grid columns for renders
      for (c=0;c<numberOfColumns;c++) {
        var col = cm.getColumnById(c);
        if (typeof(col.renderer) == 'function' || col.data) {
          // build option field for each grid row
          for (r=0;r<numberOfRows;r++) {
            var rec = store.getAt(r);

            if (gridConfig.showOption) {
              var renderOptionField = Ext.isEmpty(rec.data.opt) ? true : rec.data.opt;
              if (typeof(col.renderer) == 'function' && renderOptionField) {
                if (rec.id.indexOf('q.') > -1) {
                  var containerId = 'win' + grids[g].windowNumber + '.qCol.' + c;
                  if (document.getElementById(containerId)) {
                    var fld = IceCap.getQuickOptionField(col.dataIndex, gridConfig.quickOption);
                    var config = IceCap.buildField('advanced', scn.extraCls, fld)
                    config.grid = grids[g];
                    config.rowIndex = r;
                    var obj = Ext.ComponentMgr.create(config,'textfield');
                    obj.render(containerId);
                  }
                } else if (col.dataIndex == gridConfig.optionDataIndex) {
                  var fld = {
                    type:'input',
                    lin:rec.data['lin'],
                    col:rec.data['col'],
                    id:rec.id,
                    dta:rec.data[col.dataIndex],
                    len:gridConfig.optionFieldLength,
                    atr:'24',
                    ffw:0x4020
                  };
                  var config = IceCap.buildField('advanced', scn.extraCls, fld)
                  config.id = 'win' + grids[g].windowNumber + '.' + ((rec.id.indexOf('g.') > -1) ? rec.id.substring(rec.id.indexOf('g.') + 2) : rec.id) + '.' + rec.data['id'+(c+1)];
                  config.grid = grids[g];
                  config.rowIndex = r;
                  var obj = Ext.ComponentMgr.create(config,'textfield');
                  obj.render('win' + grids[g].windowNumber + '.o.'+rec.id);
                }
              }
            }

            if (rec.data['io'+(c+1)] == 'b' || rec.data['io'+(c+1)] == 'i') {
              var elmId = 'win' + grids[g].windowNumber + '.'+ rec.id + '.c' + (c+1);
              if (document.getElementById(elmId)) {
                var fld = {
                  type:'input',
                  lin:rec.data['lin'],
                  col:col.col,
                  id:rec.id,
                  dta:rec.data[col.dataIndex],
                  len:col.len,
                  atr:'24',
                  ffw:0x4000
                };
                if (col.align == 'right') {
                  fld.ta = 'right';
                }
                var config = IceCap.buildField('advanced', scn.extraCls, fld)
                config.id = 'win' + grids[g].windowNumber + '.' + ((rec.id.indexOf('g.') > -1) ? rec.id.substring(rec.id.indexOf('g.') + 2) : rec.id) + '.' + rec.data['id'+(c+1)];
                config.grid = grids[g];
                config.rowIndex = r;
                var obj = Ext.ComponentMgr.create(config,'textfield');
                obj.render(elmId);
              }
            }

            // extra columns
            if (col.data) {
              var containerId = 'iceCap-extraColumn-' + r + '-' + c;
              if (document.getElementById(containerId)) {
                var obj = IceCap.extraColumn(col.data, rec);
                obj.render(containerId);
              }
            }
          }
        }
      }
    }
  }

  input = IceCap.getElementsByClass('iceCap-input-field', iceCapObj, 'input');
  input = IceCap.sortInputFields(input);

  // set panel type
  var types = iceCapObj.findByType('IceCap.tabPanel');
  if (types.length == 0) {
    var types = iceCapObj.findByType('iceCap.tabPanel');
  }
  if (types[0] && types[0].xtype == 'IceCap.tabPanel' || types[0] && types[0].xtype == 'iceCap.tabPanel') {
    iceCapObj.panelType = 'tabpanel';
    input.activeTab = types[0].items.indexOf(types[0].getActiveTab());
  }

  // disable keynav if no input field.
  if (input.items[input.activeTab] && input.items[input.activeTab].items.length == 0) {
    IceCap.activeSession.nav.disable();
  } else {
    IceCap.activeSession.nav.enable();
  }
  // add key event to all input field
  for(var t=0;t<input.items.length;t++) {
    for(var i=0;i<input.items[t].items.length;i++) {
      var item = input.items[t].items[i];
      if (item.xtype == 'checkbox' || item.xtype == 'radio') {
        var obj = Ext.fly(item.innerWrap.id);
      } else if (item.xtype == 'button') {
        var obj = item.btnEl;
      } else {
        var obj = item;
        // insert placeholder
        if (Ext.isIE && typeof(obj.id) != 'undefined') {
          var f = document.getElementById(obj.id);
          var placeholder = f.getAttribute('placeholder');
          if (placeholder != null && placeholder.length > 0 && f.value.length < 1) {
            f.value = placeholder;
            f.className += ' iceCap-placeholder';
          }
        }
      }
      if (obj != undefined) {
        if (obj.xtype == 'datefield') {
		      obj.setValue(obj.getValue());
		    }
	      obj.on({
	        'focus' : {
            fn: function(obj) {
              keyCount = 0;

              // remove placeholder
              if (Ext.isIE && typeof(obj.id) != 'undefined') {
                var f = document.getElementById(obj.id);
                var placeholder = f.getAttribute('placeholder');
                if (placeholder != null && placeholder.length > 0 && f.value == placeholder) {
                  obj.setValue('');
                  obj.removeClass('iceCap-placeholder');
                }
              }

		          // IceCap.focus = this.id.substr(1);
				      if (obj.type == 'input' || obj.type == 'button') {
                if (obj.pos) {
                  input.activeObj = obj;
                } else {
                  input.activeObj = Ext.getCmp(obj.id);
                }
                // if grid row, select row
                if (input.activeObj.grid != undefined) {
                  input.activeObj.grid.getSelectionModel().selectRow(input.activeObj.rowIndex);
                }
                if (obj.type == 'input') {
				          cursorPosition.element = this;
				          cursorPosition.offset=0;
				          obj.addClass('iceCap-input-' + obj.atr + '-focus');
                }
				      } else if (obj.type == 'output') {
				        cursorPosition.element = this;
				        cursorPosition.offset=0;
				        obj.addClass('iceCap-output-' + obj.atr + '-focus');
				      }
            }
            ,scope:obj
          }
        });
	      obj.on({
	        'blur' : {
            fn: function(obj) {
              keyCount = 0;

              // insert placeholder
              if (Ext.isIE && typeof(obj.id) != 'undefined') {
                var f = document.getElementById(obj.id);
                var placeholder = f.getAttribute('placeholder');
                if (placeholder != null && placeholder.length > 0 && f.value.length < 1) {
                  obj.setValue(placeholder);
                  obj.addClass('iceCap-placeholder');
                }
              }

              // remove focus class name
				      if (obj.type == 'input') {
				        obj.removeClass('iceCap-input-' + obj.atr + '-focus');
                // set text alignment depending on input type
                var f = document.getElementById(obj.id);
                if (f) {
                  var v = obj.getValue();
                  if (IceCap.isNumeric(v) && !obj.alfaNumeric) {
                    //f.style.textAlign = 'right';
                  } else if (f.style) {
                    f.style.textAlign = 'left';
                  }
                }
				      } else if (obj.type == 'output') {
				        obj.removeClass('iceCap-output-' + obj.atr + '-focus');
				      }
              // auto enter
		          if (obj.autoEnter) {
                IceCap.autoEnter(obj);
              }
              obj.textSelected = false;
            }
            ,scope:obj
            ,delay:1  // be sure that this event is fired after keypress
          }
        });
        if (obj.type == 'input' || obj.type == 'output') {
          IceCap.addKeyEvent(obj);
        }
      }
    }
  }

  // save screen object
  iceCapObj.scn = scn;

  // display message, if any
  if (scn.msgBox.text.length > 0 && !scn.cmd) {
    IceCap.activeSession.map.disable();
    // disable tab closable
    var portfolio = iceCapGetPortfolio();
    if (portfolio != null) {
      portfolio.fireEvent('setTabClosable', false);
    }
    Ext.Msg.alert('Messsage', scn.msgBox.text, IceCap.enableKeymap);
  } else {
    // set focus
    if (scn.inFlds > 0) {
      var obj = IceCap.getComponent('i'+(scn.focus-1));
      if (obj) {
        if (IceCap.systemSetting.selectTextWhenFieldFocus) {
          obj.focus(true,10);
          obj.textSelected = true;
        } else {
          obj.focus(false,10);
        }
      } else {
        IceCap.focusOnFirstField();
      }
    } else if (scn.csrLin > 0) { // set focus in output field
      if (scn.window.level == 0) {
        var csrLin = scn.csrLin;
        var csrCol = scn.csrCol;
      } else {
        var csrLin = scn.csrLin - scn.window.lin;
        var csrCol = scn.csrCol - scn.window.col;
      }
      // find output field inside cursor line & column position
      var output = IceCap.getElementsByClass('iceCap-output-field', iceCapObj, 'input');
      for (i=0;i<output.length;i++) {
        if (csrLin == output[i].lin && csrCol >= output[i].col && csrCol <= output[i].col+output[i].len) {
          var obj = output[i];
          var pos = csrCol - output[i].col;
          if(obj.el.dom.createTextRange) {
            var range = obj.el.dom.createTextRange();
            range.move("character", pos-1);
            range.select();
          } else if(obj.el.dom.selectionStart) {
            obj.el.dom.focus();
            obj.el.dom.setSelectionRange(pos, pos);
          } else {
            obj.focus(false,10);
          }
          break;
        }
      }
    } else if (Ext.isIE) {  // focus at ENTER button
      var obj = Ext.getCmp('ENTER');
      if (typeof (obj) != 'undefined') obj.focus(false,10);
    }
  }

  return iceCapObj;
}

/** -----------------------------------------------------------------
* get quick option field for column data index
*/
IceCap.getQuickOptionField = function(index, quickOption) {
  var i = 0;
  for (i = 0; i < quickOption.length; i++) {
    if (quickOption[i].dataIndex == index)
      return quickOption[i]
  }
  return {};
}

/** -----------------------------------------------------------------
* Build form
*/
IceCap.buildForm = function(iceCapObj, scn) {
  iceCapObj.defaultType = 'textfield';
  iceCapObj.items = IceCap.buildFormFields(iceCapObj, scn);

  // set title for parent object
  if (iceCapObj.ownerCt) {
    iceCapObj.ownerCt.setTitle(scn.window.title);
  }
}

/** -----------------------------------------------------------------
* build input -& output fields
*/
IceCap.buildFormFields = function(iceCapObj, scn) {
  var items = [];

  var simpleFieldsBuild = false;
  saved.IceCapObj = iceCapObj;
  saved.SessionNumber = IceCap.activeSession.sessionNumber;
  saved.Scn = scn;

  // check extra meta fields
  for(fx in scn.metaFields) {
    var fld=scn.metaFields[fx];
    if (fld.xtype) {
      if (fld.xtype == 'iceCapEditorGrid') {
        iceCapObj.autoScroll = false;
      }
      if (fld.items) {
        for(i=0;i<fld.items.length;i++) {
          if (fld.items[i].xtype && fld.items[i].xtype == 'iceCapSimplePanel') {
            simpleFieldsBuild = true;
            break;
          }
        }
      }
		}
    if (fld.configOptions) {
      var configOptions = fld.configOptions;
      if (!Ext.isEmpty(configOptions.tabClosable)) {
        var portfolio = iceCapGetPortfolio();
        if (portfolio != null) {
          portfolio.fireEvent('setTabClosable', configOptions.tabClosable);
        }
      }
		}
  }

  // build fields or input/output
  if (scn.fields) {
    // build fields (advanced (form) layout)
    for(fx in scn.fields) {
      var fld=scn.fields[fx];
      if (fld.type == 'input' || fld.type == 'output') {
        var item = IceCap.buildField(scn.emulator, scn.extraCls, fld, 0, 0, scn.focus);
        if (IceCap.isObject(item)) {
          items.push(item);
        }
      } else if (fld.type == 'label') {
        items.push(IceCap.buildLabelField(fld));
      } else if (fld.type == 'grid') {
        items.push(
          new IceCap.Grid({
            gridConfig:fld.grid
          })
        );
        iceCapObj.panelType = 'grid';
        iceCapObj.gridPages = fld.grid.gridPages;
      }
    }
  } else {
    if (!simpleFieldsBuild) {
      var fields = IceCap.buildFormSimpleFields(iceCapObj, scn);
      items = items.concat(fields.items);
    }
  }

  // build extra meta fields fields
  for(fx in scn.metaFields) {
    var fld=scn.metaFields[fx];
    if (fld.xtype) {
      if (fld.col) fld.x = (fld.col - fields.adjustColumn) * IceCap.xScale;
      if (fld.lin) fld.y = (fld.lin - fields.adjustLine)   * IceCap.yScale - yScaleCorrection;
      items.push(fld);
		}
  }

  return items;
}

/** -----------------------------------------------------------------
* build input -& output fields for simple fields
*/
IceCap.buildFormSimpleFields = function(iceCapObj, scn) {
  var iCnt = 0;
  var items = [];

  // find first line number and calculate factor so content start at line 1
  var firstLine = 999;
  for(fx in scn.input) {
    var fld=scn.input[fx];
    if (fld.lin < firstLine) {
      firstLine = fld.lin
    }
  }
  for(fx in scn.output) {
    var fld=scn.output[fx];
    if (fld.lin < firstLine) {
      firstLine = fld.lin
    }
  }
  adjustLine = firstLine - 1;
  // build input fields (simple (absolute) layout)
  for(fx in scn.input) {
    var fld=scn.input[fx];
    if(fld.col != undefined) {
      fld.type = 'input';
      var item = IceCap.buildField(scn.emulator, scn.extraCls, fld, adjustLine, 0, scn.focus);
      if (IceCap.isObject(item)) {
        items[iCnt++] = item;
      }
    }
  }
  // build output fields
  for(fx in scn.output) {
    var fld=scn.output[fx];
    if(fld.col != undefined) {
      fld.type = 'output';
      var item = IceCap.buildField(scn.emulator, scn.extraCls, fld, adjustLine, 0, scn.focus);
      if (IceCap.isObject(item)) {
        items[iCnt++] = item;
      }
    }
  }

  var result = {};
  result.adjustLine   = adjustLine;
  result.adjustColumn = 0;
  result.items        = items;
  return result;
}

/** -----------------------------------------------------------------
* build form bottom (f-keys and message line)
*/
IceCap.buildFormBottom = function(iceCapObj, scn, width) {
  var config = {
    buttons: {
      region: 'south',
      navigationPanel: false
    }
  }

  var xml,
      dq = Ext.DomQuery;
      node = dq.selectNode('config/'+ ((scn.config == '*DFT') ? 'default' : scn.config) + '/layout/buttons', IceCap.configXml);
  if (node) {
    xml = (node.outerHTML) ? node.outerHTML : node.xml;
  }
  if (xml) {
    config = xml2json.parser(xml);
    if (scn.window.level > 0 && config.buttons.region == 'west') {
        //config.buttons.renderTo = 'navigationPanel';
        //config.buttons.region = 'south';
    }
  }

  var bodyStyle;
  if (config.buttons.region == 'west') {
    config.buttons.id = 'navigationPanel';
    config.buttons.navigationPanel = true;
    bodyStyle = 'padding-left:0px';
  } else {
    bodyStyle = 'padding-left:12px';
  }

  var result = IceCap.buildFormButtons(iceCapObj, scn, width, config.buttons);

  var header;
  if (config.buttons.split || config.buttons.title) {
    header = true;
  } else {
    header = false;
  }
  var panel = Ext.getCmp('navigationPanel');
  if (panel) {
      config.buttons.navigationPanel = true;
      panel.removeAll();

      for (var i = 0; i < result.items.length; i++) {
        panel.add(result.items[i]);
      }
      panel.doLayout();
  } else {
    var panelConfig = {
      border:false
      ,bodyBorder:false
      ,bodyStyle:bodyStyle
      ,header:header
      ,height:result.height
      ,orignalHeight:result.height
      ,items:result.items
      ,listeners:{
        resize:function(panel) {
          if (panel.region == 'west') return;

          panel.suspendEvents();

          if (panel.isResized) {
            panel.setHeight(46);
          }
          if (panel.body.dom.scrollHeight > 46) {
            panel.setHeight(panel.body.dom.scrollHeight);
            if (panel.body.dom.scrollHeight != panel.orignalHeight) {
              panel.isResized = true;
            }
          }

          panel.resumeEvents();
        }
      }
    };
    panel = new Ext.Panel(Ext.apply(panelConfig, config.buttons));
  }


  var response = {
    panel: panel,
    config: config.buttons
  }
  return response;
}

/** -----------------------------------------------------------------
* build form bottom (f-keys and message line)
*/
IceCap.addMessage = function(scn) {
  if (scn.message) {
    var msg = Ext.getCmp('iceCap-message-bar');
    for(fx in scn.message) {
      var fld=scn.message[fx];
      if (fld.text != undefined) {
        msg.plugins.addMessage({
          id:fx
          ,text:fld.text
        });
      }
    }
  }
}

/** -----------------------------------------------------------------
* build input field
*/
IceCap.buildField = function(emulator, extraCls, fld, adjustLine, adjustColumn, focusField) {
  var obj = {};
  var adjustLine   = (adjustLine)   ? adjustLine   : 0;
  var adjustColumn = (adjustColumn) ? adjustColumn : 0;

  obj.invalid = false;
  obj.iceCapTriggerField = false;

  if(fld.atr == undefined) {
    if (fld.type == 'input') {
      fld.atr = '24';
    } else {
      fld.atr = '20';
    }
  }
  if(fld.dta == undefined) {
    fld.dta = '';
  }
  if(fld.off == undefined) {
    fld.off = 0;
  }
  if(fld.ffw == undefined) {
    if (fld.type == 'input') {
      fld.ffw = 0x4020;
    }
  }

  if (fld.off > 0) {
      obj.value = blank.substring(0,fld.off) + fld.dta;
  } else {
    obj.value = fld.dta;
  }
  obj.windowNumber = IceCap.activeSession.windowNumber;

  if (fld.metaData) {
    obj = Ext.apply(obj, fld.metaData);
  }

  // Nondisplay & protected (act as a hidden field)
  if(fld.atr == '27' && (fld.ffw & 0x2000) || obj.xtype == 'hidden') {
    obj.xtype = 'hidden';
    obj.inputType = 'hidden';
    obj.labelSeparator = '';
    obj.cls = 'iceCap-hidden-field';
    if (IceCap.activeSession.windowNumber) {
      obj.id = IceCap.activeSession.id + '.win' + IceCap.activeSession.windowNumber + '.' + fld.id;
    } else {
      obj.id = IceCap.activeSession.id + '.' + fld.id;
    }
    return obj;
  }

  obj.atr  = fld.atr;
  obj.type = fld.type

  obj.iceCapInputField = true;
  obj.xtype = 'textfield';
  obj.height=IceCap.yScale - 3;

  // Continue field: Convert to textarea
  if(fld.fcw == '0xFFFF8601') {
    IceCap.continueField = {
      id: fld.id,
      col: fld.col,
      lin: fld.lin,
      count: 2
    }
    return;
  }
  if(fld.fcw == '0xFFFF8603') {
    IceCap.continueField.count++; 
    return;
  }
  if(fld.fcw == '0xFFFF8602') {
    obj.xtype = 'textarea';
    fld.id = (fld.len * IceCap.continueField.count) + '.' + IceCap.continueField.id;
    fld.col = IceCap.continueField.col;
    fld.lin = IceCap.continueField.lin;
    obj.height = (IceCap.yScale - 3) * ((IceCap.continueField.count > 4) ? IceCap.continueField.count - 3 : IceCap.continueField.count);
  }

  // icecap attribute
  if (fld.type == 'output') {
		obj.id  = 'o' + (IceCap.fieldNo++);
  } else if (fld.id) {
    if (typeof(IceCap.activeSession.windowNumber) != 'undefined') {
      obj.id=IceCap.activeSession.id + '.win' + IceCap.activeSession.windowNumber + '.' + fld.id;
    } else {
      obj.id=IceCap.activeSession.id + '.' + fld.id;
    }
  }
	obj.col = fld.col;
	obj.lin = fld.lin;
  if (fld.type == 'output') {
    obj.len = fld.len;
    obj.width=Math.round((obj.value.length*0.165) * (IceCap.xScale * 6.1) + 5);
  } else {
    obj.maxLength = fld.len;
    obj.width=Math.round((fld.len *0.14) * (IceCap.xScale * 6.1) + 5);
    if (obj.width > 600) {
      obj.width = 600;
    }
  }

  if(fld.fcw == '0xFFFF8602') {
    obj.maxLength = fld.len * IceCap.continueField.count;
    delete IceCap.continueField;
  }

  obj.hideLabel=true;
  if (emulator == 'advanced') {
    if (fld.label) {
      obj.hideLabel=false;
      obj.fieldLabel=fld.label;
      obj.labelStyle='color:#008000;'
      if(fld.labelWidth > 0) {
        obj.labelStyle='width:'+fld.labelWidth+'px;';
      } else {
        obj.labelStyle='width:200px;';
      }
      if (fld.labelStyle) {
        obj.labelStyle+=fld.labelStyle;
      } else {
        obj.labelStyle+='color:'+IceCap.activeSession.scn.labelColor+';';
      }
      obj.labelSeparator=fld.labelSep;
    }
  } else if (typeof(obj.fieldLabel) == 'undefined') {
    obj.x = (((fld.pageColumn) ? fld.pageColumn : fld.col) - adjustColumn) * IceCap.xScale;
    obj.y = (((fld.pageLine) ? fld.pageLine : fld.lin) - adjustLine) * IceCap.yScale - yScaleCorrection;
  }

  if(obj.fn) {
    obj.fn.call(fld);
  }

  // default fieldclass
  obj.fieldClass = 'x-form-field';

  obj.disabled=false;
  obj.enableKeyEvents=true;
  if (fld.type == 'input') { // input field attribute
    // input protect
    if (obj.readOnly == undefined) {
      obj.readOnly = (fld.ffw & 0x2000) || ((fld.ffw & 0x0700) == 0x0600);
    }
    if (obj.readOnly) {
      obj.hideTrigger = true;
      obj.tabIndex = '-1';
      obj.cls = 'iceCap-protect-field iceCap-input-' + fld.atr + '-protect';
      if ((fld.ffw & 0x0700) == 0x0600) {
        obj.cls += ' iceCap-input-field';
      }
    } else {
      obj.cls = 'iceCap-input-field';
    }
    obj.inputType = "text";
    if (fld.atr) {
      obj.fieldClass += ' iceCap-input-' + fld.atr;
    }
    if(focusField != undefined) {
      var focusId = 'i' + (focusField-1);
      if (fld.id == focusId) {
        obj.cls += ' iceCap-focus-field';
      }
    }
  } else if (fld.type == 'output') { // output field attribute
    obj.readOnly = true;
    obj.tabIndex = '-1';
    if (emulator == 'advanced') {
      obj.cls = 'iceCap-output-field';
    } else {
      obj.cls = 'iceCap-output-field iceCap-text-simple';
    }
    if (fld.atr) {
      obj.fieldClass += ' iceCap-output-' + fld.atr;
    }
  }
  if (typeof (extraCls) != 'undefined') {
     obj.cls += ' ' + extraCls;
  }

  // Field Format Word Format
  // ========================

  // Field Shift/Edit Specification
  switch(fld.ffw & 0x0700) {
  case 0x0000:    // Alpha shift
    break;
  case 0x0100:    // Alpha only
    obj.vtype = 'alpha';
    break;
  case 0x0200:    // Numeric shift
    allowed = '0123456789.,-';
    obj.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']');
    break;
  case 0x0300:    // Nummeric Only
    allowed = '0123456789.,-';
    obj.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']');
    break;
  case 0x0500:    // Digits only (cannot be '-')
    allowed = '0123456789';
    obj.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']');
    break;
  case 0x0700:    // Signed numeric (allow  '-')
    allowed = '0123456789-';
    obj.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']');
    break;
  }

  // Auto Enter
  obj.autoEnter = (fld.ffw & 0x0080);

  // right ajust
  obj.style='';
  if (fld.ta) {
    obj.style+='text-align:'+fld.ta+';';
  }
  //if((fld.ffw & 0x0007) == 0x0005 || (fld.ffw & 0x0007) == 0x0006) {
  //  obj.style+='text-align:'+fld.ta+';';
  //}

  // Monocase
  obj.convertToUpperCase = (fld.ffw & 0x0020);
  if(obj.convertToUpperCase) {
    obj.style+='textTransform: uppercase;'
  }

  // Mandatory Enter
  obj.mandatory = (fld.ffw & 0x0008);
  if (obj.mandatory) obj.allowBlank = false;

  // meta override
  obj.alfaNumeric = false;
  obj.iceCapParentXType = obj.xtype;
  if (fld.metaData) {
    obj = Ext.apply(obj, fld.metaData);
    if (fld.metaData.alfaNumeric) {
      obj.alfaNumeric = true;
      obj.style+='text-align:left;';
    }
  } else if (IceCap.isNumeric(fld.dta)) {
      obj.style+='text-align:right;';    
  }

  // if xtype, remove mask regular expression
  if (obj.xtype != obj.iceCapParentXType) {
    obj.maskRe = null;
  }

	if (obj.xtype == 'checkbox') {
    obj.checked = (obj.value == obj.trueValue);
  } else if (obj.xtype == 'datefield') {
    obj.value = Date.parseDate(obj.value.replace(/^\s+|\s+$/, '0'), obj.format);
  } else if (obj.xtype == 'LINKFIELD') {
    obj.hideTrigger = false;
  }

  // Nondisplay (act as a password field)
  if(fld.atr == '27') {
    obj.inputType = 'password';
  }

  // set class, if icecap trigger field
  if (obj.iceCapTriggerField && !obj.readOnly) {
    obj.fieldClass += ' iceCap-trigger-field';
  }

  if (fld.type == 'input') {
    obj.style+="z-index:100;"
  }
  if (fld.ofs) {
    obj.style+="margin-left:" + fld.ofs * IceCap.xScale + "px;"
  }

  if (obj.xtype.substring(0,2) == 'DD') {
    obj.hiddenName = 'DD.' + obj.id;
  }

  obj.modifiedDataTag = (fld.ffw & 0x0800);

  return obj;
}

/** -----------------------------------------------------------------
* build label field
*/
IceCap.buildLabelField = function(fld) {
  var obj = {};
  obj.xtype='label';
  obj.hideLabel=true;
  obj.text=fld.text;
  obj.cls='x-form-item';
  if (fld.ofs) {
    obj.style="margin-left:" + fld.ofs * IceCap.xScale + "px;"
  }
  if(fld.atr == undefined) {
    fld.atr = '20';
  }
  if (fld.atr == '27') {
    obj.hidden = true;
  }

  return obj;
}

/** -----------------------------------------------------------------
* build buttons
*/
IceCap.buildFormButtons = function(iceCapObj, scn, clientWidth, buttonLayout) {
  var keys=[];

  var height = 24;
  var buttonSpace = 26;
  var currentWidth = buttonSpace;

  if (buttonLayout.region == 'west') {
    var template = new Ext.Template(
      '<div class="iceCap-button"><button class="x-btn-text" type="{1}"><div class="iceCap-button-text">{0}</div></button></div>'
    );
  } else {
    var template = new Ext.Template(
      '<div class="iceCap-button">',
      '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
      '<td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>',
      '</tr></tbody></table>',
      '</div>'
    );
  }

  // build panel(s) with buttons
  if (typeof (scn.keys) == 'undefined') scn.keys = [];
  if (typeof (scn.keys[0]) == 'undefined' || scn.keys[0].id != 'ENTER') {
    var text = 'OK';

    var button = new Ext.Button({
      id:'ENTER.'+iceCapObj.windowNumber
      ,cls:'iceCap-button'
      ,xtype:'button'
      ,windowNumber:iceCapObj.windowNumber
      ,template:template
      ,text: text
      ,handler: function() {
        if (IceCap.keyPressed != '13') {
          IceCap.activeSession.fireEvent('sendServerRequest','ENTER');
        }
        IceCap.keyPressed = '';
      }
      ,scope:iceCapObj
    });
    keys.push(button);

    var buttonWidth = (text.length * (IceCap.xScale - 1.35)) + buttonSpace;
    currentWidth += buttonWidth;
  }

  scn.bottomKeyLayout  = (scn.bottomKeyLayout)  ? scn.bottomKeyLayout  : (buttonLayout.keylayout) ? buttonLayout.keylayout : 'fkeytext';

  // Build f-keys
  for(fx in scn.keys) {
    var key=scn.keys[fx];
    if(key.text != undefined) {
      var text = '';
      if (key.id == 'ENTER') {
        text = 'OK=' + key.text;
      } else if (scn.bottomKeyLayout == 'simple') {
        text = key.text;
      } else {
        text = key.id + '=' + key.text;
      }

      var allowed = true,
          show = true,
          message = '';
      for(dk in scn.disabledKeys) {
        var disabledKey = scn.disabledKeys[dk];
        if (disabledKey.id == key.id) {
          allowed = false;
          message = disabledKey.message;
          show = (disabledKey.showKey == '0') ? false : true;
          break;
        }
      }

      if (!show) continue;

      var buttonConfig = {
        id: key.id+'.'+iceCapObj.windowNumber
        ,cls:'iceCap-button'
        ,xtype:'button'
        ,windowNumber:iceCapObj.windowNumber
        ,template:template
        ,text: text
        ,allowed:allowed
        ,message:message
        ,handler: function(k) {
          if (k.allowed) {
            IceCap.activeSession.fireEvent('sendServerRequest',k.id);
          } else if (k.message && k.message.length > 0) {
            IceCap.activeSession.map.disable();
            Ext.Msg.alert(menu.I18N['message'], k.message, IceCap.enableKeymap);
          }
        }
        ,scope:iceCapObj
      };
      keys.push(new Ext.Button(buttonConfig));

      var buttonWidth = (text.length * (IceCap.xScale - 1.35)) + buttonSpace;
      currentWidth += buttonWidth;
      if (currentWidth > clientWidth) {
        height += 24;
        currentWidth = buttonWidth + buttonSpace;
      }
    }
  };

  // build panel with messages
  height += 24;
  keys.push(
    new Ext.StatusBar({
      id:'iceCap-message-bar'
      ,defaultText:''
      ,plugins:new Ext.ux.ValidationStatus({form:iceCapObj})
    })
  );

  var result = {};
  result.height = (buttonLayout.region == 'west') ? 600 : height;
  result.items = keys;

  return result;
}

/** -----------------------------------------------------------------
* get panel/window layout mode and size
*/
IceCap.getObjectLayout = function(scn) {
  var layout = {};
  var extraLines = (scn.extraLines) ? scn.extraLines : 0;
  if (scn.emulator == 'simple') {
    layout.mode = 'absolute';
  } else {
    layout.mode = 'form';
  }

  if (scn.window.level == 0) {
    layout.width = '100%';
  } else {
    layout.width = scn.window.width * IceCap.xScale + 100;
  }

  if (scn.window.level == 0) {
    layout.height = IceCap.getBodyHeight();
  } else {
    var h = (typeof (scn.metaFields) != 'undefined' && typeof (scn.metaFields[0].height) != 'undefined') ? (Ext.isIE) ? scn.metaFields[0].height + 2 : scn.metaFields[0].height + 1 : scn.window.height;
    if (scn.emulator == 'simple') {
      layout.height = (h > 27) ? h + 130 : ((h + extraLines) * IceCap.yScale) + 110;
    } else {
      layout.height = ((h + extraLines) * (IceCap.yScale-2));
    }
  }

  if (scn.window.level == 0) {
    layout.header = (IceCap.activeSession.portalWindow) ? false : true;
    if (layout.header) {
      layout.header = (IceCap.activeSession.portfolioWindow) ? false : true;
    }
  } else {
    layout.header = false;
  }

  return layout;
}

/** -----------------------------------------------------------------
* get document body height
*/
IceCap.getBodyWidth = function() {
  if(typeof(window.innerWidth) == 'number') {  //Non-IE
    return window.innerWidth;
  } else if(document.documentElement && document.documentElement.clientWidth) {  //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientWidth;
  } else if(document.body && document.body.clientWidth) { //IE 4 compatible
    return document.body.clientWidth;
  }
  return 0;
}

/** -----------------------------------------------------------------
* get document body height
*/
IceCap.getBodyHeight = function() {
  if(typeof(window.innerHeight) == 'number') {  //Non-IE
    return window.innerHeight;
  } else if(document.documentElement && document.documentElement.clientHeight) {  //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientHeight;
  } else if(document.body && document.body.clientHeight) { //IE 4 compatible
    return document.body.clientHeight;
  }
  return 0;
}

/** -----------------------------------------------------------------
* Add keyup event on field
*/
IceCap.addKeyEvent = function(obj) {
  var i=0, j=0;
  obj.on({
    'keyup' : {
      fn: function(o,e) {
        // tab to next felt, if input complete
        var key = e.getKey()
		    if (key > 46) { // not special keys (TAB, etc.)
          keyCount--;
  		    if (keyCount <= 0 && o.iceCapInputField && (Number(o.getRawValue().length)) >= o.maxLength) {
            keyCount = 0;
            IceCap.moveCursorRight();
          }
          o.modifiedDataTag = true;
        }
      }
      ,scope:obj
    }
  })
  obj.on({
    'keydown' : {
      fn: function(o,e) {
        // tab to next felt, if input complete
        var key = (typeof e.getKey == 'function') ? e.getKey() : '';
        switch (key) {
        case 8: // backspace
          keyCount = 0;
          break;
        case 46: // delete
          keyCount = 0;
          break;
        default:
		      if (key > 46) { // not special keys (TAB, etc.)
            keyCount++;
            if (o.textSelected && (key < 112 && key > 123)) { // do not clear value, if F1 - F12
              o.setValue('');
            }
            if (o.hiddenName && o.hiddenName.substring(0,3) == 'DD.') {
              document.getElementById(o.hiddenName).value = '';
            }
          }
          // field + pressed (IE)
          if (key == 107 && Ext.isIE) {
            e.preventDefault();
            IceCap.moveCursorRight();
          }
          // field + pressed
          if (key == 43) {
            if (keyunicode != 187) {
              e.preventDefault();
              IceCap.moveCursorRight();
            }
          }
          // field - pressed
          if (key == 45) {
            if (keyunicode != 189) {
              e.preventDefault();
              IceCap.moveCursorRight();
            }
          }
        }
        o.textSelected = false;
      }
      ,scope:obj
    }
  })
}

/** -----------------------------------------------------------------
* Move cursor left
*/
IceCap.moveCursorLeft = function() {
  if (input.items[input.activeTab].items.length == 1) {
    return;
  }
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.activeObj.id == input.items[input.activeTab].firstObj.id) {
    IceCap.setFocus(input.items[input.activeTab].lastObj);
    return;
  }
  if (!input.activeObj.pos) {
    input.activeObj.pos = [10,10];
  }
  var i = 0;
  for(i=input.items[input.activeTab].items.length-1;i>=0;i--) {
    if (input.items[input.activeTab].items[i].pos[1] == input.activeObj.pos[1] && input.items[input.activeTab].items[i].pos[0] < input.activeObj.pos[0] ||
        input.items[input.activeTab].items[i].pos[1] <  input.activeObj.pos[1]) {
      IceCap.setFocus(input.items[input.activeTab].items[i]);
      return;
    }
  }
  if (IceCap.systemSetting.selectTextWhenFieldFocus) {
    input.items[input.activeTab].lastObj.focus(true,10);
  } else {
    input.items[input.activeTab].lastObj.focus(false,10);
  }
}

/** -----------------------------------------------------------------
* Move cursor right
*/
IceCap.moveCursorRight = function() {
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.items[input.activeTab].items.length == 1) {
    return;
  }
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.activeObj.id == input.items[input.activeTab].lastObj.id) {
    IceCap.setFocus(input.items[input.activeTab].firstObj);
    return;
  }
  if (!input.activeObj.pos) {
    input.activeObj.pos = [10,10];
  }
  var i = 0;
  for(i=0; i<input.items[input.activeTab].items.length;i++) {
    if (input.items[input.activeTab].items[i].pos[1] == input.activeObj.pos[1] && input.items[input.activeTab].items[i].pos[0] > input.activeObj.pos[0] ||
        input.items[input.activeTab].items[i].pos[1] >  input.activeObj.pos[1]) {
      IceCap.setFocus(input.items[input.activeTab].items[i]);
      return;
    }
  }
  if (IceCap.systemSetting.selectTextWhenFieldFocus) {
    input.items[input.activeTab].firstObj.focus(true,10);
  } else {
    input.items[input.activeTab].firstObj.focus(false,10);
  }
}

/** -----------------------------------------------------------------
* Move cursor up
*/
IceCap.moveCursorUp = function() {
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.items[input.activeTab].items.length <= 1) {
    return;
  }
  if (!input.activeObj.pos) {
    input.activeObj.pos = [10,10];
  }
  var i = 0;
  for(i=input.items[input.activeTab].items.length-1;i>=0;i--) {
    if (input.items[input.activeTab].items[i].pos[1] < input.activeObj.pos[1] && input.items[input.activeTab].items[i].pos[0] <= input.activeObj.pos[0]) {
      IceCap.setFocus(input.items[input.activeTab].items[i]);
      return;
    }
  }
}

/** -----------------------------------------------------------------
* Move cursor down
*/
IceCap.moveCursorDown = function() {
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.items[input.activeTab].items.length <= 1) {
    return;
  }
  if (!input.activeObj.pos) {
    input.activeObj.pos = [10,10];
  }
  var i = 0, ii = -1, y = 99999;
  for(i=0; i<input.items[input.activeTab].items.length;i++) {
    if (input.items[input.activeTab].items[i].pos[1] > input.activeObj.pos[1]) {
      if (input.items[input.activeTab].items[i].pos[1] > y) {
        break;
      }
      ii = i;
      y = input.items[input.activeTab].items[i].pos[1];
      if (input.items[input.activeTab].items[i].pos[0] >= input.activeObj.pos[0]) {
        break;
      }
    }
  }
  if (ii != -1) {
    IceCap.setFocus(input.items[input.activeTab].items[ii]);
  }
}

/** -----------------------------------------------------------------
* auto enter
*/
IceCap.autoEnter = function(obj) {
	var v = obj.getValue();
	if (v != obj.initialConfig.value) {
    IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER');
    return true;
  }
  return false;
}

/** -----------------------------------------------------------------
* Get Extjs component using class name
*/
IceCap.getComponent = function(id) {
  if (id.substring(0,1) === 'o') {
    return Ext.getCmp(id);
  } else {
    var i = 0;
    var objId = (id.indexOf('.') > -1) ? id.substring(id.lastIndexOf('.') + 1) : id;

    if (input.items[input.activeTab] == undefined || input.items[input.activeTab].items == undefined) {
      return;
    }

    var items = input.items[input.activeTab].items;

    for(i=0;i<items.length;i++) {
      var itemId = (items[i].id.lastIndexOf('.') > -1) ? items[i].id.substring(items[i].id.lastIndexOf('.') + 1) : items[i].id;
      if (objId == itemId) {
        return items[i];
        break;
      }
    }
  }
  return;
}

/** -----------------------------------------------------------------
* Extend ext panel to standard iceCap panel
*/

IceCap.Form = Ext.extend(Ext.Panel,{
  // defaults - can be changed from outside
  buttonAlign: 'left'
  ,border: false
  ,bodyBorder: false
  ,hidden: true
  ,initComponent: function () {
    this.id = 'icePnl' + IceCap.activeSession.windowNumber;
    this.windowNumber = IceCap.activeSession.windowNumber
    this.sessionNumber = IceCap.activeSession.sessionNumber
    this.emulator = IceCap.activeSession.scn.emulator

    var tools = IceCap.buildPanelToolbar(IceCap.activeSession.scn);
    if (tools.length > 0) {
      this.tools = tools;
    }

    IceCap.buildForm(this, IceCap.activeSession.scn);

    IceCap.Form.superclass.initComponent.apply(this,arguments);

  }
}); // eo extend
// register xtype
Ext.reg('iceCapForm', IceCap.Form);

/** -----------------------------------------------------------------
* Extend ext panel to standard iceCap panel
*/

IceCap.SimplePanel=Ext.extend(Ext.Panel,{
  // defaults - can be changed from outside
  buttonAlign:'left'
  ,border:false
  ,bodyBorder:false
  ,layout:'absolute'
  ,autoScroll:true
  ,bodyStyle:'padding:5;'
  ,defaultType:'textfield'
  ,initComponent: function() {
    this.scn = saved.Scn;
    this.id = 'iceSmp' + saved.SessionNumber;
    this.windowNumber = saved.SessionNumber;
    this.emulator = saved.Scn.emulator;
    this.sessionNumber = saved.SessionNumber;

    var fields = IceCap.buildFormSimpleFields(saved.IceCapObj, saved.Scn);
    this.items = fields.items;

    IceCap.SimplePanel.superclass.initComponent.apply(this,arguments);
  }
}); // eo extend
// register xtype
Ext.reg('iceCapSimplePanel', IceCap.SimplePanel);

/** -----------------------------------------------------------------
* Extend ext window to standard iceCap window
*/

IceCap.Window=Ext.extend(Ext.Window,{
  // defaults - can be changed from outside
  header:false
  ,closable:false
  ,plain:true
  ,modal:false
  ,autoScroll:true
  ,initComponent: function() {
    var tools = IceCap.buildPanelToolbar(IceCap.activeSession.scn);
    if (tools.length > 0) {
      this.tools = tools;
    }

    IceCap.Window.superclass.initComponent.apply(this,arguments);



  }
}); // eo extend
// register xtype
Ext.reg('iceCapWindow', IceCap.Window);

/** -----------------------------------------------------------------
* Extend ext panel to standard iceCap panel
*/

IceCap.Panel4Area = Ext.extend(Ext.Panel,{
  // defaults - can be changed from outside
  layout: 'form'
  ,width: this.width
  ,height: this.height
  ,defaultType: 'textfield'
  ,border: false
  ,bodyBorder: false
  ,bodyStyle: { padding: 5 }
  ,initComponent: function () {
    this.id = 'iceExt' + panelNo++ + IceCap.activeSession.windowNumber;
    IceCap.activeSession.id = this.id;
    this.windowNumber = IceCap.activeSession.windowNumber;

    var i = 0, j = 0;
    var items = [];
    var iCnt = 0;
    for (i in this.items) {
      var fld = this.items[i];
      fld.labelWidth = ((this.labelWidth) ? this.labelWidth : 0);
      if (fld.type == 'input' || fld.type == 'output') {
        var item = IceCap.buildField('advanced', IceCap.activeSession.scn.extraCls, fld);
        if (IceCap.isObject(item)) {
          items[iCnt++] = item;
        }
      } else if (fld.type == 'label') {
        items[iCnt++] = IceCap.buildLabelField(fld);
      }

      if (fld.fields) {
        // build fields (advanced (form) layout)
        var fields = fld.fields;
        for (j in fields) {
          var fld=fields[j];
          if (fld.type == 'input' || fld.type == 'output') {
            var item = IceCap.buildField('advanced', IceCap.activeSession.scn.extraCls, fld);
            if (IceCap.isObject(item)) {
              items[iCnt++] = item;
            }
          } else if (fld.type == 'label') {
            items[iCnt++] = IceCap.buildLabelField(fld);
          } else if (fld.type == 'grid') {
            items[iCnt++]=new IceCap.Grid({
              gridConfig:fld.grid
              ,sessionNumber:IceCap.activeSession.sessionNumber
            })
          }
        }
      }

    }

    this.items = items;

    IceCap.Panel4Area.superclass.initComponent.apply(this,arguments);
  }
}); // eo extend
// register xtype
Ext.reg('iceCapPanel4Area', IceCap.Panel4Area);

/** -----------------------------------------------------------------
* Extend ext container to column
*/

IceCap.buildPanelToolbar = function(scn) {
  var tools = [];
  // gear: change icecaped xml
  // MUST be administrator
  if (IceCap.systemSetting.administrator) {
    var tool = {
      id:'gear'
      ,handler: function(event, toolEl, panel) {
        var win = new Ext.Window({
          layout: 'form'
          ,width: 300
          ,height: 100
          ,plain: true
          ,bodyStyle:{
            padding:5
          }
          ,labelWidth:250
          ,items: [{
            xtype:'checkbox'
            ,name:'i18nLearningMode'
            ,fieldLabel:menu.I18N['i18nLearningModeExplanation']
            ,checked:IceCap.activeSession.i18nLearningMode
          }]
          ,buttons:[{
            text: menu.I18N['ok']
            ,handler: function() {
              var boxes = win.findByType('checkbox');
              if (boxes[0].checked) {
                IceCap.activeSession.i18nLearningMode = true;
              } else {
                IceCap.activeSession.i18nLearningMode = false;
              }
              win.hide();
            }
          },{
            text: menu.I18N['cancel']
            ,handler: function() {
              win.hide();
            }
          }]
        });
        win.show();
      }
      ,scope:scn
    }
    tools.push(tool);
  }

  if (IceCap.systemSetting.administrator && IceCap.activeSession.scn.method == 'icecaped' && IceCap.activeSession.scn.panelToken > 0) {
    var tool = {
      id:'edit'
      ,handler: function(event, toolEl, panel) {
        var win = new Ext.Window({
          layout: 'fit'
          ,width: 1000
          ,height: 550
          ,items: [
            {
              xtype:'iceCapXml.panelSetting'
              ,xmlDoc:this.xmlDoc
              ,xmlHive:this.xmlHive
              ,token:this.panelToken
              ,language:'da'
              ,listeners:{
                afterSave:function() {
                  IceCap.activeSession.fireEvent('sendServerRequest', 'reload');
                }
              }
            }
          ]
        });
        win.show();
      }
      ,scope:scn
    }
    tools.push(tool);
  }

  // search: excel. Change tool icon
  if (typeof (scn.excel) != 'undefined') {
    var tool = {
      id:'excel'
      ,handler: function(event, toolEl, panel) {
      }
      ,scope:scn
    };
    tools.push(tool);
  }

  return tools;
}

/** -----------------------------------------------------------------
* Extend ext container to column
*/

IceCap.Column = Ext.extend(Ext.Container,{
  // defaults - can be changed from outside
  autoEl: {}
  ,layout: 'column'
  ,defaults: {
    xtype: 'container'
    ,autoEl: {}
    ,layout: 'form'
    ,style:'padding:8px 0 0 5px'
  }
  ,items:this.items
});
Ext.reg('iColumn',IceCap.Column);

/** -----------------------------------------------------------------
* Extend ext form textField to icecap field (both in -& output)
*/

IceCap.Field = Ext.extend(Ext.form.Field,{
  initComponent: function () {
    var config = IceCap.buildField('simple', IceCap.activeSession.scn.extraCls, this);
    if (typeof(this.placeholder) != 'undefined') {
      config.defaultAutoCreate = {tag: "input", type: "text", size: "20", autocomplete: "off", placeholder: this.placeholder};
    }

    if (config.iceCapParentXType != config.xtype) {
      var obj = Ext.ComponentMgr.create(config,'textfield');
      if (obj.triggerField && !obj.readOnly) {
        config.fieldClass += ' iceCap-trigger-field';
      }
      Ext.apply(this, config, obj);
    } else {
      Ext.apply(this, config);
    }
    IceCap.Field.superclass.initComponent.apply(this,arguments);
  }
});
Ext.reg('iField', IceCap.Field);

/** -----------------------------------------------------------------
* Extend ext form textField to icecap field (both in -& output)
*/

IceCap.Label = Ext.extend(Ext.form.Label,{
  initComponent: function () {
    var obj = IceCap.buildLabelField(this);
    obj.style = 'height:17px;';

    Ext.apply(this, obj);

    IceCap.Label.superclass.initComponent.apply(this,arguments);
  }
});
Ext.reg('iLabel', IceCap.Label);


/** -----------------------------------------------------------------
* Extend ext form textField to icecap field (both in -& output)
*/

IceCap.CommandField = Ext.extend(Ext.form.TextArea,{
  initComponent: function () {
    var width = (this.width) ? this.width : '100%';
    var height = (this.height) ? this.height : '90%';
    var hideLabel = (this.hideLabel) ? this.hideLabel : true;

    var cls = 'iceCap-input-field';
    if (IceCap.activeSession.windowNumber) {
      var id = IceCap.activeSession.id + '.win' + IceCap.activeSession.windowNumber + '.i' + this.fldNo;
    } else {
      var id = IceCap.activeSession.id + '.i' + this.fldNo;
    }

    Ext.apply(this, {
      hideLabel:hideLabel
      ,width:width
      ,height:height
      ,id:id
      ,cls:cls
      ,windowNumber:IceCap.activeSession.windowNumber
    });

    IceCap.CommandField.superclass.initComponent.apply(this,arguments);
  }
});
Ext.reg('iCommandField', IceCap.CommandField);

/** -----------------------------------------------------------------
* Extend ext tab panel
*/

IceCap.tabPanel = Ext.extend(Ext.TabPanel, {
  initComponent:function() {
    var layout = IceCap.getObjectLayout(IceCap.activeSession.scn);
    Ext.apply(this, {
      frame:false
      ,defaults:{bodyStyle:'padding:5px 5px 0;',layout:layout.mode}
      ,deferredRender:false
      ,header:layout.header
    });
    if (this.title != undefined) {
      IceCap.activeSession.scn.window.title = this.title;
    }
    IceCap.tabPanel.superclass.initComponent.call(this);
  },
  afterRender:function() {
    this.addListener({
      'tabchange' : {
        fn: function(tabPanel, panel) {
          input.activeTab = tabPanel.items.indexOf(tabPanel.getActiveTab());
          if (input.items && input.items[input.activeTab]) {
            IceCap.setFocus(input.items[input.activeTab].firstObj,10);
          }
        }
        ,scope: this
      }
    });

    var map = new Ext.KeyMap(this.el,[{}]);
    map.addBinding({
      key:'123456789'
			,ctrl:true
			,alt:false
			,fn: function (keyCode,e) {
				e.stopEvent();
				if (Ext.isIE) {
				  e.browserEvent.keyCode = 0; // Cheat IE to believe that another key was pressed.
				}
        if (e.ctrlKey) {
          var tab = keyCode - 49;
          if (tab > this.items.length) tab = 0;
          this.setActiveTab(tab);
  			}
			}
      ,scope: this
      ,stopEvent: true
    })


		IceCap.tabPanel.superclass.afterRender.call(this);
  }
});
Ext.reg('IceCap.tabPanel', IceCap.tabPanel);
Ext.reg('iceCap.tabPanel', IceCap.tabPanel); // backwards compatible

/** -----------------------------------------------------------------
* Extend ext panel
*/

IceCap.Panel = Ext.extend(Ext.Panel, {
  initComponent:function() {
    Ext.apply(this, {
      layout:'absolute'
      ,autoScroll:true
      ,border:(this.border) ? this.border : false
      ,adjustLine:(this.adjust) ? this.adjust : (this.adjustLine) ? this.adjustLine : 1
      ,adjustColumn:(this.adjustColumn) ? this.adjustColumn : 0
      ,toolbar:(this.toolbar) ? this.toolbar : false
      ,numberOfMenus:(this.numberOfMenus) ? this.numberOfMenus : 0
      ,menuEndLine:(this.menuEndLine) ? this.menuEndLine : 0
      ,menuCommandLine:(this.menuCommandLine) ? this.menuCommandLine : 0
      ,items:this.loadItems()
    });

    if (this.toolbar) this.tbar = this.loadTbar();

    // set main layout mode
    if (IceCap.activeSession.scn.metaFields.length == 1) {
      IceCap.layout = 'fit';
    } else {
      var layout = IceCap.getObjectLayout(IceCap.activeSession.scn);
      if (this.width) {
      } else if (layout.width == '100%') {
        this.width  = '100%';
      } else {
        this.width  = (Ext.isIE) ? layout.width-20 : layout.width-20;
      }
      this.height = layout.height;
    }

    if (typeof (this.parentType) == 'undefined' || this.parentType != 'tabpanel') {
      if (this.title != undefined) {
        IceCap.activeSession.scn.window.title = this.title;
        this.title = '';
      }
    }
    IceCap.Panel.superclass.initComponent.call(this);
  }
  ,loadItems:function() {
    var iCnt = 0, firstLine = (this.menuFirstLine) ? this.menuFirstLine : 99, lastLine = 0;
    var items = [];

    var fields = [];
    this.input  = (this.input)  ? this.input  : [];
    this.output = (this.output) ? this.output : [];

    if (this.listLayout) {
      var len = (this.input.length > this.output.length) ? this.input.length : this.output.length;
      var lineCnt = 0;
      for(var i = 0; i < len; i++) {
        var input = (this.input[i])  ? this.input[i]  : [];
        var output = (this.output[i]) ? this.output[i] : [];
        var array = input.concat(output);
        for(var j = 0; j < array.length; j++) {
          array[j].xy = (array[j].lin * 100) + array[j].col;
        }
        array.sort(function(a,b) {
          if (typeof a['xy'] == "number") {
            return (a['xy'] - b['xy']);
          } else {
            return ((a['xy'] < b['xy']) ? -1 : ((a['xy'] > b['xy']) ? 1 : 0));
          }
        });
        var line = 0;
        var adjCol = 0;
        for(var j = 0; j < array.length; j++) {
          if (array[j].lin != line) {
            lineCnt++;
            adjCol = array[j].col - 2;
          }
          line = array[j].lin;

          if (!array[j].blankLine) {
            array[j].pageLine   = lineCnt;
            array[j].pageColumn = array[j].col - adjCol;

            fields.push(array[j])
          }
        }
      }
    } else {
      fields = this.input.concat(this.output);
    }

    if (this.input[0]) {
      this.adjustLine = this.input[0].lin;
      if (this.output[0] && this.output[0].lin < this.adjustLine) this.adjustLine = this.output[0].lin;
    } else if (this.output[0] && this.output[0].lin) {
      this.adjustLine = this.output[0].lin;
    }

    for(var i = 0; i < fields.length; i++) {
      var fld = this.initField(fields[i]);
      if (fld.lin < firstLine) firstLine = fld.lin;
      if (fld.lin > lastLine)  lastLine  = fld.lin;

      if (fld.id) {
        fld.type = 'input';
        if (this.page) {
          fld.id = 'page.' + this.page + '.' + fld.id;
        }
      } else {
        fld.type = 'output';
      }

      var item = IceCap.buildField(IceCap.activeSession.scn.emulator, this.extraCls, fld, (this.adjustLine === 0) ? 0 : this.adjustLine-1, (this.adjustColumn === 0) ? 0 : this.adjustColumn-1, IceCap.activeSession.scn.focus);
      if (IceCap.isObject(item)) {
        items[iCnt++] = item;
      }
    }

    if (this.menuCommandLine > lastLine) {
      var fld = {}
      fld.lin = this.menuCommandLine;
      fld = this.initField(fld);
      if (fld.lin > lastLine)  lastLine  = fld.lin;
    }

    return items;
  }
  ,loadTbar:function() {
    var tbar = [];

    this.bottomKeys = (typeof(this.bottomKeys) == 'undefined') ? [] : this.bottomKeys;
    var omitKeys = [];
    for (var index in this.bottomKeys) {
      if (typeof(this.bottomKeys[index].key) != 'undefined') omitKeys.push(this.bottomKeys[index].key);
    }

    var keys = IceCap.activeSession.scn.keys;
    for (var i = 0; i < keys.length; i++) {
      var k = keys[i];
      if (omitKeys.indexOf(k.id) == -1) {
        var icon = '/system/snapOnIcon.aspx.png?keyword=' + escape(k.text) + '&default=folder.png&insertRoot=true';
        tbar.push({
          "text": k.text
          ,"key":k.id
          ,"cls":"x-btn-text-icon"
          ,"icon":icon
          ,"handler": function() {
              IceCap.activeSession.fireEvent("sendServerRequest", this.key);
          }
        });
      }
    }

    // remove keys from "bottom"
    for (var i = keys.length-1; i >= 0; i--) {
      var k = keys[i];
      if (omitKeys.indexOf(k.id) == -1) {
        keys.splice(i,1);
      }
    }

    return tbar;
  }
  ,initField:function(f) {
    var fld = f;
    // move fields below menu end line further down, if many menu items
    if (fld.lin > this.menuEndLine) {
      fld.lin = fld.lin + 2;
    }
    return fld;
  }
});
Ext.reg('IceCap.Panel', IceCap.Panel);
Ext.reg('iceCap.Panel', IceCap.Panel); // backwards compatible

IceCap.Menu = Ext.extend(IceCap.Panel, {
  initComponent:function() {
    IceCap.activeSession.isMenu = true;
    IceCap.activeSession.menu = {};
    IceCap.activeSession.menu.layout = this.layout;
    IceCap.activeSession.menu.clickEvent = this.clickEvent;
    IceCap.activeSession.menu.inputFieldNumber = this.inpFldNbr;
    IceCap.activeSession.menu.selectedElm = {};
    IceCap.activeSession.scn.buttonAlign = 'right';

    Ext.apply(this, {
      border:(this.border) ? this.border : false
      ,menuEndLine:(this.endLine) ? this.endLine : 0
      ,numberOfMenus:(this.menus) ? this.menus.length : 0
      ,menuCommandLine:(this.commandLine) ? this.commandLine.line : 0
      ,bodyStyle:{height:'100%'}
      ,html:this.buildMenu()
    });

    IceCap.Menu.superclass.initComponent.call(this);
  }
  ,buildMenu:function() {
    if (typeof(this.menus) == 'undefined') return;

    IceCap.activeSession.isMenu = false;

    this.adjustLine = (this.adjust) ? this.adjust + 1 : (this.adjustLine) ? this.adjustLine + 1 : 0;
    this.adjustColumn = (this.adjustColumn) ? this.adjustColumn + 1 : 0;

    this.warning4options = (typeof(this.warning4options) == 'undefined') ? [] : this.warning4options;
    var warning = [];
    for (var index in this.warning4options) {
      if (typeof(this.warning4options[index].option) != 'undefined') warning.push(this.warning4options[index].option);
    }

    var x=(this.menus[0].col - this.adjustColumn) * IceCap.xScale;
    var y=(this.menus[0].lin - this.adjustLine) * (IceCap.yScale - yScaleCorrection) + 5;
    var html = '';
    html += '<div class="icecap-menu-body" style="width:95%; height:94%; position:absolute;top:'+y+'px;left:'+x+'px;">';
    html += '<div class="icecap-menu-bwarp" style="width:85%;">';

    var first = 'x-grid3-row-first';
    var last  = '';

    this.colCnt = (this.colCnt) ? this.colCnt : 1;

    for (var c = 1; c <= this.colCnt; c++) {
      if (Ext.isIE) {
        html += '<div style="width:' + (95 / this.colCnt) + '%;display:inline-block;float:left;">';
      } else {
        html += '<div style="width:' + (95 / this.colCnt) + '%;display:inline-block;">';
      }
      this.menuFirstLine = 99;
      for (var i = 0; i < this.menus.length; i++) {
        var m = this.menus[i];
        m.colNbr = (m.colNbr) ? m.colNbr : 1;
        if (m.colNbr != c) continue;
        if (m.lin < this.menuFirstLine) this.menuFirstLine = m.lin;
        if (m.mnu.length == 0) {
          first = 'x-grid3-row-first';
          html += '<div style="width:100%;" class="icecap-menu-header">';
          html += '  <table cellspacing="0" cellpadding="0" border="0">';
          html += '    <tbody>';
          html += '      <tr>';
          html += '        <td class="iceCap-output-20 icecap-menu-text">'+m.txt+'</td>';
          html += '      </tr>';
          html += '    </tbody>';
          html += '  </table>';
          html += '</div>';
        } else {
          if (i == this.menus.length-1) {
            last  = 'x-grid3-row-last';
          } else if (i < this.menus.length-2 && this.menus[i+1].mnu.length == 0) {
            last  = 'x-grid3-row-last';
          } else {
            last  = '';
          }
          var wrn = false;
          if (warning.indexOf(m.mnu) != -1) {
            wrn = true;
          }

          var icon = '/system/snapOnIcon.aspx.png?keyword=' + m.txt + '&default=folder.png&insertRoot=true';
          html += '<div style="width:100%;" class="icecap-menu x-grid3-row ' + first + last + ' " onmouseover="IceCap.addClass(this, \'x-grid3-row-over\')" onmouseout="IceCap.removeClass(this, \'x-grid3-row-over\')"  onclick="IceCap.menuClicked(this, \''+m.mnu+'\', \''+m.txt+'\', '+wrn+')">';
          html += '  <table cellspacing="0" cellpadding="0" border="0">';
          html += '    <tbody>';
          html += '      <tr>';
          html += '        <td class="icecap-menu-icon"><img unselectable="on" src="'+icon+'" /></td>';
          html += '        <td class="iceCap-output-20 icecap-menu-id">'+m.mnu+'.</td>';
          html += '        <td class="iceCap-output-20 icecap-menu-text">'+m.txt+'</td>';
          html += '      </tr>';
          html += '    </tbody>';
          html += '  </table>';
          html += '</div>';
          first = '';
        }
      }
      html += '</div>';
    }
    html += '</div>';

    if (this.commandLine) {
      this.commandLine.id = 'cmd'+IceCap.activeSession.scn.sesNo+IceCap.activeSession.scn.window.level;
      html += '<div id='+this.commandLine.id+'></div>';
    }

    html += '</div>';

    delete this.menus;

    return html;
  }
  ,afterRender:function(panel) {
    IceCap.Menu.superclass.afterRender.call(this);

    if (this.commandLine) {
      new Ext.Panel({
        renderTo:this.commandLine.id
        ,width:"100%"
        ,height:this.commandLine.items.height + 20
        ,border:false
        ,items:this.commandLine.items
      });
    }
  }
});
Ext.reg('IceCap.Menu', IceCap.Menu);

/** -----------------------------------------------------------------
* add class
*/

IceCap.addClass = function(elm, cls) {
  elm.className += ' ' + cls;
}

/** -----------------------------------------------------------------
* remove class
*/

IceCap.removeClass = function(elm, cls) {
  re = new RegExp('(?:^|\\s+)' + cls + '(?:\\s+|$)', "g");
  elm.className =elm .className.replace(re, " ");
}

/** -----------------------------------------------------------------
* menu item is clicked
*/

IceCap.menuClicked = function(elm, mnu, txt, wrn) {
  IceCap.activeSession.menu.selected = mnu;

  // row styling
  if (IceCap.activeSession.menu.selectedElm.className) {
    IceCap.removeClass(IceCap.activeSession.menu.selectedElm, 'x-grid3-row-selected');
  }
  IceCap.activeSession.menu.selectedElm = elm;
  IceCap.addClass(elm, 'x-grid3-row-selected');

  IceCap.fireMenu(wrn, txt);
}

/** -----------------------------------------------------------------
* remove class
*/

IceCap.fireMenu = function(wrn, txt) {

  // build input data for firing display
  IceCap.inputData = [];
  if (typeof(IceCap.activeSession.menu.inputFieldNumber) == 'number') {
    IceCap.inputData[0] = {};
    IceCap.inputData[0].field  = 'i' + IceCap.activeSession.menu.inputFieldNumber;
    IceCap.inputData[0].option = IceCap.activeSession.menu.selected;
  }

  if (IceCap.activeSession.menu.clickEvent == 'single') {
    IceCap.finallyFireMenu(wrn, txt, IceCap.inputData);
  } else {
    cursorPosition.clicks++;
    if (cursorPosition.clicks == 1) {
      setTimeout(function() {
        if (doubleClick) {
          IceCap.finallyFireMenu(wrn, txt, IceCap.inputData);
        }
        cursorPosition.clicks = 0;
        doubleClick = false;
      }, 300);
    }
  }
}


/** -----------------------------------------------------------------
* finally firing menu
*/

IceCap.finallyFireMenu = function(wrn, txt, data) {
  if (wrn) {
    var msg = menu.I18N['sureExecuteMenu'] + ' "' + txt + '"';
    Ext.Msg.show({
      title:menu.I18N['message']
      ,msg:msg
      ,data:data
      ,buttons: Ext.Msg.YESNO
      ,fn: function(btn, txt, opt) {
        if (btn == 'yes') {
          IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', opt.data);
        }
      }
      ,icon: Ext.MessageBox.WARNING
    });
  } else {
    IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', data);
  }
}

/** -----------------------------------------------------------------
* set active session
*/

IceCap.setActiveSession = function() {
  IceCap.focusOnFirstField();
}

/** -----------------------------------------------------------------
* set focus on first input field
*/

IceCap.focusOnFirstField = function() {
  if (typeof (input.items[input.activeTab]) != 'undefined' && input.items[input.activeTab].items.length > 0 && input.items[input.activeTab].firstObj) {
    if (input.items[input.activeTab].firstObj.xtype != 'button') {
      IceCap.setFocus(input.items[input.activeTab].firstObj,10);
    }
  }
}

/** -----------------------------------------------------------------
* set focus
*/

IceCap.setFocus = function(obj, delay) {
  var o;
  if (obj.xtype == 'checkbox' || obj.xtype == 'radio' || obj.xtype == "RADIOGROUP")
  {
    if (obj.xtype == "RADIOGROUP") {
      o = obj.items.get(0);
      if (o.innerWrap) {
        o = Ext.fly(o.innerWrap.id);
      }
    }
    else if (obj.innerWrap) {
      o = Ext.fly(obj.innerWrap.id);
    }
  }
  else {
    o = obj;
  }
  if (o) {
    input.activeObj = obj;
    if (delay != undefined) {
      if (IceCap.systemSetting.selectTextWhenFieldFocus) {
        o.focus(true,delay);
        o.textSelected = true;
      } else {
        o.focus(false,delay);
      }
    } else {
      if (obj.xtype == 'textarea' || obj.xtype.substring(0,2) == 'DD') {
        var fld = document.getElementById(obj.id);
        if (fld != undefined) {
          fld.focus();
        }
      } else {
        if (IceCap.systemSetting.selectTextWhenFieldFocus) {
          o.focus(true);
          o.textSelected = true;
        } else {
          o.focus(false);
        }
      }
      if (obj.xtype == "RADIOGROUP") {
        obj.setFocus();
      }
    }
  }
  // if grid row, select row
  if (input.activeObj.grid != undefined) {
    input.activeObj.grid.getSelectionModel().selectRow(input.activeObj.rowIndex);
  }
}

/** -----------------------------------------------------------------
* Toogle between cap and not cap
*/

IceCap.toggle = function(scn) {
  IceCap.activeSession.fireEvent('sendServerRequest', 'toggle');
}

/** -----------------------------------------------------------------
* Open tab or window with excel sheet
*/

IceCap.openExcel = function(scn) {
  var url = '/icecap/iceCapXsl.aspx?type='+scn.excel.type+'&statement='+scn.excel.statement;
  var portfolio = iceCapGetPortfolio();
  if (portfolio != null) {
    portfolio.fireEvent('addTab','Excel','',url,'','');
  } else {
    alert('open window');
  }
}

/** -----------------------------------------------------------------
* Handle post message request from parent (can be cross domain)
*/

IceCap.requestFromParent = function(e) {
  if (e.data === 'close') IceCap.closeTab();
}

/** -----------------------------------------------------------------
* Close active tab or window
*/

IceCap.closeTab = function() {
  if (IceCap.activeSession.portalWindow) {
    Ext.Ajax.request({
      method:'POST'
      ,url:IceCap.activeSession.href + '&close=on'
    })
    var portfolio = iceCapGetPortfolio(IceCap.activeSession.portalWindowID);
    if (portfolio != null) {
      portfolio.fireEvent('closeWindow');
    }
  } else if (IceCap.activeSession.portfolioWindow) {
    if (portfolio.Ext.getCmp(IceCap.activeSession.portfolioWindowID)) {
      portfolio.Ext.getCmp(IceCap.activeSession.portfolioWindowID).fireEvent('closeWindow');
    }
  } else if (typeof (iceCapCloseBreakout) == 'function') {
    iceCapCloseBreakout(IceCap.activeSession, false);
  }
}

/** -----------------------------------------------------------------
* Calculate x & y scale depending on fontsize
*/

IceCap.Scale = function () {
  var value='MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM';
  var hiddenLabel=new Ext.form.Label({
    text: value
    ,renderTo: document.body
    ,hidden: true
    ,cls:'iceCap-text-simple'
  });
  var v=Ext.util.TextMetrics.createInstance(hiddenLabel.el);
  IceCap.xScale = (v.getWidth(value) / 80) + 0.05;
  IceCap.yScale = v.getHeight(value);
}

/** -----------------------------------------------------------------
* iceCap Save cursor position
*/
cursorPosition.clicks = 0;
function IceCapSaveCursorPosition(e) {
  var element = cursorPosition.element;

	if (!e) var e = window.event;
	if (e.target) cursorPosition.element = e.target;
	else if (e.srcElement) cursorPosition.element = e.srcElement;
	if (cursorPosition.element.nodeType == 3) // defeat Safari bug
		cursorPosition.element = cursorPosition.element.parentNode;

  var obj = Ext.getCmp(cursorPosition.element.id);
  if (obj === undefined || (obj.type != 'input' && obj.type != 'output')) {
    cursorPosition.element = element;
    return;
  }

  if (Ext.isIE) {
    cursorPosition.offset = 0;
  } else {
    cursorPosition.offset = e.rangeOffset;
  }

  cursorPosition.x = (Ext.isIE) ? element.x : e.clientX;
  cursorPosition.y = e.clientY;

  if (IceCap.activeSession.isMenu) {
    IceCap.fireMenu();
  }
}

/** -----------------------------------------------------------------
* iceCap clear cursor position
*/

function IceCapClearCursorPosition(e) {
  if (!e) var e = window.event;
  var key = e.keyCode ? e.keyCode : e.charCode
	if (key == 16 ) return;
	if (key < 111 || key > 123) {
    cursorPosition.x = 0;
    cursorPosition.y = 0;
	}
}

function IceCapSaveDoubleClick(e) {
  doubleClick = true;
}

/** -----------------------------------------------------------------
* iceCap return specific values from query string
*/

IceCap.getQueryString = function(query, variable) {
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0].toUpperCase() == variable.toUpperCase()) {
      return pair[1];
    }
  }
  return '';
}

/** -----------------------------------------------------------------
* change a query string value
*/

IceCap.changeQueryString = function(href, variable, value) {
  var newqrystr = '', sep = '';
  var qrystr = href.substring(href.indexOf('?') + 1);
  var vars = qrystr.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0].toUpperCase() == variable.toUpperCase()) {
      pair[1] = value;
    }
    newqrystr += sep + pair[0] + '=' + pair[1];
    sep = '&';
  }
  return href.substring(0, href.indexOf('?') + 1) + newqrystr;
}

/** -----------------------------------------------------------------
* iceCap: Find objects by classname
*/

IceCap.getElementsByClass = function(searchClass, iceCapObj, tag) {
  var result = [];
	if ( tag == null ) tag = '*';

  result = IceCap.addClassElements(tag, searchClass, iceCapObj, result);

  if (tag.toLowerCase() == 'input') { // add textarea and buttons
    var o_values = {
      "iceCap-button": {
        tag: "div",
        cls: "iceCap-button"
      },
      "iceCap-radio": {
        tag: "div",
        cls: "iceCap-radio"
      }
    };
    result = IceCap.getIceCapFields(o_values, iceCapObj, result);
    result = IceCap.addTextareaElements(searchClass, iceCapObj, result);
    // result = IceCap.addClassElements('div', 'iceCap-button', iceCapObj, result);
    if (searchClass == 'iceCap-output-field') { // add protected fields
      result = IceCap.addClassElements(tag, 'iceCap-protect-field', iceCapObj, result);
    }
  }
	return result;
};

IceCap.addClassElements = function(tag, searchClass, iceCapObj, array) {
	var els = document.getElementsByTagName(tag);
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for(var i=0;i<els.length;i++) {
		if (pattern.test(els[i].className) ) {
      array = IceCap.addElement(els[i], searchClass, iceCapObj, array);
		}
	}
  return array;
};

IceCap.getIceCapFields = function(o_values, iceCapObj, result) {

  for(s_prop in o_values) {
    var o_element = o_values[s_prop];
    result = IceCap.addClassElements(o_element.tag, o_element.cls, iceCapObj, result);
  }
  return result;
};

IceCap.addTextareaElements = function(searchClass, iceCapObj, array) {
  var els = $('textarea.'+searchClass);
	for(var i=0;i<els.length;i++) {
    array = IceCap.addElement(els[i], searchClass, iceCapObj, array);
	}
  return array;
};

IceCap.addElement = function(elm, searchClass, iceCapObj, array) {
  var obj = undefined;

  var id = elm.id;
  obj = Ext.getCmp(id);

  if (obj == undefined) {
    var ids = id.split(".");
    if (ids.length > 0) {
      obj = Ext.getCmp(ids[1]);
    }
  }

  if (obj == undefined) {
    obj = IceCap.getCmp(id, iceCapObj.windowNumber);
  }

  var o_owner = obj.ownerCt;

  if (obj && obj.windowNumber == iceCapObj.windowNumber) {
    if (searchClass == 'iceCap-protect-field') {
      obj.pos = IceCap.getFieldPosition(obj);
    }
    array.push(obj);
  }
  if (obj && obj.windowNumber == undefined && o_owner && o_owner.windowNumber == iceCapObj.windowNumber) {
    if (searchClass == 'iceCap-protect-field') {
        o_owner.pos = IceCap.getFieldPosition(o_owner);
    }
    array.push(o_owner);
  }
  return array;
}

/** -----------------------------------------------------------------
* iceCap: Sort input fields in position order
*/
IceCap.sortInputFields = function(fields) {
  var result = {};
  result.items = [];
  result.activeObj = {};

  // save position and find first/last object, if input fields
  var i = 0;
  var array = [];
  for (i=0;i<fields.length;i++) {
    fields[i].pos = IceCap.getFieldPosition(fields[i]);

    var p1 = 100000 + fields[i].pos[0];
    var p2 = 100000 + fields[i].pos[1];
    array[i] = p2.toString() + ':' + p1.toString() + ':' + i.toString();
  }
  array.sort();

  var buttons = [];

  for (var i=0;i<array.length;i++) {
    var inx = array[i].substring(array[i].lastIndexOf(':')+1);
    if (fields[inx].xtype == 'button') { // button alway last
      buttons.push(fields[inx]);
    } else {
      var pageNumber = 0;
      if (fields[inx].id.indexOf('page') > -1) {
        var str = fields[inx].id.indexOf('page') + 5;
        var end = fields[inx].id.indexOf('.',str);
        var pageNumber = fields[inx].id.substring(str,end);
      }
      if (result.items[pageNumber] == undefined) result.items[pageNumber] = {};
      if (!Ext.isArray(result.items[pageNumber].items)) result.items[pageNumber].items = [];
      result.items[pageNumber].items.push(fields[inx]);
    }
  }

  if (result.items.length == 0) {
    result.items[0] = {};
    result.items[0].items = [];
  }

  for (var i = 0; i < result.items.length; i++) {
    if (result.items[i] == undefined) result.items[i] = {};
    if (!Ext.isArray(result.items[i].items)) result.items[i].items = [];
    result.items[i].items = result.items[i].items.concat(buttons);
    result.items[i].firstObj = result.items[i].items[0];
    result.items[i].lastObj  = result.items[i].items[result.items[i].items.length-1];
  }
  result.activeTab = 0;
  return result;
}


/** -----------------------------------------------------------------
* iceCap: Sort input fields in position order
*/
IceCap.getFieldPosition = function(field) {
  var pos = [];
	try {
    if (field.xtype == 'checkbox' || field.xtype == 'radio') {
      var obj = Ext.getCmp(field.id);
      pos = Ext.fly(obj.imageEl.id).getXY();
      pos[1] = pos[1] - 3;
    } else if (field.xtype == 'textarea' || field.xtype == 'button') {
      pos = Ext.fly(field.id).getXY();
    } else if (field.xtype.substring(0,2) == 'DD') {
      pos = Ext.fly(field.id).getXY();
    } else {
      pos = field.getPosition();
      if (pos[0] == 0) {
        pos = field.getPosition(true);
      }
      if (typeof (field.selectedClass) != 'undefined' && field.selectedClass.substring(2,7) == 'combo') {
        if (Ext.isIE) {
          pos[1]--;
        }
      }
    }
	} catch (err) {
    pos = [10,10];
  }
  pos[0] = Math.ceil(pos[0]);
  pos[1] = Math.ceil(pos[1]);
  if (field.xtype == 'button') {
    pos[1] += 5000;
  }

  return pos;
}

/** -----------------------------------------------------------------
* iceCap: Format PC Command string
*/
IceCap.getCmp = function(id, windowNumber) {
  var obj = undefined;
  for(i=0;i<Ext.ComponentMgr.all.items.length;i++) {
    if (Ext.ComponentMgr.all.items[i].id == id && typeof(Ext.ComponentMgr.all.items[i].windowNumber) != 'undefined' &&Ext.ComponentMgr.all.items[i].windowNumber == windowNumber) {
      obj = Ext.ComponentMgr.all.items[i];
      break;
    }
  };
  return obj;
}

/** -----------------------------------------------------------------
* iceCap: Format PC Command string
*/
IceCap.runPco = function(scn) {
  switch (scn.cmdAct) {
  case 0: // add tab
    IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', 'pcowait');
    var portfolio = iceCapGetPortfolio();
    if (portfolio != null) {
      portfolio.fireEvent('addTab',scn.cmdTitle,'',scn.cmd,'');
    } else {
      window.open(scn.cmd,scn.cmdTitle);
    }
    break;
  case 1: // open window
    IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', 'pcowait');
    window.open(scn.cmd,scn.cmdTitle);
    break;
  default:
    var p = new Ext.data.ScriptTagProxy({
      url:scn.cmd
      ,timeout:10000
      ,nocache:false
	  });
    p.load(
      {}
      ,{
        readRecords:function(o) {
          return o;
        }
      }
      ,IceCap.runPcoCallback
    );
    p.on('loadexception', function(obj,options ) {
      IceCap.runPcoError();
    })
    break;
  }
}

IceCap.runPcoCallback = function(r) {
  IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', 'pcowait');
  switch(r) {
    case null:
      return;
      break;
    case 'OK':
      return;
      break;
    default:
      IceCap.activeSession.map.disable();
      Ext.Msg.alert(
        menu.I18N['message']
        ,r
        ,IceCap.enableKeymap
      );
      break;
  }
}

IceCap.runPcoError = function() {
  IceCap.activeSession.map.disable();

  var msg = '<div class="iceCap-msg">';
  msg += '<h3>';
  msg += menu.I18N['clientServicesMessageHeader'];
  msg += '</h3>';
  msg += '<ul>';
  msg += '<li>';
  msg += menu.I18N['clientServicesMessage1'];
  msg += '</li>';
  msg += '<li>';
  msg += menu.I18N['clientServicesMessage2'];
  msg += '</li>';
  msg += '</ul>';
  msg += '</div>';

  var msgWin = new Ext.Window({
    frame:true
    ,layout:'form'
    ,title: menu.I18N['message']
    ,bodyStyle:'padding:5px 5px 0'
    ,width: 710
    ,html:msg
    ,buttons: [{
      text: 'OK'
      ,id:'OK'
      ,handler:function() {
        msgWin.hide();
        if (typeof(IceCap.activeSession.enableKeymap) == 'function') IceCap.activeSession.enableKeymap();
      }
    }]
  });
  msgWin.show();
  Ext.getCmp('OK').focus();
}

IceCap.isNumeric = function(text) {
  if (text.length == 0 || text == undefined) {
    return false;
  }
  var validChars = "0123456789.,-";
  var isNumber=true;
  var char;
  var i = 0;

  for (i = 0; i < text.length && isNumber == true; i++) {
    char = text.charAt(i);
    if (validChars.indexOf(char) == -1) {
      isNumber = false;
    }
  }
  return isNumber;
}

/** -----------------------------------------------------------------
* iceCap: Format PC Command string
*/
IceCap.runCmd = function(scn) {
  switch (scn.cmdAct) {
  case 0: // add tab
    var portfolio = iceCapGetPortfolio();
    if (portfolio != null) {
      portfolio.fireEvent('addTab',scn.cmdTitle,'',scn.cmd,'');
    } else {
      window.open(scn.cmd,scn.cmdTitle);
    }
    break;
  case 1: // open window
    window.open(scn.cmd,scn.cmdTitle);
    break;
  }
}

/** -----------------------------------------------------------------
* iceCap Grid
*/

IceCap.Grid = Ext.extend(Ext.grid.GridPanel, {
  border:false
  ,autoHeight:true
  ,cls:{overflow:scroll}
  ,loadMask:false
  ,initComponent:function() {
    var gridConfig = this.gridConfig;

    // find default option
    var defaultOption = '';
    if (gridConfig.defaultOption != undefined) {
      var defaultPosition = 99;
      for (var i = 0; i < gridConfig.menu.length; i++) {
        var pos = gridConfig.defaultOption.indexOf(gridConfig.menu[i].id);
        if (pos > -1 && pos < defaultPosition) {
          defaultPosition = pos;
          defaultOption   = gridConfig.menu[i].id;
        }
      }
    }

    // set class for default option
    for (var i = 0; i < gridConfig.menu.length; i++) {
      if (gridConfig.menu[i].id == defaultOption) {
        gridConfig.menu[i].cls += ' iceCap-default';
      }
    }

    // row menu
    var rm = new Ext.menu.Menu({
      items:gridConfig.menu
    });

    var gridStore = new Ext.data.JsonStore({
      reader: new Ext.data.JsonReader()
    });
    if (gridConfig.store) {
      gridStore.loadData(gridConfig.store);
    }

    var cm = new Ext.grid.ColumnModel(gridConfig.header);

    // hard coded - cannot be changed from outside
    var config = {
      store:gridStore
      ,cm:cm
    }; // eo config object

    // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent
    IceCap.Grid.superclass.initComponent.apply(this, arguments);
    // add listeners
    this.on({
       'rowcontextmenu' : {
          fn: function(grid, rowIndex, e) {
            e.stopEvent();
            var coords = e.getXY();
            rm.showAt([coords[0], coords[1]]);

            grid.getSelectionModel().selectRow(rowIndex, true);

            IceCap.inputData = [];
            var rows = grid.getSelectionModel().getSelections();
            for (var i = 0; i < rows.length; i++) {
              IceCap.inputData[i] = {};
              IceCap.inputData[i].field = rows[i].id;
              IceCap.inputData[i].data  = rows[i].data;
            }
          }
          ,scope: this
       }
    })
    // add listener for default option
    if (defaultOption > '') {
      this.on({
        'rowdblclick' : {
          fn: function(grid, rowIndex, e) {
            e.stopEvent();
            IceCap.inputData = [];
            IceCap.inputData[0] = {};
            IceCap.inputData[0].field  = this.store.data.items[rowIndex].id;
            IceCap.inputData[0].option = defaultOption;
            IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', IceCap.inputData);
          }
          ,scope: this
        }
      });
    }
  }
  ,onRender:function() {
    IceCap.Grid.superclass.onRender.apply(this, arguments);
  }
});
Ext.reg('iceCapGrid', IceCap.Grid);

/** -----------------------------------------------------------------½
* iceCap Editor Grid
*/

IceCap.EditorGrid = Ext.extend(Ext.grid.GridPanel, {
  border:false
  ,deferRowRender:false
  ,style:'padding-bottom:10px;width:100%;'
  ,clicksToEdit:1
  ,initComponent:function() {
    var gridConfig = this.gridConfig;
    this.enableColumnMove = gridConfig.enableColumnMove;
    this.screenTitle = gridConfig.title;

    if (this.viewConfig && this.viewConfig.forceFit) {
      this.viewConfig.scrollOffset = 30;
    }

    // find default option
    var defaultOption = '';
    var defaultOptionKey = '';
    if (typeof(gridConfig.menu) == 'undefined') {
      var rm = new Ext.menu.Menu({});
    } else {
      if (gridConfig.defaultOption != undefined) {
        var defaultPosition = 99;
        for (var i = 0; i < gridConfig.menu.length; i++) {
          var pos = gridConfig.defaultOption.indexOf(gridConfig.menu[i].id);
          if (pos > -1 && pos < defaultPosition) {
            defaultPosition  = pos;
            defaultOption    = gridConfig.menu[i].id;
            defaultOptionKey = gridConfig.menu[i].optFldKey;
          }
        }
      }

      // Find default option
      for (var i = 0; i < gridConfig.menu.length; i++) {
        gridConfig.menu[i].text += ' (' + gridConfig.menu[i].id + ')';
        if (gridConfig.menu[i].id == defaultOption) {
          gridConfig.menu[i].cls += ' iceCap-default';
        }
      }

      // row menu
      var rm = new Ext.menu.Menu({
        items:gridConfig.menu
      });
    }

    var gridStore = new Ext.data.JsonStore({
      reader: new Ext.data.JsonReader()
    });
    if (gridConfig.store) {
      gridStore.loadData(gridConfig.store);
    }

    if (!gridConfig.header) {
      gridConfig.header = [];
    }
    for (var h = 0; h < gridConfig.header.length; h++) {
      gridConfig.header[h].menuDisabled = true;
      if (!gridConfig.header[h].renderer) {
        gridConfig.header[h].renderer = function(value, metadata, record, rowIndex, colIndex) {
          var atr = record.data['atr' + (colIndex+1)];
          if (!Ext.isEmpty(atr)) {
            return '<div class="iceCap-output-field iceCap-output-' + atr +'">'+value+'</div>';
          } else {
            return value;
          }
        }
      }
      // extra columns
      if (gridConfig.header[h].data) {
        gridConfig.header[h].renderer = function(value, metadata, record, rowIndex, colIndex) {
          return '<div id="iceCap-extraColumn-'+rowIndex+'-'+colIndex+'"></div>';
        }
      }
    }
    var cm = new Ext.grid.ColumnModel(gridConfig.header);
    var sm = new IceCap.RowSelectionModel();

    // hard coded - cannot be changed from outside
    var config = {
      windowNumber:IceCap.activeSession.windowNumber
      ,store:gridStore
      ,cm:cm
      ,sm:sm
    };
    if (gridConfig.showToolbar) {
      config.tbar = this.loadTbar();
      for (var index in config.tbar) {
        var key = config.tbar[index];
        if (key.iconCls == 'snaponicons') {
          key.cls = "x-btn-text-icon";
          key.icon = '/system/snapOnIcon.aspx.png?keyword=' + escape(key.text) + '&default=folder.png&insertRoot=true';
          delete key.iconCls;
        }
      }
    }

    // apply config
    Ext.apply(this, Ext.apply(this.initialConfig, config));
    // call parent
    IceCap.EditorGrid.superclass.initComponent.apply(this, arguments);
    // add listeners
    this.on({
      'rowcontextmenu' : {
        fn: function(grid, rowIndex, e) {
          e.stopEvent();

          grid.getSelectionModel().selectRow(rowIndex, true);
          var rows = grid.getSelectionModel().getSelections();
          if (!rows[0].data.opt) return false;

          var coords = e.getXY();
          rm.showAt([coords[0], coords[1]]);

          IceCap.inputData = [];
          for (var i = 0; i < rows.length; i++) {
            IceCap.inputData[i] = {};
            IceCap.inputData[i].field = rows[i].id;
            IceCap.inputData[i].title = grid.screenTitle;
            IceCap.inputData[i].data  = rows[i].data;
          }
        }
        ,scope: this
      }
    });
    // add listener for default option
    if (defaultOption > '') {
      this.on({
        'rowdblclick' : {
          fn: function(grid, rowIndex, e) {
            e.stopEvent();

            var row = this.store.data.items[rowIndex];
            if (!row.data.opt) return false;

            IceCap.inputData = [];
            IceCap.inputData[0] = {};
            IceCap.inputData[0].field  = row.id;
            IceCap.inputData[0].option = defaultOption;
            IceCap.activeSession.fireEvent('sendServerRequest', defaultOptionKey, IceCap.inputData);
          }
          ,scope: this
        }
      });
    }
    this.on({
      'setGridHeight' : {
        fn: function(grid, adjHeight) {
          grid.setHeight(adjHeight-(grid.getPosition()[1]));
        }
        ,scope: this
      }
    });
  }
  ,loadTbar:function() {
    var config = this.gridConfig;

    var omitKeys = [];

    if (config.toolbar) {
      config.toolbar = this.buildTbarButtons(config.toolbar, omitKeys, config);
      return config.toolbar;
    }

    this.toolbarKeyLayout = (this.toolbarKeyLayout) ? this.toolbarKeyLayout : 'icon';
    IceCap.activeSession.scn.bottomKeyLayout  = (this.bottomKeyLayout)  ? this.bottomKeyLayout  : 'fkeytext';

    config.bottomKeys = (config.bottomKeys) ? config.bottomKeys : [];
    for (var index in config.bottomKeys) {
      if (config.bottomKeys[index].key) omitKeys.push(config.bottomKeys[index].key);
    }

    var keys = IceCap.activeSession.scn.keys;

    var buttons = this.buildTbarButtons(keys, omitKeys);

    var gridConfig = (IceCap.activeSession.scn.metaFields && IceCap.activeSession.scn.metaFields[0].gridConfig) ? IceCap.activeSession.scn.metaFields[0].gridConfig : '';

    if (gridConfig.extraToolbarButtons) {
      var extraButtons = this.buildTbarButtons(gridConfig.extraToolbarButtons, omitKeys, gridConfig);
      buttons = buttons.concat(extraButtons);
    }

    // remove keys from "bottom"
    if (keys) {
      for (var i = keys.length-1; i >= 0; i--) {
        var k = keys[i];
        if (omitKeys.indexOf(k.id) == -1) {
          keys.splice(i,1);
        }
      }
    }
    // show f-keys as dropdown menu
    if (this.toolbarKeyLayout == 'dropdown') {
      var menu = new Ext.menu.Menu({
        items:tbar
      });
      var tbar = new Ext.Toolbar({
        buttons:buttons
        ,listeners:{
          render:function(tbar) {
            tbar.add({
              text:'Functions'
              ,menu:tbar.buttons
            });
            delete tbar.buttons
          }
        }
      });
      return tbar;
    } else {
      return buttons;
    }
  }
  ,buildTbarButtons:function(keys, omitKeys, gridConfig) {
    var buttons = [],
        cfg = gridConfig || {};
    if (!keys) return buttons;
    for (var i = 0; i < keys.length; i++) {
      var k = keys[i];
      if (omitKeys.indexOf(k.id) == -1) {
        var key = {
          key:(k.id) ? k.id : k.key
          ,cls:"x-btn-text-icon"
          ,handler: function() {
              IceCap.activeSession.fireEvent("sendServerRequest", this.key);
          }
        }
        if (this.toolbarKeyLayout == 'dropdown') {
          key.text = k.id + '=' + k.text;
        } else {
          key.text = k.text;
        }
        if (this.toolbarKeyLayout == 'icon') {
          key.icon = '/system/snapOnIcon.aspx.png?keyword=' + escape(k.text) + '&default=folder.png&insertRoot=true';
        }
        if (k.iconCls) {
          key.iconCls = k.iconCls;
        }
        if (k.key == 'ROLLUP' && cfg.lastPage) {
          key.disabled = true;
        }
        if (k.key == 'ROLLDOWN' && cfg.firstPage) {
          key.disabled = true;
        }
        buttons.push(key);
      }
    }
    return buttons;
  }
});
Ext.reg('iceCapEditorGrid', IceCap.EditorGrid);

function renderOptionField(val, meta, rec, row, col) {
  var atr = rec.data['atr' + (col+1)],
      html;

  html = '<div id="win' + IceCap.activeSession.windowNumber;
  if (rec.id.indexOf('q.') > -1) {
    html += '.qCol.'+col+'"';
  } else {
    html += '.o.'+rec.id+'"';
  }

  if (!Ext.isEmpty(atr)) {
    html += ' class="iceCap-output-' + atr +'"';
  }
  return html + '></div>';
}
function renderField(val, meta, rec, row, col) {
  var atr = rec.data['atr' + (col+1)],
      io = rec.data['io' + (col+1)];

  if (io != 'b' && io != 'i') return val;

  var html = '<div id="win' + IceCap.activeSession.windowNumber + '.' + rec.id + '.c' + (col+1) + '"';

  return html + '></div>';
}
function renderQuickKeyField(val, meta, rec, row, col) {
  var atr = rec.data['atr' + (col+1)],
      html;

  if (rec.id.indexOf('q.') > -1) {
    html = '<div id="win' + IceCap.activeSession.windowNumber + '.qCol.'+col+'"';
    if (!Ext.isEmpty(atr)) {
      html += ' class="iceCap-output-' + atr +'"';
    }
    html += '></div>';
  } else if (!Ext.isEmpty(atr)) {
    html = '<div class="iceCap-output-' + atr +'">'+val+'</div>';
  } else {
    html = val;
  }
  return html;
}

// Click handler: Grid right-click menu
function onRowRightClick(item) {
  var sendServerRequest = false;
  for (var i = 0; i < IceCap.inputData.length; i++) {
    if (typeof (item.initialConfig.breakout) != 'undefined' && item.initialConfig.breakout.length > 0) {
      var func = eval(item.initialConfig.breakout);
      if(typeof(func) === 'function') {
        func(IceCap.inputData[i].title, IceCap.inputData[i].data);
      }
    } else {
      sendServerRequest = true;
      IceCap.inputData[i].option = item.id
    }
  }
  if (sendServerRequest) {
    var key = (item.initialConfig.optFldKey) ? item.initialConfig.optFldKey : 'ENTER';
    IceCap.activeSession.fireEvent('sendServerRequest', key, IceCap.inputData);
  }
  return;
}

function iceCapFormatNumeric(obj, decimalSeparator, newDecimalSeparator) {
  var decSep = ((decimalSeparator) ? decimalSeparator : ',');
  var newDecSep = ((newDecimalSeparator) ? newDecimalSeparator : '.');

  var numberOfDecimal = ((obj.lastIndexOf(decSep) == -1) ? 0 : (obj.length - obj.lastIndexOf(decSep))-1);
  var value = new String(obj.replace(/[^\d]/g,''));
  if (numberOfDecimal == 0) {
    return value;
  } else {
    return value.substring(0,(value.length-numberOfDecimal)) + newDecSep + value.substring(value.length-numberOfDecimal);
  }
}

function iceCapGetPortfolio(objId) {
  try {
    var obj = (typeof(objId) == 'undefined') ? 'portfolio-tabpanel' : objId;
    if (parent.Ext && parent.Ext.getCmp(obj)) {
      return parent.Ext.getCmp(obj);
    } else if (parent.parent.Ext && parent.parent.Ext.getCmp(obj)) {
      return parent.parent.Ext.getCmp(obj);
    }
    return null;
  } catch (err) {
    return null;
  }
}

IceCap.extraColumn = function(data, rec) {
  var obj;
  if (data.xtype == 'button') {
    var smallButton = new Ext.Template(
      '<div class="iceCap-button">',
        '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap">',
          '<tbody>',
            '<tr>',
              '<td class="x-btn-left" style="padding:0px;"><i>&#160;</i></td>',
              '<td class="x-btn-center" style="padding:0px; vertical-align:middle;"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td>',
              '<td class="x-btn-right" style="padding:0px;"><i>&#160;</i></td>',
            '</tr>',
          '</tbody>',
        '</table>',
      '</div>'
    );

    obj = new Ext.Button({
      text:data.text
      ,template:smallButton
      ,data:data
      ,handler:function(button) {
        if (button.data.optionValue) {
          var data = [];
          data[0] = {};
          data[0].field  = rec.id;
          data[0].option = button.data.optionValue;
          IceCap.activeSession.fireEvent('sendServerRequest', 'ENTER', data);
        } else if (button.data.breakout) {
          var func = eval(button.data.breakout);
          if(typeof(func) === 'function') {
            func(button.data.text, rec);
          }
        }
      }
    })
  }
  return obj;
}

IceCap.isObject = function(obj) {
  if( (typeof obj === "object") && (obj !== null) ) {
    return true;
  } else {
    return false;
  }
}


/** -----------------------------------------------------------------
* key mapping for 5250
*/

Ext.namespace('IceCap.keyMap');

IceCap.keyMap.keys = [
  [Ext.EventObject.ENTER, 'ENTER', false]
 ,[Ext.EventObject.F1,'F1',false]
 ,[Ext.EventObject.F2,'F2',false]
 ,[Ext.EventObject.F3,'F3',false]
 ,[Ext.EventObject.F4,'F4',false]
 ,[Ext.EventObject.F5,'F5',false]
 ,[Ext.EventObject.F6,'F6',false]
 ,[Ext.EventObject.F7,'F7',false]
 ,[Ext.EventObject.F8,'F8',false]
 ,[Ext.EventObject.F9,'F9',false]
 ,[Ext.EventObject.F10,'F10',false]
 ,[Ext.EventObject.F11,'F11',false]
 ,[Ext.EventObject.F12,'F12',false]
 ,[Ext.EventObject.F1,'F13',true]
 ,[Ext.EventObject.F2,'F14',true]
 ,[Ext.EventObject.F3,'F15',true]
 ,[Ext.EventObject.F4,'F16',true]
 ,[Ext.EventObject.F5,'F17',true]
 ,[Ext.EventObject.F6,'F18',true]
 ,[Ext.EventObject.F7,'F19',true]
 ,[Ext.EventObject.F8,'F20',true]
 ,[Ext.EventObject.F9,'F21',true]
 ,[Ext.EventObject.F10,'F22',true]
 ,[Ext.EventObject.F11,'F23',true]
 ,[Ext.EventObject.F12,'F24',true]
 ,[Ext.EventObject.PAGE_DOWN, 'ROLLUP', false]
 ,[Ext.EventObject.PAGE_UP, 'ROLLDOWN', false]
 ,[Ext.EventObject.PRINT_SCREEN, 'PRINT', false]
 ,[Ext.EventObject.ESC, 'ATTN', false]
];

IceCap.keys = new Ext.data.SimpleStore({
  fields: ['eventObject', 'keyValue', 'shiftRequired'],
  data : IceCap.keyMap.keys
});

/**
 * Clone Function
 * @param {Object/Array} o Object or array to clone
 * @return {Object/Array} Deep clone of an object or an array
 * @author Ing. Jozef Sakáloš
 */
IceCap.clone = function(o) {
    if(!o || 'object' !== typeof o) {
        return o;
    }
    if('function' === typeof o.clone) {
        return o.clone();
    }
    var c = '[object Array]' === Object.prototype.toString.call(o) ? [] : {};
    var p, v;
    for(p in o) {
        if(o.hasOwnProperty(p)) {
            v = o[p];
            if(v && 'object' === typeof v) {
                c[p] = IceCap.clone(v);
            }
            else {
                c[p] = v;
            }
        }
    }
    return c;
}; // eo function clone

/** ----------------------------------------------------------------------------------
* Override field class with tooltip-functionality (will be added to all formfields
*/
Ext.override(Ext.form.Field, {
  afterRender : Ext.form.Field.prototype.afterRender.createSequence(function() {
		var qt = this.qtip;
		if (qt) {
      Ext.QuickTips.register({
		    target:  this,
		    title: '',
		    text: qt,
		    enabled: true,
		    showDelay: 20
		  });
		}
	})
});

/** -----------------------------------------------------------------
* Extjs 2.x Extra
*/

/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

/**
 * @class Ext.ux.ValidationStatus
 * A {@link Ext.StatusBar} plugin that provides automatic error notification when the
 * associated form contains validation errors.
 * @extends Ext.Component
 * @constructor
 * Creates a new ValiationStatus plugin
 * @param {Object} config A config object
 */
Ext.ux.ValidationStatus = Ext.extend(Ext.Component, {
  errorIconCls : 'x-status-error'
  ,errorListCls : 'x-status-error-list'
  ,validIconCls : 'x-status-valid'
  ,showText : menu.I18N['formHasErrorsShowText']
  ,hideText : menu.I18N['formHasErrorsHideText']
  ,submitText : menu.I18N['formHasErrorsSubmit']

    // private
  ,init : function(sb){
    sb.on('render', function(){
      this.statusBar = sb;
      this.monitor = true;
      this.errors = new Ext.util.MixedCollection();
      this.listAlign = (sb.statusAlign=='right' ? 'br-tr?' : 'bl-tl?');

      if(this.form){
        //this.form = Ext.getCmp(this.form).getForm();
        this.startMonitoring();

        // Have to give the status bar time to render since it happens in afterRender
        (function(){
          sb.statusEl.on('click', this.onStatusClick, this, {buffer:200});
        }).defer(200, this);

        this.form.on('beforeaction', function(f, action){
          if(action.type == 'submit'){
            // Ignore monitoring while submitting otherwise the field validation
            // events cause the status message to reset too early
            this.monitor = false;
          }
        }, this);
        var startMonitor = function(){
          this.monitor = true;
        }
        this.form.on('actioncomplete', startMonitor, this);
        this.form.on('actionfailed', startMonitor, this);
      }
    }, this, {single:true});
  }

  // private
  ,startMonitoring : function(){
    this.form.items.each(function(f){
      f.on('invalid', this.onFieldValidation, this);
      f.on('valid', this.onFieldValidation, this);
    }, this);
  }

  // private
  ,stopMonitoring : function(){
    this.form.items.each(function(f){
      f.un('invalid', this.onFieldValidation, this);
      f.un('valid', this.onFieldValidation, this);
    }, this);
  }

  // private
  ,onDestroy : function(){
    this.stopMonitoring();
    if (this.statusBar && this.statusBar.statusEl) {
      this.statusBar.statusEl.un('click', this.onStatusClick, this);
    }
    Ext.ux.ValidationStatus.superclass.onDestroy.call(this);
  }

  // private
  ,onFieldValidation : function(f, msg){
    if(!this.monitor){
      return false;
    }
    if(msg){
      this.errors.add(f.id, {msg:msg});
      f.invalid = true;
    }else{
      f.invalid = false;
      this.errors.removeKey(f.id);
    }
    this.updateErrorList();
    if (this.errors.getCount() == 1) {
      if(this.getMsgEl().isVisible()){
        this.hideErrors();
      }
      this.statusBar.setStatus({text:this.errors.items[0].msg, iconCls:this.errorIconCls});
    } else if(this.errors.getCount() > 1){
      if(this.statusBar.getText() != this.showText && !this.getMsgEl().isVisible()){
        this.statusBar.setStatus({text:this.showText, iconCls:this.errorIconCls});
      }
      if(!this.getMsgEl().isVisible()){
        this.showErrors();
      }
    } else {
      this.statusBar.clearStatus().setIcon(this.validIconCls);
    }
  }

  // private
  ,addMessage : function(msg){
    if(!this.monitor){
      return false;
    }
    if(msg){
      this.errors.add(msg.id, {msg:msg.text});
    }else{
      this.errors.removeKey(msg.id);
    }
    this.updateErrorList();
    if (this.errors.getCount() == 1) {
      this.getMsgEl().update('');
      this.statusBar.setStatus({text:this.errors.items[0].msg, iconCls:this.errorIconCls});
    } else if(this.errors.getCount() > 1){
      if(this.statusBar.getText() != this.showText){
        this.statusBar.setStatus({text:this.showText, iconCls:this.errorIconCls});
      }
      if(!this.getMsgEl().isVisible()){
        this.showErrors();
      }
    } else {
      this.statusBar.clearStatus().setIcon(this.validIconCls);
    }
  }

  // private
  ,updateErrorList : function(){
    if(this.errors.getCount() > 1){
      var msg = '<ul>';
      this.errors.each(function(err){
        msg += ('<li>' + err.msg + '</li>');
      }, this);
      this.getMsgEl().update(msg+'</ul>');
    }else{
      this.getMsgEl().update('');
    }
  }

  // private
  ,getMsgEl : function(){
    if(!this.msgEl){
      this.msgEl = Ext.DomHelper.append(Ext.getBody(), {
        cls: this.errorListCls+' x-hide-offsets'
      }, true);

      this.msgEl.on('click', function(e){
        var t = e.getTarget('li', 10, true);
        if(t){
          Ext.getCmp(t.id.split('x-err-')[1]).focus();
          this.hideErrors();
        }
      }, this, {stopEvent:true}); // prevent anchor click navigation
    }
    return this.msgEl;
  }

  // private
  ,showErrors : function(){
    this.updateErrorList();
    if(this.errors.getCount() > 1){
      this.getMsgEl().alignTo(this.statusBar.getEl(), this.listAlign).slideIn('b', {duration:.3, easing:'easeOut'});
      this.statusBar.setText(this.hideText);
      this.form.getEl().on('click', this.hideErrors, this, {single:true}); // hide if the user clicks directly into the form
    }
  }

  // private
  ,hideErrors : function(){
    var el = this.getMsgEl();
    if(el.isVisible()){
      el.slideOut('b', {duration:.2, easing:'easeIn'});
      this.statusBar.setText(this.showText);
    }
    this.form.getEl().un('click', this.hideErrors, this);
  }

  // private
  ,onStatusClick : function(){
    if(this.getMsgEl().isVisible()){
      this.hideErrors();
    }else if(this.errors.getCount() > 0){
      this.showErrors();
    }
  }
});

/** -----------------------------------------------------------------
* Extjs 2.x override
*/

/** -----------------------------------------------------------------
* remove/destroy also remove fieldLabel
*/

Ext.override(Ext.layout.FormLayout, {
	renderItem : function(c, position, target){
		if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){
			var args = [
				   c.id, c.fieldLabel,
				   c.labelStyle||this.labelStyle||'',
				   this.elementStyle||'',
				   typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator,
				   (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''),
				   c.clearCls || 'x-form-clear-left'
			];
			if(typeof position == 'number'){
				position = target.dom.childNodes[position] || null;
			}
			if(position){
        if (c.fieldTpl) {
				  c.formItem = c.fieldTpl.insertBefore(position, args, true);
        } else {
				  c.formItem = this.fieldTpl.insertBefore(position, args, true);
        }
			}else{
        if (c.fieldTpl) {
  				c.formItem = c.fieldTpl.append(target, args, true);
        } else {
  				c.formItem = this.fieldTpl.append(target, args, true);
  			}
			}
			c.actionMode = 'formItem';
			c.render('x-form-el-'+c.id);
			c.container = c.formItem;
			c.actionMode = 'container';
		}else {
			Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
		}
	}
});
Ext.override(Ext.form.TriggerField, {
	actionMode: 'wrap',
	onShow: Ext.form.TriggerField.superclass.onShow,
	onHide: Ext.form.TriggerField.superclass.onHide
});
Ext.override(Ext.form.Checkbox, {
	actionMode: 'wrap',
	getActionEl: Ext.form.Checkbox.superclass.getActionEl
});
Ext.override(Ext.form.HtmlEditor, {
	actionMode: 'wrap'
});

/** -----------------------------------------------------------------
* panel toolbar buttons with fine round border
*/

Ext.override(Ext.StatusBar, {
  autoCreate: {
    cls:'x-panel-btns x-panel-btns-left'
    ,html:'<table cellspacing="5"><tr></tr></table>'
  }
});

Ext.override(Ext.layout.TableLayout, {
  onLayout : function(ct, target){
    var cs = ct.items.items, len = cs.length, c, i;

    if(!this.table){
      target.addClass('x-table-layout-ct');

      this.table = target.createChild(
        {tag:'table', cls:'x-table-layout', cellspacing: 3, cn: {tag: 'tbody'}}, null, true);
    }
    this.renderAll(ct, target);
  }
});

/** -----------------------------------------------------------------
* Alignment of checkbox
*/

Ext.override(Ext.form.Checkbox, {
  getResizeEl : function(){
    return this.wrap;
  }
});

/** -----------------------------------------------------------------
* keynav undefined when destroy
*/

Ext.override(Ext.DatePicker, {
  beforeDestroy : function() {
    if(this.rendered){
      if(this.keyNav){
        this.keyNav.disable();
        this.keyNav = null;
        Ext.destroy(
          this.leftClickRpt,
          this.rightClickRpt,
          this.monthPicker,
          this.eventEl,
          this.mbtn,
          this.todayBtn
        );
      }
    }
  }
});

/* Override keymap, because of an error with F13 (F1 + shift), F14 - F24
--------------------------------------------------------------------- */
Ext.override(Ext.KeyMap,{
  addBinding: function (config) {
    if (Ext.isArray(config)) {
      for (var i = 0,len = config.length;i < len;i++) {
        this.addBinding(config[i]);
      }
      return;
    }
    var keyCode = config.key,
        shift = config.shift,
        ctrl = config.ctrl,
        alt = config.alt,
        fn = config.fn || config.handler,
        scope = config.scope;

    if (config.stopEvent) {
      this.stopEvent = config.stopEvent;
    }

    if (typeof keyCode == "string") {
      var ks = [];
      var keyString = keyCode.toUpperCase();
      for (var j = 0,len = keyString.length;j < len;j++) {
        ks.push(keyString.charCodeAt(j));
      }
      keyCode = ks;
    }
    var keyArray = Ext.isArray(keyCode);

    var handler = function (e) {
      //if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) &&  (!alt || e.altKey)){
      if (((shift === undefined) || (shift === e.shiftKey)) &&
				        ((ctrl === undefined) || (ctrl === e.ctrlKey)) &&
				        ((alt === undefined) || (alt === e.altKey))) {
        var k = e.getKey();
        if (keyArray) {
          for (var i = 0,len = keyCode.length;i < len;i++) {
            if (keyCode[i] == k) {
              if (this.stopEvent) {
                e.stopEvent();
              }
              fn.call(scope || window,k,e);
              return;
            }
          }
        } else {
          if (k == keyCode) {
            if (this.stopEvent) {
              e.stopEvent();
            }
            fn.call(scope || window,k,e);
          }
        }
      }
    };
    this.bindings.push(handler);
  }
})

/** -----------------------------------------------------------------
* set record value - do not set dirty (modified)
*/

Ext.override(Ext.data.Record, {
  set : function(name, value){
    if(String(this.data[name]) == String(value)){
      return;
    }
    this.dirty = false;
    if(!this.modified){
      this.modified = {};
    }
    if(this.modified[name] == undefined){
      this.modified[name] = this.data[name];
    }
    this.data[name] = value;
    if(!this.editing && this.store){
      this.store.afterEdit(this);
    }
  }
 });

/** -----------------------------------------------------------------
* set grid column movable
*/

Ext.override(Ext.grid.ColumnModel, {
  /**
  * @cfg {Boolean} movable (optional) Specify as <tt>false</tt> to prevent the user from moving this column
  * (defaults to true).  To disallow column moving globally for all columns in the grid, use
  * {@link Ext.grid.GridPanel#enableColumnMove} instead.
  */

  moveColumn : function(oldIndex, newIndex){
    if (this.isMovable(oldIndex)){
      var c = this.config[oldIndex];
      this.config.splice(oldIndex, 1);
      this.config.splice(newIndex, 0, c);
      this.dataMap = null;
      this.fireEvent("columnmoved", this, oldIndex, newIndex);
    }
  },
  isMovable: function(col){
    if(this.config[col].movable == undefined){
      return this.enableColumnMove || true;
    }
    return this.config[col].movable;
  }
});

IceCap.RowSelectionModel = Ext.extend(Ext.grid.RowSelectionModel,{
  //if you want single cell selection or multiple
  singleSelect : true,

  //if when a cell is selected with control or shift if the entire row should be selected
  rowSelection: true,

  // private
  initEvents : function(){
    if (Ext.isIE) {
      this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), {
        "up" : function(e) {
          IceCap.moveCursorUp();
        }
        ,"down" : function(e) {
          IceCap.moveCursorDown();
        },
        scope: this
      });
    }
  }
});

/** -----------------------------------------------------------------
* Table layout - able to right align buttons by added extra class
*/

Ext.override(Ext.layout.TableLayout, {
  onLayout : function(ct, target){
    var cs = ct.items.items, len = cs.length, c, i;

    if(!this.table){
      target.addClass('x-table-layout-ct');

      var cls = 'x-table-layout';
		  if(ct.tableCls){
			  cls += ' ' + ct.tableCls
		  }

      this.table = target.createChild(
          {tag:'table', cls:cls, cellspacing: 0, cn: {tag: 'tbody'}}, null, true);
    }
    this.renderAll(ct, target);
  }
});

/**
* Add "indexOf()" function to array
*
* Description:
* Javascript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
*
* Syntax:
* array.indexOf(searchElement[, fromIndex]);
*/

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/)   {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

xml2json={
  parser:function(xmlcode,ignoretags,debug){
    if(!ignoretags){ignoretags=""};
    xmlcode=xmlcode.replace(/\s*\/>/g,'/>');
    xmlcode=xmlcode.replace(/<\?[^>]*>/g,"").replace(/<\![^>]*>/g,"");
    if (!ignoretags.sort){ignoretags=ignoretags.split(",")};
    var x=this.no_fast_endings(xmlcode);
    x=this.attris_to_tags(x);
    x=escape(x);
    x=x.split("%3C").join("<").split("%3E").join(">").split("%3D").join("=").split("%22").join("\"");
    for (var i=0;i<ignoretags.length;i++){
      x=x.replace(new RegExp("<"+ignoretags[i]+">","g"),"*$**"+ignoretags[i]+"**$*");
      x=x.replace(new RegExp("</"+ignoretags[i]+">","g"),"*$***"+ignoretags[i]+"**$*")
    };
    x='<JSONTAGWRAPPER>'+x+'</JSONTAGWRAPPER>';
    this.xmlobject={};
    var y=this.xml_to_object(x).jsontagwrapper;
    if(debug){y=this.show_json_structure(y,debug)};
    return y
  },
  xml_to_object:function(xmlcode){
    var x=xmlcode.replace(/<\//g,"§");
    x=x.split("<");
    var y=[];
    var level=0;
    var opentags=[];
    for (var i=1;i<x.length;i++){
      var tagname=x[i].split(">")[0];
      opentags.push(tagname);
      level++
      y.push(level+"<"+x[i].split("§")[0]);
      while(x[i].indexOf("§"+opentags[opentags.length-1]+">")>=0){level--;opentags.pop()}
    };
    var oldniva=-1;
    var objname="this.xmlobject";
    for (var i=0;i<y.length;i++){
      var preeval="";
      var niva=y[i].split("<")[0];
      var tagnamn=y[i].split("<")[1].split(">")[0];
      tagnamn=tagnamn.toLowerCase();
      var rest=y[i].split(">")[1];
      if(niva<=oldniva){
        var tabort=oldniva-niva+1;
        for (var j=0;j<tabort;j++){objname=objname.substring(0,objname.lastIndexOf("."))}
      };
      objname+="."+tagnamn;
      var pobject=objname.substring(0,objname.lastIndexOf("."));
      if (eval("typeof "+pobject) != "object"){preeval+=pobject+"={value:"+pobject+"};\n"};
      var objlast=objname.substring(objname.lastIndexOf(".")+1);
      var already=false;
      for (k in eval(pobject)){if(k==objlast){already=true}};
      var onlywhites=true;
      for(var s=0;s<rest.length;s+=3){
        if(rest.charAt(s)!="%"){onlywhites=false}
      };
      if (rest!="" && !onlywhites){
        if(rest/1!=rest){
          rest="'"+rest.replace(/\'/g,"\\'")+"'";
          rest=rest.replace(/\*\$\*\*\*/g,"</");
          rest=rest.replace(/\*\$\*\*/g,"<");
          rest=rest.replace(/\*\*\$\*/g,">")
        }
      }
      else {rest="{}"};
      if(rest.charAt(0)=="'"){rest='unescape('+rest+')'};
      if (already && !eval(objname+".sort")){preeval+=objname+"=["+objname+"];\n"};
      var before="=";after="";
      if (already){before=".push(";after=")"};
      var toeval=preeval+objname+before+rest+after;
      eval(toeval);
      if(eval(objname+".sort")){objname+="["+eval(objname+".length-1")+"]"};
      oldniva=niva
    };
    return this.xmlobject
  },
  show_json_structure:function(obj,debug,l){
    var x='';
    if (obj.sort){x+="[\n"} else {x+="{\n"};
    for (var i in obj){
      if (!obj.sort){x+=i+":"};
      if (typeof obj[i] == "object"){
        x+=this.show_json_structure(obj[i],false,1)
      }
      else {
        if(typeof obj[i]=="function"){
          var v=obj[i]+"";
          //v=v.replace(/\t/g,"");
          x+=v
        }
        else if(typeof obj[i]!="string"){x+=obj[i]+",\n"}
        else {x+="'"+obj[i].replace(/\'/g,"\\'").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r")+"',\n"}
      }
    };
    if (obj.sort){x+="],\n"} else {x+="},\n"};
    if (!l){
      x=x.substring(0,x.lastIndexOf(","));
      x=x.replace(new RegExp(",\n}","g"),"\n}");
      x=x.replace(new RegExp(",\n]","g"),"\n]");
      var y=x.split("\n");x="";
      var lvl=0;
      for (var i=0;i<y.length;i++){
        if(y[i].indexOf("}")>=0 || y[i].indexOf("]")>=0){lvl--};
        tabs="";for(var j=0;j<lvl;j++){tabs+="\t"};
        x+=tabs+y[i]+"\n";
        if(y[i].indexOf("{")>=0 || y[i].indexOf("[")>=0){lvl++}
      };
      if(debug=="html"){
        x=x.replace(/</g,"&lt;").replace(/>/g,"&gt;");
        x=x.replace(/\n/g,"<BR>").replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;")
      };
      if (debug=="compact"){x=x.replace(/\n/g,"").replace(/\t/g,"")}
    };
    return x
  },
  no_fast_endings:function(x){
    x=x.split("/>");
    for (var i=1;i<x.length;i++){
      var t=x[i-1].substring(x[i-1].lastIndexOf("<")+1).split(" ")[0];
      x[i]="></"+t+">"+x[i]
    } ;
    x=x.join("");
    return x
  },
  attris_to_tags: function(x){
    var d=' ="\''.split("");
    x=x.split(">");
    for (var i=0;i<x.length;i++){
      var temp=x[i].split("<");
      for (var r=0;r<4;r++){temp[0]=temp[0].replace(new RegExp(d[r],"g"),"_jsonconvtemp"+r+"_")};
      if(temp[1]){
        temp[1]=temp[1].replace(/'/g,'"');
        temp[1]=temp[1].split('"');
        for (var j=1;j<temp[1].length;j+=2){
          for (var r=0;r<4;r++){temp[1][j]=temp[1][j].replace(new RegExp(d[r],"g"),"_jsonconvtemp"+r+"_")}
        };
        temp[1]=temp[1].join('"')
      };
      x[i]=temp.join("<")
    };
    x=x.join(">");
    x=x.replace(/ ([^=]*)=([^ |>]*)/g,"><$1>$2</$1");
    x=x.replace(/>"/g,">").replace(/"</g,"<");
    for (var r=0;r<4;r++){x=x.replace(new RegExp("_jsonconvtemp"+r+"_","g"),d[r])}  ;
    return x
  }
};


if(!Array.prototype.push){
  Array.prototype.push=function(x){
    this[this.length]=x;
    return true
  }
};

if (!Array.prototype.pop){
  Array.prototype.pop=function(){
      var response = this[this.length-1];
      this.length--;
      return response
  }
};
