
Ext.namespace("Ext.hansub.panel");


Ext.hansub.panel.InlineBlogImage = function(config){
	
	this.config = config;
	
	this.regImgButton = new Ext.Button({
  	text:'<b>나의 캠핑 사진올리기</b> - 한장의 추억을 등록해 주세요 (여기를 선택)',
  	handler:this.upload,
  	scope:this
  });

	this.regImgButton2 = new Ext.Button({
  	text:'우리집(텐트)사진올리기',
  	iconCls:'img_icon',
  	handler:this.upload,
  	scope:this
  });

	this.regImgButton3 = new Ext.Button({
  	text:'아들,딸 사진올리기',
  	iconCls:'img_icon',
  	handler:this.upload,
  	scope:this
  });

	this.regImgButton4 = new Ext.Button({
  	text:'우리집캠핑요리 사진올리기',
  	iconCls:'img_icon',
  	handler:this.upload,
  	scope:this
  });

	this.imageUploadButton = new Ext.menu.Item({
  	text:'<b>나의 캠핑 사진올리기</b>',
  	iconCls:'img_icon',
  	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.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
    });
	


	/**
	 * 버튼 메뉴
	 */
	this.popupMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        this.imageUploadButton,
				this.viewBoardButton,
        		this.viewCampingButton ,
				'-',
        		this.viewUserInfoButton,
				this.viewMemoButton,
				'-',
				this.viewReplyButton,
				'-',
				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',
			'image_flag':'true'
		},
	    
	    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: '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
		            }
		        ])
	
	 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.addButton = new Ext.Button({
		text:'등록',
		iconCls:'inlinewrite',
		handler:this.addInline,
		scope:this,
		keys: [{
        	key: Ext.EventObject.ENTER,
        	scope:this,
        	fn: this.addInline
     	}]
		
	});
	
	
	
	
	this.pagingBar = new Ext.PagingToolbar({
        pageSize: 10,
        store: this.store,
		beforePageText:"",
        displayInfo: true,
        displayMsg: '<b>{2}</b> 의견',
        autoWidth:true,
        emptyMsg: "내용이 없습니다."
      
    });

	if (!this.config.inputdisable) {
		tbar = [this.inline, this.addButton];
	}else{
		tbar = [];
	}

	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{
		this.autoHeight = true;
	}
	
	
	Ext.hansub.panel.InlineBlogImage.superclass.constructor.call(this, {
		title : '<b>사진한컷</b>',
		id:'InlineBlogImage_'+this.config.id,
		iconCls:'img_icon',
		ds: this.store,
		autoHeight:this.autoHeight,
		bbar : this.pagingBar,
		autoWidth:true,
		border:true,
		hideHeaders:true,
		split: true,
		enableTabScroll:true,
		collapsible: true,
		collapseMode: "mini",
		hideCollapseTool:true,
		defaults: {autoScroll:true},
		loadMask: {msg:'화면 구성 중'},
		//tbar:tbar,
		tbar:["<image src=images/camera_add_48.png width=24>","-",this.regImgButton,"-",this.regImgButton2,"-",this.regImgButton3,"-",this.regImgButton4],
		//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';
		    }
		},

		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_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.on('afterlayout', function(){
		
			if(this.isfirst){
				this.store.load({
					params:{
							start:0,
							limit:this.pagingBar.pageSize
							}
						});
			}
			this.isfirst = false;
			
								},this);

	this.on('rowclick',this.contextMenu, this);
	this.on('rowcontextmenu',this.contextMenu, this);
   
};

Ext.extend(Ext.hansub.panel.InlineBlogImage, Ext.grid.GridPanel, {
	
	reformat: function(value, p, record) {
		
		if(!record.data.isreply){
			return value;
		}else{
			return "<div class=reply>"+value+"</div>";
		}
    	
    },
	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();
		}
	},
	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();
		}
	},
	
	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.setDisabled(true);
		}else{
			this.viewCampingButton.setDisabled(false);
		}
		
		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.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.MyCampingWrapperPanel({
				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.CampingWrapperPanel({
  				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);
      }
		}
	},



	addInline : function(){
		
		this.store.load();
		
	
	},
	
	reload:function(){
		
		this.store.load();
		
	},
	
	setData : function(title, uid){
		this.config.camping_list_uid = uid;
		this.setTitle('<font color=red>'+title+'</font> 한줄 의견');
		this.inline.setValue('');
		this.store.load();

	},

	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:'0'
												
											},
          									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();
				
			}
		
		
	},

	
	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';
        
       
    }
		

});

