
	
	TJ.Admin.HTMLPopupWindowComponent = Ext.extend(Ext.Window,{
		stateful: true,
                constrainHeader:true,				
		stateId: 'TJ_Admin_HTMLPopupWindowComponent',		
		width: 800,
		height: 500,
		modal: true,
		layout: 'fit',
		title: 'Edit Html',
		closeAction: 'hide',
		previewFrame: null,
		selectedHTML: '',
		initComponent: function() {

		this.tiny =  new TJ.comp.HtmlTinyMCE({});

		this.saveTemplateName = new Ext.form.TextField({width: 100,enableKeyEvents:true, maxLength: 16,	maskRe: /[_a-z0-9]/i});
		this.saveTemplateBtn = 	new Ext.Toolbar.Button({iconCls: 'icon_disk',text:'Save',handler: this.saveTemplate,scope: this, disabled:true});

		this.saveTemplateName.on('keyup',function(f){ this.saveTemplateBtn.setDisabled(!f.isValid() || (f.getValue().length===0));},this);

		this.autoSaveBtn = 				new Ext.Toolbar.Button({iconCls:  'icon_disk',text:'Autosave',handler: this.autoSave, scope: this});

		this.editPanel = new Ext.Panel({
			title: 'Editor',
			layout: 'fit',
			border: false,
			tbar: [
				'Save as user template',
				' ',
				this.saveTemplateName,
				this.saveTemplateBtn
				],
			items: this.tiny
		});

		this.deleteBtn= new Ext.Toolbar.Button({ text: 'Delete',iconCls: 'icon_cancel',handler: this.deleteSaved,scope: this, disabled: true});
		
		this.tree = new Ext.tree.TreePanel({
						region: 'west',
						width: 200,
						split: true,
		border: false,
						autoScroll:true,
						animate:true,
						enableDD:false,
						rootVisible : false,
						containerScroll: true ,
						loader : new Ext.tree.TreeLoader( {
								dataUrl: TJ.LANGUAGESS + '/form:htmlgetnodes'  }),
						root:  new Ext.tree.AsyncTreeNode({
							text: 'Saved',
							draggable: false,
							id: 'root'
								}),
						tbar:
						[
							{
								text:'Refresh',
							   iconCls: 'icon-refresh',
					            handler: function() {
										this.tree.getLoader().load(this.tree.getRootNode());
										this.tree.getRootNode().expand();
								},
								scope: this
							}
							,							
								this.deleteBtn
						]});


	

			this.replaceBtn=new Ext.Toolbar.Button({iconCls: 'icon_html',text: 'Use this HTML', disabled: true, handler: this.replaceHTML, scope: this});

			this.insertBtn = new Ext.Toolbar.Button({iconCls: 'icon_html_add',text: 'Append this HTML', disabled: true, handler: this.insertHTML, scope: this});

			this.preview = new TJ.comp.IFramePanel( { 
											tbar:  ['<b>Preview</b>',' ',this.insertBtn,this.replaceBtn],
											region: 'center',
											border: false,
											bodyClasses: ['mceContentBody','yui-cssbase'],
											stylesheets: [TJ.CLIENTCSS]
												});

			this.tree.getSelectionModel().on('selectionchange',function(sm,node){ 
					this.selectedHTML='';
					if(node)
						this.selectedHTML=node.attributes.html||'';

					this.preview.setContent(this.selectedHTML);

					this.replaceBtn.setDisabled(node===null || node.attributes.html ==undefined );
					this.insertBtn.setDisabled(node===null || node.attributes.html ==undefined );
					this.deleteBtn.setDisabled(node===null || node.attributes.html ==undefined );
			},this);


			this.items = [
				{
				activeTab: 0,
				xtype: 'tabpanel',
				border: false,
				items: [	this.editPanel,
							{	title:'Saved HTML',
								layout: 'border',
								border: false,
								items: [
										this.tree,
										this.preview
									]
							}
				]}];

//			this.items =this.tiny;
		this.status= new Ext.StatusBar ({
								defaultText:'Ready'
			});


			this.bbar= [this.status,'->',this.autoSaveBtn];
			TJ.Admin.HTMLPopupWindowComponent.superclass.initComponent.call(this);

			

			this.addEvents('save');
			this.selBtn = new Ext.Button({
						text: 'Save',
						handler: this.save,
						scope: this
					});

			this.cancelBtn = new Ext.Button({ text: 'Cancel', handler: function(){ this.hide(); }, scope: this });

			this.buttons = [this.selBtn, this.cancelBtn];



//			console.log(this.tiny);
//			this.tiny.on('keyup',function(){console.log('change');});


		},
		replaceHTML: function(){
			this.tiny.setValue(this.selectedHTML);
			this.items.get(0).activate(this.editPanel);
//			console.log();


		},
		insertHTML: function(){
			// not implemented.

			this.tiny.setValue(this.tiny.getValue() + this.selectedHTML);
			this.items.get(0).activate(this.editPanel);
		},
		deleteSaved: function(){
			// This not properly implemented
			node=this.tree.getSelectionModel().getSelectedNode();

			if(node) {
							Ext.Msg.show({
							   title:'Please confirm',
							   width: 300,
							   msg: 'Are you sure you want to delete this saved HTML template?<BR> ' + node.text,
							   buttons: Ext.Msg.YESNO,
							   scope: this,
							   fn: function(btn){ if(btn=='yes') {


						   			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + 'form:htmlUserTemplateRemove',
														params: {node: node.getPath()},
														callback: function (options,success, response) {
															var res=TJ.Admin.ProcessJSONResponse(options,success, response);
															if(res.success){
																node.remove();
																this.status.setStatus({ text: 'User template removed',
																	iconCls: 'x-status-success',
																	clear: true});
															}
															else {
																	this.status.setStatus({ text: 'User template removal failed',
																	iconCls: 'x-status-fail'
															});
										}
									},
									scope: this	});


								 }
							   },
							   icon: Ext.MessageBox.QUESTION
							});

			}

			console.log(node,node.getPath());
//			if(node){
//				node.remove();

//			}





		},

		saveTemplate: function(){

			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + 'form:htmlUserTemplateSave',
					params: {html: this.tiny.getValue(),name:this.saveTemplateName.getValue()},
					callback: function (options,success, response) {
						var res=TJ.Admin.ProcessJSONResponse(options,success, response);
						if(res.success){
							this.saveTemplateName.setValue('');
							this.status.setStatus({ text: 'User template saved',
													iconCls: 'x-status-success',
													clear: true});

						}
						else {
							this.status.setStatus({ text: 'User template save failed',
													iconCls: 'x-status-fail'
												});
						}
					},
					scope: this	});



		},
		autoSavedValue: null,
		autoSaveInterval: 60,
		autoSaveTimer:0,
		checkAutoSave: function(){
//			console.log(this.

			if((this.tiny.getValue() == this.autoSavedValue) || this.autoSaveBtn.disabled ||(this.hidden)) {  // no autosave needed
				this.autoSaveBtn.setText('Autosave');
				this.autoSaveTimer=this.autoSaveInterval;
			} 
			else {
				if(this.autoSaveTimer >0){
					this.autoSaveBtn.setText('Autosave (' + this.autoSaveTimer + ')');
					this.autoSaveTimer--;
				}
				else
					this.autoSave();
			}
			this.checkAutoSave.defer(1000,this);
		},

		autoSave: function(){
			this.autoSaveBtn.setDisabled(true);
			this.autoSaveBtn.setText('Autosave');
			this.autoSaveTime=this.autoSaveInterval;


			this.status.showBusy('Auto saving...');
			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + 'form:htmlautosave',
					params: {html: this.tiny.getValue(),name:this.name},
					callback: function (options,success, response) {
						var res=TJ.Admin.ProcessJSONResponse(options,success, response);
						this.autoSaveBtn.setDisabled(false);
						if(res.success){
							this.autoSavedValue=options.params.html;
							this.status.setStatus({ text: 'Auto save complete',
													iconCls: 'x-status-success',
													clear: true});
						}
						else {
							this.status.setStatus({ text: 'Auto save failed',
													iconCls: 'x-status-fail'
												});
						}
					},
					scope: this	});
		},
		render: function(pos,ct){
			TJ.Admin.HTMLPopupWindowComponent.superclass.render.call(this,pos,ct);
			this.checkAutoSave();


		},
		name: '',
		setValue: function(value){
			this.tiny.setValue(value);
			this.autoSavedValue=this.tiny.getValue();

		},
		getValue: function(){

			return this.tiny.getValue();

		},
		save: function() {
			this.callback.call(this.scope,this);
		},
		show:function(obj){
			obj.value=obj.value||'';
			this.setValue(obj.value);

			obj.name=obj.name||'default';
			this.name=obj.name;

			this.callback=obj.callback;
			this.scope=obj.scope;

			this.setTitle('Editing HTML field "' + this.name + '"');
			this.items.get(0).activate(this.editPanel);

			TJ.Admin.HTMLPopupWindowComponent.superclass.show.call(this);



		}

	});

