 /**
 * @author siegech
 */

// reference local blank image is implemented into rd html
/**
 * The line above should be included somewhere in your js code after the ext
 * library has been referenced. The ext-all.js file by default has
 * BLANK_IMAGE_URL = http://www.extjs.com). Since we don't want to link back
 * there we need to assign a reference a local version of this file. What is
 * this file even used for? See http://en.wikipedia.org/wiki/Spacer_GIF. URL to
 * a 1x1 transparent gif image used by Ext to create inline icons with CSS
 * background images. An image is the only inline element that has a true box
 * (width and height) cross browser. It allows Ext to reserve the space for an
 * image, and still use a CSS background image to specify which image is
 * actually displayed.
 */

//
$ = jQuery.noConflict();

// create a namespace object
Ext.ns('HL.OLB', 'HL.Session', 'Ext.ux');
/**
 * By specifying our own namespace we encapsulate all variables and methods in one 
 * global object in order to avoid any conflicts or changes when working with other
 * javascript files. This pattern scales well as the project becomes more complex 
 * and as its API grows. It stays out of the global namespace, provides publicly 
 * addressable API methods, and supports protected or private data and methods 
 * along the way.
 */

// constants for localization
// ==========================
HL.Localization = function(){};
HL.Localization.prototype = {
	// loading mask
	loadingText					: 'Loading page ...',
	// session timeout
	sessionWarningTitleText		: 'Hapag-Lloyd Online Session',
	sessionWarningBodyText		: 'To assure the safety and protection of your data, your Hapag-Lloyd online session will time out within 5 minutes if there is no additional activity.<br /><br />If you are still working in your Hapag-Lloyd online session simply click "Extend My Session" to continue.',
	sessionWarningExtendText	: 'Extend My Session',
	sessionTimeoutBodyText		: 'There has been no activity for 30 minutes.<br /><br />To assure the safety and protection of your data, your Hapag-Lloyd online session has timed out.',
	sessionTimeoutProgressText	: 'Session has timed out',
	sessionTimeoutCloseText		: 'Close',
	// olb start page
	olbStartPageDefaultTitleText: 'Online Business Overview',
	olbStartPageDialogTitleText	: 'Mark As Online Business Start Page',
	olbStartPageDialogText		: 'Mark this page as your new Online Business start page?',
	olbStartPageCurrentLabel	: 'Your current start page:',
	olbStartPageNewLabel		: 'Your new start page:',
	olbStartPageDialogOkText	: 'Ok',
	olbStartPageDialogCancelText: 'Cancel',
	// stripes
	olbStripeTitleExpandText	: 'Show',
	olbStripeTitleCollapseText	: 'Hide',
	// spotlight help
	spotlightAjaxUrlText		: '/en/ajax/spotlightOlb',
	spotlightQTipText			: 'Help',
	spotlightCloseText			: 'Close',
	spotlightPreviousText		: 'Previous',
	spotlightNextText			: 'Next',
	spotlightTitleText			: 'Help',
	spotlightQTipCloseText		: 'Close Help',
	spotlightErrorText			: '<p>Error: The help content could not be retrieved.</p>'
}
HL.Constants = new HL.Localization();

HL.pageCorsetId = 'corset';

// searching for trancode in url
// =============================
HL.updateBookmarkTrancodeInit = function(){
	var searchStr = location.search;
	if(searchStr && searchStr != ''){
		var searchIndex = searchStr.indexOf('view=');
		if(searchIndex != -1){
			searchIndex = searchIndex + 5;
			if(searchIndex <= searchStr.length){
				searchStr = searchStr.substring(searchIndex);
				if(searchStr != ''){
					searchIndex = searchStr.indexOf('&');
					if(searchIndex != -1){
						searchStr = searchStr.substring(0, searchIndex);
					}
					if(searchStr != ''){
						searchIndex = searchStr.indexOf(',');
						if(searchIndex != -1){
							searchStr = searchStr.substring(0, searchIndex);
						}
						if(searchStr != ''){
							searchIndex = searchStr.indexOf(';');
							if(searchIndex != -1){
								searchStr = searchStr.substring(0, searchIndex);
							}
							if(searchStr != ''){
								//workaround for interactive schedule (HACK)
								if(searchStr.toLowerCase() == 'v7060'){
									searchStr = 'v7050';
								}
								HL.OLB.bookmarkTrancode = searchStr;
							}
						}
					}
				}
			}
		}
	}
}

// masking - unmasking page
// ========================
HL.pageHostElement = null;
HL.pageHostElementInit = function(){
	//HL.pageHostElement = Ext.get(HL.pageCorsetId);
	HL.pageHostElement = null;
	if(!HL.pageHostElement){
		HL.pageHostElement = Ext.getBody();
	}
}

window.loadingMask = new Ext.LoadMask(Ext.getBody(), {msg:"Loading data, please wait...",id:"loadingMask"});

HL.pageMasking = function(isCovered){
		if(isCovered){
			if(HL.pageHostElement){
				//HL.pageHostElement.mask(HL.Constants.loadingText, 'x-mask-loading');
				
				window.loadingMask.show();
			}
		} else {
			if(HL.pageHostElement){
				//HL.pageHostElement.unmask();
				
				window.loadingMask.hide();
			}
		}
}

// set provider for state management
// =================================
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

// overwrite Shadow utility class
// ==============================
// Private utility class that manages the internal Shadow cache
Ext.Shadow.Pool = function(){
	var p = [];
	var markup = Ext.isIE ?
                 '<div class="x-ie-shadow"></div>' :
                 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
	return {
		pull : function(){
			var sh = p.shift();
			if(!sh){
				if(HL.pageHostElement){
					sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", HL.pageHostElement.dom, markup));
				} else {
					sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
				}
				sh.autoBoxAdjust = false;
			}
			return sh;
		},

		push : function(sh){
			p.push(sh);
		}
	};
}();

// overwrite methods of element
// ============================
Ext.override(Ext.Element, {
	addBehaviourOnFocus : function(behaviour){
		var b = (behaviour && typeof behaviour == 'object') ? behaviour : {};
		this.on("focus", function(){
			if(b.className){
				Ext.fly(this, '_internal').addClass(b.className);
			}
			if(b.behaviour) {
				if( this.value == this.defaultValue ) {
					this.value = '';
				}
			}
		}, this.dom);
		this.on("blur", function(){
			if(b.className){
				Ext.fly(this, '_internal').removeClass(b.className);
			}
			if(b.behaviour) {
				if( !this.value.length ) {
					this.value = this.defaultValue;
				}
			}
		}, this.dom);
		return this;
	},
	
	mask : function( msg, msgCls ){
		if(!Ext.isIE7 && this.getStyle("position") == "static"){
			this.setStyle("position", "relative");
		}
		if(!this._mask){
			this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true);
		}
		this.addClass("x-masked");
		this._mask.setDisplayed(true);
		if(typeof msg == 'string'){
			if(!this._maskMsg){
				this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true);
			}
			var mm = this._maskMsg;
			mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg";
			mm.dom.firstChild.innerHTML = msg;
			mm.setDisplayed(true);
			mm.center(this);
		}
		if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ 
			this._mask.setHeight(this.getHeight());
		}
		return this._mask;
	}
	
	
	
	
	/*,
	mask : function(msg, msgCls){
        if(this.getStyle("position") == "static"){
            this.addClass("x-masked-relative");
        }
        if(this._maskMsg){
            this._maskMsg.remove();
        }
        if(this._mask){
            this._mask.remove();
        }

        this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true);

        this.addClass("x-masked");
        this._mask.setDisplayed(true);
        if(typeof msg == 'string'){
            this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true);
            var mm = this._maskMsg;
            mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg";
            mm.dom.firstChild.innerHTML = msg;
            mm.setDisplayed(true);
            mm.center(this);
        }
        if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
            //changed [this.getWidth()] to [undefined]!!!
            //this._mask.setSize(this.getWidth(), this.getHeight());
            this._mask.setSize(undefined, this.getHeight());
        }
        return this._mask;
    }*/
});

// overwrite methods of component
// ==============================
Ext.Component.override({
    initState : function(config){
        if(Ext.state.Manager){
            var id = this.getStateId();
            if(id){
                var state = Ext.state.Manager.get(id);
                if(state){
                    if(this.fireEvent('beforestaterestore', this, state) !== false){
                        this.applyState(state);
                        this.fireEvent('staterestore', this, state);
                    }
                }
            }
        }
    },
    saveState : function(){
        if(Ext.state.Manager){
            var id = this.getStateId();
            if(id){
                var state = this.getState();
                if(this.fireEvent('beforestatesave', this, state) !== false){
                    Ext.state.Manager.set(id, state);
                    this.fireEvent('statesave', this, state);
                }
            }
        }
    },
    getStateId : function(){
        return this.stateId || ((this.id.indexOf('ext-comp-') == 0 || this.id.indexOf('ext-gen') == 0) ? null : this.id);
    }
});

// overwrite render method of trigger field
// ========================================
Ext.override(Ext.form.TriggerField, {
	onRender : function(ct, position) {
		Ext.form.TriggerField.superclass.onRender.call(this, ct, position);
		this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
		this.trigger = this.wrap.createChild(this.triggerConfig || {
			tag: 'img', 
			src: Ext.BLANK_IMAGE_URL, 
			cls: 'x-form-trigger ' + this.triggerClass
		});
		if(this.hideTrigger){
			this.trigger.setDisplayed(false);
		}
		this.initTrigger();
	}
});

