Ext.namespace("Ext.hansub.naverAPI");

Ext.hansub.naverAPI.NaverOpenAPIPanel = function(config) { 
	
	this.config = config;
	
	
	this.detailButton = new Ext.menu.Item({
		text:'자세하게 보기',
		iconCls:'exist_win_icon',
		handler:this.linkLoad,
		scope:this
	});
	
	this.newDetailButton = new Ext.menu.Item({
		text:'새창으로 보기',
		iconCls:'new_win_icon',
		handler:this.newWindow,
		scope:this
	});
	
	this.titleLayoutButton = new Ext.menu.Item({
		id:'titleLayoutButtonID',
		text:'제목만 보기',
		iconCls:'view_title',
		tooltip:{title:'제목만 보기', text:'검색결과의 제목만 표시 합니다..'},
		handler:this.setListLayout.createDelegate(this, ['title']),
		scope:this
	});
	
	this.summaryLayoutButton = new Ext.menu.Item({
		id:'summaryLayoutButtonID',
		text:'간략하게 보기',
		iconCls:'view_summary',
		tooltip:{title:'간략하게 보기', text:'검색결과의 제목과 요약정보를 표시합니다.'},
		handler:this.setListLayout.createDelegate(this, ['summary']),
		scope:this
	});
	
	this.layoutMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.titleLayoutButton,
        		this.summaryLayoutButton	
	        	]
    });
    
    this.layoutItemButton = new Ext.Toolbar.SplitButton({
		iconCls:'login_icon',
		text:'제목만 보기',
		iconCls:'view_title',
		menu:this.layoutMenu,
		handler:this.setListLayout.createDelegate(this, ['swiching'])
    })

	this.searchTextField = new Ext.form.TwinTriggerField({
				width: 250
				,emptyText:'검색어 입력'
				,selectOnFocus:undefined === this.selectOnFocus ? true : this.selectOnFocus
	            ,trigger1Class:'x-form-clear-trigger'
	            ,trigger2Class:'x-form-search-trigger'
	            ,onTrigger1Click:this.onTriggerClear.createDelegate(this)
	            ,onTrigger2Click:this.search.createDelegate(this)
	            //,minLength:this.minLength
			});
