﻿
if(Ext && Ext.ux && Ext.ux.grid && Ext.ux.grid.GridFilters){
	Ext.override( Ext.ux.grid.GridFilters , { 
	    buildQuery : function(filters) { 
	       return {filters: Ext.encode(filters)}; 
	    } 
	});
};


Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createInterceptor(function() {
  this.form.items.each(function(item) {
    if (item.el.getValue() == item.emptyText) {
      item.el.dom.value = '';
    }
    });
 });

Ext.form.Action.Submit.prototype.run = Ext.form.Action.Submit.prototype.run.createSequence(function() {
  this.form.items.each(function(item) {
    if (item.el.getValue() == '' && item.emptyText) {
      item.el.dom.value = item.emptyText;
    }
    });
 });




Ext.app.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.app.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    hasSearch : false,
    paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.el.dom.value = '';
            var o = {start: 0};
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            this.store.reload({params:o});
            this.triggers[0].hide();
            this.hasSearch = false;
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        var o = {start: 0};
        this.store.baseParams = this.store.baseParams || {};
        this.store.baseParams[this.paramName] = v;
        this.store.reload({params:o});
        this.hasSearch = true;
        this.triggers[0].show();
    }
});


Ext.namespace('Ext.ux.plugins');
Ext.ux.plugins.FitToParent = function(parent) {
	return {
		init: function(c) {
			c.on('render', function(c) {
				parent = Ext.get(parent || c.el.dom.parentNode);
			});
			c.monitorResize = true;
			c.doLayout = c.doLayout.createInterceptor(function(){
				var pos = this.getPosition(), size = parent.getViewSize();
				this.setSize(size.width - pos[0], size.height - pos[1]);
			}, c);
		}
	}
}


Ext.override(Ext.form.CheckboxGroup, {
  getName: function() {
    return this.items.first().getName();
  },


	getNames: function() {
    var n = [];

    this.items.each(function(item) {
      if (item.getValue()) {
        n.push(item.getName());
      }
    });

    return n;
  },

  getValues: function() {
    var v = [];

    this.items.each(function(item) {
      if (item.getValue()) {
        v.push(item.getRawValue());
      }
    });

    return v;
  },

  setValue: function(v) {
  a = eval('[' + v + ']');
    this.items.each(function(item) {
	    for(var i = 0; i<a.length; i++){
	    	if(a[i]==item.inputValue){
	    		item.setValue(true);
	    	}
	    }
   	});
  },

setValues: function(v) {
  alert('setValues:' + v);
    var r = new RegExp('(' + v.join('|') + ')');

    this.items.each(function(item) {
      item.setValue(r.test(item.getRawValue()));
    });
  }
});



Ext.override(Ext.form.RadioGroup, {
  getName: function() {
    return this.items.first().getName();
  },

  getValue: function() {
    var v;

    this.items.each(function(item) {
      v = item.getRawValue();
      return !item.getValue();
    });

    return v;
  },

  setValue: function(v) {
    this.items.each(function(item) {
      item.setValue(item.getRawValue() == v);
    });
  }
});


/*Create a NULL plugin to deal*/
Ext.ns('Ext.ux.plugins');
Ext.ux.plugins.Null = function(){};
Ext.ux.plugins.Null.prototype = {
	init: function () {}
};
		

Ext.override(Ext.form.CheckboxGroup, {
	afterRender: function(){
		Ext.form.CheckboxGroup.superclass.afterRender.apply(this, arguments);
		var form = this.findParentByType('form').getForm();
		form.add.apply(form, this.items.items);
	}
});

/*
NOTE: No override needed for ReadioBox as it extends checkbox.
*/

Ext.QuickTips.init(); 

Ext.form.Field.prototype.msgTarget = 'side';

/* Override for hiding container */

Ext.override(Ext.form.Field, {
    showContainer: function() {
        this.enable();
        this.show();
        this.getEl().up('.x-form-item').setDisplayed(true); // show entire container and children (including label if applicable)
    },
    hideContainer: function() {
        this.disable(); // for validation
        this.hide();
        this.getEl().up('.x-form-item').setDisplayed(false); // hide container and children (including label if applicable)
    },
    setContainerVisible: function(visible) {
        if (visible) {
            this.showContainer();
        } else {
            this.hideContainer();
        }
        return this;
    }
}); 