// overwrite methods of combo box
// ==============================
Ext.override(Ext.form.ComboBox, {
	maxListWidth: 0,
	matchAnyting: false,
	initComponent : function() {
		Ext.form.ComboBox.superclass.initComponent.call(this);
		this.addEvents(
			/**
			 * @event expand Fires when the dropdown list is expanded
			 * @param {Ext.form.ComboBox}
			 *            combo This combo box
			 */
			'expand',
			/**
			 * @event collapse Fires when the dropdown list is collapsed
			 * @param {Ext.form.ComboBox}
			 *            combo This combo box
			 */
			'collapse',
			/**
			 * @event beforeselect Fires before a list item is selected.
			 *        Return false to cancel the selection.
			 * @param {Ext.form.ComboBox}
			 *            combo This combo box
			 * @param {Ext.data.Record}
			 *            record The data record returned from the
			 *            underlying store
			 * @param {Number}
			 *            index The index of the selected item in the
			 *            dropdown list
			 */
			'beforeselect',
			/**
			 * @event select Fires when a list item is selected
			 * @param {Ext.form.ComboBox}
			 *            combo This combo box
			 * @param {Ext.data.Record}
			 *            record The data record returned from the
			 *            underlying store
			 * @param {Number}
			 *            index The index of the selected item in the
			 *            dropdown list
			 */
			'select',
			/**
			 * @event beforequery Fires before all queries are processed.
			 *        Return false to cancel the query or set the
			 *        queryEvent's cancel property to true.
			 * @param {Object}
			 *            queryEvent An object that has these properties:
			 *            <ul>
			 *            <li><code>combo</code> : Ext.form.ComboBox <div
			 *            class="sub-desc">This combo box</div></li>
			 *            <li><code>query</code> : String <div
			 *            class="sub-desc">The query</div></li>
			 *            <li><code>forceAll</code> : Boolean <div
			 *            class="sub-desc">True to force "all" query</div></li>
			 *            <li><code>cancel</code> : Boolean <div
			 *            class="sub-desc">Set to true to cancel the query</div></li>
			 *            </ul>
			 */
			'beforequery'
		);
		if (this.transform) {
			//timing of select transform - start
			//if(window.console && window.console.error && window.console.time){
			//	console.time('Transforming SELECT Tag');
			//}
			
			this.allowDomMove = false;
			var s = Ext.getDom(this.transform);
			if (!this.hiddenName) {
				this.hiddenName = s.name;
			}
		
			//add tabindex
			if(s.tabIndex){
				this.tabIndex = s.tabIndex;
			}
			this.id = s.name;
		
			//log id
			//if(window.console && window.console.error && window.console.info){
			//	console.info('Transforming SELECT Tag: id=' + this.id);
			//}
			
			var d = [];
			var arrLength = 2;
			if (!this.store) {
				this.mode = 'local';	
				
				//options
				var opts = s.options;
				
				for (var i = 0, len = opts.length; i < len; i++) {
					//option
					var o = opts[i];
					//value of option
					var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
					//if option selected set option value as component value
					if (o.selected) {
						this.value = value;
					}
					
					var optArray = new Array(3);
					optArray[0] = value;
					optArray[1] = o.text;
					optArray[2] = o.text;
					if(optArray[1] == "") {
						optArray[2] = "...";
					}
					
					d.push(optArray);
				}
				
				var f = new Array(3);
				f[0] = 'value';
				f[1] = 'text';
				f[2] = 'col';

				this.store = new Ext.data.SimpleStore({
					'id' : 0,
					fields : f,
					data : d
				});
					
				this.valueField = f[0];
				this.displayField = f[1];
				this.tpl = '<tpl for="."><div class="x-combo-list-item">{col}</div></tpl>';
			}
			s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
		
			if (!this.lazyRender) {
				this.target = true;
				this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
				Ext.removeNode(s); // remove it
				this.render(this.el.parentNode);
			} else {
				Ext.removeNode(s); // remove it
			}
			//timing of select transform - start
			//if(window.console && window.console.error && window.console.timeEnd){
			//	console.timeEnd('Transforming SELECT Tag');
			//}
		}
		// auto-configure store from local array data
		else if (Ext.isArray(this.store)) {
			if (Ext.isArray(this.store[0])) {
				this.store = new Ext.data.SimpleStore({
					fields : ['value', 'text'],
					data : this.store
				});
				this.valueField = 'value';
			} else {
				this.store = new Ext.data.SimpleStore({
					fields : ['text'],
					data : this.store,
					expandData : true
				});
				this.valueField = 'text';
			}
			this.displayField = 'text';
			this.mode = 'local';
		}

		this.selectedIndex = -1;
		if (this.mode == 'local') {
			if (this.initialConfig.queryDelay === undefined) {
				this.queryDelay = 10;
			}
			if (this.initialConfig.minChars === undefined) {
				this.minChars = 0;
			}
		}
		// set maxListWidth
		/*
		var tm = Ext.util.TextMetrics.createInstance(this.innerList);
		for (var i = 0, len = this.store.getCount(); i < len; i++){
			var r = this.store.getAt(i);
			var displayText = r.data[this.displayField];
			var displayWidth = tm.getWidth(displayText);
			if (displayWidth > this.maxListWidth){
				this.maxListWidth = displayWidth;
			}
		}
		*/
		this.maxListWidth = 50;
	},
	// private
	initList : function(){
		if(!this.list){
			var cls = 'x-combo-list';

			this.list = new Ext.Layer({
				shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
			});

			//set visibility mode
			//this.list.setVisibilityMode(Ext.Element.DISPLAY);

			var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
			this.list.setWidth(lw);
			this.list.swallowEvent('mousewheel');
			this.assetHeight = 0;

			if(this.title){
				this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
				this.assetHeight += this.header.getHeight();
			}

			this.innerList = this.list.createChild({cls:cls+'-inner'});
			this.innerList.on('mouseover', this.onViewOver, this);
			this.innerList.on('mousemove', this.onViewMove, this);
			this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));

			if(this.pageSize){
				this.footer = this.list.createChild({cls:cls+'-ft'});
				this.pageTb = new Ext.PagingToolbar({
					store:this.store,
					pageSize: this.pageSize,
					renderTo:this.footer
				});
				this.assetHeight += this.footer.getHeight();
			}

			if(!this.tpl){
				/**
				* @cfg {String/Ext.XTemplate} tpl The template string, or {@link Ext.XTemplate}
				* instance to use to display each item in the dropdown list. Use
				* this to create custom UI layouts for items in the list.
				* <p>
				* If you wish to preserve the default visual look of list items, add the CSS
				* class name <pre>x-combo-list-item</pre> to the template's container element.
				* <p>
				* <b>The template must contain one or more substitution parameters using field
				* names from the Combo's</b> {@link #store Store}. An example of a custom template
				* would be adding an <pre>ext:qtip</pre> attribute which might display other fields
				* from the Store.
				* <p>
				* The dropdown list is displayed in a DataView. See {@link Ext.DataView} for details.
				*/
				this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
				/**
				* @cfg {String} itemSelector
				* <b>This setting is required if a custom XTemplate has been specified in {@link #tpl}
				* which assigns a class other than <pre>'x-combo-list-item'</pre> to dropdown list items</b>.
				* A simple CSS selector (e.g. div.some-class or span:first-child) that will be
				* used to determine what nodes the DataView which handles the dropdown display will
				* be working with.
				*/
			}

			/**
			* The {@link Ext.DataView DataView} used to display the ComboBox's options.
			* @type Ext.DataView
			*/
			this.view = new Ext.DataView({
				applyTo: this.innerList,
				tpl: this.tpl,
				singleSelect: true,
				selectedClass: this.selectedClass,
				itemSelector: this.itemSelector || '.' + cls + '-item'
			});

			this.view.on('click', this.onViewClick, this);

			this.bindStore(this.store, true);

			if(this.resizable){
				this.resizer = new Ext.Resizable(this.list,  {
					pinned: true,
					transparent: true,
					handles:'s se e'
				});
				this.resizer.on('resize', function(r, w, h){
					this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
					this.listWidth = w;
					this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
					this.restrictHeight();
				}, this);
				this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
			}
		}
	},
	expand : function(){
		if(this.isExpanded() || !this.hasFocus){
			return;
		}
		this.list.alignTo(this.el, this.listAlign);
		// edit:
		// if (maxListWidth > this.width)
		// above line didn't work for combos in toolbars or grids
		if (this.maxListWidth > this.list.getWidth())
		{
			this.list.setWidth(this.maxListWidth);
			this.innerList.setWidth(this.maxListWidth - this.list.getFrameWidth('lr'));
		}
		this.list.show();
		Ext.get(document).on('mousedown', this.collapseIf, this);
		Ext.get(document).on('mousewheel', this.collapseIf, this);
		this.fireEvent('expand', this);
	},
	doQuery : function(q, forceAll){
		if(q === undefined || q === null){
			q = '';
		}
		var qe = {
			query: q,
			forceAll: forceAll,
			combo: this,
			cancel:false
		};
		if(this.fireEvent('beforequery', qe)===false || qe.cancel){
			return false;
		}
		q = qe.query;
		forceAll = qe.forceAll;
		if(forceAll === true || (q.length >= this.minChars)){
			if(this.lastQuery !== q){
				this.lastQuery = q;
				if(this.mode == 'local'){
					this.selectedIndex = -1;
					if(forceAll){
						this.store.clearFilter();
					}else{
						//3rd param set to true to match anything
						this.store.filter(this.displayField, q, this.matchAnything);
					}
					this.onLoad();
				}else{
					this.store.baseParams[this.queryParam] = q;
					this.store.load({
						params: this.getParams(q)
					});
					this.expand();
				}
			}else{
				this.selectedIndex = -1;
				this.onLoad();
			}
		}
	}
});

// overwrite methods of date picker
// ================================
Ext.override(Ext.DatePicker, {
	// private
	onRender : function(container, position){
		var m = [
             '<table cellspacing="0">',
                '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
                '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
        var dn = this.dayNames;
        for(var i = 0; i < 7; i++){
            var d = this.startDay+i;
            if(d > 6){
                d = d-7;
            }
            m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
        }
        m[m.length] = "</tr></thead><tbody><tr>";
        for(var i = 0; i < 42; i++) {
            if(i % 7 == 0 && i != 0){
                m[m.length] = "</tr><tr>";
            }
            m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
        }
        m.push('</tr></tbody></table></td></tr>', 
        	this.showToday ? '<tr><td colspan="3" class="x-date-bottom" align="center"><table cellspacing="0"><tbody><tr><td class="today-btn"></td><td class="ok-btn"></td></tr></tbody></table></td></tr>' : '', '</table><div class="x-date-mp"></div>');

        var el = document.createElement("div");
        el.className = "x-date-picker";
        el.innerHTML = m.join("");

        container.dom.insertBefore(el, position);

        this.el = Ext.get(el);
        this.eventEl = Ext.get(el.firstChild);

        this.leftClickRpt = new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), {
            handler: this.showPrevMonth,
            scope: this,
            preventDefault:true,
            stopDefault:true
        });

        this.rightClickRpt = new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), {
            handler: this.showNextMonth,
            scope: this,
            preventDefault:true,
            stopDefault:true
        });

        this.eventEl.on("mousewheel", this.handleMouseWheel,  this);

        this.monthPicker = this.el.down('div.x-date-mp');
        this.monthPicker.enableDisplayMode('block');
        
        var kn = new Ext.KeyNav(this.eventEl, {
            "left" : function(e){
                e.ctrlKey ?
                    this.showPrevMonth() :
                    this.update(this.activeDate.add("d", -1));
            },

            "right" : function(e){
                e.ctrlKey ?
                    this.showNextMonth() :
                    this.update(this.activeDate.add("d", 1));
            },

            "up" : function(e){
                e.ctrlKey ?
                    this.showNextYear() :
                    this.update(this.activeDate.add("d", -7));
            },

            "down" : function(e){
                e.ctrlKey ?
                    this.showPrevYear() :
                    this.update(this.activeDate.add("d", 7));
            },

            "pageUp" : function(e){
                this.showNextMonth();
            },

            "pageDown" : function(e){
                this.showPrevMonth();
            },

            "enter" : function(e){
                e.stopPropagation();
                return true;
            },

            scope : this
        });

        this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});

        this.el.unselectable();
        
        this.cells = this.el.select("table.x-date-inner tbody td");
        this.textNodes = this.el.query("table.x-date-inner tbody span");

        this.mbtn = new Ext.Button({
            text: "&#160;",
            tooltip: this.monthYearText,
            renderTo: this.el.child("td.x-date-middle", true)
        });

        this.mbtn.on('click', this.showMonthPicker, this);
        this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");

        if(this.showToday){
            this.todayKeyListener = this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday,  this);
            var today = (new Date()).dateFormat(this.format);
            this.todayBtn = new Ext.Button({
                renderTo: this.el.child("td.today-btn"),
                text: String.format(this.todayText, today),
                tooltip: String.format(this.todayTip, today),
                handler: this.selectToday,
                scope: this
            });
            this.okBtn = new Ext.Button({
                renderTo: this.el.child("td.ok-btn"),
                text: this.okText,
				handler: function(){
					this.setValue(this.activeDate);
					this.fireEvent("select", this, this.value);
				},
                scope: this
            });
        } 
     
		if(Ext.isIE){
			this.el.repaint();
		}
		this.update(this.value);
	}
});