TJ.Admin.HTMLPopupWindow = function(){
	win=null;
	return {
		get: function(){
			if(win===null){
				win=new TJ.Admin.HTMLPopupWindowComponent();
			}
			return win;
		}
	};
}();

TJ.comp.HTMLPopup = Ext.extend(Ext.form.TriggerField, {
	width: 600,
	height: 200,
	selectOnFocus: false,
	value:'',
    defaultAutoCreate : {tag: "iframe"},
	initComponent: function(){
		this.hiddenName = this.name;
        TJ.comp.HTMLPopup.superclass.initComponent.call(this);
	},
    onRender : function(ct, position){

        TJ.comp.HTMLPopup.superclass.onRender.call(this, ct, position);

         this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
                id: (this.hiddenId||this.hiddenName)}, 'before', true);
           this.el.dom.removeAttribute('name');
	},
	setValue: function(val){

		var doc=this.el.dom.contentWindow.document;
		doc.open();
		if(val)
			doc.write(val);
		doc.close();

		Ext.fly(doc.body).addClass(['mceContentBody','yui-cssbase']);
		  var sheet = doc.createElement("link");
		  sheet.setAttribute("rel", "stylesheet");
		  sheet.setAttribute("type", "text/css");
		  sheet.setAttribute("href", TJ.CLIENTCSS);

		doc.getElementsByTagName('head')[0].appendChild(sheet);


		TJ.comp.HTMLPopup.superclass.setValue.call(this,val);
		this.hiddenField.value=val;

	},
    onTriggerClick : function() {
		if(this.propertyGrid)
			this.propertyGrid.stopEditing();
		var browse=TJ.Admin.HTMLPopupWindow.get();
		browse.show( { value: this.getValue(),
							name:  this.getName(),
							callback: this.callback,
							scope:    this});
	},
	callback: function(browse){
		// extra handling to support setting value within property grid.
		if(this.propertyGrid && this.propertyGrid.selModel.selection)
			this.propertyGrid.selModel.selection.record.set('value',browse.getValue());
		this.setValue(browse.getValue());
		browse.hide();
	}
});

