Ext.namespace("Ext.hansub.camping");

Ext.hansub.camping.CampingWrapperPanel = function(config) {
	
	this.config = config;

	
	this.reservationButton = new Ext.Button({
		text:'예약',
		iconCls:'board_modify',
		handler:this.reservation,
		scope:this
	});
	
	this.regReservationSysButton = new Ext.Button({
		text:'예약시스템 신청',
		iconCls:'board_modify',
		hidden : true,
		handler:this.regReservationSys,
		scope:this
	});

	this.regBasicButton = new Ext.Button({
		text:'캠핑장 정보 수정하기',
		iconCls:'board_modify',
		handler:this.regCamping,
		scope:this
	});
	
	
	
	this.regImgButton = new Ext.Button({
		text:this.config.name + '에서 찍은 사진올리기',
		iconCls:'img_icon',
		handler:this.upload,
		scope:this
	});

	this.regMyNextCampingjangButton = new Ext.Button({
		text: '\"' + this.config.name + '\"을 나의 Next 캠핑지로 설정',
		iconCls:'flag',
		handler:this.setNextCampingjang,
		scope:this
	});

	this.regMyNextCampingjangBottomButton = new Ext.Button({
		text: '\"' + this.config.name + '\"을 나의 Next 캠핑지로 설정',
		iconCls:'flag',
		handler:this.setNextCampingjang,
		scope:this
	});

	this.regConquerorMarkButton = new Ext.Button({
		text: '내가 정복한 곳으로 마크',
		iconCls:'flag',
		handler:this.setConquerorMark,
		scope:this
	});

	
	this.naverBlog = new Ext.hansub.naverAPI.NaverOpenAPIPanel({
				id: this.config.name+"BLOG",
				title: this.config.name + ' 블러그',
				target: 'blog',
				region:'center',
				keyword: this.config.name,
				viewtype: 'summary',
				border: false,
				start: 1,
				display: 5
			
			});
	
	this.mapPanel = new Ext.hansub.camping.CampingMapPanel({
				id: this.config.name+"MAP",
				region:'west',
				x: this.config.x,
				y: this.config.y,
				camping_list_uid:this.config.record_data.camping_list_uid,
				border: false
			
			});
	//this.inlinePanelBlog = new Ext.hansub.panel.InlineBlog();
	
	/**
     * adsense panel 정의
     */
    this.adsense = new Ext.Panel({
    	region:'center',
    	height:'200',
    	border:false,
        html: "<script type='text/javascript'> google_ad_client = 'ca-pub-4083834243023892'; google_ad_slot = '4011939061'; google_ad_width = 728; google_ad_height = 90;</script><script type='text/javascript' src='http://pagead2.googlesyndication.com/pagead/show_ads.js'></script>" 
        
        
    }); 	
    

	
	this.daumImage = new Ext.hansub.daumAPI.DaumIMGOpenAPIPanel({
			id:this.config.name+"IMAGE",
			region:'south',
	   		border:false,
	   		start:1,
	   		display:10,
			data:{
					isSearch:true,
					viewtype:'summary',
					target:'image',
					keyword:this.config.name,
			camping_list_uid:this.config.record_data.camping_list_uid
				}
			
			});
	
	this.campingImage = new Ext.hansub.camping.CampingIMGPanel({
			id:this.config.name+"CAMPINGIMAGE",
			region:'center',
	   		border:false,
			camping_list_uid:this.config.record_data.camping_list_uid
			});
			
	this.infoPanel = new Ext.hansub.camping.CampingInfoPanel({
			id:this.config.name+"INFO",
			region:'north',
   		border:false,
			height:350,
   		autoHeight:true,
			autoWidth:true,
 			camping_uid:this.config.camping_uid,
   		data:this.config.record_data
			
			});	

  if(this.config.camping_uid) this.config.record_data.camping_list_uid = this.config.camping_uid;
	
	//this.inlinePanelBlog = new Ext.hansub.panel.InlineBlog(this.config.name,this.config.record_data.camping_list_uid);
	
	this.inlinePanelBlog = new Ext.hansub.panel.InlineBlog({
		
		id:'inlineBlog_ID_CAM_'+this.config.record_data.camping_list_uid,
		title:this.config.name,
		camping_user_uid : '',
		camping_list_uid : this.config.record_data.camping_list_uid,
		region:'center',
		closable:false,
		fieldWidth : 320,
		inputdisable : false
		
	});

	this.campingUser = new Ext.hansub.camping.CampingUserGridPanel({
		id:'CampingUserGridPanel1_ID'+this.config.record_data.camping_list_uid,
		camping_list_uid : this.config.record_data.camping_list_uid,
		region:'center',
 		autoHeight:true,
		autoWidth:true,
 		border:false
	});
	
	Ext.hansub.camping.CampingWrapperPanel.superclass.constructor.call(this, {
		id:this.config.id,
		title:this.config.name,
		tbar : [" ",this.reservationButton,this.regReservationSysButton,"-",this.regBasicButton,'-',this.regImgButton,'-',this.regMyNextCampingjangButton,'-',this.regConquerorMarkButton],
		//layout:'border',
		closable:true,
    padding: 10,
    viewConfig:{
      forceFit:true
      },
      autoHeight:false,
		border:false,
		defaults: {autoScroll:true},
		items:[this.infoPanel,
		
					{
						autoScroll:false,
						border:false,
						autoWidth:true,
						height:350,
						layout:'border',
						items:[this.mapPanel,this.inlinePanelBlog ]
					},
		this.campingImage,
		this.naverBlog,
		this.campingUser,
		this.regMyNextCampingjangBottomButton,
		this.daumImage,
		this.adsense 
		]
        
	});
	
	this.on('afterlayout', this.init, this);
	this.on('activate', this.initLayout, this);
	this.on('close', this.closed, this);
	
	this.on('render',this.loginState,this);
   
};

