Ext.namespace("Ext.hansub.board");

Ext.hansub.board.AddBoardHtmlContentWindow = function(config){
	
	this.config = config;
	
    this.itemStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url:'./src/api/Interface.php'		
		}),
		baseParams:{
			'class':'Board',
			'method':'getBoardCatList'
			
		},
	  	reader: new Ext.data.JsonReader(
	  		{
	   			root:'data'
			},
	  		[{name: 'camping_boardcat_uid', mapping:'camping_boardcat_uid'}, {name: 'name', mapping:'name'}])
	 
	 });
	 
	 this.itemStore.load();

	this.categoryComboBox = new Ext.form.ComboBox({
		
		hideLabel: true,
		anchor:'100%',
		store:this.itemStore,
		displayField:'name',
        editable:false,
        hiddenName:'camping_boardcat_uid',
       	valueField:'camping_boardcat_uid',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'분류를 선택하세요',
        allowBlank:false,
        selectOnFocus:true
    });
		
	this.nameTextField = new Ext.form.TextField({
		
		hideLabel: true,
		blankText:'게시물의 제목을 입력해 주세요',
		emptyText :'게시물의 제목을 입력해 주세요',
		name: 'name',
        anchor:'100%',
        allowBlank:false
	});
	
	this.contentHtmlEditor = new Ext.form.HtmlEditor({
		//fieldLabel: '내용',
		hideLabel: true,
		fontFamilies : ['맑은 고딕','돋움체'],
        name: 'content',
        border:false,
        width:400,
        height : 300, 
        anchor:'100%',
        enableAlignments:false,
        //enableColors:false,
        enableFont:false,
        //enableFontSize :false,
        //enableFormat :false,
        enableLinks :false,
        enableSourceEdit:false,
        enableLists :false,
        plugins:[ new Ext.ux.plugins.HtmlEditorImageInsert({
                    text: '이미지 주소로 등록',
                    iconCls: 'editor_url_img',
                    scope: this,
                    handler: this.imgURL
                }),new Ext.ux.plugins.HtmlEditorImageInsert({
                    text: '이미지 업로드',
                    iconCls: 'editor_upload_img',
                    scope: this,
                    handler: this.upload
                })]

        //allowBlank:false
	});
	/**
	this.contentHtmlEditor.tb.add({
                //itemId : 'htmlEditorImage',
                cls : 'x-btn-icon x-edit-insertimage',
                enableToggle: false,
                scope: this,
                handler:function(){ this.imgURL; },
                clickEvent:'mousedown',
                tabIndex:-1
            });
            **/
	/**
	this.contentHtmlEditor = new Ext.form.TextArea({
		fieldLabel: '내용 작성',
        name: 'content',
        anchor:'100%',
        width:250,
        height : 300, 
        allowBlank:false
	});
	**/
	
	this.insertImgButton = new Ext.menu.Item({
    	text:'이미지 표시',
		iconCls:'camping_icon',
		scope:this,
		handler:this.insertImg
    });
	
	this.deleteImgButton = new Ext.menu.Item({
    	text:'이미지 삭제',
		iconCls:'user_icon',
		scope:this,
		handler:this.deleteImg
    });
	/**
	 * 버튼 메뉴
	 */
	this.popupMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.insertImgButton ,
        		'-',
				this.deleteImgButton
	        	]
    });
	// rowaction
	this.rowAction = new Ext.ux.grid.RowActions({
		header:'',
		autoWidth:false,
		scope:this,
		allowRule:true,
		resizeable:false,
		width:150,
		actions:[
					/**
					{
						iconCls:'row_preview',
						text:'미리보기',
						qtip:'선택된 이미지를 미리보기 합니다.',
						scope:this,
						callback:this.priview
					},**/
					{
						iconCls:'row_add',
						text:'내용에 표시',
						qtip:'이미지를 작성 내용에 표시합니다.',
						scope:this,
						callback:this.insertImg
					},{
						iconCls:'row_delete',
						text:'삭제',
						qtip:'선택된 이미지를 삭제합니다.',
						scope:this,
						callback:this.deleteImg
					}
				]

	});
	
	this.filedata = new Ext.data.Store({ 
			proxy : new Ext.data.HttpProxy({
		    	url : './src/api/Interface.php',
		       	method : 'POST'
		       	
		    }),
		    baseParams : {
				'class':'Board',
				method:'getBoardFile'
			},
		    
		    reader: new Ext.data.JsonReader({ 
	            root: 'rows', 
	            totalProperty: 'count',
	            id:'uid'
	        }, [ 
	        	{name: 'uid', mapping:'uid', type: 'string'},
	        	{name: 'camping_user_uid', mapping: 'camping_user_uid', type: 'string'},
	        	{name: 'name', mapping: 'name', type: 'string'},
	        	{name: 'realname', mapping: 'realname', type: 'string'},
	        	{name: 'content', mapping: 'content', type: 'string'},
	        	{name: 'regdate', mapping: 'regdate', type: 'string'}
	        	
	        ])
	    })
	/**
	this.fileUpload = new Ext.Toolbar.Button({
    	text:'이미지 업로드 하기',
		iconCls:'new_win_icon',
		scope:this,
		handler:this.upload
    });
 
    
    
	this.fileUploadMenu = new Ext.menu.Menu({
		scope:this,
        items:[this.fileUpload]
	});
    **/
	this.pagingBar = new Ext.PagingToolbar({
	        pageSize: 5,
	        store: this.filedata,
	       	displayInfo: true,
	        displayMsg: '{0} - {1} of {2}',
	        autoWidth:true,
	        emptyMsg: "내용이 없습니다."
      
    });
	this.uploadGridPanel = new Ext.grid.GridPanel({
		id:'uploadGridPanelID',
		title: NAME+'님께서 업로드한 이미지',
		height:175,
		width:'auto',
		border:true,
		hideHeaders:true,
		columns : [
					{header: "업로드된 이미지", width: 110, sortable: true,dataIndex: 'name'},
					{header: "내용", width: 250, sortable: true,dataIndex: 'content'},
					//{header: "설명", width: 300, sortable: true,dataIndex: 'content'},
		            this.rowAction
		        ],
        ds : this.filedata,
        bbar : this.pagingBar,
	    plugins:this.rowAction
	    //tbar : [this.fileUpload,'-']
  	});
  	
  	this.uploadGridPanel.getSelectionModel().on('rowselect', this.selectRowImg, this);

	
	this.imgPanel = new Ext.Panel({
									title:'미리보기',
									height:175,
									border:true
						      });
	
	
	this.formPanel = new Ext.form.FormPanel({
		labelAlign: 'top',
        labelWidth: 50,
        baseCls: 'form',      
        frame:false,
        method: 'POST',
        //bodyStyle:'padding:5px 5px 0',
	    
        items: [{
            layout:'column',
            border:false,
            
            items:[{
		                columnWidth:.2,
		                layout: 'form',
		                bodyStyle:'background-color: #CCD9E8',
		                border:false,
		                items: [this.categoryComboBox]
		            },{
		                columnWidth:.8,
		                layout: 'form',
		                bodyStyle:'background-color: #CCD9E8',
		                border:false,
		                items: [this.nameTextField]
		          }]
        },this.contentHtmlEditor
        ,{
            layout:'column',
            border:false,
            
            items:[{
		                columnWidth:.8,
		                layout: 'form',
		               // bodyStyle:'background-color: #CCD9E8',
		                border:false,
		                items: [this.uploadGridPanel]
		            },{
		                columnWidth:.2,
		                layout: 'form',
		               // bodyStyle:'background-color: #CCD9E8',
		                border:false,
		                items: [this.imgPanel]
		          }]
        }
        ]
        
        
        
        
        
        
        //[this.categoryComboBox,this.nameTextField ,this.contentHtmlEditor]
        
        
        
        //items: [this.itemComboBox, this.nameTextField, this.contentHtmlEditor ]       
    });
    
    this.config.buttons = [
    	
        {
            text: '저장',
            type:'submit',
            scope:this,
            handler: this.submit
        },{
            text: '취소',
            type:'cancel',
            scope:this,
            handler: this.cancel
        }];
    this.config.items = this.formPanel;
    this.config.layout = 'fit';
    this.config.closable = true;
    this.config.plain = true;
    this.config.modal = true;
    this.config.buttonAlign ='right';
    this.config.closeAction ='hide';

	Ext.hansub.board.AddBoardHtmlContentWindow.superclass.constructor.call(this, this.config);
	this.on('hide',this.init,this);
	
	this.uploadGridPanel.on('rowdblclick', this.dbClick, this);
	this.uploadGridPanel.on('rowclick',this.contextMenu, this);
	this.uploadGridPanel.on('rowcontextmenu',this.contextMenu, this);
	
	
	this.itemStore.on("beforeload", function(){
		
		this.itemStore.baseParams.camping_boardtype_uid = this.config.data.camping_boardtype_uid;
		
	},this);
	
	this.itemStore.on("load", function(){
		
		if(this.config.data.camping_boardcat_uid || this.config.data.camping_boardcat_uid != 0 ){
			this.categoryComboBox.setValue(this.config.data.camping_boardcat_uid);
		}
		
	},this);
	/**camping_boardtype_uid:this.config.data.camping_boardtype_uid
	this.filedata.on("beforeload", function(store, options){
		
		if(this.config.data){
			this.filedata.baseParams.uid =  this.config.data.uid;
		}
		
	},this);
	**/
	//this.filedata.load();
	this.filedata.load({
			params:{
					start:0,
					limit:5
			}
	});
	
	
};

