Ext.namespace("Ext.hansub.board");

Ext.hansub.board.BoardGridPanel = function(obj) {
	
	this.isfirst = true;
	this.obj = obj;
	this.pageSize = 20;
	this.isloaded = false;
	text = "글쓰기";

	this.addButton = new Ext.Button({
    	text:text,
		//tooltip:{title:text, text:'게시글을 작성합니다.'},
		iconCls:'write',
		scope:this,
		handler:this.addItem
    });
    
	if(UID){
		this.addButton.setDisabled(false);
	}else{
		this.addButton.setDisabled(true);
	}
    
    this.itemStore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url:'./src/api/Interface.php'		
		}),
		baseParams:{
			'class':'Board',
			'method':'getBoardCatList',
			includeTotal : true,
			camping_boardtype_uid:this.obj.data.camping_boardtype_uid
			
		},
	  	reader: new Ext.data.JsonReader(
	  		{
	   			root:'data'
			},
	  		[{name: 'camping_boardcat_uid', mapping:'camping_boardcat_uid'}, {name: 'name', mapping:'name'}])
	 
	 });
	 
	

	this.categoryComboBox = new Ext.form.ComboBox({
		hideLabel: true,
		width:100,
		store:this.itemStore,
		displayField:'name',
        editable:false,
        hiddenName:'camping_boardcat_uid',
       	valueField:'camping_boardcat_uid',
        typeAhead: true,
        mode: 'remote',
        triggerAction: 'all',
        emptyText:'분류 선택',
        allowBlank:true,
        selectOnFocus:true
    });
    
   this.viewUserInfoButton = new Ext.menu.Item({
    	text:'등록자 정복지 보기',
		tooltip:{title:'등록자 정복지 보기', text:'등록자의 캠핑 정복지도를  화면에 표시해 줍니다.'},
		iconCls:'user_icon',
		scope:this,
		handler:this.viewUserInfo
    });

	/**
	 * 버튼 메뉴
	 */
	this.popupMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.viewUserInfoButton
	        	]
    });
    
    this.categoryComboBox.on('select', function(combo, record, index){
    
    	if(this.obj.data.camping_boardcat_uid != record.data.camping_boardcat_uid){
    		
    		this.obj.data.camping_boardcat_uid = record.data.camping_boardcat_uid;
    		this.searchField.onTriggerClear();
    		this.obj.ds.load({
					params:{
							start:0,
							limit:this.pagingBar.pageSize
							}
				});
    	}
    	
    },this);
    
    this.itemStore.load();
    
    
    
    
    
    this.titleButton = new Ext.menu.Item({
		text:'제목만 보기',
		iconCls:'view_title',
		scope:this,
		handler:this.setListLayout.createDelegate(this, ['title'])
	        
	});
	this.summaryButton = new Ext.menu.Item({
		text:'간략하게 보기',
		iconCls:'view_summary',
		scope:this,
		handler: this.setListLayout.createDelegate(this, ['summary'])
	});
	this.detailButton = new Ext.menu.Item({
		text:'전체내용 보기',
		iconCls:'view_full',
		scope:this,
		handler: this.setListLayout.createDelegate(this, ['full'])
	});
	
	/**
	 * view 메뉴
	 */
	if (this.obj.data.camping_boardtype_type == 'acount'){
		items = [this.titleButton,this.summaryButton];
	}else{
		items = [this.titleButton,this.summaryButton,this.detailButton];
	}
	this.viewMenu = new Ext.menu.Menu({
		scope:this,
        items: items
    });

    
    /**
     * SpliteButton
     */
    this.viewSplitButton = new Ext.Toolbar.SplitButton({
		iconCls:'view_summary',
		text:'간략하게 보기',
		menu:this.viewMenu,
		handler:this.setListLayout.createDelegate(this, ['swiching'])
    })
	
	
    
    
    /**
    this.deleteButton = new Ext.Toolbar.Button({
    	text:'삭제',
		tooltip:{title:'삭제', text:'선택한 항목을 삭제 합니다.'},
		iconCls:'delete',
		scope:this,
		handler:this.deleteItem
    });
    **/
    /**
    this.newWinButton = new Ext.Toolbar.Button({
    	text:'새창보기',
		tooltip:{title:'새 창에서 보기', text:'현재 게시판을 새창으로 봅니다.'},
		iconCls:'new_win_icon',
		scope:this,
		handler:this.newWin
    });
 	**/
    //Ext.DomHelper.append(Ext.getCmp('id').body, {tag: 'img', src: 'foo', width: '50', height: '50'});
    /**
	 * 버튼 메뉴
	 */
    /**
	this.addMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.addButton ,
        		'-',
        		this.newWinButton
	        	]
    });
    **/
    
	// data store 설정
	this.obj.ds = new Ext.data.GroupingStore({ 
		proxy : new Ext.data.HttpProxy({
	    	url : './src/api/Interface.php',
	       	method : 'POST'
	       	
	    }),
	    baseParams : {
			'class':'Board',
			method:'getBoardList',
			html:'true'
		},
	    
	    reader: new Ext.data.JsonReader({ 
            root: 'rows', 
            totalProperty: 'count',
            id:'uid'
        }, [ 
        	{name: 'uid', mapping:'uid', type: 'string'},
        	{name: 'camping_boardtype_uid', mapping: 'camping_boardtype_uid', type: 'string'},
			{name: 'camping_boardtype_type', mapping: 'camping_boardtype_type', type: 'string'},
			{name: 'camping_bitemcat_uid', mapping: 'camping_bitemcat_uid', type: 'string'},
        	{name: 'camping_user_uid', mapping: 'camping_user_uid', type: 'string'},
        	{name: 'camping_user_name', mapping: 'camping_user_name', type: 'string'},
        	{name: 'camping_boardcat_uid', mapping: 'camping_boardcat_uid', type: 'string'},
        	{name: 'camping_boardcat_name', mapping: 'camping_boardcat_name', type: 'string'},
			{name: 'comment', mapping: 'comment', type: 'auto'},
            {name: 'name', mapping: 'name', type: 'string'},
            {name: 'files', mapping: 'files', type: 'auto'},
            {name: 'content', mapping: 'content', type: 'string'},
           	{name: 'regdate', mapping: 'regdate', type: 'string'},
            {name: 'modifydate', mapping: 'modifydate', type: 'string'},
			{name: 'comment', mapping: 'comment', type: 'auto'}
        ]),
       	groupField: 'regdate',
       	remoteSort:true,
       	remoteGroup:true,
       	groupOnSort:true,
        sortInfo: {field: 'regdate', direction: 'DESC'}
    });
    
    this.pagingBar = new Ext.PagingToolbar({
        pageSize: this.pageSize,
        store: this.obj.ds,
        displayInfo: true,
        displayMsg: '{0} - {1} of {2}',
        autoWidth:true,
        emptyMsg: "내용이 없습니다.",
        plugins:new Ext.ux.PageSizePlugin()
      
    });
    
   // this.pageSizePlugin = new Ext.ux.PageSizePlugin();

	
	
	/**
	
	this.expander = new Ext.grid.RowExpander({
		lazyRender:true,
		enableCaching:false,
        tpl : new Ext.XTemplate(
        	'<div class=boardcontent>',
        		'{content}',
        	'</div>'
        )
    });
    **/
    if(this.obj.text){
		this.obj.title = this.obj.text;
	}
	
	// rowaction
	/**
	this.rowAction = new Ext.ux.grid.RowActions({
		header:'',
		autoWidth:false,
		scope:this,
		width:120,
		actions:[
					{
						iconCls:'row_modify',
						text:'변경',
						qtip:'선택된 내용을 변경합니다.',
						scope:this,
						callback:this.modify
					},{
						iconCls:'row_delete',
						text:'삭제',
						qtip:'선택된 내용을 삭제합니다.',
						scope:this,
						callback:this.deleteItem
					}
					
					
				]
	});
	**/
	//this.rowAction.camping_boardtype_uid = this.obj.data.camping_boardtype_uid;
	//alert(this.rowAction.camping_boardtype_uid);
	this.searchField = new Ext.ux.grid.Search({
					        position:'top',
				            iconCls:'board_search',
				            searchTipText:'검색어를 입력하세요',
				            dateFormat:'m/d/Y',
				            minLength:2,
				            disableIndexes:['camping_boardcat_name','camping_user_name','regdate'],
				            width:150,
				            searchText:'검색',
				            selectAllText:'전체',
				            paramNames: {
						         fields:'fields'
						        ,query:'keyword'
						    }
				        })
	/**
	this.rowAction.on({ 
		header:'Actions',
		action:function(grid, record, action, row, col) {}
	})
**/

		this.obj.columns = [	//this.expander,
		{
			header: "제목",
			width: 500,
			sortable: false,
			dataIndex: 'name',
			renderer: this.titleFormat
		}, {
			header: "내용",
			hidden: true,
			sortable: true,
			dataIndex: 'content'
		}, {
			header: "댓글수",
			width: 40,
			sortable: true,
			dataIndex: 'comment'
		}, {
			header: "분류",
			width: 70,
			sortable: true,
			dataIndex: 'camping_boardcat_name'
		}, {
			header: "등록자",
			width: 70,
			sortable: true,
			dataIndex: 'camping_user_name'
		}, {
			header: "작성일",
			width: 70,
			sortable: true,
			dataIndex: 'regdate'
		}	//this.rowAction
		//,{header: "수정일", width: 80,	sortable: true,dataIndex: 'modifydate'}          
		];

    // select model
    this.obj.sm = new Ext.grid.RowSelectionModel({
		            singleSelect:true
		        });
	
   this.obj.viewConfig = {
            forceFit:true
   };
   
   this.obj.loadMask = {msg:'게시판 화면 구성 중..'};
   
   this.obj.view = new Ext.grid.GroupingView({
            forceFit:true,
            enableRowBody:true,
            showGroupName: false,
            showPreview:true,
           	getRowClass : this.applyRowClass,
            groupTextTpl: '{text} ( {[values.rs.length]} {[values.rs.length > 1 ? "개 등록됨." : "개 등록됨."]})'
        })
        
    this.obj.plugins = [
    		//this.rowAction,
			//this.expander, 
			this.searchField
			];
    //this.obj.tbar = [this.titleButton, this.summaryButton, this.detailButton,'-',this.addButton ];
			
	
	this.obj.tbar = ['-',this.categoryComboBox,'-',this.viewSplitButton,'-',this.addButton];
    
    this.obj.bbar = this.pagingBar;
	   
   
	Ext.hansub.board.BoardGridPanel.superclass.constructor.call(this, this.obj);
							      
	
	//this.on('render',function(){Ext.getCmp('viewportID').doLayout();},this);
	/*
	this.boardGridSM = this.getSelectionModel();
	this.boardGridSM.on('rowselect', this.selectedRow, this);
	*/
	this.on('cellclick',this.clickRow, this);
	
			
	this.obj.ds.on("beforeload", function(store, options){
		
		//start = (this.pagingBar.getPageData().activePage-1) * 10;
           
		//alert(this.pagingBar.getPageData().activePage);
		//this.obj.ds.baseParams.start = 0;
		this.obj.ds.baseParams.limit = this.pagingBar.pageSize,
		this.obj.ds.baseParams.camping_boardtype_uid = this.obj.data.camping_boardtype_uid;
		this.obj.ds.baseParams.camping_boardcat_uid = this.obj.data.camping_boardcat_uid;
		this.obj.ds.baseParams.camping_bitemcat_uid = this.obj.data.camping_bitemcat_uid;
		this.obj.ds.baseParams.userOnly = this.obj.data.userOnly;
		
		this.obj.data.camping_bitemcat_uid = "";
		
	
	},this);
	

	
	
	/**
	this.obj.ds.on("load", function(store){
		
		//this.view.refresh(true);
		//this.getView().refresh();
		//alert('view refresh');
		//this.expander
		
	},this);
	**/
	//});
	
	this.on('activate', function(){
			if(this.isfirst){
				this.obj.ds.load({
					params:{
							start:0,
							limit:this.pagingBar.pageSize,
							camping_boardtype_uid:this.obj.data.camping_boardtype_uid,
							camping_boardcat_uid:this.obj.data.camping_boardcat_uid,
							camping_bitemcat_uid:this.obj.data.camping_bitemcat_uid
							}
						});
			}else{
				//this.obj.ds.reload();
			}
			this.isfirst = false;
			
								},this);
	
		
	this.view.showView = this.obj.data.viewtype;
	
	this.itemStore.on("load", function(){
		
		if(this.obj.data.camping_boardcat_uid){
			this.categoryComboBox.setValue(this.obj.data.camping_boardcat_uid);
		}
		
	},this);
	
    
};