// spotlight
// =========
Ext.Spotlight = function(config){
	Ext.apply(this, config);
}
Ext.Spotlight.prototype = {
	active : false,
	animate : true,
	animated : false,
	//duration: .25, //default
	duration : .2,
	//easing: 'easeNone', //default
	easing : 'easeOut',
	

	createElements : function(){
		var bd = HL.pageHostElement;

		this.right = bd.createChild({cls:'x-spotlight'});
		this.left = bd.createChild({cls:'x-spotlight'});
		this.top = bd.createChild({cls:'x-spotlight'});
		this.bottom = bd.createChild({cls:'x-spotlight'});

		this.all = new Ext.CompositeElement([this.right, this.left, this.top, this.bottom]);
	},

	show : function(el, callback, scope){
		if(this.animated){
			this.show.defer(50, this, [el, callback, scope]);
			return;
		}
		this.el = Ext.get(el);
		if(!this.right){
			this.createElements();
		}
		if(!this.active){
			this.all.setDisplayed('');
			this.applyBounds(true, false);
			this.active = true;
			Ext.EventManager.onWindowResize(this.syncSize, this);
			this.applyBounds(false, this.animate, false, callback, scope);
		}else{
			this.applyBounds(false, false, false, callback, scope); // all these booleans look hideous
		}
	},

	hide : function(callback, scope){
		if(this.animated){
			this.hide.defer(50, this, [callback, scope]);
			return;
		}
		Ext.EventManager.removeResizeListener(this.syncSize, this);
		this.applyBounds(true, this.animate, true, callback, scope);
	},

	doHide : function(){
		this.active = false;
		this.all.setDisplayed(false);
	},

	syncSize : function(){
		this.applyBounds(false, false);
	},

	applyBounds : function(basePts, anim, doHide, callback, scope){
		var rg = this.el.getRegion();

		var dw = Ext.lib.Dom.getViewWidth(true);
		var dh = Ext.lib.Dom.getViewHeight(true);

		var c = 0, cb = false;
		if(anim){
			cb = {
				callback: function(){
					c++;
					if(c == 4){
						this.animated = false;
						if(doHide){
							this.doHide();
						}
						Ext.callback(callback, scope, [this]);
					}
				},
				scope: this,
				duration: this.duration,
				easing: this.easing
			};
			this.animated = true;
		}

		this.right.setBounds(
			rg.right,
			basePts ? dh : rg.top,
			dw - rg.right,
			basePts ? 0 : (dh - rg.top),
			cb
		);

		this.left.setBounds(
			0,
			0,
			rg.left,
			basePts ? 0 : rg.bottom,
			cb
		);

		this.top.setBounds(
			basePts ? dw : rg.left,
			0,
			basePts ? 0 : dw - rg.left,
			rg.top,
			cb
		);

		this.bottom.setBounds(
			0,
			rg.bottom,
			basePts ? 0 : rg.right,
			dh - rg.bottom,
			cb
		);

		if(!anim){
			if(doHide){
				this.doHide();
			}
			if(callback){
				Ext.callback(callback, scope, [this]);
			}
		}
	},

	destroy : function(){
		this.doHide();
		Ext.destroy(
			this.right,
			this.left,
			this.top,
			this.bottom);
		delete this.el;
		delete this.all;
	}
};

// session timeout handling
// ========================
HL.Session.timeoutPreWarningTime = 1500000; // in milliseconds
HL.Session.timeoutWarningBoxTime = 300; // in seconds
HL.Session.timeoutWarningBoxTimeLeft = HL.Session.timeoutWarningBoxTime;
HL.Session.timeoutWarningBox = null;
HL.Session.timeoutWarningBoxInterval = null;	
HL.Session.timeoutWarningBoxHandler = function(buttonId){
	if(buttonId == 'ok' || buttonId == 'cancel'){
		location.reload();
	}
}
HL.Session.setCountdownText = function(seconds) {
    //get minutes
    var minutes = parseInt(seconds/60);
    //shrink
    seconds = (seconds%60);
    //get hours
    //var hours = parseInt(minutes/60);
    //shrink
    minutes = (minutes%60);
    //build text
    //var strText = AddZero(hours) + ":" + AddZero(minutes) + ":" + AddZero(seconds);
    var strText = HL.Session.addZero(minutes) + ":" + HL.Session.addZero(seconds);
    //return text
    return strText;
}
HL.Session.addZero = function(num) {
    return ((num >= 0)&&(num < 10)) ? "0" + num : num + "";
}
HL.Session.timeoutWarningBoxProgressBarHandler = function(){
	HL.Session.timeoutWarningBoxTimeLeft--;
	if(HL.Session.timeoutWarningBoxTimeLeft >= 0){
		HL.Session.timeoutWarningBox.updateProgress(HL.Session.timeoutWarningBoxTimeLeft/HL.Session.timeoutWarningBoxTime, HL.Session.setCountdownText(HL.Session.timeoutWarningBoxTimeLeft), '');
	} else {
		clearInterval(HL.Session.timeoutWarningBoxInterval);
		HL.Session.timeoutWarningBox.show({
			buttons	: {
						cancel: HL.Constants.sessionTimeoutCloseText
					},
			closable: false,
			fn		: HL.Session.timeoutWarningBoxHandler,
			icon	: Ext.MessageBox.INFO,
			msg		: HL.Constants.sessionTimeoutBodyText,
			title	: HL.Constants.sessionWarningTitleText,
			width	: 300	
		});
	}
}
HL.Session.timeoutWarningBoxInit = function(){
	window.focus();
	HL.Session.timeoutWarningBox = Ext.Msg.show({
		buttons	: {
					ok: HL.Constants.sessionWarningExtendText
				},
		closable: false,
		fn		: HL.Session.timeoutWarningBoxHandler,
		icon	: Ext.MessageBox.WARNING,
		msg		: HL.Constants.sessionWarningBodyText,
		progress: true,
		title	: HL.Constants.sessionWarningTitleText,
		width	: 300	
	});
	var dialog = HL.Session.timeoutWarningBox.getDialog();
	dialog.hide();
	dialog.removeClass('x-window-plain');
	var contentChild = dialog.body.dom.childNodes[0].childNodes[1];
	if(contentChild){
		for(i=1; i<3; i++){
			var child = contentChild.childNodes[1];
			if(child){
				Ext.get(child).remove();
			}
		}
	}
	var progressChild = dialog.body.dom.childNodes[0].childNodes[2];
	var footerChild = dialog.footer.dom.childNodes[0].childNodes[0];
	if(progressChild && footerChild){
		var progress = Ext.get(progressChild);
		var footer = Ext.get(footerChild);
		var footerContainer = footer.createChild({cls:'x-progress-center'});
		footerContainer.createChild({cls:'x-clear'});
		footerContainer.insertFirst(progress);
		footer.insertFirst(footerContainer);
	}
	dialog.show();
	HL.Session.timeoutWarningBox.updateProgress(1, '', '');
	HL.Session.timeoutWarningBoxInterval = setInterval(HL.Session.timeoutWarningBoxProgressBarHandler, 1000);
}
HL.Session.timeoutWarningInit = function(){
	if(HL.Session.Active){
		setTimeout(HL.Session.timeoutWarningBoxInit, HL.Session.timeoutPreWarningTime);
	}
}

// set default focus
// =================
HL.OLB.inputDateClass = 'inputDate';
HL.OLB.defaultFocusClass = 'focus';
HL.OLB.defaultFocusInit = function(){	
	var defaultFocusField = Ext.select('.' + HL.OLB.defaultFocusClass + ':first').first();
	if(defaultFocusField){
		if(defaultFocusField.hasClass(HL.OLB.inputDateClass)){
			defaultFocusField.removeClass(HL.OLB.defaultFocusClass);
			defaultFocusField.focus(); 
		} else {
			defaultFocusField.focus();
			defaultFocusField.dom.value = defaultFocusField.dom.value;
		}
	}
}

// prevent key events from submitting olb form
// ===========================================
HL.OLB.formClass = '.olbForm';
HL.OLB.formSubmitted = false;
HL.OLB.defaultButtonClass = 'default';
HL.OLB.getViewState = function(form) {
	var viewStateElement = form.select('input[id=javax.faces.ViewState]').first();
	if(viewStateElement) {
			return 'action_submitted_' + viewStateElement.getValue();
	}
	return null;
}
HL.OLB.submitForm = function(e) {
	var extForm = Ext.Element(this.form);
	var cookieName = HL.OLB.getViewState(extForm);
	//readCookie
	if(cookieName == null || HL.readCookie(cookieName) == null){
		//createCookie
		var timeInSeconds = 60;
		var date = new Date();
		date.setTime(date.getTime()+(timeInSeconds*1000));
		var expires = '; expires=' + date.toGMTString();
		document.cookie = cookieName + '=1' + expires + '; path=/';
		//create hidden field
		var hiddenField = Ext.DomHelper.append(extForm, {
			tag: 'input', 
			type: 'hidden',
			name: this.name,
			value: this.value
		}, true);
		//visualize lock
		var formButtons = extForm.select('.button', true);
		formButtons.each(function(formButton) {
			if(formButton.hasClass('next')){
				formButton.addClass('next-inactive');
			} else if(formButton.hasClass('previous')){
				formButton.addClass('previous-inactive');
			} else {
				formButton.addClass('inactive');
			}
		});
		//submit form
		this.form.submit();
		//remove hidden field
		hiddenField.remove();
	}
	e.stopEvent();
}
HL.OLB.changeInputType = function(el) {
	var newButton = Ext.DomHelper.insertAfter(el, {
		tag: 'input',
		type: 'button',
		id: el.dom.id,
		name: el.dom.name,
		value: el.dom.value,
		cls: el.dom.className
	}, true);
	el.remove();
	return newButton;
}
HL.OLB.defaultButtonInit = function(){
	var formElements = Ext.select(HL.OLB.formClass, true);
	formElements.each(function(el) {
		var map = new Ext.KeyMap(el, {
			key: Ext.EventObject.ENTER, // or [10,13]
			scope: el,
			stopEvent: false,
			fn: function(key, e){
				var extTarget = e.getTarget(null, null, true);
				//ignore text area fields
				if(!extTarget.is('textarea')){
					var defaultButton = this.select('.' + HL.OLB.defaultButtonClass + ':first').first();
					if(defaultButton){
						e.stopEvent();
						defaultButton.dom.click();
					}
				}
			}
		});
		//attach submit handler to submit buttons
		var submitButtons = el.select('input[type=submit]');
		submitButtons.each(function(submitButton) {
			submitButton = HL.OLB.changeInputType(submitButton);
			submitButton.on({
				click: HL.OLB.submitForm
			});
		});
	});
}

// error box enhancement
// =====================
HL.OLB.onErrorBoxClick = function(e) {
	var errorBox = e.getTarget(null, null, true);
	errorBox.addClass('messageHidden');
	var viewStateElementValue = null;
	var errorBoxParentForm = errorBox.parent(HL.OLB.formClass);
	if(errorBoxParentForm) {
		var viewStateElement = errorBoxParentForm.select('input[id=javax.faces.ViewState]').first();
		if(viewStateElement) {
			viewStateElementValue = viewStateElement.getValue();
		}
	}
	Ext.Ajax.request({
		url: errorBox.dom.getAttribute('releaseMessageURL'),
		method: 'POST',
		params: { 
			'javax.faces.ViewState': viewStateElementValue
		}
	});
}
HL.OLB.enhanceErrorBoxInit = function() {	
	var errorBoxes = Ext.select('div.qaf span.error', true);
	errorBoxes.each(function(el) {
		//hide error row in qaf
		var errorParent = el.parent('tr');
		if(errorParent){
			var errorParentChildren = errorParent.select('td', true);
			errorParentChildren.setHeight(0);
		}
		//messagePointer class
		el.addClass('messagePointer');
		//click handler
		el.on('click', HL.OLB.onErrorBoxClick, this);
	});
}