TJ.comp.IFramePanel = Ext.extend(Ext.Panel, {
	stylesheets: [],
	bodyClasses: [],
	iframeHtml: null,
	initComponent: function(){
		this.html='<iframe style="border: none;">';
		TJ.comp.IFramePanel.superclass.initComponent.call(this);

	},
	render: function(pos,ct){
		TJ.comp.IFramePanel.superclass.render.call(this,pos,ct);
		this.iframe=Ext.get(this.body.dom.firstChild);

		this.on('resize',this.doResize,this);
		this.doResize();
		this.iframeDoc=this.iframe.dom.contentWindow.document;

		this.iframeDoc.open();			// Write sample content to create Head/Body.
		this.iframeDoc.write('&nbsp;');
		this.iframeDoc.close();
		this.setStyles();
		if(this.iframeHtml)
			this.setContent(this.iframeHtml);
	},
	doResize: function(){
			if(this.rendered && this.iframe){
				this.iframe.setWidth(this.body.getWidth());
				this.iframe.setHeight(this.body.getHeight());
			}
	},
	
	setContent: function(val){
		this.iframeDoc.body.innerHTML=val;
	},
	setStyles: function(){
		Ext.fly(this.iframeDoc.body).addClass(this.bodyClasses);
		var sheet;
		for(var i=0; i < this.stylesheets.length; i++){
			sheet= this.iframeDoc.createElement("link");
			sheet.setAttribute("rel", "stylesheet");
			sheet.setAttribute("type", "text/css");
			sheet.setAttribute("href", this.stylesheets[i]);
			this.iframeDoc.getElementsByTagName('head')[0].appendChild(sheet);
		}
	}
});


Ext.reg('tjhtmlpopup',TJ.comp.HTMLPopup);
Ext.reg('tjtinymce',TJ.comp.HTMLPopup);

