Ext.ux.ThemePanel = Ext.extend(Ext.Panel, {
	border: false,
	hidden: false,
	fieldLabel: "",
	cookieExpire: 60*60*24*7, // 1week

	styles: new Array(),
	stylesDom: new Array(),
	isRendered: false,

	initComponent: function(){
		Ext.ux.ThemePanel.superclass.initComponent.call(this);

		this.themeCookie = new Ext.state.CookieProvider({
			expires: new Date( new Date().getTime() + Number( this.cookieExpire ) )
		});

		this.getStyle();
		this.setStyle(true);

		this.theme = new Ext.form.ComboBox({
			store: new Ext.data.SimpleStore({
				fields: [ "name", "href" ],
				data: this.styles
			}),
			displayField: "name",
			valueField: "href",
			typeAhead: true,
			mode: "local",
			width: 70,
			triggerAction: "all",
			selectOnFocus: true,
			editable: false,
			emptyText: this.themeCookie.get( "theme", this.defaultStyleTitle ),
			fieldLabel: this.fieldLabel
		});
		this.theme.on("select", function(){
			this.cssChange( arguments[1].data[this.theme.displayField] );
		}, this);
	},

	onRender: function(ct, position) {
		if(this.isRendered) {
			return;
		}
		Ext.ux.ThemePanel.superclass.onRender.call(this, ct, position);
		this.theme.render( this.body );
		this.isRendered = true;
		if( this.hidden ) this.hide();
	},

	getStyle: function() {
		if( !this.styles.length ) {
			var stylesLink = Ext.query("link", Ext.getDoc().dom);
			for ( var i = 0; i < stylesLink.length; i++ ) {
				if( stylesLink[i].rel == "stylesheet" && stylesLink[i].href.match(new RegExp( "ext-all.css$", "ig" )) ) {
					this.defaultStyleTitle = stylesLink[i].title || "ext-all.css";
					this.styles.push([ this.defaultStyleTitle, stylesLink[i].href ]);
					this.stylesDom.push( stylesLink[i] );
				} else if( stylesLink[i].rel == "alternate stylesheet" ) {
					this.styles.push([ stylesLink[i].title, stylesLink[i].href ]);
					this.stylesDom.push( stylesLink[i] );
				}
			}
		}
	},

	cssChange: function( title, first ) {
		if( this.fireEvent( "beforechange", this, title ) !== false ) {
			if( !title ) title = this.defaultStyleTitle;
			for ( var i = 0; i < this.stylesDom.length; i++ ) {
				if ( this.stylesDom[i].title == title ) {
					if( Ext.isWebKit && first === true ) {
						this.stylesDom[i].disabled = !this.stylesDom[i].disabled;
						this.stylesDom[i].disabled = !this.stylesDom[i].disabled;
					} else {
						this.stylesDom[i].disabled = false;
					}
				} else if ( this.stylesDom[i].rel == "alternate stylesheet" ) {
					if( Ext.isWebKit && first === true ) {
						this.stylesDom[i].disabled = !this.stylesDom[i].disabled;
					} else {
						this.stylesDom[i].disabled = true;
					}
				}
			}
			this.themeCookie.set( "theme", title );
			this.fireEvent( "select", this, title );
		}
	},

	setStyle: function(first) {
		this.cssChange( this.themeCookie.get( "theme", this.defaultStyleTitle ), first );
	}
});
Ext.reg("theme", Ext.ux.ThemePanel);