/**			
   if(this.config.data.isSearch){
   	
	   this.toolbar = new Ext.Toolbar({
			items:[this.layoutItemButton,'-',this.searchTextField]
			
		});
		
   }else{
   **/	
   		this.toolbar =  new Ext.Toolbar({
			items:[this.layoutItemButton]});
   		
   //}
	

	
	this.addMenu = new Ext.menu.Menu({
		scope:this,
        items: [
        		this.detailButton,'-',this.newDetailButton
	        	]
    });
    
    this.rowAction = new Ext.ux.grid.RowActions({
		header:'',
		autoWidth:false,
		scope:this,
		allowRule:false,
		width:80,
		actions:[
					{
						iconCls:'tab_gosite',
						text:'내용보기',
						qtip:'해당 내용에 대한 사이트를 현재 창에 추가한다.',
						scope:this,
						callback:this.addTab
					},
					{
						iconCls:'new_gosite',
						text:'새 창으로',
						qtip:'해당 내용에 대한 사이트 새창을 통해 이동합니다.',
						scope:this,
						callback:function(grid, records, action, groupId){
							window.open(records.data.link);
						}
					}
					
					
				]
	});
    
    


	this.store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url : './src/api/OpenAPI.php',
	       	method : 'POST'
        }),  
        baseParams:{
				'class':'OpenAPI',
				'method':'getNaverXML',
				//keyword:this.config.data.keyword,
				target:this.config.target,
				start:this.config.start,
				display:this.config.display
		},

        reader: new Ext.data.XmlReader(
            {
            	record: 'item',
            	totalProperty: 'total'
            },
            
            [
            	{name: 'title', mapping:'title', type: 'string'},
            	{name: 'link', mapping:'link', type: 'string'},
            	{name: 'thumbnail', mapping:'thumbnail', type: 'string'},
            	{name: 'publisher', mapping:'publisher', type: 'string'},
            	{name: 'price', mapping:'price', type: 'string'},
            	{name: 'discount', mapping:'discount', type: 'string'},
            	{name: 'bloggername', mapping:'bloggername', type: 'string'},
            	{name: 'description', mapping:'description', type: 'string'},
            	{name: 'telephone', mapping:'telephone', type: 'string'},
            	{name: 'address', mapping:'address', type: 'string'},
            	{name: 'mapx', mapping:'mapx', type: 'string'},
            	{name: 'member', mapping:'member', type: 'int'},
            	{name: 'totalarticles', mapping:'totalarticles', type: 'int'},
            	{name: 'mapy', mapping:'mapy', type: 'date'},
            	{name: 'pubDate', mapping:'pubDate', type: "date", dateFormat:"Y-m-d"}
            	]
//
        )
    });
  
    
    //this.store.setDefaultSort('pubDate', "DESC");
    // 지역 검색
    
    	
    	cm = new Ext.grid.ColumnModel([
    			{
	            	width: 250,
	            	sortable: true,
	            	header:'블러그',
	            	dataIndex: 'title',
	            	scope:this,
	            	menuDisabled:true,
	            	renderer:this.titleFormat
	            }/**,{
	            	width: 50,
	            	sortable: true,
	            	header:'작성일',
	            	menuDisabled:true,
	            	dataIndex: 'pubDate'
	            }**///,this.rowAction
	            
	    ]);
	
	if(this.config.title){
		
		title = this.config.title + "  인기리뷰";
	}else{
		title = "";
	}
   
  
	Ext.hansub.naverAPI.NaverOpenAPIPanel.superclass.constructor.call(this, {
		
		id:this.config.id,
		border:false,
		title:title,
		region:this.config.region,
		iconCls:this.config.target+'_icon',
		hideHeaders:true,
		split: true,
		collapsible: false,
		loadMask: {msg:'화면 구성 중'},
		autoHeight:true,
		autoWidth:true,
		closable:true,
		ds: this.store,
		scope:this,
		cm: cm,
        sm: new Ext.grid.RowSelectionModel({
		            singleSelect:true
		        }),
		view: new Ext.grid.GridView({
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        }),
        keys: [{
		        	key: Ext.EventObject.ENTER,
		        	scope:this,
		        	fn: this.search
		     	}]/**,
        tbar:this.toolbar//,**/
        //plugins:this.rowAction

        
							        
									
	});
	
	
	//this.on('rowcontextmenu', this.onContextClick, this);					      
	
	this.on('expand', this.loadAPI, this);
	
	this.view.showView = this.config.viewtype;
	
	
	//this.view.target = this.config.target;
	/**
	this.boardGridSM = this.getSelectionModel();

    this.boardGridSM.on('rowselect', function(sm, index, record){
    	
    	this.selectedRecord = record;
    	if(index == 1){
    		this.linkLoad();
    	}
    	
    	
    }, this)
    **/
    this.on('rowclick', this.onDbClick, this);
       
    this.on('render', this.loadAPI, this);

    //this.on('activate', function(){Ext.getCmp('mainToolbarID').layout('main');},this);
    
    
 
};