// captcha reload
// ==============
HL.OLB.captchaInit = function() {	
	var spans = Ext.select('span[newCaptchaUrl]', true);
	spans.each(function(el) {
		var newCaptchaUrl = el.dom.getAttribute('newCaptchaUrl');
		var anchor = el.select('a').last();
		if (anchor) {
			anchor.on('click', HL.OLB.onNewCaptchaClick, this);
			anchor.dom.setAttribute('newCaptchaUrl', newCaptchaUrl);
			el.dom.removeAttribute("style");
		}
	});
}
HL.OLB.onNewCaptchaClick = function(e) {
	var anchor = e.getTarget(null, null, true);
	var newCaptchaUrl = anchor.dom.getAttribute('newCaptchaUrl');
	var ancestor = anchor.parent('table');
	
	// Eingabefeld leeren
	var input = ancestor.select('input', true).first();
	input.dom.value = '';

	// Bild austauschen
	var img = ancestor.select('img', true).first();
	var url = newCaptchaUrl + '&ts=' + (new Date()).getTime();
	img.dom.setAttribute('src', url);
	
	// Evtl. Fehler-Meldung entfernen
	var errorSpan = ancestor.select('span.error', true).first();
	if (errorSpan) {
		errorSpan.addClass('messageHidden');
		// Fehler-Meldung auch Server-Seitig entfernen
		var errorSpanParentForm = errorSpan.parent(HL.OLB.formClass);
		if(errorSpanParentForm) {
			var viewStateElement = errorSpanParentForm.select('input[id=javax.faces.ViewState]').first();
			if(viewStateElement) {
				var viewStateElementValue = viewStateElement.getValue();
				Ext.Ajax.request({
					url: errorSpan.dom.getAttribute('releaseMessageURL'),
					method: 'POST',
					params: { 
						'javax.faces.ViewState': viewStateElementValue
					}
				});	
			}
		}
	}
}

// show/hide manual box
// ====================
HL.manualBoxId = 'boxApplicationCrossLinks';
HL.manualBoxInit = function() {
	Ext.override(Ext.Panel, {
		showButtonId: 'showButton',
		hideButtonId: 'hideButton',
		invisibleClass: 'invisible',
		toggleCollapse : function(animate){
			var collapseStatus = '';
			if(this.collapsed){
				collapseStatus = 'expand';
				var showButton = Ext.get(this.showButtonId);
				var hideButton = Ext.get(this.hideButtonId);
				showButton.addClass(this.invisibleClass);
				hideButton.removeClass(this.invisibleClass);
			} else {
				collapseStatus = 'collapse';
				var showButton = Ext.get(this.showButtonId);
				var hideButton = Ext.get(this.hideButtonId);
				hideButton.addClass(this.invisibleClass);
				showButton.removeClass(this.invisibleClass);
			}
			this[collapseStatus](animate);
			return this;
		},
		setTitle : function(title, iconCls){
			this.title = title;
			if(this.header && this.headerAsText){
				this.header.child('span').update(title);
			} else {
				this.header.dom.innerHTML = title;
			}
			if(iconCls){
				this.setIconClass(iconCls);
			}
			this.fireEvent('titlechange', this, title);
			return this;
		}
	});
	var boxApplicationCrossLinks = Ext.get(HL.manualBoxId);
	if(boxApplicationCrossLinks){
		// configure new header
		var manualBoxShowButtonId = 'showButton';
		var manualBoxHideButtonId = 'hideButton';
		var manualBoxInvisibleClass = 'invisible';
		var manualBoxContentId = 'hideShow';
		var manualBoxHeaderId = 'headerCrosslinks';
		var manualBoxHeader = Ext.get(manualBoxHeaderId);
    	var manualBoxHeaderTitle = manualBoxHeader ? '<div id="' + manualBoxHeaderId + '">' + manualBoxHeader.dom.innerHTML + '</div>' : '';
    	//transform panel
		var manualBox = new Ext.Panel({
			title: manualBoxHeaderTitle,
			header: true,
			collapsible: true,
			animCollapse: false,
			titleCollapse : true,
			hideCollapseTool: true,
			baseCls:'form-group',
			border : false,
			bodyBorder: false,
			autoScroll: false,
			renderTo: HL.manualBoxId,
			layout: 'fit',
			contentEl: manualBoxContentId,
			showButton: manualBoxShowButtonId,
			hideButton: manualBoxHideButtonId,
			invisibleClass: manualBoxInvisibleClass,
			headerAsText: false
    	});
    	//remove old header
    	if(manualBoxHeader){
    		manualBoxHeader.remove();
    	}
    	//show hide button
    	var manualBoxHideButton = Ext.get(manualBoxHideButtonId);
    	if(manualBoxHideButton){
			manualBoxHideButton.removeClass(manualBoxInvisibleClass);
		}
		//set panel content visibility
		var contentVisible = boxApplicationCrossLinks.hasClass('expand');
		if(!contentVisible){
			manualBox.toggleCollapse();
		}
    }
}

// autocomplete for select input field
// ===================================
HL.OLB.inputComboClass = 'inputCombo';
HL.OLB.multiColListClass = 'multiColList';
HL.OLB.sizeSingleCharComboClass = 'sizeSingleCharCombo';
HL.OLB.sizeTinyComboClass = 'sizeTinyCombo';
HL.OLB.sizeSmallComboClass = 'sizeSmallCombo';
HL.OLB.sizeNormalComboClass = 'sizeNormalCombo';
HL.OLB.sizeBigComboClass = 'sizeBigCombo';
HL.OLB.sizeLargeComboClass = 'sizeLargeCombo';
HL.OLB.sizeGiganticComboClass = 'sizeGiganticCombo';
HL.OLB.sizeBombasticComboClass = 'sizeBombasticCombo';
HL.OLB.inputComboAutoCompleteInit = function(){
	var selectFields = Ext.select('.' + HL.OLB.inputComboClass);
	selectFields.each(function(el) {	
		var label = Ext.DomQuery.selectNode('label[for=' + el.dom.id + ']');
		var comboClass = HL.OLB.inputComboClass;
		var comboListClass = '';
		if(el.hasClass(HL.OLB.multiColListClass)){
			comboClass += ' ' + HL.OLB.multiColListClass;
			comboListClass = HL.OLB.multiColListClass;	
		}
		if(el.hasClass(HL.OLB.sizeSingleCharComboClass)){
			comboClass += ' ' + HL.OLB.sizeSingleCharComboClass;
		} else if(el.hasClass(HL.OLB.sizeTinyComboClass)){
			comboClass += ' ' + HL.OLB.sizeTinyComboClass;
		} else if(el.hasClass(HL.OLB.sizeSmallComboClass)){
			comboClass += ' ' + HL.OLB.sizeSmallComboClass;
		} else if(el.hasClass(HL.OLB.sizeNormalComboClass)){
			comboClass += ' ' + HL.OLB.sizeNormalComboClass;
		} else if(el.hasClass(HL.OLB.sizeBigComboClass)){
			comboClass += ' ' + HL.OLB.sizeBigComboClass;
		} else if(el.hasClass(HL.OLB.sizeLargeComboClass)){
			comboClass += ' ' + HL.OLB.sizeLargeComboClass;
		} else if(el.hasClass(HL.OLB.sizeGiganticComboClass)){
			comboClass += ' ' + HL.OLB.sizeGiganticComboClass;
		} else if(el.hasClass(HL.OLB.sizeBombasticComboClass)){
			comboClass += ' ' + HL.OLB.sizeBombasticComboClass;
		}
		var converted = new Ext.form.ComboBox({
			cls: comboClass,
			emptyText : '...',
			forceSelection : true,
			hideMode: 'display',
			lazyInit: false,
			listClass: comboListClass,
			mode: 'local',
			queryDelay: 0,
			resizable : true,
			selectOnFocus : true,
			shadow : 'sides',
			transform : el.dom,
			triggerAction : 'all',
			typeAhead : false
		});
		if(label) {
			label.htmlFor = converted.el.dom.id;
		}
	});
}

// date picker for date input field
// ================================
HL.datePatternDe = 'd.m.Y';
HL.dateMaskDe = '99.99.9999';
HL.datePatternEn = 'Y-m-d';
HL.dateMaskEn = '9999-99-99';
HL.function_exists = function(fName, pObj) {
	if(!pObj){
		pObj = window;
	}
	return (typeof pObj[fName] == 'function') ? true : false;
}
HL.maskFieldInit = function(element, pattern){
	var field = $(element);
	if(HL.function_exists('mask', field)){
		if(pattern == HL.datePatternDe){
			field.mask(HL.dateMaskDe);
		} else {
			field.mask(HL.dateMaskEn);
		}
	}
}
HL.OLB.inputDatePopupInit = function(){
	var dateFields = Ext.select('.' + HL.OLB.inputDateClass);
	dateFields.each(function(el) {
		var parentEl = el.parent();
		var pattern = el.dom.alt;
		if(pattern){
			
		} else {
			pattern = HL.datePatternEn;
		}
		var converted = new Ext.form.DateField({
			el: el.dom,
			allowBlank: true,
			selectOnFocus: true,
			format: pattern
		});
		converted.render(parentEl);
		
		HL.maskFieldInit(el.dom, pattern);
	});
}

// set/update cookie
// =================
HL.createCookie = function(name, value, days) {
	var expires = '';
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = '; expires=' + date.toGMTString();
	}
	document.cookie = name + '=' + value + expires + '; path=/';
}
HL.readCookie = function(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}
HL.eraseCookie = function(name) {
	createCookie(name, "", -1);
}

// olb start page handling
// =======================
HL.OLB.currentDisplayName = null;
HL.OLB.currentName = null;
HL.OLB.currentUrl = null;

HL.OLB.newDisplayName = null;
HL.OLB.newName = null;
HL.OLB.newUrl = null;

HL.OLB.bookmarkField = null;
HL.OLB.bookmarkaddField = null;

HL.OLB.dialog = null;

