Ext.ux.pageSelector = Ext.extend(Ext.form.ComboBox, {
	tree: null,
	treeId: 0,
	initComponent: function () {
		this.treeId = Ext.id();
		this.focusLinkId = Ext.id();
		Ext.apply(this, {
			store: new Ext.data.ArrayStore({
		    data: [['', '', '']],
		    fields: ['id', 'name']
		  }),
			valueField: 'id',
			displayField: 'name',
			editable: false,
			shadow: false,
			mode: 'local',
			triggerAction: 'all',
			maxHeight: 200,
			tpl: '<tpl for="."><div style="height:200px"><div id="' + this.treeId + '"></div><a href="#" class="x-grid3-focus" id="' + this.focusLinkId + '" tabIndex="-1"/></div></tpl>',
			selectedClass: '',
			onSelect: Ext.emptyFn,
			listWidth: 250
		});
		this.on('expand', function () {
		  if (!this.treeRendered) {
				this.tree.render(this.treeId);
				this.treeRendered = true;
			} else if (!this.preventCollapse) {
				this.renderedTreeElement.children(':first').appendTo(jQuery('#' + this.treeId));
				this.tree.getRootNode().reload();
			}
			jQuery('#' + this.treeId).find('.x-panel-body:first').css('overflow', 'hidden'); // IE issue
			this.tree.focus();
		});
		var lastValidatedValue;
		this.on('valid', function () { // gets the page details on change/setting of the value
    	var myVal = parseInt(this.getValue());
    	if (isNaN(myVal) || lastValidatedValue == myVal) return;
    	lastValidatedValue = myVal;
			if (myVal > 0 && !extUxPageSelectorPageStore[myVal]) jQuery.post(
				'index.php?ajaxPhpScriptId=' + extUxPageSelectorGetPageInfoAjaxId,
				{id: this.getValue()},
				function (data) {
					if (data.charAt(0) == "{" && data.charAt(data.length-1) == "}") {
						data = Ext.decode(data);
						data.text = data.name;
						if (!extUxPageSelectorPageStore[data.id]) extUxPageSelectorPageStore[data.id] = data;
						if (data.id == me.getValue() && !me.isExpanded()) {
							jQuery(me.getEl().dom).attr('ext:qtip', data.qtip);
							me.store.removeAll();
							me.store.add(new Ext.data.Record({ id: data.id, name: data.name }));
					    me.setValue(data.id);
						}
					}
				}
			); else if (extUxPageSelectorPageStore[myVal]) {
			  var data = extUxPageSelectorPageStore[myVal];
			  jQuery(me.getEl().dom).attr('ext:qtip', data.qtip);
				me.store.removeAll();
				me.store.add(new Ext.data.Record({ id: data.id, name: data.name, realFileName: data.physName }));
		    me.setValue(data.id);
			}
		});
		// prevent combo from hiding when a +/- icon is clicked
			this.on('collapse', function () {
				if (!this.preventCollapse) return;
				this.expand();
				this.preventCollapse = false;
			});
			var me = this; // necessary for access to the combo inside the following jQuery event functions
			jQuery(".x-combo-list .x-tree-ec-icon").live('mouseup', function () {
				me.preventCollapse = true;
			});
		var treeLoadMask;
		var treeConfig = Ext.apply({
	    loader: new Ext.tree.TreeLoader({
        dataUrl: 'index.php?ajaxPhpScriptId=' + extUxPageSelectorGetTreeAjaxId
      }),
      root: new Ext.tree.AsyncTreeNode({
        text: '<b>WEBSEITE</b>',
        expanded: true,
        leaf: false,
        id: '0',
        listeners: {
					beforecollapse: function () { return false; },
					beforeload: function () {
					  if (!treeLoadMask) treeLoadMask = new Ext.LoadMask(jQuery("#"+me.treeId).parent().get(0), {msg: "lade..."});
						treeLoadMask.show();
					},
					load: function () { treeLoadMask.hide(); }
				}
      }),
      rootVisible: false,
      border: false
		}, this.treeConfig);
		if (!treeConfig.root) treeConfig.root = new Ext.tree.AsyncTreeNode({text: 'treeRoot', id: '0'});
		this.tree = new Ext.tree.TreePanel(treeConfig);
		this.tree.on('click', this.onClick, this);
		// save expanded/collapsed state of tree nodes on state change
			this.tree.on('expandnode', function (node) {
			  if (node.id > 0 && !node.attributes.expanded)
			    jQuery.post("index.php?ajaxPhpScriptId=" + extUxPageSelectorToggleTreeNodeStatusAjaxId, { 'id': node.id });
			  else node.attributes.expanded = false;
			});
			this.tree.on('collapsenode', function (node) {
			  if (node.id > 0) jQuery.post("index.php?ajaxPhpScriptId=" + extUxPageSelectorToggleTreeNodeStatusAjaxId, { 'id': node.id });
			});
		this.triggerConfig = {
		  tag:'span', cls:'x-form-twin-triggers', cn:[
		  {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
		  {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
		]};
		this.renderedTreeElement = jQuery('<div />');
		Ext.ux.pageSelector.superclass.initComponent.call(this);
	},
  trigger1Class: 'x-form-clearfield-trigger',
  trigger2Class: 'x-form-pageselector-trigger',
  getTrigger: function (index) {
    return this.triggers[index];
  },
  initTrigger : function() {
    var ts = this.trigger.select('.x-form-trigger', true);
    var triggerField = this;
    ts.each(function(t, all, index){
      t.hide = function(){
        var w = triggerField.wrap.getWidth();
        this.dom.style.display = 'none';
        triggerField.el.setWidth(w-triggerField.trigger.getWidth());
      };
      t.show = function(){
        var w = triggerField.wrap.getWidth();
        this.dom.style.display = '';
        triggerField.el.setWidth(w-triggerField.trigger.getWidth());
      };
      var triggerIndex = 'Trigger'+(index+1);
      if(this['hide'+triggerIndex]){
        t.dom.style.display = 'none';
      }
      t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
      t.addClassOnOver('x-form-trigger-over');
      t.addClassOnClick('x-form-trigger-click');
    }, this);
    this.triggers = ts.elements;
  },
  onTrigger1Click : function () {
		if (this.disabled) return;
		// save tree dom-element before altering the store (altering the store recreates the template containing the tree element which means we loose the tree)
	    if (jQuery('#' + this.treeId).children(':first').length) {
				jQuery('#' + this.treeId).children(':first').appendTo(this.renderedTreeElement);
				this.collapse();
			}
    Ext.QuickTips.unregister(this.getEl().dom);
    // set focus to make sure a change event is fired on blur
			Ext.ux.pageSelector.superclass.onFocus.call(this);
			Ext.get(this.focusLinkId).focus();
		this.store.removeAll();
		this.store.add(new Ext.data.Record({ id: "", name: "" }));
    this.setValue("");
  },
  onTrigger2Click : function () {
		if (this.disabled) return;
		if (this.isExpanded()) this.collapse();
		else {
			Ext.ux.pageSelector.superclass.onFocus.call(this);
			Ext.get(this.focusLinkId).focus();
			if (this.triggerAction == 'all') this.doQuery(this.allQuery, true);
			else this.doQuery(this.getRawValue());
		}
  },
	onClick: function (node) {
		if (!node) return;
		// save tree dom-element before altering the store (altering the store recreates the template containing the tree element which means we loose the tree)
			jQuery('#' + this.treeId).children(':first').appendTo(this.renderedTreeElement);
		node.attributes.name = node.attributes.text;
		dataObj = { id: node.attributes.id, name: node.attributes.name };
		if (!extUxPageSelectorPageStore[node.attributes.id]) extUxPageSelectorPageStore[node.attributes.id] = node.attributes;
    Ext.QuickTips.unregister(this.getEl().dom);
		Ext.QuickTips.register({
		    target: this.getEl().dom,
		    text: node.attributes.qtip
		});
		this.store.removeAll();
		this.store.add(new Ext.data.Record(dataObj));
    this.setValue(node.attributes.id);
		this.collapse();
		// hide quicktips
		  if (Ext.QuickTips.isEnabled()) {
		    Ext.QuickTips.disable();
		    Ext.QuickTips.enable();
			}
	}
});