Ext.extend(Ext.hansub.naverAPI.NaverOpenAPIPanel, Ext.grid.EditorGridPanel, {
	
	setUid:function(uid){

		this.config.uid = uid;
		
	},
	
	setKeyword:function(keyword){
		
		this.isloaded = false;
		this.config.keyword = keyword.replace(" ", "+");
		
	},
	
	setViewType:function(viewtype){
		
		this.config.viewtype = viewtype
		this.view.showView = this.config.viewtype;
		this.view.refresh();

	},
	
	loadAPI : function(){
		if(!this.isloaded){
			this.store.load(
				{
					params:{
						keyword:this.config.keyword,
						uid:this.config.uid
					}
				}
			);
			this.isloaded = true;
		}
		
		
		
	},
	
	onDbClick:function(grid,index,e){
		
		this.addTab(null,this.store.getAt(index),null,null);
		
	},
	
	addTab:function(grid, records, action, groupId){
		
		//this.linkLoad(records);
		
		if(records && records.data.link ){
			
			records.data.link = Ext.util.Format.htmlDecode( records.data.link) 
			
			window.open(records.data.link,"_blank");
			
		}
		
	},
	
	linkLoad:function(selectedRecord){
		
		if(selectedRecord && selectedRecord.data.link ){
			
			selectedRecord.data.link = Ext.util.Format.htmlDecode( selectedRecord.data.link) 
			
			//title = Ext.util.Format.ellipsis(this.selectedRecord.data.title, 20);
			title = selectedRecord.data.title;
			
			if(Ext.getCmp(selectedRecord.data.title)){
				Ext.getCmp('centerCenterPanel').activate(Ext.getCmp(selectedRecord.data.title));
			}else{
				alert(selectedRecord.data.link);
				var iframe = new Ext.ux.ManagedIframePanel({
						id:selectedRecord.data.title,
						title:title,
						cls:'scroll',
						autoWidth:true,
						autoHeight:true,
						autoScroll:true,
						closable:true,
						defaultSrc:selectedRecord.data.link,
						loadMask : false,
			    		animCollapse:true
				});
				
				Ext.getCmp('centerCenterPanel').add(iframe);
				Ext.getCmp('centerCenterPanel').activate(iframe);
				
			}
			
			
		}
		
	},
	
	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.stripScripts(record.data.description);
        	if(content == ""){
        		return 'x-grid3-row-collapsed';
        	}
			
        	p.body = '<div class=boardsummary>' + content + '</div>';
            return 'x-grid3-row-expanded';
        }else if(this.showView == 'full'){
			p.body = '<div class=boardcontent>' + record.data.description + '</div>';
            return 'x-grid3-row-expanded';
        }else{
        	return 'x-grid3-row-collapsed';
        }
        
    },
    
    formatDate : function(date) {
        if (!date) {
            return '';
        }
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return '오늘 ' + date.dateFormat('g:i a');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D g:i a');
        }
        return date.dateFormat('n/j g:i a');
    },
    

    
    titleFormat: function(value, p, record,rowIndex, colIndex, store) {
    	
    	return String.format(
                '<div class="'+store.baseParams.target+'">{0}</div>',
                value, record.data.author, record.id, record.data.forumid
                );
    },
    
    imageFormat: function(value, p, record) {
    	return String.format('<img src={0} height=100>',value);
    },
    
    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 + ' 원';
                 
	},
    
    onContextClick : function(grid,index,e){
    	
    	this.getSelectionModel().selectRow(index);
    	this.selectedRecord = this.store.getAt(index);
		
        this.addMenu.showAt(e.getXY());
      
    },
    onTriggerClear:function() {
        this.searchTextField.setValue('');
        this.field.focus();
        
    },
    
    search:function(){
		
		keyword = this.searchTextField.getValue();

		if(keyword){
			
			this.setKeyword(keyword);
			this.loadAPI();
						
		}
	},
	
	setListLayout:function(viewtype){
    	   	
  
		if(viewtype == 'title'){
			
    		this.layoutItemButton.setText('간략하게 보기');
    		this.layoutItemButton.setIconClass('view_summary');
    		this.titleLayoutButton.disable();
    		this.summaryLayoutButton.enable();
				
    	}else if(viewtype == 'summary'){
    		
    		this.layoutItemButton.setText('제목만 보기');
    		this.layoutItemButton.setIconClass('view_title');
    		this.titleLayoutButton.enable();
    		this.summaryLayoutButton.disable();
			
    	}else{
    		
    		if(this.viewtype == 'title'){
    			this.layoutItemButton.setText('제목만 보기');
    			this.layoutItemButton.setIconClass('view_title');
    			this.titleLayoutButton.enable();
    			this.summaryLayoutButton.disable();
    			viewtype = "summary";
    		}else{
    			this.layoutItemButton.setText('간략하게 보기');
    			this.layoutItemButton.setIconClass('view_summary');
    			this.titleLayoutButton.disable();
    			this.summaryLayoutButton.enable();
    			viewtype = "title";
    		}
 		
    	}
		
    	this.viewtype = viewtype;
    	
		this.setViewType(viewtype);

		

    }
	

});