HL.OLB.getCookieValue = function(cookieVar){
	var cookieValue = HL.readCookie(cookieVar);
	if(cookieValue == null){
		cookieValue = HL.Constants.olbStartPageDefaultTitleText;
	}
	return cookieValue;
}	
HL.OLB.getNewDisplayName = function() {
	var contentOlb = Ext.get('contentOlb');
	if(contentOlb){
		var tempFields = contentOlb.query('H1');
		if(tempFields){
			var tempField = Ext.get(tempFields[0]);
			if(tempField){
				return tempField.dom.innerHTML;
			}
		}
	}
	return null;
}
HL.OLB.getTitleDiv = function() {
	var contentOlb = Ext.get('contentOlb');
	if(contentOlb){
		var tempFields = contentOlb.query('H1');
		if(tempFields){
			var tempField = Ext.get(tempFields[0]);
			return tempField;
		}
	}
	return null;
}
HL.OLB.onMarkAsStartPageClick = function(e) {
	var el = Ext.get(e.getTarget());
	HL.OLB.dialog.show(el);
	var data = {
		startPageDialogText		: HL.Constants.olbStartPageDialogText,
		startPageCurrentLabel	: HL.Constants.olbStartPageCurrentLabel,
		startPageCurrentValue	: HL.OLB.currentDisplayName,
		startPageNewLabel		: HL.Constants.olbStartPageNewLabel,
		startPageNewValue		: HL.OLB.newDisplayName
	};
	HL.OLB.tpl.overwrite(HL.OLB.dialog.body, data);
}
HL.OLB.getBookmarkField = function(tempClass) {
	var tempFields = Ext.query(tempClass);
	if(tempFields){
		var tempField = Ext.get(tempFields[0]);
		if(tempField){
			tempField.setVisibilityMode(Ext.Element.DISPLAY);
			return tempField;
		}
	}
	return null;
}
HL.OLB.getBookmarkAddField = function(tempClass) {
	var tempFields = Ext.query(tempClass);
	if(tempFields){
		var tempField = Ext.get(tempFields[0]);
		if(tempField){
			tempField.on('click', HL.OLB.onMarkAsStartPageClick, this);
			tempField.setVisibilityMode(Ext.Element.DISPLAY);
			return tempField;
		}
	}
	return null;
}
HL.OLB.toggleBookmark = function() {
	if(HL.OLB.currentName == HL.OLB.newName){
		HL.OLB.bookmarkaddField.setVisible(false);
		HL.OLB.bookmarkField.setVisible(true);	
	} else {
		HL.OLB.bookmarkField.setVisible(false);
		HL.OLB.bookmarkaddField.setVisible(true);
	}
}
HL.OLB.moveBookmarkPics = function(){
	var olbName = HL.OLB.getTitleDiv();
	if(olbName){
		HL.OLB.bookmarkField = HL.OLB.bookmarkField.insertBefore(olbName);
		Ext.QuickTips.register({
			floating: true,
			target:  HL.OLB.bookmarkField,
			text: HL.OLB.bookmarkField.dom.title,
			title: 'Information',
			trackMouse: true
		});
		HL.OLB.bookmarkField.dom.title = '';
		HL.OLB.bookmarkaddField = HL.OLB.bookmarkaddField.insertBefore(olbName);
		Ext.QuickTips.register({
			floating: true,
			target:  HL.OLB.bookmarkaddField,
			text: HL.OLB.bookmarkaddField.dom.title,
			title: 'Information',
			trackMouse: true
		});
		HL.OLB.bookmarkaddField.dom.title = '';
	}
}
HL.OLB.initBookmark = function(){
	if(HL.OLB.isBookmarkable && HL.OLB.bookmarkField && HL.OLB.bookmarkaddField){
		//move pics in dom
		HL.OLB.moveBookmarkPics();
		
		//create dialog
		HL.OLB.dialog = new Ext.Window({
			animCollapse	: true,
			autoHeight		: true,
			buttonAlign		: 'right',
			buttons			: [{
								id		: 'okBtn',
								text	: HL.Constants.olbStartPageDialogOkText,
								handler	: function() {
											HL.createCookie('hlWebPortal.olbStartPageDisplayName', HL.OLB.newDisplayName, 10000);
											HL.createCookie('hlWebPortal.olbStartPageName', HL.OLB.newName, 10000);
											HL.createCookie('hlWebPortal.olbStartPage', HL.OLB.newUrl, 10000);
											HL.OLB.currentName = HL.OLB.newName;
											HL.OLB.toggleBookmark();
											HL.OLB.dialog.close();
										}
							},{
								id		: 'cancelBtn',
								text	: HL.Constants.olbStartPageDialogCancelText,
								handler	: function() {
											HL.OLB.dialog.hide();
										}
							}],
			closeAction		: 'hide',
			defaultButton	: 'okBtn',
			hidden			: true,
			layout			: 'fit',
			modal			: true,
			plain			: false,
			resizable		: false,
			shadow			: true,
			title			: HL.Constants.olbStartPageDialogTitleText,
			width			: 350
		});
		
		//show icon
		HL.OLB.toggleBookmark();
	}
}
HL.OLB.getNewUrl = function(){
	var newUrl = window.document.URL.toString();
	var ndx = newUrl.indexOf("\/\/");
	if (ndx >= 0) {
		var tempUrl = newUrl.substring(ndx + 2);
		ndx = tempUrl.indexOf("\/");
		if (ndx >= 0) {
			tempUrl = tempUrl.substring(ndx);
		}
	}
	var cutIndex = tempUrl.indexOf('.html');
	if(cutIndex > 0){
		tempUrl = tempUrl.substring(0, cutIndex+5);
	}
	newUrl = escape(tempUrl);
	return newUrl;
}
HL.OLB.startPageInit = function(){
	HL.OLB.currentDisplayName = HL.OLB.getCookieValue('hlWebPortal.olbStartPageDisplayName');
	HL.OLB.currentName = HL.OLB.getCookieValue('hlWebPortal.olbStartPageName');
	HL.OLB.currentUrl = HL.OLB.getCookieValue('hlWebPortal.olbStartPage');
	
	HL.OLB.newDisplayName = HL.OLB.getNewDisplayName();
	HL.OLB.newName = HL.OLB.bookmarkTrancode;
	HL.OLB.newUrl = HL.OLB.getNewUrl();
	
	HL.OLB.bookmarkField = HL.OLB.getBookmarkField('.startpage');
	HL.OLB.bookmarkaddField = HL.OLB.getBookmarkAddField('.startpagebookmark');
	
	HL.OLB.initBookmark();
}
//use of template
HL.OLB.tpl = new Ext.XTemplate(
	'<p>{startPageDialogText}</p>',
	'<div style="float: left; padding-right: 0.5em;">',
		'<div><p>{startPageCurrentLabel}</p></div>',
		'<div><p>{startPageNewLabel}</p></div>',
	'</div>',
	'<div style="float: left;">',
		'<div><p><strong>{startPageCurrentValue}</strong></p></div>',
		'<div><p><strong>{startPageNewValue}</strong></p></div>',
	'</div>'
);
HL.OLB.tpl.compile();

// stripe handling
// ===============
//search stripe
HL.OLB.searchStripeId = 'search-stripe';
HL.OLB.searchStripeQTip = 'Help';
//table stripe
HL.OLB.tableStripeId = 'table-stripe';
HL.OLB.tableStripeQTip = 'Help';
//detail stripe
HL.OLB.detailStripeId = 'detail-stripe';
HL.OLB.detailStripeQTip = 'Help';
//stripe classes
HL.OLB.baseStripeClass = 'form-group';
HL.OLB.expandStripeClass = 'expand';
HL.OLB.hasStripeContent = function(stripe){ 
	var hasContent = true;
	if(stripe && stripe.dom.hasChildNodes()){
		if(stripe.dom.childNodes.length == 1){
			var stripeNodeChild = stripe.dom.firstChild;
			if(!stripeNodeChild.hasChildNodes() && Ext.type(stripeNodeChild) == 'whitespace'){
				hasContent = false;
			}
		}
		if(hasContent && stripe.dom.getAttribute('scroll') == 'true'){
			HL.OLB.scrollPosition = stripe.id;
		}
	} else {
		hasContent = false;
	}
	return hasContent;
}
HL.OLB.stripeInit = function(stripeId, stripeQTip){
	var stripeParent = null;
	var stripe = Ext.get(stripeId);
	if(stripe){
		stripeParent = stripe.parent('.' + HL.OLB.baseStripeClass);
	}
	if(stripe && stripeParent && HL.OLB.hasStripeContent(stripe)){
		var stripePanel = new Ext.Panel({
			animCollapse	: false,
			applyTo			: stripeParent,
			autoHeight		: true,
			autoScroll		: false,
			baseCls			: HL.OLB.baseStripeClass,
			bodyBorder		: false,
			border			: false,
			collapsible		: true,
			contentEl		: stripeId,
			getState		: function(){
									return {
										collapsed:this.collapsed
									};
							},
			hideCollapseTool: true,
			layout			: 'fit',
			listeners		: {
								'expand': {
									fn: function(){
											this.setTitle(HL.Constants.olbStripeTitleCollapseText);
									}
								},
								'collapse': {
									fn: function(){
											this.setTitle(HL.Constants.olbStripeTitleExpandText);
									}
								}
							},
			stateEvents		: ['expand','collapse'],
			title			: HL.Constants.olbStripeTitleCollapseText,
			titleCollapse	: true
    	});	
		if(stripeParent.hasClass(HL.OLB.expandStripeClass)){
			stripePanel.expand();
		}
	}
}
HL.OLB.stripeHandlingInit = function(){
	HL.OLB.stripeInit(HL.OLB.searchStripeId, HL.OLB.searchStripeQTip);
	HL.OLB.stripeInit(HL.OLB.tableStripeId, HL.OLB.tableStripeQTip);
	HL.OLB.stripeInit(HL.OLB.detailStripeId, HL.OLB.detailStripeQTip);
}

// scroll to defined stripe position
// =================================
HL.OLB.scrollPosition = 'none';
HL.OLB.scrollInit = function(){
	if(HL.OLB.scrollPosition != 'none') {
		location.hash = HL.OLB.scrollPosition;
	}
}

// hover effect for buttons
// ========================
HL.buttonClass = 'button';
HL.buttonHoverInit = function(){
	var button = Ext.select('.' + HL.buttonClass, true);
	button.addClassOnOver('hover-b');
}

// hover effect for pickbuttons
// ============================
HL.pickbuttonClass = 'inputPickBox';
HL.pickbuttonHoverInit = function(){
	var button = Ext.select('.' + HL.pickbuttonClass, true);
	button.addClassOnOver('inputPickBoxOver');
	button.addClassOnClick('inputPickBoxClick');
}

// hover effect for link buttons
// =============================
HL.linkButtonClass = 'linkButton';
HL.linkButtonHoverInit = function(){
	var linkButton = Ext.select('.' + HL.linkButtonClass, true);
	linkButton.addClassOnOver('hover-lb');
}

// onFocus effect for search input fields
// ======================================
HL.setSearch = function(prefix, fieldClass){
	var extQuery = prefix + '.' + fieldClass;
	var fields = Ext.select(extQuery, true);
	if(prefix == HL.officeFinderSearchIdPrefix) {
		for (var index = 0; index < fields.getCount(); index++) {
			var currentField = fields.item(index);
			if(currentField.hasClass(HL.initialStateClass)){
				currentField.addBehaviourOnFocus({
					className: 'focus',
					behaviour: true
				});
			} else {
				currentField.addBehaviourOnFocus({
					className: 'focus'
				});
			}
		}
	} else {
		for (var index = 0; index < fields.getCount(); index++) {
			var currentField = fields.item(index);
			currentField.addBehaviourOnFocus({
				behaviour: true
			});
		}
	}
}
HL.setSearchInit = function(){
	// search portlet
	HL.setSearch(HL.searchIdPrefix, HL.inputEditClass);
	// office finder search portlet
	HL.setSearch(HL.officeFinderSearchIdPrefix, HL.inputEditClass);
}

// onFocus effect for input fields
// ===============================
// general input field
HL.inputFieldClass = 'inputField';
// text area
HL.textAreaClass = 'textArea';
// match code field
HL.mcNameClass = 'mcName';
HL.mcSupplementClass = 'mcSupplement';
// harmonized system code field
HL.hscChapterClass = 'hscChapter';
HL.hscPositionClass = 'hscPosition';
HL.hscSubPositionClass = 'hscSubPosition';
// telephone number field
HL.tnfInternationalDialingClass = 'tnfInternationalDialing';
HL.tnfNationalDialingCodeClass = 'tnfNationalDialingCode';
HL.tnfSubscriberNumberClass = 'tnfSubscriberNumber';
// search input field
HL.searchIdPrefix = '#search ';
HL.contentSearchIdPrefix = '#contentSearch ';
HL.officeFinderSearchIdPrefix = '#contentRight ';
HL.initialStateClass = 'initialState';
HL.inputEditClass = 'inputEdit';
HL.setFocus = function(prefix, fieldClass, fieldFocusClass){
	var extQuery = prefix + '.' + fieldClass;
	var fields = Ext.select(extQuery, true);
	for (var index = 0; index < fields.getCount(); index++) {
		var currentField = fields.item(index);
		currentField.addBehaviourOnFocus({
			className: fieldFocusClass
		});
	}
}
HL.setFocusInit = function(){
	HL.setFocus('', HL.inputFieldClass, 'focus');
	HL.setFocus('', HL.textAreaClass, 'focus');
	HL.setFocus('', HL.mcNameClass, 'focus');
	HL.setFocus('', HL.mcSupplementClass, 'focus');
	HL.setFocus('', HL.hscChapterClass, 'focus');
	HL.setFocus('', HL.hscPositionClass, 'focus');
	HL.setFocus('', HL.hscSubPositionClass, 'focus');
	HL.setFocus('', HL.tnfInternationalDialingClass, 'focus');
	HL.setFocus('', HL.tnfNationalDialingCodeClass, 'focus');
	HL.setFocus('', HL.tnfSubscriberNumberClass, 'focus');
	HL.setFocus(HL.contentSearchIdPrefix, HL.inputEditClass, 'focus');
}

