
Ext.namespace("Ext.hansub.camping");

Ext.hansub.camping.CampingUserGridPanel = function(config) {
	this.isfirst = true;
	this.config = config;
	this.pageSize = 100;
	
	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.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.viewNextCampingButton = new Ext.menu.Item({
    	text:'Next 캠핑장 설정',
		//iconCls:'memo_icon',
		scope:this,
		handler:this.setNextCampingjang
    });
	//setNextCampingjang
	/**
	 * 버튼 메뉴
	 */
	this.popupMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.viewCampingButton ,
				this.viewNextCampingButton,
				'-',
        		this.viewUserInfoButton,
				this.viewMemoButton
	        	]
    });
    this.config.ds = new Ext.data.GroupingStore({ 
		proxy : new Ext.data.HttpProxy({
	    	url : './src/api/Interface.php',
	       	method : 'POST'
	       	
	    }),
	    baseParams:{
				'class':'Camping',
				method:'getCampingUser',
				'camping_list_uid':this.config.camping_list_uid
			},
	    reader: new Ext.data.JsonReader({ 
            root: 'rows', 
            totalProperty: 'count',
            id:'uid'
	        }, [ 
	        	{name: 'uid', mapping:'uid', type: 'string'},
	        	{name: 'name', mapping: 'name', type: 'string'},	        
				{name: 'userimage', mapping: 'userimage', type: 'auto'},
				{name: 'description', mapping: 'description', type: 'auto'},
				{name: 'camping_list_uid', mapping: 'camping_list_uid', type: 'string'},
				{name: 'x', mapping: 'x', type: 'string'},
				{name: 'y', mapping: 'y', type: 'string'},
				{name: 'hobby', mapping: 'hobby', type: 'auto'},
				{name: 'nextcampingname', mapping: 'nextcampingname', type: 'auto'},
				{name: 'nextcampingnamecolor', mapping: 'nextcampingnamecolor', type: 'auto'},
				{name: 'lastlogindate', mapping: 'lastlogindate', type: 'auto'},
				{name: 'loginstatus', mapping: 'loginstatus', type: 'auto'},
	        	{name: 'nextcampinguid', mapping: 'nextcampinguid', type: 'string'},
	           	{name: 'conqueror_rate', mapping: 'conqueror_rate', type: 'string'},
				{name: 'conquercontents', mapping: 'conquercontents', type: 'string'}
	        ]),
       	groupField: 'nextcampingnamecolor',
       	remoteSort:true,
       	remoteGroup:true,
       	groupOnSort:true,
        sortInfo: {field: 'nextcampingnamecolor', direction: 'DESC'}
    });
	//$result = $result."{uid:$data[uid],name:'$data[name]',userimage:'$data[userimage]',description:'$data[description]',hobby:'$data[hobby]', next_camping_name:'$camping_list_name', next_camping_uid:'$camping_list_uid',conqueror_rate:'$conqueror_rate'}";
    // $result = $result."{uid:'$i', camping_user_uid:'$data[uid]' , camping_user_name:'$data[name]', conquercount:'$data[conquercount]', camping_list_uid:'$camping_list_uid', camping_list_name:'$camping_list_name'}";
	//$result = $result."{uid:'$i', camping_user_uid:'$data[uid]' , camping_user_name:'$data[name]', conquercount:'$data[conquercount]', totalcount:'$totalcount', conqueror_rate:'$conqueror_rate', camping_list_uid:'$camping_list_uid', camping_list_name:'$camping_list_name'}";			
    this.config.cm = new Ext.grid.ColumnModel([
			{header: "사진", hidden:false, width: 15,	sortable: false,dataIndex: 'userimage',renderer:this.imgFormat},
    		{header: "NEXT 캠핑지", hidden:false, width: 45,	sortable: false,dataIndex: 'nextcampingnamecolor'},
			{header: "로그인", hidden:false, width: 15,	sortable: true,dataIndex: 'loginstatus'},
			{header: "아이디", hidden:false, width: 30,	sortable: false,dataIndex: 'name'},
			{header: "최근접속일", hidden:false, width: 45,	sortable: false,dataIndex: 'lastlogindate'},
			{header: "나의", width: 30,	sortable: false,dataIndex: 'conquercontents'},
			{header: "Comment", width: 90,	sortable: false,dataIndex: 'description'}
	]);
        //
    this.config.sm =  new Ext.grid.RowSelectionModel({
														singleSelect:true
		        									});
	this.pagingBar = new Ext.PagingToolbar({
        pageSize: this.pageSize,
        store: this.config.ds,
        displayInfo: true,
        displayMsg: '{0}-{1} of {2}',
        autoWidth:true,
        emptyMsg: "내용이 없습니다.",
        plugins:new Ext.ux.PageSizePlugin()
      
    });	     
	
	if(!this.config.camping_list_uid){
	  	this.config.bbar = this.pagingBar;
	  	this.config.tbar = ["나와 Next캠핑장이 같은분들은?? 캠핑이 두배로 즐거워집니다.~","-","Next캠핑장은 캠핑장화면에서 설정가능합니다."];
	  	this.config.plugins = [this.searchField];
	}else{
	  //this.config.headerAsText = false;
	    this.config.hideHeaders = true;
	    this.config.unstyled = true;
	}
	   		
	this.config.viewConfig = {
            					forceFit:true
								};
	
	this.config.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 ? "분이 Next 캠핑장으로 설정하셨습니다." : "분이 Next 캠핑장으로 설정했습니다."]}'
					})
	

	//this.config.closable = false;
					
	Ext.hansub.camping.CampingUserGridPanel.superclass.constructor.call(this, this.config);
	
	//this.on('render',function(){Ext.getCmp('layout').doLayout();},this);
	
	//this.boardGridSM = this.getSelectionModel();
	//this.boardGridSM.on('rowselect', this.selectedRow, this);

				
	this.view.showView = "full";
	
	this.config.ds.on('load',function(){
	
		//this.addButton 
		/**
		record = this.getStore().getAt(0);
		if(record.get('uid') == "0"){
			this.addButton.setDisabled(true);
		}else{
			this.addButton.setDisabled(false);
		}
		**/
		
		
	},this);
	
	
	if(!this.config.camping_list_uid){
  	this.on('rowclick',this.contextMenu, this);
	}else{
  	this.on('rowclick',this.viewUserInfoDirect, this);
	}
	
	
	//this.on('rowcontextmenu',this.contextMenu, this);
	this.on('activate', function(){
		
			if(this.isfirst){
				this.config.ds.load({
					params:{
							start:0,
							limit:this.pagingBar.pageSize
							}
						});
			}else{
				this.config.ds.reload();
			}
			this.isfirst = false;
			
								},this);
    
};