Ext.extend(Ext.hansub.board.BoardGridPanel, Ext.grid.GridPanel, {
	
	modify:function(grid, records, action, groupId){
		
		if(!Ext.getCmp('addBoardContentWindowID')){
		
			this.addBoardContentWindow = new Ext.hansub.board.AddBoardHtmlContentWindow({
						id:'addBoardContentWindowID',
						title: '게시물 등록',
						iconCls:'add',
				        width: 700,
				        resizable:false,
				        height: 690			        
			});
		}
		
		Ext.getCmp('addBoardContentWindowID').setData({
			camping_boardtype_uid : records.data.camping_boardtype_uid,
			camping_boardcat_uid : records.data.camping_boardcat_uid,
			camping_board_uid : records.data.uid,
			camping_boardcat_name: records.data.camping_boardcat_name,
			name : records.data.name,
			content : records.data.content,
			parentID : grid.getId()
								
		});
		
		Ext.getCmp('addBoardContentWindowID').show();
		
		
		
		
	},
	setData:function(obj){
		
		if(obj.data.camping_bitemcat_uid == this.obj.data.camping_bitemcat_uid){
			return;	
		}
		this.obj = obj;
		this.setTitle(this.obj.text);
		this.view.showView = this.obj.data.viewtype;
		
		this.obj.ds.load();
	
	},
	
	applyRowClass: function(record, rowIndex, p, ds) {
		
		if(this.showView == 'title'){
						
        	return 'x-grid3-row-collapsed';
			     	
        }else if(this.showView == 'summary'){
			
        	var content = Ext.util.Format.stripTags(record.data.content);
        	if(content == ""){
        		return 'x-grid3-row-collapsed';
        	}
        	p.body = '<div class=boardsummary>' + Ext.util.Format.ellipsis(content, 70) + '</div>';
            return 'x-grid3-row-expanded';
			
        }else if(this.showView == 'full'){
			
			p.body = '<div class=boardcontent>' + record.data.content + '</div>';
            return 'x-grid3-row-expanded';
			
        }else{
        	return 'x-grid3-row-collapsed';
        }
       
    },
    
	
	newWin : function(){
		
		var window = new DetailWindow();
        window.init("centerBottomTabPanelID", Ext.getCmp('ItemInfoLayoutPanelID'));
	},
	
	viewUserInfo : function(){
		
		if (Ext.getCmp("myCampingWrapper_" + this.record.data.camping_user_uid)) {
			
			Ext.getCmp('centerCenterPanel').activate("myCampingWrapper_" + this.record.data.camping_user_uid);
			
		}else {
			
			this.mycamping = new Ext.hansub.camping.MyCampingPortalPanel({
				id:'myCampingWrapper_'+this.record.data.camping_user_uid,
				camping_user_uid : this.record.data.camping_user_uid,
				title : this.record.data.camping_user_name+'님의 캠핑장 정복지도',
				camping_user_name : this.record.data.camping_user_name,
				closable:true
				
			})
			Ext.getCmp('centerCenterPanel').add(this.mycamping);
			Ext.getCmp('centerCenterPanel').activate(this.mycamping);
		}		
		
	}, 
	clickRow : function(grid, index, columIndex,e){
		
		
		this.record = this.obj.ds.getAt(index);
		
		if (columIndex == '4') {
			
			if(this.record.data.camping_user_uid == "0" || this.record.data.camping_user_uid == ""){
				this.viewUserInfoButton.setDisabled(true);
			}else{
				this.viewUserInfoButton.setDisabled(false);
			}
			
			this.viewUserInfoButton.setText("<b>"+this.record.data.camping_user_name+"</b>님 캠핑지도 홈 바로가기");
			this.popupMenu.showAt(e.getXY());
			return;
		}
		
    	
    	if(!Ext.getCmp('BoardContentWrapper_'+this.record.data.uid)){
			
			var boardContentWrapper = new Ext.hansub.board.BoardContentWrapperPanel(
									this,
									{
										title:"ss",
										id:this.record.data.uid,
										closable:true,					
										border:false						
									}
								);
						
		}
		Ext.getCmp('BoardContentWrapper_'+this.record.data.uid).setContent({
			uid : this.record.data.uid
		});
		
		
		Ext.getCmp('centerCenterPanel').add('BoardContentWrapper_'+this.record.data.uid);
		Ext.getCmp('centerCenterPanel').activate('BoardContentWrapper_'+this.record.data.uid);
		
		
		
	},
   
    selectedRow : function(sm, index, record){
    	/**
    	if(this.view.showView == 'full'){
    		if(!Ext.getCmp('commentGridPanelID')){
	    		this.commentGridPanel = new Ext.ux.hansub.board.CommentGridPanel({
					title: "댓글 목록",
					id: "commentGridPanelID",
					closable:false,
					loadMask: {msg:'댓글화면 구성 중'},
					defaults: {autoScroll:true},
					split: true,
					collapsible: true,
			        animCollapse: false,
			        border:false,
			        hideHeaders:true
				});
	    		
	    	}
	    	
	    	Ext.getCmp('commentGridPanelID').setData({
					dbtable_uid:record.get('uid'),
					dbtable:'camping_board'
				});
		
			Ext.getCmp('centerCenterPanel').add('commentGridPanelID');
			Ext.getCmp('centerCenterPanel').activate('commentGridPanelID');
    		return;
    	}
    	
		if(!Ext.getCmp('boardContentPanel_'+record.data.uid)){
			var boardContentPanel = new Ext.hansub.board.BoardContentPanel(
									this,
									{
										title:record.data.name,
										id:'boardContentPanel_'+record.data.uid,
										closable:true,
										closeAction:'false',
										height:300,
										collapsible: true,								
										border:false,
										split: true,
										data:record.data								
									}
								);
		}else{
			Ext.getCmp('boardContentPanel_'+record.data.uid).setContent(record.data);
		}
							
    	Ext.getCmp('centerCenterPanel').add('boardContentPanel_'+record.data.uid);
		Ext.getCmp('centerCenterPanel').activate('boardContentPanel_'+record.data.uid);
 	**/
	},
	
	
	addItem : function(){
		
			this.camping_boardcat_uid = this.categoryComboBox.getValue();
			
			if(!Ext.getCmp('addBoardContentPanelID')){
		
				this.addBoardContentPanel = new Ext.hansub.board.AddBoardHtmlContentPanel({
							id:'addBoardContentPanelID',
							title: '게시물 등록',
							iconCls:'add',
					        width:770,
					        resizable:false
					        //height: 620
					        				        
				});
			}
			
			Ext.getCmp('addBoardContentPanelID').setData({
					
				camping_boardtype_uid : this.obj.data.camping_boardtype_uid,
				camping_boardcat_uid : this.camping_boardcat_uid,
				parentID : this.getId()
									
			});
				
			//Ext.getCmp('addBoardContentWindowID').show();
			//Ext.getCmp('addBoardContentWindowID')
			
			Ext.getCmp('centerCenterPanel').add('addBoardContentPanelID');
			Ext.getCmp('centerCenterPanel').activate('addBoardContentPanelID');
		
		
		
		


	},
	
	deleteItem : function(grid, record, action, rowIndex, col){
		
		if(record == null){
			return;
		}
		
		
		//alert(this.text);
		this.dataStore = grid.getStore();
		this.selectRecord = record;
		
		Ext.Msg.show({
			title:'삭제 확인',
			scope:this,
			msg: 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':'deleteContent',
							'camping_board_uid':this.selectRecord.data.uid
						},
						waitMsg:'항목을 삭제하고 있습니다.',
						scope:this,
						success:function(response, options){
							
							this.dataStore.reload();				
						},
						failure:function(response, options){
							Ext.MessageBox.alert('ERROR', '항목 삭제시 오류가 발생하였습니다..');
						}
						            	
								
					});
				}
			}
		});
		
		
		
	},
	
	reload : function(){
		this.obj.ds.reload();
	},
	
	titleFormat: function(value, p, record,rowIndex, colIndex, store) {
    	
    	return String.format(
                '<div class=board_title>{0}</div>', value
                );
    },
    
    setListLayout:function(viewtype){
 	
	  	if (this.obj.data.camping_boardtype_type == 'acount') {
			if(viewtype == 'title'){
				
	    		this.viewSplitButton.setText('간략하게 보기');
	    		this.viewSplitButton.setIconClass('view_summary');
	    		this.titleButton.disable();
	    		this.summaryButton.enable();
	    		this.detailButton.enable();
					
	    	}else if(viewtype == 'summary'){
	    		
	    		this.viewSplitButton.setText('제목만 보기');
	    		this.viewSplitButton.setIconClass('view_title');
	    		this.detailButton.disable();
	    		this.titleButton.enable();
	    		this.summaryButton.enable();
			
	    		
	    	}else{
	    		
	    		if(this.view.showView == 'title'){
	    			
	    			this.viewSplitButton.setText('간략하게 보기');
	    			this.viewSplitButton.setIconClass('view_full');
	    			this.summaryButton.disable();
	    			this.titleButton.enable();
	    			this.detailButton.enable();;
	    			viewtype = "summary";
	    			
	    		}else if(this.view.showView == 'summary'){
	    			
	    			this.viewSplitButton.setText('제목만  보기');
	    			this.viewSplitButton.setIconClass('view_summary');
	    			this.titleButton.disable();
		    		this.summaryButton.enable();
		    		this.detailButton.enable();
	    			viewtype = "title";
	    		}
	 		
	    	}
			
			
			
		}
		else {
			if(viewtype == 'title'){
				
	    		this.viewSplitButton.setText('간략하게 보기');
	    		this.viewSplitButton.setIconClass('view_summary');
	    		this.titleButton.disable();
	    		this.summaryButton.enable();
	    		this.detailButton.enable();
					
	    	}else if(viewtype == 'summary'){
	    		
	    		this.viewSplitButton.setText('전체내용 보기');
	    		this.viewSplitButton.setIconClass('view_full');
	    		this.summaryButton.disable();
	    		this.titleButton.enable();
	    		this.detailButton.enable();
			
	    	}else if(viewtype == 'full'){
	    		
	    		this.viewSplitButton.setText('제목만 보기');
	    		this.viewSplitButton.setIconClass('view_title');
	    		this.detailButton.disable();
	    		this.titleButton.enable();
	    		this.summaryButton.enable();
			
	    		
	    	}else{
	    		
	    		if(this.view.showView == 'title'){
	    			
	    			this.viewSplitButton.setText('전체내용 보기');
	    			this.viewSplitButton.setIconClass('view_full');
	    			this.summaryButton.disable();
	    			this.titleButton.enable();
	    			this.detailButton.enable();;
	    			viewtype = "summary";
	    			
	    		}else if(this.view.showView == 'summary'){
	    			
	    			this.viewSplitButton.setText('제목만 보기');
	    			this.viewSplitButton.setIconClass('view_title');
	    			this.detailButton.disable();
	    			this.titleButton.enable();
	    			this.summaryButton.enable();
	    			viewtype = "full";
	    			
	    		}else{
	    			this.viewSplitButton.setText('간략하게 보기');
	    			this.viewSplitButton.setIconClass('view_summary');
	    			this.titleButton.disable();
		    		this.summaryButton.enable();
		    		this.detailButton.enable();
	    			viewtype = "title";
	    		}
	 		
	    	}
			
		}
		
	
		
    	this.view.showView = viewtype;
		this.view.refresh();
	    
		

    },
	korMoney :  function(v, params, record){
		
		var usMoney = Ext.util.Format.usMoney(v);
		if(usMoney == '$NaN.00'){
			hanMoney = '0';
			record.data.expected = 0;
		}else{
			hanMoney = usMoney.substr(1,usMoney.length-4);
		}
		return hanMoney + ' 원';
                 
	}
		

});