// HDHM = Horizontal-Dropdown-Hover-Menu
// =====================================
HL.subMenuRollOverClass = 'subMenuRollOver';
HL.subMenuRollOverShadow = new Ext.Shadow({
	mode: 'drop',
	offset: 5
});
HL.subMenuRollOverIn = function() {
	var subMenuRollOver_a =  Ext.fly(this, '_internal').down('a');
	var subMenuRollOver_ul =  Ext.fly(this, '_internal').down('ul');
	subMenuRollOver_a.addClass('hover');
	subMenuRollOver_ul.addClass('hover');
	HL.subMenuRollOverShadow.show(subMenuRollOver_ul);
}
HL.subMenuRollOverOut = function() {		
	var subMenuRollOver_a =  Ext.fly(this, '_internal').down('a');
	var subMenuRollOver_ul =  Ext.fly(this, '_internal').down('ul');
	HL.subMenuRollOverShadow.hide();
	subMenuRollOver_ul.removeClass('hover');
	subMenuRollOver_a.removeClass('hover');
}
HL.subMenuRollOverInit = function(){
	var subMenuRollOver = Ext.select('.' + HL.subMenuRollOverClass);
	subMenuRollOver.hover(
		function(){
			this.timeoutId = HL.subMenuRollOverIn.defer(300, this);
		},
		function(){
			window.clearTimeout(this.timeoutId);
			HL.subMenuRollOverOut.defer(0, this);
		}
	);
}

// hover effect for data table rows
// selection of data table rows
// context menu for data table 
// ================================
HL.OLB.dataTableSingleSelectClass = 'single-select';
HL.OLB.dataTableMultipleSelectClass = 'multiple-select';
HL.OLB.dataTableBehaviorInit = function() {
	// enhance table with single select data set
	var singleSelectTables = Ext.select('.' + HL.OLB.dataTableSingleSelectClass);
	singleSelectTables.each(function(el) {
		var newTableBehavior = new Ext.ux.TableBehavior();
		newTableBehavior.init(el);
	});
	// enhance table with multiple select data set
	var multipleSelectTables = Ext.select('.' + HL.OLB.dataTableMultipleSelectClass);
	multipleSelectTables.each(function(el) {
		var newTableBehavior = new Ext.ux.TableBehavior({
			singleSelect : false
		});
		newTableBehavior.init(el);
	});
}
Ext.ux.TableBehavior = function(config){
    this.singleSelect = true;
    
    Ext.apply(this, config);
    
    this.tbl = null;
	this.rCnt = 0;
	this.colIndex = [];
	this.rowIndex = [];
	this.lastClick = [-1, -1];
}
Ext.ux.TableBehavior.prototype = {
	allowHead : false,
	allowBody : true,
	allowFoot : false,

	headRows : false,
	bodyRows : true,
	footRows : false,
	spanRows : false,

	headCols : false,
	bodyCols : true,
	footCols : false,
	spanCols : true,
	ignoreCols : [],

	headCells : false,
	bodyCells : true,
	footCells : false,
	
	//css classes
	rowClass : 'hover',
	colClass : '',
	cellClass : '',
	clickClass : 'click',

	init : function(target){
		target = Ext.get(target);
		
		this.tbl = target.dom;

		if ( !this.tbl.tBodies || !this.tbl.tBodies.length ){
			return;
		}
		
		this.fixCellIndexes(this.tbl);
		this.fixRowIndexes(this.tbl);

		//init rowIndex
		for ( var r = 0; r < this.tbl.rows.length; r++ ){
			this.rowIndex[r] = [];
		}
			
		//add header cells to index
		if ( this.tbl.tHead ){
			this.addToIndex(this.tbl.tHead.rows, 'THEAD');
		}
			
		//create index - loop through the bodies
		for ( var r = 0; r < this.tbl.tBodies.length; r++ ){
			this.addToIndex(this.tbl.tBodies[r].rows, 'TBODY');
		}
			
		//add footer cells to index
		if ( this.tbl.tFoot ){
			this.addToIndex(this.tbl.tFoot.rows, 'TFOOT');
		}
		
		
		target.on('mouseover', this.onOver, this);
		target.on('mouseout', this.onOut, this);
		target.on('click', this.onClick, this);
		if(this.singleSelect){
			target.on('contextmenu', this.onContextMenu, this);
		}
	},

	fixCellIndexes: function(table){
		var matrix = [];
		for ( var i = 0; i < table.rows.length; i++ ){
			var cells = table.rows[i].cells;
			for ( var j = 0; j < cells.length; j++ ){
				var cell = cells[j];
				var rowSpan = cell.rowSpan || 1;
				var colSpan = cell.colSpan || 1;
				var firstAvailCol = -1;
				if ( !matrix[i] ){ 
					matrix[i] = []; 
				}
				var m = matrix[i];
				
				// Find first available column in the first row
				while ( m[++firstAvailCol] ) {}
				
				cell.realIndex = firstAvailCol;
				
				for ( var k = i; k < i + rowSpan; k++ ){
					if ( !matrix[k] ){ 
						matrix[k] = []; 
					}
					var matrixrow = matrix[k];
					for ( var l = firstAvailCol; l < firstAvailCol + colSpan; l++ ){
						matrixrow[l] = 1;
					}
				}
			}
		}
	},

	fixRowIndexes: function(table){
		var v = 0;
		var r = ( table.tHead ) ? table.tHead.rows : 0;
		if ( r ){
			for ( var i = 0; i < r.length; i++ ){
				r[i].realRIndex = v++;
			}
		}
		for ( var k = 0; k < table.tBodies.length; k++ ){
			r = table.tBodies[k].rows;
			if ( r ){
				for ( var i = 0; i < r.length; i++ ){
					r[i].realRIndex = v++;
				}
			}
		}
		r = ( table.tFoot ) ? table.tFoot.rows : 0;
		if ( r ){
			for ( var i = 0; i < r.length; i++ ){
				r[i].realRIndex = v++;
			}
		}
	},

	addToIndex: function(rows, nodeName){
		var cell;
		var row;
		var s;
		//loop through the rows
		for ( var rowI = 0; rowI < rows.length; rowI++, this.rCnt++ ){
			row = rows[rowI];
			//each cell
			for ( var cI = 0; cI < row.cells.length; cI++ ){
				cell = row.cells[cI];
				//add to rowindex
				if ( (nodeName == 'TBODY' && this.bodyRows) || (nodeName == 'TFOOT' && this.footRows) || (nodeName == 'THEAD' && this.headRows) ){
					s = cell.rowSpan;
					while ( --s >= 0 ){
						this.rowIndex[this.rCnt + s].push(cell);
					}
				}
				//add do colindex
				if ( (nodeName == 'TBODY' && this.bodyCols) || (nodeName == 'THEAD' && this.headCols) || (nodeName == 'TFOOT' && this.footCols) ){
					s = cell.colSpan;
					while ( --s >= 0 ){
						var rI = cell.realIndex + s;
						var ignoreColumn = false;
						for(var i = 0; i < this.ignoreCols.length; i++){
							if(rI + 1 == this.ignoreCols[i]){
								 ignoreColumn = true;
							}
						}
						if(ignoreColumn){
							//dont highlight the columns in the ignoreCols array
							break;
						}
						if ( !this.colIndex[rI] ){
							this.colIndex[rI] = [];
						}
						this.colIndex[rI].push(cell);
					}
				}
				//allow hover for the cell?
				if ( (nodeName == 'TBODY' && this.allowBody) || (nodeName == 'THEAD' && this.allowHead) || (nodeName == 'TFOOT' && this.allowFoot) ) {
					cell.thover = true;
				}
			}
		}
	},

	onOver: function(e){
		var t = e.target;
		//search the real target
		while ( t && t != this.tbl && !t.thover ){ 
			t = t.parentNode;
		}
		if ( t.thover === true ){
			this.highlight(t, true);
		}
	},

	onOut: function(e){
		var t = e.target;
		//search the real target
		while ( t && t != this.tbl && !t.thover ){ 
			t = t.parentNode;
		}
		if ( t.thover === true ){
			this.highlight(t, false);
		}
	},
			
	onClick: function(e){
		//check input fields
		var el = e.getTarget(null, null, true);
		var isInput = el.is('input')
		var isA = el.is('a') || el.up('a',1);
		if(!(isInput || isA)){
			//select row
			this.checkInput(el);
		}
		
		if(!isA){
			var t = e.target;
			//search the real target
			while ( t && t != this.tbl && !t.thover ){ 
				t = t.parentNode;
			}
			if ( t.thover && this.clickClass != '' ){
				var x = t.realIndex;
				var y = t.parentNode.realRIndex;
				if(this.singleSelect){
					if ( x != this.lastClick[0] || y != this.lastClick[1] ){
						var extTable = Ext.get(this.tbl.id);
						var extElementsClick = extTable.select('.' + this.clickClass, true);
						//click..
						this.addClickClass(extTable, this.rowClass, extElementsClick);
						this.addClickClass(extTable, this.colClass, extElementsClick);
						this.addClickClass(extTable, this.cellClass, extElementsClick);
						//unclick
						extElementsClick.removeClass(this.clickClass);
						this.lastClick = [x, y];
					} else {
						this.lastClick = [-1, -1];
					}
				} else {
					var extTable = Ext.get(this.tbl.id);
					//click..
					this.toggleClickClass(extTable, this.rowClass);
					this.toggleClickClass(extTable, this.colClass);
					this.toggleClickClass(extTable, this.cellClass);
					this.lastClick = [x, y];
				}
			}
			this.clickFirstTableButton(el);
		}
	},
	
	onContextMenu: function(e){
		//check input fields
		var el = e.getTarget(null, null, true);
		var isInput = el.is('input')
		var isA = el.is('a') || el.up('a',1);
		if(!(isInput || isA)){
			//select row
			this.checkInput(el);
		}
		
		if(!isA){
			var t = e.target;
			//search the real target
			while ( t && t != this.tbl && !t.thover ){ 
				t = t.parentNode;
			}
			if ( t.thover && this.clickClass != '' ){
				var x = t.realIndex;
				var y = t.parentNode.realRIndex;
				if(this.singleSelect){
					if ( x != this.lastClick[0] || y != this.lastClick[1] ){
						var extTable = Ext.get(this.tbl.id);
						var extElementsClick = extTable.select('.' + this.clickClass, true);
						//click..
						this.addClickClass(extTable, this.rowClass, extElementsClick);
						this.addClickClass(extTable, this.colClass, extElementsClick);
						this.addClickClass(extTable, this.cellClass, extElementsClick);
						//unclick
						extElementsClick.removeClass(this.clickClass);
						this.lastClick = [x, y];
					} else {
						this.lastClick = [-1, -1];
					}
				} else {
					var extTable = Ext.get(this.tbl.id);
					//click..
					this.toggleClickClass(extTable, this.rowClass);
					this.toggleClickClass(extTable, this.colClass);
					this.toggleClickClass(extTable, this.cellClass);
					this.lastClick = [x, y];
				}
			}
			if ( t.thover === true ){
				var el = e.getTarget(null, null, true);
				//show context menu
				this.showContextMenu(el, e.getXY());
				//prevent popup of default context menu
				e.stopEvent();
			}
		}
	},
	
	addClickClass: function(table, styleClass, extElementsClick){
		if ( styleClass != '' ){
			var extElements = table.select('.' + styleClass, true);
			for(var temp = 0; temp < extElements.getCount(); temp++){
				var tempEl = extElements.item(temp);
				if(extElementsClick.contains(tempEl)){
					extElementsClick.removeElement(tempEl);
				} else {
					tempEl.addClass(this.clickClass);
				}
			}
		}
	},
	
	toggleClickClass: function(table, styleClass){
		if ( styleClass != '' ){
			var extElements = table.select('.' + styleClass, true);
			for(var temp = 0; temp < extElements.getCount(); temp++){
				var tempEl = extElements.item(temp);
				if(tempEl.hasClass(this.clickClass)){
					tempEl.removeClass(this.clickClass);
				} else {
					tempEl.addClass(this.clickClass);
				}
			}
		}
	},
	
	
	
	showContextMenu: function(el, position){
		//select row
		this.checkInput(el);

		if (!this.contextMenu) {
			this.contextMenu = new Ext.menu.Menu({
				id : 'contextMenu'
			});
		} else {
			this.contextMenu.removeAll();
		}

		var elTable = el.parent('table.data');
		var elButtons = elTable.select('.button');
		if (elButtons.getCount() > 0) {
			var next = false;
			var previous = false;
			for (var index = 0; index < elButtons.getCount(); index++) {
				var currentButton = elButtons.item(index);
				var iconPath = '';

				if(currentButton.hasClass('next')){
					next = true;
					iconPath = HL.OLB.DATA_TABLE_CONTEXT_NEXT_IMG;
				} else 
				if(currentButton.hasClass('previous')){
					previous = true;
					iconPath = HL.OLB.DATA_TABLE_CONTEXT_PREVIOUS_IMG;
				} else 
				if(next || previous){
					next = false;
					previous = false;
					this.contextMenu.addSeparator();
				}
					
				this.contextMenu.addMenuItem({
					icon : iconPath,
					text : currentButton.dom.value,
					scope : this,
					handler : this.onContextMenuItemClick.createDelegate(this, [currentButton.dom.id], 0)
				});	
			}
			this.contextMenu.showAt(position);
		}
	},
	
	onContextMenuItemClick: function(id) {
		Ext.get(id).dom.click();
	},
			
	highlight: function(cell, on){
		var i = 0;
		//highlight columns
		if ( this.colClass != '' ){
			var h = this.colIndex[cell.realIndex] || [];
			while ( this.spanCols && ++i < cell.colSpan && this.colIndex[cell.realIndex + i] ){
				h = h.concat(this.colIndex[cell.realIndex + i]);
			}
			if(on){
				Ext.get(h).addClass(this.colClass);
			} else {
				Ext.get(h).removeClass(this.colClass);
			}
		}
		//highlight rows
		if ( this.rowClass != '' ){
			var rH = [];
			var rI = cell.parentNode.realRIndex;
			if ( this.rowIndex[rI] ){
				rH = rH.concat(this.rowIndex[rI]);
			}
			i = 0;
			while ( this.spanRows && ++i < cell.rowSpan ){
				if ( this.rowIndex[rI + i] ){
					rH = rH.concat(this.rowIndex[rI + i]);
				}
			}
			if(on){
				Ext.get(rH).addClass(this.rowClass);
			} else {
				Ext.get(rH).removeClass(this.rowClass);
			}
		}
		//highlight cell
		if ( this.cellClass != '' ){
			var nn = cell.parentNode.parentNode.nodeName.toUpperCase();
			if ( (nn == 'TBODY' && this.bodyCells) || (nn == 'THEAD' && this.headCells) || (nn == 'TFOOT' && this.footCells) ){
				if(on){
					Ext.get(cell).addClass(this.cellClass);
				} else {
					Ext.get(cell).removeClass(this.cellClass);
				}
			}
		}
	},
	
	checkInput: function(el){
		var elRow = el.parent('tr');
		if(elRow){
			var elInput = elRow.select('td:nth(1) input:nth(1)').first();
			if(elInput){	
				if(elInput.is('input.inputRadio')){
					if(!elInput.dom.checked){
						elInput.dom.checked = true;
					}
				} else
				if(elInput.is('input.inputCheckBox')){	
					if(elInput.dom.checked){
						elInput.dom.checked = false;
					} else {
						elInput.dom.checked = true;
					}
				}
			}
		}
	},
	
	clickFirstTableButton: function(el){
		var elTable = el.parent('table.data');
		if(elTable){
			var elButton = elTable.select('tfoot:nth(1) tr:nth(1) td:nth(2) input:nth(1)').first();
			if(elButton && elButton.hasClass('supernatural')){
				elButton.dom.click();
			}
		}
	}
}
Ext.reg('tablebehavior', Ext.ux.TableBehavior);