Ext.extend(Ext.hansub.camping.CampingUserGridPanel, Ext.grid.GridPanel, {
	
	imgFormat: function(value, p, record) {
		if(!value){
			
			return String.format('<img src=campingicons/PNG/16x16/search_user.png>',value);
		}
    	return String.format('<img src=./images/upload/thumb/user/50/{0}>',value);
    },
	
	viewMemo:function(){
		
		if(Ext.getCmp('AddMemoWindowID')){
			Ext.getCmp('AddMemoWindowID').reset();
			Ext.getCmp('AddMemoWindowID').init(
			{
				camping_user_uid:this.record.data.uid
				
			},this);
			Ext.getCmp('AddMemoWindowID').show();
		}else{
			memoWindow = new Ext.ux.hansub.window.AddMemoWindow(
			{
				camping_user_uid:this.record.data.uid
			
			},this);
			memoWindow.show();
		}
	},
	
	/**
	 * 우측 버튼 팝업 메뉴
	 */
    contextMenu : function(grid, index, e){
		
		this.record = this.store.getAt(index);
		
		if(this.record.data.nextcampinguid == "0" || this.record.data.nextcampinguid == ""){
			this.viewCampingButton.setDisabled(true);
		}else{
			this.viewCampingButton.setDisabled(false);
		}
		
		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);
		}
		
		
		
		
		this.viewCampingButton.setText("<b>"+this.record.data.nextcampingname+"</b> 바로가기");
		this.viewUserInfoButton.setText("<b>"+this.record.data.name+"</b>님 캠핑지도 홈 바로가기");
		this.viewMemoButton.setText("<b>"+this.record.data.name+"</b>님께 쪽지 쓰기");
		this.viewNextCampingButton.setText("<b>"+this.record.data.nextcampingname+"</b> Next 캠핑장 설정");
		
		
		//alert(e.getXY());
		this.popupMenu.showAt(e.getXY());
      	//alert(e.getXY());
    },
	
	
	setNextCampingjang : function() {
		if(IS_LOGIN){		
	  		Ext.Ajax.request({
	  			url: './src/api/Interface.php',
	  			params:{
	  					'class':'Camping',
	      			method:'setNextCampingjang',
	      			camping_list_uid:this.record.data.nextcampinguid
	  					},
	  			scope:this,
	  			success:function(response, options){
	  				var json = Ext.decode(response.responseText);
	  				Ext.MessageBox.alert('확인', '나의 Next 캠핑지로 설정되었습니다.')
					this.config.ds.reload();
	  			},
	  			failure:function(response, options){
	  				Ext.MessageBox.alert('오류', '서버에 응답이 없습니다. 잠시 후 다시 접근해 주세요.')
	  			}
	  		});	
	    }//end if (IS_LOGIN)
			else{
					if(!Ext.getCmp('loginWindowID')){
						this.loginWin = new Ext.hansub.user.LoginWindow();
	        }
	        Ext.getCmp('loginWindowID').reset();
		    	Ext.getCmp('loginWindowID').show();
			}
    
    
	},
	
	viewUserInfo : function(){
		if (Ext.getCmp("myCampingWrapper_" + this.record.data.uid)) {
			
			Ext.getCmp('centerCenterPanel').activate("myCampingWrapper_" + this.record.data.uid);
			
		}else {
			
			this.mycamping = new Ext.hansub.camping.MyCampingPortalPanel({
				id:'myCampingWrapper_'+this.record.data.uid,
				camping_user_uid : this.record.data.uid,
				title : this.record.data.name+'님의 캠핑장 정복지도',
				camping_user_name : this.record.data.name,
				closable:true
				
			})
			Ext.getCmp('centerCenterPanel').add(this.mycamping);
			Ext.getCmp('centerCenterPanel').activate(this.mycamping);
		}		
		
	},
	viewUserInfoDirect : function(grid, index, e){
		this.record = this.store.getAt(index);
		
		if (Ext.getCmp("myCampingWrapper_" + this.record.data.uid)) {
			
			Ext.getCmp('centerCenterPanel').activate("myCampingWrapper_" + this.record.data.uid);
			
		}else {
			
			this.mycamping = new Ext.hansub.camping.MyCampingPortalPanel({
				id:'myCampingWrapper_'+this.record.data.uid,
				camping_user_uid : this.record.data.uid,
				title : this.record.data.name+'님의 캠핑장 정복지도',
				camping_user_name : this.record.data.name,
				closable:true
				
			})
			Ext.getCmp('centerCenterPanel').add(this.mycamping);
			Ext.getCmp('centerCenterPanel').activate(this.mycamping);
		}
		

		
		
		
		
	},
	
	viewCamping : function(){
		
		
		if (Ext.getCmp("CampingWrapperPanel_"+this.record.data.nextcampinguid)) {
		
			Ext.getCmp('centerCenterPanel').activate("CampingWrapperPanel_"+this.record.data.nextcampinguid);
		}
		else {
		 // if(this.record.data.nextcampinguid){
  			this.campingWrapperPanel = new Ext.hansub.camping.CampingDetailPortalPanel({
  				id:"CampingWrapperPanel_"+this.record.data.nextcampinguid,
  				
  				name: this.record.data.nextcampingname,
  				'camping_uid':this.record.data.nextcampinguid,
  				record_data : this.record.data
  			});
  			Ext.getCmp('centerCenterPanel').add(this.campingWrapperPanel);
  			Ext.getCmp('centerCenterPanel').activate(this.campingWrapperPanel);
     // }
		}
		
		
		
		
		
		
		
		
		
		
	},
	
	getEmotion : function(value,p,record){
		return "<img src='./images/emotion/"+record.data.emotion+".gif'>";
	},
	
	setData:function(obj){
		
		if(this.obj){
			
			if( obj.dbtable_uid != undefined && this.obj.dbtable_uid == obj.dbtable_uid){
								
				return;				
			}
			if( obj.s_bitemcat_uid != undefined  && this.obj.s_bitemcat_uid == obj.s_bitemcat_uid){	
						
				return;				
			}
		}
		
		this.obj = obj;
		if (this.obj.title) {
			this.setTitle(this.obj.title);
		}
		
		this.config.ds.load({
			params:{
					dbtable_uid:this.obj.dbtable_uid,
					s_bitemcat_uid:this.obj.s_bitemcat_uid,
					dbtable:this.obj.dbtable
					}
				});
				
	},
	
	applyRowClass: function(record, rowIndex, p, ds) {

		
        var description = Ext.util.Format.stripTags(record.data.description);
        //if(description)
        //p.body = '<div class=boardsummary><b>본인 소개</b> : ' + Ext.util.Format.ellipsis(description, 70) + '</div>';
        return 'x-grid3-row-expanded';
		
        
       
    },
    
	/**
	newWin : function(){
		
		var window = new DetailWindow();
        window.init("centerBottomTabPanelID", Ext.getCmp('ItemInfoLayoutPanelID'));
	},
    **/
    /**
    selectedRow : function(sm, index, record){
    	
    	this.selecteduid = record.data.uid;
  	
	},
	**/
	
	addItem : function(){
		if(Ext.getCmp('AddBoardContentWindowID')){
			
			
			
			Ext.getCmp('AddBoardContentWindowID').setData({
				
				s_boardtype_uid : this.obj.data.s_boardtype_uid,
				parentID : this.obj.text
				
				
			});
			
			Ext.getCmp('AddBoardContentWindowID').show();
			
		}else{
			
			addBoardContentWindow = new AddBoardContentWindow({
				
				s_boardtype_uid : this.obj.data.s_boardtype_uid,
				parentID : this.obj.text
				
				
			});
			addBoardContentWindow.show()
			
		}
		
	},
	
	deleteItem : function(grid, records, action, groupId){
		
		
		Ext.Msg.show({
			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':'Board',
							'method':'deleteComment',
							's_comment_uid':records.data.uid
						},
						waitMsg:'항목을 삭제하고 있습니다.',
						scope:this,
						success:function(response, options){
							grid.getStore().remove(records);
							
						},
						failure:function(response, options){
							Ext.MessageBox.alert('ERROR', '항목 삭제시 오류가 발생하였습니다..');
						}
						            	
								
					});
				}
			}
		});

		
		
		
		
	},
	
	addComment:function(){
		if(Ext.getCmp('AddCommentWindowID')){
			Ext.getCmp('AddCommentWindowID').reset();
			Ext.getCmp('AddCommentWindowID').init(
			{
				dbtable_uid:this.obj.dbtable_uid,
				s_bitemcat_uid:this.obj.s_bitemcat_uid,
				dbtable:this.obj.dbtable
			
			},this);
			Ext.getCmp('AddCommentWindowID').show();
		}else{
			commentWindow = new Ext.ux.hansub.window.AddCommentWindow(
			{
				dbtable_uid:this.obj.dbtable_uid,
				s_bitemcat_uid:this.obj.s_bitemcat_uid,
				dbtable:this.obj.dbtable
			
			},this);
			commentWindow.show();
		}
		
	},
	
	showPanel : function(){
			if(this.isfirst){
				this.config.ds.load({
					params:{
							start:0,
							limit:this.pagingBar.pageSize
							}
						});
			}else{
				this.config.ds.reload();
			}
			this.isfirst = false;
			
	},
	reload : function(){
		this.config.ds.reload();
	}
		

});

