/*
 * Tree Search Form
 * This form displays the user interface for /search
 * - Browse Families and Regions
 * - Search by node_name, node_code, pub attributes
 * - Display tree listings
 */

// create namespace
Ext.namespace('Multitree');

Multitree.TreeSearchForm = Ext.extend(Ext.Panel, {
  constructor: function(config) {
    
    var this_panel = this;
	this.viewer;
	this.compare_tree_id = null;
  this.expand_all_results = false;
	var search_msg = null;
  var limit = 20;
  
  
	
	var search_handler = function(){
		retired_code_panel.hide();
		search_msg = Ext.Msg.wait("Searching...");
    
			trees_proxy.conn = {
				url: '/trees.json',
				method: 'GET'
			};
		
		//show code retire message if code_retire is returned true	
		trees_proxy.on('load', function(this_proxy, o, arg){
			if(o.reader.jsonData.code_retired){
				var code = o.request.scope.baseParams.node_code;
				var el = retired_code_panel.getEl();
				el.dom.innerHTML = '<p id="error_code_msg">' + 
					'The code '+ 
					'<a href="/codes/' + code + '" target="_blank">'+ code + '</a> ' +
					' has been retired. Click ' +
					'<a href="/codes/' + code + '" target="_blank">here</a> ' +
					'for more information.' +
				'</p>';
				retired_code_panel.show();
			}
		});
        
        params = search_form.getForm().getValues();
        params.limit = limit;
        trees_store.baseParams = params;
		trees_store.load();
	};
	
	var reset_handler = function(){
		retired_code_panel.hide();
		search_form.getForm().reset();
		trees_store.removeAll();
	};
	
	
	//Define Search Bar
	var search_bbar = new Ext.Toolbar({
		cls: 'tbar',
		height: 26
	});
	search_bbar.on("render", function(){
		search_bbar.add({
			text: 'Reset',
			cls: 'search-btn',
			handler: reset_handler
		},'->',{
			text: 'Search &raquo;',
			cls: 'search-btn',
			handler: search_handler
		});
	});
	
	var publication_types_store = new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({url: '/publication_types.json', method:'get'}),
      autoLoad: true,
      reader: new Ext.data.JsonReader({
          totalProperty: 'results',
          root: 'publication_types'
        }, 
        [{name: 'publication_type'}]
      )
    });    
    
    var publication_type_combo = new Ext.form.ComboBox({
        fieldLabel: 'Pub Type',
        allowBlank: true,
		    width: 125,
        hiddenName:'pub_type',
        store: publication_types_store,
        editable: false,
        valueField:'publication_type',
        displayField:'publication_type',
        mode: 'local',
        triggerAction: 'all',
        emptyText:'Select a type...',
        selectOnFocus:true
     });
    
    var retired_code_panel = new Ext.Panel({
    	height: 100,
    	layout: 'fit',
    	hidden: true
    });
	
	//Define Search Form
	var search_form = new Ext.form.FormPanel({
		autoScroll: true,
		border: false,
		baseCls: 'left-panel',
		itemCls: 'search-field',
		keys: [{
          key: Ext.EventObject.ENTER,
          fn: search_handler,
          scope: this
        }],
		items: [{ 	
					xtype: 'label',
					text: "Family/Subgroup/Language/Dialect",
					cls: 'search-head-lbl'
			},{
					xtype:'textfield',
					fieldLabel: 'Name',
                    name: 'node_name'
			},{
					xtype:'textfield',
					fieldLabel: 'Code',
                    name: 'node_code'
			},{ 	
					xtype: 'label',
					text: "Publication",
					cls: 'search-head-lbl'
			},{
					xtype:'textfield',
					fieldLabel: 'Title',
                    name: 'pub_title'
			},{
					xtype:'textfield',
					fieldLabel: 'Scholar',
                    name: 'pub_person'
			},{
					xtype:'textfield',
					fieldLabel: 'Language',
                    name: 'pub_lang'
			},
					publication_type_combo
			,{
					layout: 'absolute',
					baseCls: "pub-year-pnl",
					height: 50,
					border: false,
					items: [{
						xtype: 'label',
						text: "Year:",
						cls: 'pub-year-lbl',
						x: 23
					},{
						xtype:'numberfield',
						fieldLabel: 'Year',
	                    name: 'pub_year_start',
						width:50,
						x:128
					},{ 
						xtype: 'label',
						text: "-",
						cls: 'pub-year-lbl',
						x: 190
					},{ 
						xtype:'numberfield',
	                    name: 'pub_year_end',
						width:50,
						x: 206
					}]
			},{
        xtype:'checkbox',
          fieldLabel: 'Expand All',
          cls: 'search-head-lbl',
          handler: function(chkbox, checked){
            this_panel.expand_all_results = checked;
            if(checked){
              this_panel.expandAll();
            }else{
              this_panel.collapseAll();
            }
          }
      },retired_code_panel,{
			xtype: 'hidden',
			name: 'search_form',
			value: true
	  }],
	  bbar: search_bbar
	});

    //Define Browse Panel
    this.root = new Ext.tree.AsyncTreeNode({
      text: 'Invisible Root',
      draggable: false,
      id: '0'
    });	
    var browse_panel = new Ext.tree.TreePanel({
      autoScroll: true,
      root: this.root,
      rootVisible: false,
	  baseCls: 'left-panel',
	  border: false,
      loader: new Ext.tree.TreeLoader({
        url:'/browse_regions',
        requestMethod:'GET',
        baseParams:{format:'json'}
      }),
      listeners: {
        click: function(node, e){
          if(node.attributes.type == 'family'){
            var family_id = parseInt(node.id.split('-')[0]);
            search_msg = Ext.Msg.wait("Searching...");
      			trees_proxy.conn = {
      				url: '/browse_families/'+ family_id +'/trees.json',
      				method: 'GET'
      			};
      			trees_store.load();
          }
        }
      } 
    });
   this.root.expand();



    //Set Left Toolbar
	var leftbar = new Ext.Toolbar({
		style: 'padding-top: 7px;',
    cls: 'tbar',
		height: 30,
    items: [{
      text: 'Browse',
      toggleGroup: 'leftTbar',
      enableToggle: true,
      cls: 'left-tbar-btn',
      pressed: true,
      handler: function(){left_panel.getLayout().setActiveItem(0);}
    },{
      text: 'Search',
      toggleGroup: 'leftTbar',
      cls: 'left-tbar-btn',
      enableToggle: true,
      pressed: false,
      handler: function(){
    	retired_code_panel.hide();
    	left_panel.getLayout().setActiveItem(1);
      }     
    }]
	});

	var left_panel = new Ext.Panel({
      region: 'west',
      width: 285,
	  activeItem: 0,
	  border: false,
	  layout: 'card',
	  tbar: leftbar,
	  items: [browse_panel, search_form]
	});
	
	var trees_proxy = new Ext.data.HttpProxy();
	var trees_store = new Ext.data.Store({
		proxy: trees_proxy,
		reader: new Ext.data.JsonReader({
			root: 'trees',
			id: 'id',
			totalProperty: 'results'
		}, [{name: 'id'}, 
			{name: 'tree_type_val'},
      {name: 'family_codes'}, 
			{name: 'val'},
			{name: 'node_count'}, 
			{name: 'publications'},
			{name: 'nodes'} 
			]
		),
    listeners: {
      load: function(this_store, records, options){
        search_msg.hide();
        if(records.length == 0){
          Ext.Msg.alert('Sorry', 'No Records were found.');
        }
        
        if(this_panel.expand_all_results){
          this_panel.expandAll();
        }
      }
    }
	});	
	

	var tree_tpl = new Ext.XTemplate(
	    '<tpl for=".">',
	        '<div class="tree-item" id="{id}">',
		        '<a href="" class="tree-link" onclick="search_form.openViewer({id}); return false;">{val}</a>',
				'<tpl for="publications">',
					'<p class="tree-pub">{.}</p>',
				'</tpl>',
				'<ul class="tree-foot">',
					'<li class="tree-foot-item">nodes: {node_count}</li>',
          //'<li class="tree-foot-item"><a target="_blank" href="/codes/{family_codes}">details</a></li>',
					'<li class="tree-foot-item"><a target="_blank" href="../trees/{id}.xml">xml</a></li>',
					'<li class="tree-foot-item"><a href="" onclick="search_form.addCompareTree(\'{val}\',{id}); return false;">compare</a></li>',
				  '<tpl if="nodes">',
            '<li id="show-nodes-link-{id}" class="tree-foot-item expand-results">[+] <a href="" onclick="search_form.showNodeGroup({id}); return false;">expand results</a></li>',
            '<li id="hide-nodes-link-{id}" class="tree-foot-item hide-results" style="display: none;">[-] <a href="" onclick="search_form.hideNodeGroup({id}); return false;">hide results</a></li>',
          '</tpl>',
        '</ul>',
				'<tpl if="nodes">',
					'<div style="clear: both;"></div>',
          '<div id="node-group-{id}" style="display: none;">',
					'<tpl for="nodes">',
						'<div class="node-item" id="{id}">',
							'<a href="" class="tree-link" onclick="search_form.openViewerAtNode({parent.id},{id}); return false;">{pri_name}</a>',
							'<tpl if="alt_names">',
								'<span class="node-alt-names">({alt_names})</span>',
							'</tpl>',
							'<ul class="node-info-list">',
								'<li><span class="info-lbl">type:</span>{node_type}</li>',
								'<li><span class="info-lbl">code(s):</span>{codes}</li>',
								'<li><ul class="tree-foot">',
									//'<li class="tree-foot-item"><a href="../codes/{codes}" target="_blank">details</a></li>',
									'<li class="tree-foot-item"><a href="" onclick="search_form.addCompareTree(\'{parent.val}\',\'{parent.id}@{id}\'); return false;">compare</a></li>',
								'</ul></li>',
							'</ul>',
						'</div>',
						'<div style="clear: both;"></div>',
					'</tpl>',
          '</div>',
				'</tpl>',
	     '</div>',
			'<div style="clear: both;"></div>',
	    '</tpl>'
	);
	
	this_panel.center_tbar = new Ext.Toolbar({
		style: 'padding-top: 7px;',
		cls: 'tbar',
		height: 30,
		items: ['<span class="tbar-lbl">Compare: </span>']
	});
  
  this_panel.bottomPaging = new Ext.PagingToolbar({
          pageSize: limit,
          store: trees_store,
          displayInfo: true,
          emptyMsg: "No records found"
        });
	
	
	//Define main layout
    if (config == undefined){config = {}};
    config.layout = 'border';
    config.items = [
		left_panel,
		new Ext.Panel({
			tbar: this_panel.center_tbar,
      bbar: this_panel.bottomPaging,
			border: false,
			autoScroll: true,
			region: 'center',
			cls: 'tree-results-panel',
			//layout: 'fit',
      width: 700,
			items: [
				new Ext.DataView({
					border: false,
			        store: trees_store,
					autoHeight:true,
					itemSelector: 'div.tree-item',
			        tpl: tree_tpl
		    })
			]
		})
	];
	config.height = 500;
	config.border = false;
	config.autoWidth = true;


    this.root.reload();
    
    Multitree.TreeSearchForm.superclass.constructor.call(this, config);
  },
  
  openViewer: function(tree_id){
		if (this.viewer && this.viewer.open) {
			this.viewer.close();
		}
    this.viewer = window.open('../trees/' + tree_id, 'mtTreeViewer');
	},
	
  openViewerAtNode: function(tree_id, node_id){
		if (this.viewer && this.viewer.open) {
			this.viewer.close();
		}	
		this.viewer = window.open('../trees/' + tree_id + '@' + node_id, 'mtTreeViewer');
	},
	
  addCompareTree: function(tree_name, tree_id){
  		var this_panel = this;
		
		//set compare tree id
  		if (this_panel.compare_tree_id == null) {
			this_panel.compare_tree_id = tree_id;		
			this.center_tbar.add({
				text: tree_name + " [X]",
				cls: 'compare-tree-btn',
				handler: function(btn){
					this_panel.compare_tree_id = null;
					btn.destroy();
				}
			});
		
		//compare tree id has already been set. open viewer with both trees.
		}else{
			if (this.viewer && this.viewer.open) {
				this.viewer.close();
			}
			this.viewer = window.open('../trees/' + this_panel.compare_tree_id + ',' + tree_id, 'mtTreeViewer');
		}
  },
  
  showNodeGroup: function(id){
    Ext.get("node-group-" + id).setStyle('display', 'block');
    Ext.get("show-nodes-link-" + id).setStyle('display', 'none');
    Ext.get("hide-nodes-link-" + id).setStyle('display', 'block');
  },
  
  hideNodeGroup: function(id){
    Ext.get("node-group-" + id).setStyle('display', 'none');
    Ext.get("hide-nodes-link-" + id).setStyle('display', 'none');
    Ext.get("show-nodes-link-" + id).setStyle('display', 'block');
  },
  
  expandAll: function(){
    var items = Ext.query(".expand-results");
    var items_length = items.length;
    for(i=0;i<items_length;i++){
      this.showNodeGroup(items[i].id.split("-").pop());
    }
  },
  
  collapseAll: function(){
    var items = Ext.query(".expand-results");
    var items_length = items.length;
    for(i=0;i<items_length;i++){
      this.hideNodeGroup(items[i].id.split("-").pop());
    }
  }
});