// zoom manual image
// =================
HL.screenshotClass = 'screenshot';
HL.screenshotLinkClass = 'screenshot-link';
HL.manualImageZoomInit = function(){
	var hlScreenshotLink = $('.' + HL.screenshotLinkClass);
	if(hlScreenshotLink.length > 0){
		if(HL.function_exists('lightBox', hlScreenshotLink)){
			//hlScreenshotLink.removeAttr("target");
			hlScreenshotLink.lightBox({
				overlayBgColor: '#999999',
				overlayOpacity: 0.5,
				imageBlank: '/styles/images/lightbox-blank.gif',
				imageLoading: '/styles/images/lightbox-ico-loading.gif',
				imageBtnClose: '/styles/images/lightbox-btn-close.gif',
				imageBtnPrev: '/styles/images/lightbox-btn-prev.gif',
				imageBtnNext: '/styles/images/lightbox-btn-next.gif',
				containerResizeSpeed: 350
			});
		}
	}
}

// internet help identifier - spotlight proof of concept
// =====================================================
HL.spotlightClass = 'inetHelpId';
HL.spotlightElArray = [];
HL.spotlightHost = 'host';
HL.spotlightIds = '';

HL.spotlight = new Ext.Spotlight();

HL.spotlightHelpLayer = null;

HL.HelpButton = Ext.extend(Ext.Component, {
	/**
	 * 
	 * @type String
	 */
	elHelpId: '',
	
	/**
	 * 
	 * @type Ext.Element
	 */
	elParent: null,
						
	/**
	 * Read-only. True if this button is disabled
	 * @type Boolean
	 */
	disabled : false,
    
	/**
	 * @cfg {String} clickEvent
	 * The type of event to map to the button's event handler (defaults to 'click')
	 */
    clickEvent : 'click',

	cls: ['x-tool','x-tool-help'],
	
	overCls: 'x-tool-help-over',
	
	initComponent : function(){
		HL.HelpButton.superclass.initComponent.call(this);
		
		this.addEvents(
			/**
			 * @event click
			 * Fires when this button is clicked
			 * @param {Button} this
			 * @param {EventObject} e The click event
			 */
            'click'
		);
	},
    
    click : function(){
		if(!this.disabled){  
			if (HL.spotlight.active) {
				HL.spotlightHelpLayer.fireEvent('hidewindow');
			} else {
				HL.spotlight.show(this.elParent);
				HL.spotlightHelpLayer.fireEvent('showwindow', this);
			}
		}
	},
    
	onClick : function(e){
		if(e){
			e.preventDefault();
		}
		if(!this.disabled){  
			if (HL.spotlight.active) {
				HL.spotlightHelpLayer.fireEvent('hidewindow');
			} else {
				HL.spotlight.show(this.elParent);
				HL.spotlightHelpLayer.fireEvent('showwindow', this);
			}
		}
	},
    
	// private
	onRender : function(ct, position){
		HL.HelpButton.superclass.onRender.call(ct, position);
		if(this.el){
    		this.el.on({
    					'click'	: {
    								fn		: this.onClick, 
    								scope	: this
    							}
			});
		}
	}
});

HL.HelpWindow = Ext.extend(Ext.Window, {
	helpId : '',

	nextHelpId : '',

	pageHostElement : '',

	prevHelpId : '',
	
	spotlightAjaxParamHelp : 'helpId',
	
	spotlightAjaxParamApp : 'appId',
	
	spotlightAjaxUrlText : '',
	
	spotlightElArray : [],
	
	spotlightErrorText : '',
	
	spotlightFirstCall : true,
	
	spotlightIds : '',

	spotlightTrancode: '',
	
	initComponent	: function(){
		// call the superclass to preserve base class functionality
		HL.HelpWindow.superclass.initComponent.apply(this, arguments);
		
		this.addEvents(
			/**
			 * @event hidewindow
			 * Fires before this window is hidden
			 * @param {Window} this
			 * @param {EventObject} e The event
			 */
			'hidewindow',
			/**
             * @event hidespotlight
			 * Fires after this window is hidden
			 * @param {Window} this
			 * @param {EventObject} e The event
			 */
			'windowhidden'
		);

		this.on({
					'hidewindow': {
									fn		: this.onHideWindow,
									scope	: this
								},
					'showwindow': {
									fn		: this.onShowWindow,
									scope	: this
								}
		});
	},
    
	useButton : function(button){
		if(button){
			if(button.id == 'prevBtn'){
				var helpButton = Ext.getCmp(this.prevHelpId);
				if(helpButton){
					HL.spotlight.show(helpButton.elParent);
    				this.fireEvent('showwindow', helpButton);
				}
			} else if(button.id == 'nextBtn'){
				var helpButton = Ext.getCmp(this.nextHelpId);
				if(helpButton){
    				HL.spotlight.show(helpButton.elParent);
					this.fireEvent('showwindow', helpButton);
				}
			}
		}
	},
    
	onHideWindow : function(button){
		this.hide();
		if (HL.spotlight.active) {
			HL.spotlight.hide(this.useButton.createDelegate(this, [button]));
		}
	},
    
	onShowWindow : function(helpButton){
		this.helpId = '';
		this.prevHelpId = '';
		this.nextHelpId = '';
		this.buttons[1].disable();
		this.buttons[2].disable();
		if(helpButton){
			this.helpId = helpButton.elHelpId;
			var tempSpotlightEl = this.getPreviousSpotlight(helpButton, this.spotlightElArray);
			if(tempSpotlightEl){
				this.prevHelpId = tempSpotlightEl.getId();
				this.buttons[1].enable();
			}
			tempSpotlightEl = this.getNextSpotlight(helpButton, this.spotlightElArray);
			if(tempSpotlightEl){
				this.nextHelpId = tempSpotlightEl.getId();
				this.buttons[2].enable();
			}
		}
		
		if(this.spotlightFirstCall){
			// position window in upper right corner
			var xy = this.el.getAlignToXY(this.container, 'tr-tr', [-17,0]);
			var pos = this.el.translatePoints(xy[0], xy[1]);
			this.x = pos.left;
			this.y = pos.top;
			
			//this.alignTo(this.container, 'tr-tr', [-17,0]);
		}
		
		// show window
		this.show();
		
		// show spotlight content
		this.showSpotlightContent();
	},
	
	getPreviousSpotlight : function(spotlightEl, spotlightElArray){
		var spotlightIndex = spotlightElArray.indexOf(spotlightEl);
		var prevSpotlightIndex = spotlightIndex - 1;
		if(prevSpotlightIndex >= 0){
			return spotlightElArray[prevSpotlightIndex];
		}
		return null;
	},
	
	getNextSpotlight : function(spotlightEl, spotlightElArray){
		var spotlightIndex = spotlightElArray.indexOf(spotlightEl);
		var nextSpotlightIndex = spotlightIndex + 1;
		if(nextSpotlightIndex > 0 && nextSpotlightIndex < spotlightElArray.length){
			return spotlightElArray[nextSpotlightIndex];
		}
		return null;
	},
	
	showSpotlightContent : function(){
		if(this.spotlightFirstCall){
			this.spotlightFirstCall = false;
			this.getSpotlightContent();
		} else {
			this.updateHelpContent();
			this.setPosition(this.getPosition(true));
		}
	},
	
	getSpotlightContent : function(){
		//construct url for ajax request
		var requestUrl = this.spotlightAjaxUrlText + '?';
		if(this.spotlightTrancode == 'overview'){
			requestUrl += this.spotlightAjaxParamHelp + '=' + this.spotlightIds;	
		}else{
			requestUrl += this.spotlightAjaxParamApp + '=' + this.spotlightTrancode.toLowerCase();
		}
		
		//ajax call
		var request = Ext.Ajax.request({
			url: requestUrl,
			success: function(response, options){
				//create empty spotlight container
				var spotlightDiv = Ext.DomHelper.append(this.pageHostElement, {tag:'div', id: 'contentHelp'}, true);
				//insert ajax response in spotlight container
				Ext.DomHelper.insertFirst(spotlightDiv, response.responseText);
				
				//remove <a> tags
				var links = spotlightDiv.select('a',true);
				links.each(function(el) {
					Ext.DomHelper.insertHtml( 'beforeBegin', el.dom, el.dom.innerHTML);
					el.remove();
				});
				
				//make spotlight container invisible
				spotlightDiv.setVisibilityMode(Ext.Element.DISPLAY);
				spotlightDiv.hide();
				//show specific spotlight help content
				this.updateHelpContent();
				this.setPosition(this.getPosition(true));
			},
			failure: function(response, options){
				Ext.Msg.alert('Ajax Request', 'Ajax Request failed. [' + response + '/' + options + ']');
			},
			scope: this
		});
	},
	
	updateHelpContent : function(){
		var helpContent = Ext.get(this.helpId);
		if(helpContent){
			this.body.update(helpContent.dom.innerHTML);
		} else {
			this.body.update(this.spotlightErrorText);
		}
	}
});

