
Ext.namespace("Ext.hansub.panel");


Ext.hansub.panel.InlineBlog = function(config){
	
	this.config = config;
	if(!this.config.pageSize){
		this.config.pageSize = 30
	}
	
	this.regImgButton = new Ext.menu.Item({
	  	text:'캠핑 사진올리기',
	  	handler:this.upload,
	  	scope:this
	  });

	this.viewBoardButton = new Ext.menu.Item({
    	text:'관련 게시물 상세 보기',
		iconCls:'community_icon',
		scope:this,
		handler:this.viewBoard
    });
	
	this.viewCampingButton = new Ext.menu.Item({
    	text:'캠핑장 상세 보기',
		tooltip:{title:'캠핑장 상세 보기', text:'캠핑장 상세정보를 화면에 표시해 줍니다.'},
		iconCls:'camping_icon',
		scope:this,
		handler:this.viewCamping
    });
	
	this.viewToolButton = new Ext.menu.Item({
    	text:'캠핑장비 상세 보기',
		tooltip:{title:'캠핑장비 상세 보기', text:'캠핑장비 상세정보를 화면에 표시해 줍니다.'},
		iconCls:'camping_icon',
		scope:this,
		handler:this.viewTool
    });
	
	this.viewUserInfoButton = new Ext.menu.Item({
    	text:'등록자 정복지 보기',
		tooltip:{title:'등록자 정복지 보기', text:'등록자의 캠핑 정복지도를  화면에 표시해 줍니다.'},
		iconCls:'user_icon',
		scope:this,
		handler:this.viewUserInfo
    });
	
	this.viewMemoButton = new Ext.menu.Item({
    	text:'쪽지 쓰기',
		iconCls:'memo_icon',
		scope:this,
		handler:this.viewMemo
    });
	
	this.viewReplyButton = new Ext.menu.Item({
    	text:'댓글 쓰기',
		iconCls:'reply_icon',
		scope:this,
		handler:this.viewReply
    });
	
	this.deleteButton = new Ext.menu.Item({
    	text:'삭제',
		iconCls:'delete',
		scope:this,
		handler:this.deleteComment
    });
	


	/**
	 * 버튼 메뉴
	 */
	if(this.config.imageable){
		this.popupMenu = new Ext.menu.Menu({
			scope:this,
	        items: [
	                this.regImgButton,
	                '-',
					this.viewReplyButton,
	        		this.viewCampingButton ,
	        		this.viewToolButton,
					'-',
	        		this.viewUserInfoButton,
					this.viewMemoButton,
					'-',
					this.viewBoardButton,
					'-',
					this.deleteButton
		        	]
	    });
	}else{
		this.popupMenu = new Ext.menu.Menu({
			scope:this,
	        items: [
					this.viewReplyButton,
	        		this.viewCampingButton ,
	        		this.viewToolButton,
					'-',
	        		this.viewUserInfoButton,
					this.viewMemoButton,
					'-',
					this.viewBoardButton,
					'-',
					this.deleteButton
		        	]
	    });
	}

	
	// data store 설정
	this.store = new Ext.data.GroupingStore({ 
		proxy : new Ext.data.HttpProxy({
	    	url : './src/api/Interface.php',
	       	method : 'POST'
	       	
	    }),
	    baseParams : {
			'class':'Camping',
			'method':'getInlineBlog'
		},
	    
	    reader: new Ext.data.JsonReader({ 
            root: 'rows', 
            totalProperty: 'count',
            id:'uid'
        }, [ 
        	
			{name: 'uid', mapping: 'uid', type: 'string'},
			{name: 'ip', mapping: 'ip', type: 'string'},
      		{name: 'content', mapping: 'content', type: 'string'},
			{name: 'camping_uid', mapping: 'camping_uid', type: 'string'},
			{name: 'camping_tool_uid', mapping: 'camping_tool_uid', type: 'string'},
			{name: 'product', mapping: 'product', type: 'string'},
			{name: 'board_uid', mapping: 'board_uid', type: 'string'},
			{name: 'name', mapping: 'name', type: 'string'},
			{name: 'username', mapping: 'username', type: 'string'},
			{name: 'camping_list_uid', mapping: 'camping_list_uid', type: 'string'},
			{name: 'x', mapping: 'x', type: 'string'},
			{name: 'y', mapping: 'y', type: 'string'},
			{name: 'realusername', mapping: 'realusername', type: 'string'},
			{name: 'camping_user_uid', mapping: 'camping_user_uid', type: 'string'},
			{name: 'regdate', mapping: 'regdate', type: 'string'},
			{name: 'total_count', mapping: 'total_count', type: 'string'},
			{name: 'isreply', mapping: 'isreply', type: 'auto'}
			//total_count//isreply
        ])//,

        //sortInfo: {field: 'regdate', direction: 'desc'}
    });
	

  
	this.cm = new Ext.grid.ColumnModel([
			
		            {
		            	header: "한줄평",
		            	//width: 720,
		            	autowidth:true,
		            	sortable: false,
		            	id: 'x-grid3-cell-inner2',
		            	dataIndex: 'content',
		            	menuDisabled:true,
						renderer:this.reformat
		            }/*,
					
					
					{
		            	header: "등록일",
		            	width: 250,
		            	minColumnWidth: 250,
		            	sortable: true,
		            	dataIndex: 'regdate',
		            	menuDisabled:true
		            },this.rowAction*/
		            
		            
		        ])
	/*
	this.addButton = new Ext.Toolbar.Button({
    	text:text,
		tooltip:{title:text, text:'게시글을 작성합니다.'},
		iconCls:'write',
		scope:this,
		handler:this.addItem
    });
	this.text = new Ext.Toolbar.TextItem({
    	
    });
	*/
	/**
	this.searchField = new Ext.ux.grid.Search({
					        position:'top',
				           // iconCls:'board_search',
				            searchTipText:'의견을 등록하세요 ',
				            //dateFormat:'m/d/Y',
				            minLength:2,
				            //disableIndexes:['content'],
				            width:200,
							showSelectAll:false,
				            searchText:'의견',
				            selectAllText:'전체',
				            paramNames: {
						         fields:'fields'
						        ,query:'content'
						    }
				        })
**/
   	
	
	 this.inline = new Ext.form.TextField({
        
        name:'content',
        emptyText:'한줄 수다 입력하는 곳 ~',
        selectOnFocus:true,
        width:this.config.fieldWidth,
		keys: [{
        	key: Ext.EventObject.ENTER,
        	scope:this,
        	fn: this.addInline
     	}]
    });
    

	
	
	
	
	this.pagingBar = new Ext.PagingToolbar({
        pageSize: this.config.pageSize,
        store: this.store,
		beforePageText:"",
        displayInfo: true,
        displayMsg: '<b>{2}</b> 의견',
        autoWidth:true,
        emptyMsg: "내용이 없습니다."
      
    });

	if (!this.config.inputdisable) {
		
		if(this.config.imageable){
			this.addButton = new Ext.Button({
				text:"글등록",
				iconCls:'inlinewrite',
				handler:this.addInline,
				scope:this,
				keys: [{
		        	key: Ext.EventObject.ENTER,
		        	scope:this,
		        	fn: this.addInline
		     	}]
				
			});
			this.addImgButton = new Ext.Button({
				text:"사진등록",
				iconCls:'img_icon',
				handler:this.upload,
				scope:this
				
			});
			tbar = [this.inline," ", this.addButton, this.addImgButton];
		}else{
			this.addButton = new Ext.Button({
				text:"글등록",
				iconCls:'inlinewrite',
				handler:this.addInline,
				scope:this,
				keys: [{
		        	key: Ext.EventObject.ENTER,
		        	scope:this,
		        	fn: this.addInline
		     	}]
				
			});
			tbar = [this.inline," ", this.addButton];
		}
	  
		
		
		
	}else{
		tbar = ["<image src=images/camera_add_48.png width=24>","-",this.regImgButton];
	}

	if(this.config.private){
	    this.inline.emptyText = this.config.private_name + "님께 글남기기.";
	}
	
	if(this.config.isBoard == "yes"){
		this.pagingBar = "";
		this.autoHeight = true;
		this.inline.emptyText = "게시 내용에 한줄 댓글을 달아 주세요 ~~"
		tbar = ['->',this.inline, this.addButton];
	}else{
		if(this.config.height){
			this.autoHeight = false;
		}else{
			this.autoHeight = true;
		}
	}
	
	if(this.config.title){
		if(this.config.camping_list_uid){
		  //this.config.tabtitle = "<font face=\"맑은 고딕\"><span style=font-size:11px;>(캠핑지도) "+this.config.title+' 한줄 후기</style></font>';
		}else if(this.config.private){
		  //this.config.tabtitle = "<font face=\"맑은 고딕\"><span style=font-size:11px;>캠핑지도 "+this.config.title+' 이야기</style></font>';
		}else{
		  //this.config.tabtitle = "<font face=\"맑은 고딕\"><span style=font-size:11px;>캠핑지도 최신 이야기</style></font>";
		  this.inline.emptyText = "한줄댓글 끄적끄적.";//NAME + "님, 출석 한 줄 부탁해요~~^^*";
		}
		this.config.tabtitle = this.config.title;
	}else{
		this.config.tabtitle  = "";
	}
	
	if(!this.config.isowner && this.config.camping_user_uid && !this.config.private){
		tbar = [];
	}
	
	Ext.hansub.panel.InlineBlog.superclass.constructor.call(this, {
		title : this.config.tabtitle,
		id:'InlineBlog_'+this.config.id,
		//region:this.config.region,
		closable:this.config.closable,
		ds: this.store,
		autoHeight:this.autoHeight,
		iconCls:this.config.iconCls,
		//plugins : [this.rowAction],
		//height:300,
		bbar : this.pagingBar,
		autoWidth:true,
		border:this.config.border,
		hideHeaders:true,
		split: true,
        enableTabScroll:true,
        collapsible: true,
		collapseMode: "mini",
		hideCollapseTool:true,
		defaults: {autoScroll:true},
		loadMask: {msg:'화면 구성 중'},
		tbar:tbar,
		//plugins : [this.searchField],

		viewConfig: {
		    forceFit: true,
		    showPreview: true, // custom property
		    enableRowBody: true, // required to create a second, full-width row to show expanded Record data
		    getRowClass: function(record, rowIndex, rp, ds){ // rp = rowParams
		        if(this.showPreview){
		            rp.body = '<p>'+record.data.content+'</p>';
		            return 'x-grid3-row-expanded';
		        }
		        return 'x-grid3-row-collapsed';
		    }
		},

/*
		viewConfig : {
            					forceFit:false
								},
*/
		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 ? "한줄의견" : "한줄의견"]})'
					}),
		cm: this.cm,
        sm: new Ext.grid.RowSelectionModel({
		            singleSelect:true
		        })
       
		
		
	});
							      

	
	
	
	this.store.on("beforeload", function(store, options){
		
		this.store.baseParams.limit = this.pagingBar.pageSize,
		this.store.baseParams.content = this.inline.getValue();
		this.store.baseParams.uid = this.config.camping_list_uid;
		
		this.store.baseParams.camping_tool_uid = this.config.camping_tool_uid;
		
		
		this.store.baseParams.camping_user_uid = this.config.camping_user_uid;
		this.store.baseParams.board_uid = this.config.board_uid;
		this.store.baseParams.private_uid = this.config.private_uid;
		
	},this);
	
	this.isfirst = true;
	this.store.on('load', function(store,record, options){
		
		
		this.inline.setValue('');
		
		
		
	}, this);
	
	this.store.load({
			params:{
					start:0,
					limit:this.pagingBar.pageSize
					}
				});

	this.on('rowclick',this.contextMenu, this);
	this.on('rowcontextmenu',this.contextMenu, this);
	
	this.on('render',this.repeater, this);
    
};