Ext.extend(Ext.hansub.board.AddBoardHtmlContentWindow, Ext.Window, {
	
    contextMenu : function(grid, index, e){
		
		this.record = this.filedata.getAt(index);
		
		this.popupMenu.showAt(e.getXY());
      	
    },
	
	
	insertImg : function(){
		//Ext.getCmp('addBoardContentWindowID').contentHtmlEditor.setValue(Ext.getCmp('addBoardContentWindowID').contentHtmlEditor.getValue()+"<br><img width='400' src=./images/upload/"+records.data.realname+"><br>");
		
		//Ext.getCmp('addBoardContentWindowID').contentHtmlEditor.relayCmd('insertimage', "./images/upload/"+this.record.data.realname);
		this.contentHtmlEditor.setValue(this.contentHtmlEditor.getValue()+"<br><img width='720' src='./images/upload/"+this.record.data.realname+"'><br>");
		
	},
	
	selectRowImg:function(sm, index, record){
		
		
		Ext.DomHelper.overwrite(this.imgPanel.body, {tag: 'img', src: './images/upload/'+record.data.realname, width: '150', height: '150'});
		this.imgPanel.setTitle(record.data.name);
		//alert(record.data.realname);
		
		
	},
	
	
	deleteImg : function(){
		
		//record.data.uid//realname
		Ext.Msg.show({
			title:'삭제 확인',
			scope:this,
			msg: this.record.data.name +'을 삭제 하시겠습니까 ?',
			buttons:Ext.Msg.YESNO,
			icon:Ext.MessageBox.QUESTION,
			fn:function(btn, text){
				if(btn == 'yes'){
					
					Ext.Ajax.request({
						url: './src/api/Interface.php',
						params:{
							'class':'Board',
							'method':'deleteFile',
							'uid': this.record.data.uid,
							'realname': this.record.data.realname
						},
						waitMsg:'등록된 이미지를 삭제합니다.',
						scope:this,
						success:function(response, options){
							
							Ext.getCmp('uploadGridPanelID').getStore().reload();
							//grid.ds.reload();
							//this.filedata.reload();
							
											
						},
						failure:function(response, options){
							Ext.MessageBox.alert('ERROR', '이미지 삭제에 오류가 발생하였습니다.');
						}
						            	
								
					});
				}
			}
		});
		
	},
	
	// 값 설정
	setData : function(data){
		
		this.config.data = data;
		this.parentID = this.config.data.parentID;
		
		this.init();
		
		

		
		if (this.config.data.uid) {
			Ext.Ajax.request({
				url: './src/api/Interface.php',
				params: {
					'class': 'Board',
					method: 'getCampingBoard',
					uid: this.config.data.uid
				},
				scope: this,
				success: function(response, options){
					var json = Ext.decode(response.responseText);
					if (json.success) {
					
						this.nameTextField.setValue(json.realname);
						this.contentHtmlEditor.setValue(json.content);
						
						this.config.data = json;
						
						this.itemStore.load();						
					}
					else {
						Ext.MessageBox.alert('오류', '서버에 응답이 없습니다. 잠시 후 다시 접근해 주세요.')
					}
					
				},
				failure: function(response, options){
					Ext.MessageBox.alert('오류', '서버에 응답이 없습니다. 잠시 후 다시 접근해 주세요.')
				}
			});
		}else{
			this.itemStore.load();	
		}
		
		
		
		/**
		this.init();
		
		this.config.data = data;
		//this.filedata.load();
		
		this.itemStore.load({
			params:{
					camping_boardtype_uid:this.config.data.camping_boardtype_uid
					}
				});
		
		if(this.config.data.name){
			this.nameTextField.setValue(this.config.data.name);	
		}
				
		if(this.config.data.content){
			this.contentHtmlEditor.setValue(this.config.data.content);
		}
		
		**/
	},
	
	submit : function(){
		
		if(this.formPanel.getForm().isValid()){
			this.formPanel.form.submit(
			{	waitMsg: '게시물 등록 중...',
				url:'./src/api/Interface.php',
				params :{
							'class':'Board',
							method:'addContent',
							camping_boardtype_uid:this.config.data.camping_boardtype_uid,
							uid:this.config.data.uid
							
						},
				scope:this,
				success: function(form, action) {
                  	if(action.result.success){
                  		this.hide();
                  		this.formPanel.form.reset();
						Ext.getCmp(this.parentID).reload();;
                  		/**
                  		if(this.mode == 'new'){
                  			this.fireEvent('addBoard',action.result);
                  		}else if(this.mode == 'modify'){
                  			this.fireEvent('modifyBoard',action.result);
                  		}
                  		**/
						
                  	}else{
                  		Ext.MessageBox.alert('Error', 'Error')
                  	}
  										
				},
				failure: function(form, action) { 
					Ext.MessageBox.alert('Error', 'Error')
				}
			});
            		
		}
		
	},
	
	cancel : function(){
		this.hide();
	},
	
	init : function(){
		
		this.categoryComboBox.reset();
		this.nameTextField.setValue('');
		this.contentHtmlEditor.setValue(' ');
	
	},
	
	setModify : function(record){
		this.mode = 'modify';
		this.uid = record.get('id');
		this.nameTextField.setValue(record.get('name'));
		this.contentHtmlEditor.setValue(record.get('content'));
	},
	
	imgURL : function(){
		
		this.imgURLField =  new Ext.form.TextField({
			name:'url',
			fieldLabel: '주소 입력',
			allowBlank:true
		});
		this.imgURLField.setValue("http://");
		
		var fp = new Ext.FormPanel({
		        fileUpload: true,
		        width: 500,
		        frame: true,
		        autoHeight: true,
		        bodyStyle: 'padding: 10px 10px 0 10px;',
		        labelWidth: 65,
		        defaults: {
		            anchor: '95%',
		            allowBlank: false,
		            msgTarget: 'side'
		        },
		        items: [this.imgURLField],
		        buttons: [{
		            text: '이미지 추가',
		            scope: this,
		            handler: function(){
		            	
		            	//this.contentHtmlEditor.relayCmd('insertimage', this.imgURLField.getValue());
		                this.contentHtmlEditor.setValue(this.contentHtmlEditor.getValue()+"<br><img width='400' src="+this.imgURLField.getValue()+"><br>");
		            	this.urlWindow.close();
		            
		                
		            }
		        }]
		    });
		//this.uploadWindow.add(fp);
		
		this.urlWindow = new Ext.Window({
			title:'이미지 주소 직접 입력',
			modal:true,
			width:500,
			model:true,
			items:fp
			
		});
		
		this.urlWindow.show();
	},
	
	upload : function(){
		
				
		this.descField =  new Ext.form.TextField({
			emptyText: '업로드 이미지에 대한 간략한 설명을 입력해 주세요.',
		    fieldLabel: '설명',
		    name: 'content'			
		});
		
		this.fileUploadField =  new Ext.form.FileUploadField({
			emptyText: '업로드 파일을 선택해 주세요.(이미지 파일만 가능합니다)',
		    fieldLabel: '이미지',
		    name: 'file',
		    buttonCfg: {
			    text: '',
			    iconCls: 'upload-icon'
		    }			
		});

		
		var fp = new Ext.FormPanel({
		        fileUpload: true,
		        width: 500,
		        frame: true,
		        autoHeight: true,
		        bodyStyle: 'padding: 10px 10px 0 10px;',
		        labelWidth: 65,
		        defaults: {
		            anchor: '95%',
		            allowBlank: false,
		            msgTarget: 'side'
		        },
		        items: [this.fileUploadField,this.descField],
		        buttons: [{
		            text: '업로드',
		            scope: this,
		            handler: function(){
		                if(fp.getForm().isValid()){
			                fp.getForm().submit({
			                    waitMsg: '이미지 업로드 중 입니다....',
								url:'./src/api/Interface.php',
								params :{
											'class':'Board',
											method:'uploadFile',
											uid:this.config.data.uid
											
										},
								scope:this,
			                    success: function(fp, o){
			                    	this.config.data.uid = o.result.uid;
			                    	
			                    	this.contentHtmlEditor.relayCmd('insertimage', "./images/upload/"+o.result.realname);
			                    	//this.contentHtmlEditor.setValue(this.contentHtmlEditor.getValue()+"<br><img width='400' src=./images/upload/"+o.result.realname+"><br>"); 
			                    	/**
			                    	Ext.Msg.show({
							            title: '성공', 
							            msg: '"'+o.result.name+ '" 파일 업로드가 성공했습니다.',
							            minWidth: 200,
							            modal: true,
							            icon: Ext.Msg.INFO,
							            buttons: Ext.Msg.OK
							        });
							        **/
							        this.uploadWindow.close();
									this.filedata.reload();
			                    },
			                    failure:function(fp,o){
			                    	Ext.Msg.show({
							            title: '실패', 
							            msg:o.result.realname,
							            minWidth: 200,
							            modal: true,
							            icon: Ext.Msg.INFO,
							            buttons: Ext.Msg.OK
							        });
			                    }
			                    
			                });
		                }
		            }
		        }]
		    });
		//this.uploadWindow.add(fp);
		
		this.uploadWindow = new Ext.Window({
			title:'이미지 업로드',
			modal:true,
			width:500,
			model:true,
			items:fp
			
		});
		
		this.uploadWindow.show();
		
		
	}

});