/*
 * Step		: 1
 * Function	: init creation of spotlight architecture
 * =======================================================
 */
HL.spotlightInit = function(){
	if(HL.OLB.bookmarkTrancode){
		HL.spotlightSetupSpotlights();
		HL.spotlightSetupHelpLayer();
	}
}

/*
 * Step		: 2
 * Function	: setup spotlights
 * =======================================================
 */
HL.spotlightSetupSpotlights = function(){
	var elArrayIndex = 0;
	var spotlightIds = [];
	
	//var helpIdsToIgnore = ['d5090.general', 'd5090.table', 'd5100.general', 'd5100.details', 'd5100.table'];
	var helpIdsToIgnore = [];
	
	//set up spotlights
	var spotlightHost = Ext.select('.'+ HL.spotlightClass, true);
	spotlightHost.each(function(el) {
		//get help id attribute
		var elHelpId = el.dom.getAttribute(HL.spotlightClass);
		if(elHelpId && helpIdsToIgnore.indexOf(elHelpId) == -1){
			//get help host attribute
			var elHost = el.dom.getAttribute(HL.spotlightHost);
			if(elHost){
				//get help host element
				var elParent = el.parent(elHost);
				if(elParent){
					var helpToolCls = ['x-tool','x-tool-help'];
					var helpToolOverCls = 'x-tool-help-over';
					
					if(el.hasClass('icon-large')){
						helpToolCls = ['x-tool','x-tool-plus'];
						helpToolOverCls = 'x-tool-plus-over';
					}
					
					//create new help tool
					var helpTool = new HL.HelpButton({
						cls		: helpToolCls,
						el		: el,
						elHelpId: elHelpId,
						elParent: elParent,
						overCls	: helpToolOverCls
					});
					
					//remove hidden state class
					helpTool.removeClass('x-hidden');
					
					//render help tool
					helpTool.render();
					
					//add tool tip
					Ext.QuickTips.register({
						target	: helpTool.el,
						text	: HL.Constants.spotlightQTipText
					});
					
					//register spotlight element
					HL.spotlightElArray[elArrayIndex] = helpTool;
					
					//collection of helpids for use on olb overview page 
					spotlightIds[elArrayIndex] = elHelpId;
					
					elArrayIndex++;
				}
			}
		}
	});
	
	//helpid string for use on olb overview page
	for(var i = 0; i < spotlightIds.length; i++){
		if(i > 0){
			HL.spotlightIds += ',' + spotlightIds[i];
		} else {
			HL.spotlightIds += spotlightIds[i];
		}
	}
}

/*
 * Step		: 3
 * Function	: setup spotlight window
 * =======================================================
 */
HL.spotlightSetupHelpLayer = function(){
	//instantiate spotlight help window
	HL.spotlightHelpLayer = new HL.HelpWindow({
		animCollapse		: true,
		autoHeight			: true,
		bodyCssClass		: 'user-generated-content',
		buttonAlign			: 'right',
		buttons			: [{
							id		: 'closeBtn',
							text	: HL.Constants.spotlightCloseText,
							handler	: function(btn){
										btn.ownerCt.fireEvent('hidewindow');
									}
						},{
							id		: 'prevBtn',
							text	: HL.Constants.spotlightPreviousText,
							handler	: function(btn){
										btn.ownerCt.fireEvent('hidewindow', this);
									}
						},{
							id		: 'nextBtn',
							text	: HL.Constants.spotlightNextText,
							handler	: function(btn){
										btn.ownerCt.fireEvent('hidewindow', this);
									}
						}],
		closable			: false,
		closeAction			: 'hide',
		constrain			: true,
		defaultButton		: 'closeBtn',
		height				: 400,
		hidden				: true,
		html				: '<div class="loading-indicator" style="margin-left:auto;margin-right:auto;width:32px;">Loading...</div>',
		layout				: 'fit',
		modal				: false,
		pageHostElement 	: HL.pageHostElement,
		plain				: false,
		resizable			: true,
		renderTo			: HL.pageHostElement,
		shadow				: true,
		spotlightAjaxUrlText: HL.Constants.spotlightAjaxUrlText,
		spotlightElArray 	: HL.spotlightElArray,
		spotlightErrorText 	: HL.Constants.spotlightErrorText,
		spotlightIds 		: HL.spotlightIds,
		spotlightTrancode	: HL.OLB.bookmarkTrancode,
		title				: HL.Constants.spotlightTitleText,
		tools				: [{
								id		: 'close',
								qtip	: HL.Constants.spotlightQTipCloseText,
								handler	: function(event, toolEl, panel){
											panel.fireEvent('hidewindow');
										}
							}],
		width				: 500
	});
	
	/*
	// fixed position of spotlight window while scrolling the page
	Ext.EventManager.on(window, 'scroll', function(){
		if(HL.spotlightHelpLayer.isVisible()){
			/*
			var position = HL.spotlightHelpLayer.getPosition(true);
			var xPos = position[0];
			var yPos = position[1];
			var scrollPos = (document.documentElement || document.body).scrollTop;
			//if(yPos > 0){
				//HL.spotlightHelpLayer.setPosition(xPos, scrollPos + yPos);
			//} else {
				HL.spotlightHelpLayer.setPosition(xPos, scrollPos);
			//}
			*/
			/*
			var position1 = HL.spotlightHelpLayer.getPosition();
			var position2 = HL.spotlightHelpLayer.getPosition(true);
			var scrollPos = (document.documentElement || document.body).scrollTop;
			
			
			if(window.console && window.console.error && window.console.info){
				console.info('              x[' + HL.spotlightHelpLayer.x + ']');
				console.info('              y[' + HL.spotlightHelpLayer.y + ']');
				console.info('     containerX[' + HL.spotlightHelpLayer.container.x + ']');
				console.info('     containerY[' + HL.spotlightHelpLayer.container.y + ']');
				console.info('     positionXY[' + position1[0] + '][' + position1[1] + ']');
				console.info('positionLeftTop[' + position2[0] + '][' + position2[1] + ']');
				console.info('      scrollPos[' + scrollPos + ']');
			}
			
			HL.spotlightHelpLayer.setPosition(HL.spotlightHelpLayer.x, scrollPos + HL.spotlightHelpLayer.y);
		}
	}, window, {buffer: 50});
	*/
	
	// keyboard navigation - left/right arrow keys
	var nav = new Ext.KeyNav(HL.spotlightHelpLayer.getEl(), {
		'left' : function(e){
			if(!this.buttons[1].disabled){
				this.fireEvent('hidewindow', this.buttons[1]);
			}
		},
		'right' : function(e){
			if(!this.buttons[2].disabled){
				this.fireEvent('hidewindow', this.buttons[2]);
			}
		},
		scope : HL.spotlightHelpLayer
	});
}

// opener list
// ===========
HL.slideToggle = function(e) {
	if(e.isDisplayed()){
		e.stopFx();
		e.syncFx();
		e.fadeOut({
			endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
			easing: 'easeOut',
			duration: .2,
			remove: false,
			useDisplay: true
		});
		e.slideOut('t', {
			useDisplay: true
		});
		e.sequenceFx();
	} else {
		e.stopFx();
		e.syncFx();
		e.fadeIn({
			useDisplay: true
		});
		e.slideIn('t', {
			useDisplay: true
		});
		e.sequenceFx();
	}
}
HL.initOpenerList = function() {
	var ulOpener = Ext.select('ul.opener', true);
	ulOpener.each(function(opener) {
		var openerLi = opener.select('li');
		openerLi.addClass('closed');
		var openerAnswer = opener.select('.answer');
		openerAnswer.enableDisplayMode();
		openerAnswer.hide();
		var openerQuestion = opener.select('a.question', true);
		openerQuestion.each(function(question) {
			question.on({
				'click' : {
					fn: function(e){
							e.stopEvent();
							var elem = Ext.Element(this);
							if(elem){
								var elemParent = elem.parent();
								if(elemParent){
									var elemAnswer = elemParent.child('.answer');
									if(elemAnswer){
										HL.slideToggle(elemAnswer);
										elemParent.toggleClass('closed');
									}
								}
							}
					},
					scope: this
				}
			});
		});
	});	
}

/****************************************************************************/
Ext.onReady(function() {
	
	//
	// Ext JS ===============================================
	//
	
	// get corset container
	// ====================
	HL.pageHostElementInit();
	
	// masking page
	// ============
	//HL.pageMasking(true);
	
	// ======================================================
	
	//init tooltips
	Ext.QuickTips.init();

	// error box enhancement
	// =====================
	HL.OLB.enhanceErrorBoxInit();

	//  captcha reload function
	// ========================
	HL.OLB.captchaInit();
	
	// searching for trancode in url
	// =============================
	HL.updateBookmarkTrancodeInit();

	// HDHM = Horizontal-Dropdown-Hover-Menu
	// =====================================
	HL.subMenuRollOverInit();	
	
	// stripe handling
	// ===============
	HL.OLB.stripeHandlingInit();
	
	// olb start page handling
	// =======================
	HL.OLB.startPageInit();
	
	// internet help identifier
	// ========================
	HL.spotlightInit();
	
	// date picker for date input field
	// ================================
	HL.OLB.inputDatePopupInit();

	// prevent key events from submitting olb form
	// ===========================================
	HL.OLB.defaultButtonInit();

	// onFocus effect for search input field
	// =====================================
	HL.setSearchInit();

	// onFocus effect for input fields
	// ===============================
	HL.setFocusInit();

	// hover effect for buttons
	// =============================
	HL.buttonHoverInit();
	
	// hover effect for buttons
	// =============================
	HL.pickbuttonHoverInit();
	
	// hover effect for link buttons
	// =============================
	HL.linkButtonHoverInit();

	try {
	
		// autocomplete for select input field
		// ===================================
		HL.OLB.inputComboAutoCompleteInit();
		
		// hover effect for data table rows
		// selection of data table rows
		// context menu for data table 
		// ================================
		HL.OLB.dataTableBehaviorInit();

		// opener list
		// ===========
		HL.initOpenerList();

		// show/hide manual box
		// ====================
		HL.manualBoxInit();

		//
		// jQuery ===============================================
		//

		// zoom manual image
		// =================
		HL.manualImageZoomInit();

		//
		// Ext JS ===============================================
		//

		// unmasking page
		// ==============
		//HL.pageMasking(false);
	
		// scroll to defined stripe position
		// =================================
		HL.OLB.scrollInit();
	
		// set default focus
		// ================= 
		HL.OLB.defaultFocusInit();
	
		// session timeout handling
		// ========================
		HL.Session.timeoutWarningInit();
	
	} catch (e) {
	
		// hover effect for data table rows
		// selection of data table rows
		// context menu for data table 
		// ================================
		HL.OLB.dataTableBehaviorInit();

		// opener list
		// ===========
		HL.initOpenerList();

		// show/hide manual box
		// ====================
		HL.manualBoxInit();
		
		//
		// jQuery ===============================================
		//

		// zoom manual image
		// =================
		HL.manualImageZoomInit();

		//
		// Ext JS ===============================================
		//
		
		// unmasking page
		// ==============
		//HL.pageMasking(false);
	
		// scroll to defined stripe position
		// =================================
		HL.OLB.scrollInit();
		
		// set default focus
		// ================= 
		HL.OLB.defaultFocusInit();
		
		// session timeout handling
		// ========================
		HL.Session.timeoutWarningInit();
	}
});