Ext.extend(Ext.hansub.panel.InlineBlog, Ext.grid.GridPanel, {
	
	reformat: function(value, p, record) {
		
		if(!record.data.isreply){
			return value;
		}else{
			return "<div class=reply>"+value+"</div>";
		}
    	
    },
	viewReply:function(){
		
		
		
		if(Ext.getCmp('AddReplyWindowID')){
			Ext.getCmp('AddReplyWindowID').reset();
			Ext.getCmp('AddReplyWindowID').init(
			{
				uid:this.record.data.uid
				
			},this);
			Ext.getCmp('AddReplyWindowID').show();
		}else{
			commentWindow = new Ext.ux.hansub.window.AddReplyWindow(
			{
				uid:this.record.data.uid
			
			},this);
			commentWindow.show();
		}
	},
	
	viewMemo:function(){
		
		if(Ext.getCmp('AddMemoWindowID')){
			Ext.getCmp('AddMemoWindowID').reset();
			Ext.getCmp('AddMemoWindowID').init(
			{
				camping_user_uid:this.record.data.camping_user_uid
				
			},this);
			Ext.getCmp('AddMemoWindowID').show();
		}else{
			memoWindow = new Ext.ux.hansub.window.AddMemoWindow(
			{
				camping_user_uid:this.record.data.camping_user_uid
			
			},this);
			memoWindow.show();
		}
	},
	
	repeater:function(){
		if(this.config.autorefrash) {
			setInterval(this.checkServer.createDelegate(this), 10000);
		} 
	},
	
	
	checkServer :function(){
		//total_count
				var total_count = '0';
				if(this.store.getTotalCount() > 0){
					
					total_count = this.store.getAt(0).data.total_count;
					//alert(total_count);
					
				}
				Ext.Ajax.request({
						url: './src/api/Interface.php',
						params:{
							'class':'Camping',
							'method':'checkInlineblog',
							total:total_count 
							
						},
						scope:this,
						success:function(response, options){
							var json = Ext.decode(response.responseText);
				
							if(json.isReload && this.inline.getValue() == ""){
								this.store.load();
								//Ext.getCmp('leftCenterPanel').setActiveTab(Ext.getCmp('inlineBlog_ID'));

							}
											
						},
						failure:function(response, options){
						
					}
						            	
								
				});
					
		//setInterval(this.store.load.createDelegate(), 5000); 
	},
	
	
	
	deleteComment : function(){
		
		Ext.Msg.show({
			width:300,
			title:'삭제 확인',
			scope:this,
			msg: '삭제 하시겠습니까 ?',
			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':'Camping',
							'method':'deleteInlineblog',
							'camping_inlineblog_uid':this.record.data.uid
						},
						waitMsg:'항목을 삭제하고 있습니다.',
						scope:this,
						success:function(response, options){
							
							this.store.load({
											params:{
													start:0,
													limit:this.pagingBar.pageSize
													}
												});				
						},
						failure:function(response, options){
							Ext.MessageBox.alert('ERROR', '항목 삭제시 오류가 발생하였습니다..');
						}
						            	
								
					});
				}
			}
		});
	},
	/**
	 * 우측 버튼 팝업 메뉴
	 */
    contextMenu : function(grid, index, e){
		
		this.record = this.store.getAt(index);
		
		if(this.record.data.camping_uid == "0" || this.record.data.camping_uid == ""){
			this.viewCampingButton.setVisible(false);
		}else{
			this.viewCampingButton.setVisible(true);
		}
		
		if(this.record.data.camping_tool_uid == "0" || this.record.data.camping_tool_uid == ""){
			this.viewToolButton.setVisible(false);
		}else{
			this.viewToolButton.setVisible(true);
		}

		
		if(this.record.data.board_uid == "0" || this.record.data.board_uid == ""){
			this.viewBoardButton.setDisabled(true);
		}else{
			this.viewBoardButton.setDisabled(false);
		}
		
		
		//this.viewBoardButton
		
		
		if(this.record.data.camping_user_uid == "0" || this.record.data.camping_user_uid == ""){
			this.viewUserInfoButton.setDisabled(true);
			this.viewMemoButton.setDisabled(true);
		}else{
			this.viewUserInfoButton.setDisabled(false);
			this.viewMemoButton.setDisabled(false);
		}
		
		if(this.record.data.camping_user_uid == UID){
			this.deleteButton.setDisabled(false);
		}else{
			this.deleteButton.setDisabled(true);
		}
		
		
		
		this.viewCampingButton.setText("<b>"+this.record.data.name+"</b> 바로가기");
		this.viewToolButton.setText("<b>"+this.record.data.name+"</b> 바로가기");
		this.viewUserInfoButton.setText("<b>"+this.record.data.realusername+"님 캠핑 홈</b> 바로가기");
		this.viewMemoButton.setText("<b>"+this.record.data.realusername+"</b>님께 쪽지 쓰기");
		//alert(e.getXY());
		this.popupMenu.showAt(e.getXY());
      	//alert(e.getXY());
    },
	
	viewBoard : function(){
		
		if(!Ext.getCmp('BoardContentWrapper_'+this.record.data.board_uid)){
			
			var boardContentWrapper = new Ext.hansub.board.BoardContentWrapperPanel(
									this,
									{
										title:"내용",
										id:this.record.data.board_uid,
										closable:true,					
										border:false						
									}
								);
						
		}
		Ext.getCmp('BoardContentWrapper_'+this.record.data.board_uid).setContent({
			uid : this.record.data.board_uid
		});
		
		
		Ext.getCmp('centerCenterPanel').add('BoardContentWrapper_'+this.record.data.board_uid);
		Ext.getCmp('centerCenterPanel').activate('BoardContentWrapper_'+this.record.data.board_uid);
		
	},
	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.realusername+'님의 캠핑장 정복지도',
				camping_user_name : this.record.data.realusername,
				closable:true
				
			})
			Ext.getCmp('centerCenterPanel').add(this.mycamping);
			Ext.getCmp('centerCenterPanel').activate(this.mycamping);
		}		
		
		
				
		
		
		
		
		
		
	},
	
	viewCamping : function(){
		
		if (Ext.getCmp("CampingWrapperPanel_"+this.record.data.camping_uid)) {
		
			Ext.getCmp('centerCenterPanel').activate("CampingWrapperPanel_"+this.record.data.camping_uid);
		}
		else {
		  if(this.record.data.name != "전체"){
  			this.campingWrapperPanel = new Ext.hansub.camping.CampingDetailPortalPanel({
  				id:"CampingWrapperPanel_"+this.record.data.camping_uid,
  				x:this.record.data.x,
  				y:this.record.data.y,
  				name: this.record.data.name,
  				'camping_uid':this.record.data.camping_uid,
  				record_data : this.record.data
  			});
  			Ext.getCmp('centerCenterPanel').add(this.campingWrapperPanel);
  			Ext.getCmp('centerCenterPanel').activate(this.campingWrapperPanel);
      }
		}
	},
	
	viewTool : function(){
		
		if (Ext.getCmp("ToolDetailPortalPanel_"+this.record.data.camping_tool_uid)) {
			
			Ext.getCmp('centerCenterPanel').activate("ToolDetailPortalPanel_"+this.record.data.camping_tool_uid);
			
		}else {
			
			this.toolDetailPortalPanel = new Ext.hansub.camping.ToolDetailPortalPanel({
												id:"ToolDetailPortalPanel_"+this.record.data.camping_tool_uid,
												name: this.record.data.name,
												record_data : this.record.data
											});
			
			Ext.getCmp('centerCenterPanel').add(this.toolDetailPortalPanel);
			Ext.getCmp('centerCenterPanel').activate(this.toolDetailPortalPanel);
			
		
		}
	},

	upload : function(){
		
		if(IS_LOGIN){		
			
			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: '100%',
			            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':'Camping',
												method:'uploadFile',
												camping_list_uid:this.config.camping_list_uid,
												camping_tool_uid:this.config.camping_tool_uid
												
												
											},
          									scope:this,
				                    success: function(fp, o){
        										this.store.load();
    								        this.uploadWindow.close();
				                    },
				                    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:520,
				model:true,
				items:fp
				
			});
			
			this.uploadWindow.show();
		
		}else{
				if(!Ext.getCmp('loginWindowID')){
					this.loginWin = new Ext.hansub.user.LoginWindow();
				    //this.loginWin.on('login', this.loginState, this);
		        }
		        Ext.getCmp('loginWindowID').reset();
		    	Ext.getCmp('loginWindowID').show();
				
			}
		
		
	},


	addInline : function(){
		
		this.store.load();
		
	
	},
	
	reload:function(){
		
		this.store.load();
		
	},
	
	setData : function(title, uid){
		this.config.camping_list_uid = uid;
		if(this.config.camping_user_uid){
			this.setTitle('캠핑이야기 (<font color=red>'+title+'</font>)');
		}else{
			this.setTitle('<font color=red>'+title+'</font> 한줄 의견');
		}
		this.inline.setValue('');
		this.store.load();

	},
	
	applyRowClass: function(record, rowIndex, p, ds) {
			if (!record.data.isreply) {
				p.body = '<p class=inline><div class=inline_content STYLE=\"white-space:normal\">' + record.data.username + '</div></p>';
			}else{
				p.body = '<div class=reply_name>'+ record.data.username + '</div>';
			}
            return 'x-grid3-row-expanded';
        
       
    }
		

});

