/*
Author: Torstein Hønsi.
Use this code as you want.
*/
var colorPickerCounter = 0;
Ext.ux.ColorPicker = Ext.extend( Ext.form.TriggerField, {
	constructor: function(config) {
		Ext.ux.ColorPicker.superclass.constructor.apply(this, arguments);
		//this.trigger.dom.style.backgroundColor = '#'+ this.value;
		var cp = this;
		this.on('render', function() {
			window.colorPickerValues[cp.id] = cp.value;
			cp.trigger.dom.style.backgroundColor = cp.value;
		});
		
		
		this.on('change', function(el, newValue) {
			if (cp.regex.test(newValue)) {
				cp.setValue(newValue);
			}
		});
		/*this.on('valid', function(obj) {
			cp.fireEvent('change', obj.el, obj.el.dom.value);
		});*/
		
		if (config) {
			this.grid = config.grid;
			this.gridProp = config.gridProp;		
		}
	},
	onRender: function() {
		Ext.ux.ColorPicker.superclass.onRender.apply(this, arguments);
		
		// common listeners
		this.addListener('keyup', function(obj, e) {
			if (e.isNavKeyPress()) return;
			if (obj.validate()) obj.setValue(e.target.value);
		});
		this.addListener('valid', changeHandler);
		this.addListener('focus', focusHandler);
	},
	setValue: function() {
        Ext.ux.ColorPicker.superclass.setValue.apply(this, arguments);
        window.colorPickerValues[this.id] = this.value;
		if (this.trigger) this.trigger.dom.style.backgroundColor = this.value;
		
		// update the possible grid
		if (this.grid) var grid = Ext.getCmp(this.grid);
		if (grid) grid.store.getById(this.gridProp).set('value',this.value);
	},


    onTriggerClick: function(){
    	var colorpicker = this;
    	if (this.disabled) return;
	    var win = new Ext.ux.Window({
	        title    : 'Color picker',
	        closable : true,
	        width    : 450,
	        height   : 370,
	        modal: true,
	        plain    : true,
	        layout   : 'fit',
	        id: 'colorpicker-window-'+ colorpicker.id +'-'+
				window.colorPickerValues[colorpicker.id].replace('#', ''),
	        name: 'colorpicker-window-'+ colorpicker.id +'-'+
				window.colorPickerValues[colorpicker.id].replace('#', ''),
	        items: [ new Ext.ux.IFrameComponent({
	        	id: 'colorpicker-iframe-'+ colorpicker.id,
	        	url: 'colorpicker/iframe.htm?color='+window.colorPickerValues[colorpicker.id]
	        		+'&name='+ colorpicker.id
	        }) ],
        	buttons: [{
                text     : 'Cancel',
                handler : function() {
					win.close();
				}
            },{
                text     : 'OK',
                handler  : function(){
                	colorpicker.setValue(window.colorPickerValues[colorpicker.id]);
                    win.close();
                }
            }]


	    });
		win.show();

    },
	allowBlank: false,
    ctCls: 'x-form-element-colorpicker',
	maskRe: /[#0-9a-fA-F]/,
	regex: /^#[0-9a-fA-F]{6}$/,
	regexText: 'A valid hex color is required.',
	enableKeyEvents: true
});
Ext.ux.IFrameComponent = Ext.extend(Ext.BoxComponent, {
     onRender : function(ct, position){
          this.el = ct.createChild({
          		tag: 'iframe',
          		id: this.id,
          		name: this.id,
          		frameBorder: 0,
          		src: this.url
     		});
     }
});

Ext.ComponentMgr.registerType ('colorpicker', Ext.ux.ColorPicker);
var colorPickerValues = {};

/*
	IncrementalField user extension
*/
Ext.ux.IncrementalField = Ext.extend( Ext.form.TriggerField, {
    constructor: function(config) {
		var self = this;
		Ext.ux.IncrementalField.superclass.constructor.apply(this, arguments);
		this.increment = (config && config.increment) ? config.increment : 1;
		this.unit = (config && config.unit) ? config.unit : '';
		
		this.regex = this.allowDecimals ? new RegExp('[\-]?[0-9\.]'+ this.unit) : 
			new RegExp('^[\-]?[0-9]+'+ this.unit +'$');
			
		this.regexText = this.unit ? 'Invalid number or unit' : 'Invalid number'
		
		
	},
	onRender: function() {
		Ext.ux.IncrementalField.superclass.onRender.apply(this, arguments);

		var cmp = this, trigger = this.trigger;
		this.trigger.dom.onclick = function(e) {
			if (cmp.disabled) return;
			
			/* ie normalize */
			if (!e) e = window.event;
			if (e.layerY === undefined) e.layerY = e.offsetY;
			
			
			var up = e.layerY < trigger.dom.offsetHeight / 2 ? 1 : -1 ;
			var newValue = parseFloat(cmp.el.dom.value) + up * cmp.increment;
			newValue = (Math.round(newValue * 1000000) / 1000000) + cmp.unit;
			cmp.setValue(newValue);
		}
		// common listeners
		this.addListener('keyup', function(obj, e) {
			if (e.isNavKeyPress()) return;
			if (obj.validate()) obj.setValue(e.target.value);
		});
		this.addListener('valid', changeHandler);
		this.addListener('focus', focusHandler);
	},
    setValue: function() {
    	Ext.ux.IncrementalField.superclass.setValue.apply(this, arguments);
		if (this.value < this.minValue) this.setValue(this.minValue);
		else if (this.value > this.maxValue) this.setValue(this.maxValue);
	},
	ctCls: 'x-form-element-incremental',
	enableKeyEvents: true,
	
	allowBlank: false,
	maskRe: /[0-9\.\-]/
});
Ext.ComponentMgr.registerType ('incrementalfield', Ext.ux.IncrementalField);



/*
	Extended checkbox
*/
Ext.ux.Checkbox = Ext.extend( Ext.form.Checkbox, {
	onRender: function() {
		Ext.ux.Checkbox.superclass.onRender.apply(this, arguments);
		// common listeners
		this.addListener('check', changeHandler);
		this.addListener('check', focusHandler);
	}
});
Ext.ComponentMgr.registerType ('uxcheckbox', Ext.ux.Checkbox);

/*
 * Extended ComboBox
 */
Ext.ux.ComboBox = Ext.extend( Ext.form.ComboBox, {
	onRender: function() {
		Ext.ux.ComboBox.superclass.onRender.apply(this, arguments);
		// common listeners
		this.addListener('valid', changeHandler);
		this.addListener('focus', focusHandler);
	}
});
Ext.ComponentMgr.registerType ('uxcombo', Ext.ux.ComboBox);

/*
 * Extended fieldset
 */
Ext.ux.FieldSet = Ext.extend( Ext.form.FieldSet, {
	onRender: function() {
		Ext.ux.FieldSet.superclass.onRender.apply(this, arguments);
		var self = this;
		
		this.addListener('beforecollapse', function() {
			return false;
		});
		if (this.checkbox) {
			var cmp = this;
			$(this.checkbox.dom).bind('click', function() {
				cmp.setDisabled(!this.checked);
				update(cmp);
				
				// show help 
				focusHandler.call(cmp);
			});
			
			// initial state
			if (this.collapsed) cmp.setDisabled(1);
			
		}
		
		// fix mask layout		
		if (!$.browser.mozilla) {	
			function fixMask() {
				if (self.el._mask && self.el._mask.dom) {
					var mask = self.el._mask.dom,
						body = self.bwrap.dom;
						
					$.extend(mask.style, {
						width: body.offsetWidth +'px',
						height: (body.offsetHeight + 2) +'px',
						top: (body.offsetTop - 2) +'px',
						left: body.offsetLeft +'px'
					});
					
				}
			}
			this.on('afterlayout', fixMask);
			this.on('disable', fixMask);
			if ($.browser.msie || $.browser.opera) {	
				this.on('disable', function() {
					self.el.dom.disabled = false;
				});
			}
		}
	},
	setValue: function(val) {
		this.checkbox.dom.checked = val;
		this.setDisabled(!val);
	}
});
Ext.ComponentMgr.registerType ('uxfieldset', Ext.ux.FieldSet);


/*
 * Extended Window
 */
Ext.ux.Window = Ext.extend( Ext.Window, {
	onRender: function() {
		Ext.ux.Window.superclass.onRender.apply(this, arguments);
		
		// the mask is transparent, but makes the window jump to catch the user's attention
		if (this.mask) {
			var id = this.id,
				$mask = $(this.mask.dom);
			$mask.click( function() {
				var $win = $('#'+ id),
					top = parseInt($win[0].style.top);
			
				$win.animate({
					top: top - 5
				}, 50).animate({
					top: top + 2
				}, 100).animate({
					top: top
				}, 25);
			});
			
			if (this.id) $mask.addClass('mask-'+ this.id);
		}
	}
});