function fxFormatUkMoney(v){
    v = (Math.round((v-0)*100))/100;
    v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.'+ ps[1] : '.00';
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    v = whole + sub;
    if(v.charAt(0) == '-'){
        return '-$' + v.substr(1);
    }
    return "&pound;" +  v;
}


// 2008-05-01 - Patch for date parsing error in Ext 2.1
Ext.apply(Date.parseCodes, {
    j: {
        g:1,
        c:"d = parseInt(results[{0}], 10);\n",
        s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
    },
    M: function() {
        for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names
        return Ext.applyIf({
            s:"(" + a.join("|") + ")"
        }, Date.formatCodeToRegex("F"));
    },
    n: {
        g:1,
        c:"m = parseInt(results[{0}], 10) - 1;\n",
        s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
    },
    o: function() {
        return Date.formatCodeToRegex("Y");
    },
    g: function() {
        return Date.formatCodeToRegex("G");
    },
    h: function() {
        return Date.formatCodeToRegex("H");
    },
    P: function() {
      return Ext.applyIf({
        s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
      }, Date.formatCodeToRegex("O"));
    }
});

Date.formatCodeToRegex = function(character, currentGroup) {
    // Note: currentGroup - position in regex result array (see notes for Date.parseCodes above)
    var p = Date.parseCodes[character];

    if (p) {
      p = Ext.type(p) == 'function'? p() : p;
      Date.parseCodes[character] = p; // reassign function result to prevent repeated execution      
    }

    return p? Ext.applyIf({
      c: p.c? String.format(p.c, currentGroup || "{0}") : p.c
    }, p) : {
        g:0,
        c:null,
        s:Ext.escapeRe(character) // treat unrecognised characters as literals
    }
};


/*Fix for bug in EXT 2.2, subsequently fixed in SVN by EXT team.*/
Ext.form.TriggerField.override({
    afterRender : function(){
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){
            this.el.position();
            this.el.setY(y);
        }
    }
});


Ext.override( Ext.ux.grid.GridFilters , { 
    buildQuery : function(filters) { 
       return {filters: Ext.encode(filters)}; 
    } 
});  




Ext.ux.WizardPanel = Ext.extend(Ext.Panel, {
	
	currentPage: 0,

    initComponent:function(config) {

		    Ext.apply(this,
		    {
    	    layout: 'card'
				    ,layoutConfig: {deferredRender:false}
				    ,frame:true
				    ,activeItem: 0
				    ,bbar: [
					    new Ext.Toolbar.Fill()
					    ,'-'
				    ]
		    }
		    );

        Ext.ux.WizardPanel.superclass.initComponent.call(this);
    },




		onRender : function(ct, position){
        Ext.ux.WizardPanel.superclass.onRender.call(this, ct, position);
        tb = this.getBottomToolbar();
        this.restartButton = tb.addButton({disabled:true, text: '<< Restart', scope: this, handler: this.goRestart});
        tb.addSeparator();
        this.backButton = tb.addButton({disabled:true, text: '<< Back', scope: this, handler: this.goPreviousPage});
        tb.addSeparator();
        this.nextButton = tb.addButton({scope: this, disabled:false, text: 'Next >>', handler: function(){this.goNextPage()}});
        tb.addSeparator();
        this.repeatButton = tb.addButton({disabled:true, text: 'Repeat >>', scope: this, handler: this.goRepeatPage});
        tb.addSeparator();
        this.finishButton = tb.addButton({disabled:true, text: 'Finish', scope: this, handler: this.finish});
        
        this.on('afterlayout',function(){
		    if(this.layout.activeItem.fxAllowMultiple == 'true'){
		        this.repeatButton.setDisabled(false);
		    }else{
		        this.repeatButton.setDisabled(true);
		    }
	    },this);
	
    },
    
    
	
    onAfterLayout : function(ct, layout){
        alert('asd');
        Ext.ux.WizardPanel.superclass.onAfterLayout.call(this, ct, layout);
    },

	changePage: function(x){
		this.currentPage += x;
		this.getLayout().setActiveItem(this.currentPage);
		if(this.layout.activeItem.fxAllowMultiple == 'true'){
		    this.repeatButton.setDisabled(false);
		}else{
		    this.repeatButton.setDisabled(true);
		}
		this.backButton.setDisabled(this.currentPage == 0);
		this.nextButton.setDisabled(this.currentPage == this.items.getCount() -2);
		this.finishButton.setDisabled(this.currentPage != this.items.getCount() -2);
	},
	
	goRepeatPage: function(x){
	    try{OnNextButton(this.layout.activeItem);}catch(e){}
	    for(var i=0; i<this.findByType('form').length; i++){
	        this.findByType('form')[i].getForm().reset();
	    }
	    
	},
	
	goNextPage: function(x){
		try{OnNextButton(this.layout.activeItem);}catch(e){}
        this.changePage(1);
	},

	goPreviousPage: function(x){
		this.changePage(-1);
	},
	
	goRestart: function(x){
	    for(var i=0; i<this.findByType('form').length; i++){
	        this.findByType('form')[i].getForm().reset();
	    }
		this.currentPage = 0;
		this.changePage(0);
		this.restartButton.setDisabled(true);
	},
	
	finish: function(x){
	    try{OnFinishButton(this.layout.activeItem);}catch(e){}
	    this.changePage(1);
	    this.backButton.setDisabled(true);
	    this.nextButton.setDisabled(true);
	    this.restartButton.setDisabled(false);
	}

});