Ext.extend(Ext.hansub.camping.CampingWrapperPanel, Ext.Panel, {
	
	regReservationSys : function(){
		
		if(IS_LOGIN){
			
			this.RegReservationSysWindow = new RegReservationSysWindow({
						id:'RegReservationSysWindowID',
						title: this.config.name+ ' 예약 시스템 신청  - 캠핑장 관리자만  신청이 가능합니다.-',
						iconCls:'add',
				        width:500,
				        resizable:true,
				        height: 170,
						data:{
							parentID : this.config.id,
							camping_list_uid : this.config.record_data.camping_list_uid,	
							camping_list_name : this.config.name
													
						}
					        				        
			});
		
			
		
				
			this.RegReservationSysWindow.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();
			
		}
		
		
	},
	
	
	loginState: function(){
		/**
		if (IS_LOGIN) {
			this.regBasicButton.setVisible(true);
			this.regImgButton.setVisible(true);
		}else{
			this.regBasicButton.setVisible(false);
			this.regImgButton.setVisible(false);
		}
		**/
	},
	
	setNextCampingjang : function() {
		if(IS_LOGIN){		
  		Ext.Ajax.request({
  			url: './src/api/Interface.php',
  			params:{
  					'class':'Camping',
      			method:'setNextCampingjang',
      			camping_list_uid:this.config.record_data.camping_list_uid
  					},
  			scope:this,
  			success:function(response, options){
  				var json = Ext.decode(response.responseText);
  				Ext.MessageBox.alert('확인', '나의 Next 캠핑지로 설정되었습니다.')
  			},
  			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();
		}
    
    
	},
	setConquerorMark : function() {
		if(IS_LOGIN){		
  		addCamingConquerorInfoWindow = new AddCampingConquerorInfoWindow({
  		  camping_name:this.config.record_data.name,
  		  camping_list_uid:this.config.record_data.camping_list_uid,
  		  grid_index:500
  		  });
  		addCamingConquerorInfoWindow.show();
    }//end if (IS_LOGIN)
		else{
				if(!Ext.getCmp('loginWindowID')){
					this.loginWin = new Ext.hansub.user.LoginWindow();
        }
        Ext.getCmp('loginWindowID').reset();
	    	Ext.getCmp('loginWindowID').show();
		}
	},
	
	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.record_data.camping_list_uid
												
											},
									scope:this,
				                    success: function(fp, o){
				                    	
										this.campingImage.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();
				
			}
		
		
	},
	regCamping : function(){
		
			if(IS_LOGIN){
		
				this.addCampingContentWindow = new Ext.hansub.camping.AddCampingContentWindow({
							id:'addCampingContentWindowID',
							title: '캠핑장 기본정보 수정',
							iconCls:'add',
					        width:800,
					        resizable:true,
					        height: 570,
							data:{
								parentID : this.config.id,
								camping_list_uid : this.config.record_data.camping_list_uid	
														
							}
						        				        
				});
			
				
			
					
				this.addCampingContentWindow.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();
				
			}
		
		
	},
	
	closed:function(){
		
		/**		
		this.tabPanel.items.each(function(item){
                        
                        this.tabPanel.remove(item);
                        
                    },this);
        **/
	},
	
	initLayout : function(){

		this.mapPanel.init();
		//this.inlinePanelBlog.checkServer();
		//Ext.getCmp('InlineBlog').setData(this.config.name,this.config.record_data.uid);
		this.campingUser.showPanel();
		
	},
	
	init : function(){
		
		
		// 예약 타입 확인
		Ext.Ajax.request({
    		
			url: './src/api/Interface.php',
			params:{
				'class':'Reservation',
				'method':'getReservationType',
				'camping_list_uid': this.config.record_data.camping_list_uid
			},
			scope:this,
			success:function(response, options){
				
				var json = Ext.decode(response.responseText);
				
				this.reservationType = json.type;
				this.reservationValue = json.value;
				
				if(this.reservationType != "reservationsystem"){
					
					this.regReservationSysButton.setVisible(true);
					
				}
				
				
			},
			failure:function(response, options){
				Ext.MessageBox.alert('ERROR', '예약정보를 로딩에 오류가 발생하였습니다.');
			}
			            	
					
		});
		
		
		//this.add(this.naverBlog); 
		//this.mapPanel.init();
		
		
		
		
		
	},
	
	reservation : function(){
		
		
		if(this.reservationType == 'tel'){
			
			Ext.MessageBox.alert(this.config.name+' 예약', '<br><p>현재 예약시스템을 제공하지 않습니다.</p><br><p><b>'+this.config.name+'</b>예약은  전화  또는 홈페이지를 이용해 주십시오.</p><br><p>#캠핑지도  예약시스템은 무료로 제공되며, 예약 시스템 신청 버튼을 통해 등록이 가능합니다.</p>');
			
		}else if(this.reservationType == 'url'){
		
			Ext.MessageBox.alert(this.config.name+' 예약', '<br><p>'+this.config.name+'은 자체  예약시스템을 제공하며, 예약 문의는 '+this.config.name+'으로 연락하십시오.</p><br><p>#캠핑지도  예약시스템은 무료로 제공되며, 예약 시스템 신청 버튼을 통해 등록이 가능합니다.</p>');
			
			var iframe = new Ext.ux.ManagedIframePanel({
				id:this.reservationValue,
				title:this.config.name+' 예약',
				cls:'scroll',
				width:100,
				height:100,
				closable:true,
				defaultSrc:this.reservationValue,
				loadMask : false,
	    		animCollapse:true
			});
			
			iframe.on('activate', function(){
				Ext.getCmp('layout').doLayout();
			},this);
			
			Ext.getCmp('centerCenterPanel').add(iframe);
			Ext.getCmp('centerCenterPanel').activate(iframe);
			
			
		}else if(this.reservationType == 'reservationsystem'){
			
			Ext.Ajax.request({
	    		
				url: './src/api/Interface.php',
				params:{
					'class':'Reservation',
					'method':'getOwnerInformation',
					'camping_list_uid': this.config.record_data.camping_list_uid
				},
				scope:this,
				success:function(response, options){
					
					this.config.reservation  = Ext.decode(response.responseText);
					
					this.reservationWrapperPanel = new ReservationWrapperPanel(this.config);
					Ext.getCmp('centerCenterPanel').add(this.reservationWrapperPanel);
					Ext.getCmp('centerCenterPanel').activate(this.reservationWrapperPanel);
					
					
					
					
				},
				failure:function(response, options){
					Ext.MessageBox.alert('ERROR', '예약정보를 로딩에 오류가 발생하였습니다.');
				}
				            	
						
			});
			
			
			
		}
		
		
		/**
		this.userReservationPanel = new UserReservationPanel(
				{	
					id:"UserReservaion_"+this.config.id,
					title:"예약자 현황",
					border:true,
					defaults: {autoScroll:true},
					split: true,
					//region:'east',
					layout:'fit',
					width:300,
					autoHeight:true
				}
			);
		
		Ext.getCmp('centerCenterPanel').add(this.userReservationPanel);
		Ext.getCmp('centerCenterPanel').activate(this.userReservationPanel);
		**/
		
		
	/**	
		 this.calendarStore = new Ext.data.JsonStore({
             storeId: 'calendarStore',
             root: 'calendars',
             idProperty: 'id',
             data: {
                 "calendars":[{
                     "id":1,
                     "title":"Home"
                 },{
                     "id":2,
                     "title":"Work"
                 },{
                     "id":3,
                     "title":"School"
                 }]
             },
             proxy: new Ext.data.MemoryProxy(),
             autoLoad: true,
             fields: [
                 {name:'CalendarId', mapping: 'id', type: 'int'},
                 {name:'Title', mapping: 'title', type: 'string'}
             ],
             sortInfo: {
                 field: 'CalendarId',
                 direction: 'ASC'
             }
         });

         // A sample event store that loads static JSON from a local file. Obviously a real
         // implementation would likely be loading remote data via an HttpProxy, but the
         // underlying store functionality is the same.  Note that if you would like to 
         // provide custom data mappings for events, see EventRecord.js.
		this.eventStore = new Ext.data.JsonStore({
		       id: 'eventStore',
		       root: 'evts',
		       //data: eventList, // defined in event-list.js
		       proxy: new Ext.data.MemoryProxy(),
		       fields: Ext.calendar.EventRecord.prototype.fields.getRange(),
		       sortInfo: {
		           field: 'StartDate',
		           direction: 'ASC'
		       }
		});
		
		
		
		this.calendarPanel = new Ext.calendar.CalendarPanel({
			title:this.config.name +' 예약',
			closable:true,
            eventStore: this.eventStore,
            calendarStore: this.calendarStore,
            monthText:"",
            border: false,
            showWeekView : false,
            showDayView : false,
            showTime : false,
            todayText : this.config.name,
            id:'app-calendar_'+this.config.uid,
   
           // activeItem: 2, // month view
            
            // CalendarPanel supports view-specific configs that are passed through to the 
            // underlying views to make configuration possible without explicitly having to 
            // create those views at this level:
            monthViewCfg: {
                showHeader: true,
                showWeekLinks: true,
                showWeekNumbers: true,
                //showTodayText : false,
                todayText:this.config.name
            },
            
            // Some optional CalendarPanel configs to experiment with:
            //showDayView: false,
            //showWeekView: false,
            //showMonthView: false,
            //showNavBar: false,
            //showTodayText: false,
            //showTime: false,
            //title: 'My Calendar', // the header of the calendar, could be a subtitle for the app
            
            // Once this component inits it will set a reference to itself as an application
            // member property for easy reference in other functions within App.
            initComponent: function() {
                //App.calendarPanel = this;
                this.constructor.prototype.initComponent.apply(this, arguments);
            },
            
            listeners: {
                'eventclick': {
                    fn: function(vw, rec, el){
                        this.showEditWindow(rec, el);
                        this.clearMsg();
                    },
                    scope: this
                },
                'eventover': function(vw, rec, el){
                    //console.log('Entered evt rec='+rec.data.Title+', view='+ vw.id +', el='+el.id);
                },
                'eventout': function(vw, rec, el){
                    //console.log('Leaving evt rec='+rec.data.Title+', view='+ vw.id +', el='+el.id);
                },
                'eventadd': {
                    fn: function(cp, rec){
                        this.showMsg('Event '+ rec.data.Title +' was added');
                    },
                    scope: this
                },
                'eventupdate': {
                    fn: function(cp, rec){
                        this.showMsg('Event '+ rec.data.Title +' was updated');
                    },
                    scope: this
                },
                'eventdelete': {
                    fn: function(cp, rec){
                        this.showMsg('Event '+ rec.data.Title +' was deleted');
                    },
                    scope: this
                },
                'eventcancel': {
                    fn: function(cp, rec){
                        // edit canceled
                    },
                    scope: this
                },
                'viewchange': {
                    fn: function(p, vw, dateInfo){
                        if(this.editWin){
                            this.editWin.hide();
                        };
                        if(dateInfo !== null){
                            // will be null when switching to the event edit form so ignore
                           // Ext.getCmp('app-nav-picker').setValue(dateInfo.activeDate);
                            this.updateTitle(dateInfo.viewStart, dateInfo.viewEnd);
                        }
                    },
                    scope: this
                },
                'dayclick': {
                    fn: function(vw, dt, ad, el){
                        this.showEditWindow({
                            StartDate: dt,
                            IsAllDay: ad
                        }, el);
                        this.clearMsg();
                    },
                    scope: this
                },
                'rangeselect': {
                    fn: function(win, dates, onComplete){
                        this.showEditWindow(dates);
                        this.editWin.on('hide', onComplete, this, {single:true});
                        this.clearMsg();
                    },
                    scope: this
                },
                'eventmove': {
                    fn: function(vw, rec){
                        rec.commit();
                        var time = rec.data.IsAllDay ? '' : ' \\a\\t g:i a';
                        this.showMsg('Event '+ rec.data.Title +' was moved to '+rec.data.StartDate.format('F jS'+time));
                    },
                    scope: this
                },
                'eventresize': {
                    fn: function(vw, rec){
                        rec.commit();
                        this.showMsg('Event '+ rec.data.Title +' was updated');
                    },
                    scope: this
                },
                'eventdelete': {
                    fn: function(win, rec){
                        this.eventStore.remove(rec);
                        this.showMsg('Event '+ rec.data.Title +' was deleted');
                    },
                    scope: this
                },
                'initdrag': {
                    fn: function(vw){
                        if(this.editWin && this.editWin.isVisible()){
                            this.editWin.hide();
                        }
                    },
                    scope: this
                }
            }
        });
		
		
		
		Ext.getCmp('centerCenterPanel').add(this.calendarPanel);
		Ext.getCmp('centerCenterPanel').activate(this.calendarPanel);
		
		
	**/	
		
	}
	/**
	updateTitle: function(startDt, endDt){
    	
    	toolbarText = this.config.name+" 예약  ( ";
    	
    	
    	if(startDt.format('d') > 20){
    		month = startDt.getMonth() + 2;
    		
    	}else{
    		month = startDt.getMonth() + 1;
    	}
    	if(month == 13){
			month = 1;
		}
    	
    	Ext.getCmp('app-calendar_'+this.config.uid+'-tb-month').setText(toolbarText+month+"월)");
    	   	
    	Ext.Ajax.request({
    		
			url: './src/api/Interface.php',
			params:{
				'class':'Reservation',
				'method':'getReservation',
				'uid': this.config.uid,
				'year': startDt.getYear(),
				'month': month
			},
			waitMsg: month+'월 예약정보를 로딩합니다.',
			scope:this,
			success:function(response, options){
				
				
				var json = Ext.decode(response.responseText);
				
				this.calendarPanel.eventStore.loadData(json);		
				
				this.calendarPanel.doLayout();
				
				
			},
			failure:function(response, options){
				Ext.MessageBox.alert('ERROR', '예약정보를 로딩에 오류가 발생하였습니다.');
			}
			            	
					
		});
    	
    	
    	/**
    	this.calendarPanel.eventStore.loadData({
    		    "evts": [{
    		        "id": 1001,
    		        "cid": 1,
    		        "title": "0/50",
    		        "start": new Date("2001-11-01"),
    		        "end": new Date("2001-11-01"),
    		        "ad": false,
    		        "notes": "Have fun"
    		    },
    		    {
    		        "id": 1002,
    		        "cid": 2,
    		        "title": "0/50",
    		        "start": new Date(2011,10,20),
    		        "end": new Date(2011,10,20),
    		        "ad": false//,
    		        //"loc": "Chuy's!",
    		        //"url": "http://chuys.com",
    		        //"notes": "Order the queso",
    		        //"rem": "15"
    		    }]
    		},false);
    	this.calendarPanel.doLayout();
    	**/
    	//this.calendarPanel.eventStore.reload();
    	/**
        
        
        if(startDt.clearTime().getTime() == endDt.clearTime().getTime()){
            p.setTitle(startDt.format('F j, Y'));
        }
        else if(startDt.getFullYear() == endDt.getFullYear()){
            if(startDt.getMonth() == endDt.getMonth()){
                p.setTitle(startDt.format('F j') + ' - ' + endDt.format('j, Y'));
            }
            else{
                p.setTitle(startDt.format('F j') + ' - ' + endDt.format('F j, Y'));
            }
        }
        else{
            p.setTitle(startDt.format('F j, Y') + ' - ' + endDt.format('F j, Y'));
        }
     
    }
	   **/
	
});