Ext.reg("uxwizardpanel", Ext.ux.WizardPanel);		   


Ext.override(Ext.menu.Menu, {
    autoWidth : function(){
        var el = this.el, ul = this.ul;
        if(!el){
            return;
        }
        var w = this.width;
        if(w){
            el.setWidth(w);
        }else if(Ext.isIE && !Ext.isIE8){
            el.setWidth(this.minWidth);
            var t = el.dom.offsetWidth; // force recalc
            el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
        }
    }
});

Ext.ns('Ext.ux.form');
Ext.ux.form.XCheckbox = Ext.extend(Ext.form.Checkbox, {
     submitOffValue:'false'
    ,submitOnValue:'true'

    ,onRender:function(ct) {

        this.inputValue = this.submitOnValue;

        // call parent
        Ext.ux.form.XCheckbox.superclass.onRender.apply(this, arguments);

        // create hidden field that is submitted if checkbox is not checked
        this.hiddenField = this.wrap.insertFirst({tag:'input', type:'hidden'});

        // update value of hidden field
        this.updateHidden();

    } // eo function onRender

    /**
     * Calls parent and updates hiddenField
     * @private
     */
    ,setValue:function(val) {
        Ext.ux.form.XCheckbox.superclass.setValue.apply(this, arguments);
        this.updateHidden();
    } // eo function setValue

    /**
     * Updates hiddenField
     * @private
     */
    ,updateHidden:function() {
        if(this.hiddenField) {
            this.hiddenField.dom.value = this.checked ? this.submitOnValue : this.submitOffValue;
            this.hiddenField.dom.name = this.checked ? '' : this.el.dom.name;
        }
    } // eo function updateHidden

}); // eo extend

// register xtype
Ext.reg('xcheckbox', Ext.ux.form.XCheckbox);

function fxFormatUkMoney(v) {
	v = (Math.round((v - 0) * 100)) / 100;
	v = (v == Math.floor(v)) ? v + ".00" : ((v * 10 == Math.floor(v * 10)) ? v
			+ "0" : v);
	v = String(v);
	var ps = v.split('.');
	var whole = ps[0];
	var sub = ps[1] ? '.' + ps[1] : '.00';
	var r = /(\d+)(\d{3})/;
	while (r.test(whole)) {
		whole = whole.replace(r, '$1' + ',' + '$2');
	}
	v = whole + sub;
	if (v.charAt(0) == '-') {
		return '-$' + v.substr(1);
	}
	return "&pound;" + v;
}
