
// Global vars
var WTtasksDataStore;
var WTtasksColumnModel;
var WTtasksListingEditorGrid;
var WTtasksListingWindow;
var WTtaskListingSelectedRow;
var WTtaskListingContextMenu;
var TbarObj;
var WTdefaultListingTitle = 'Hunde im DRC - Suchergebnis';
var WTdefaultSearchTitle = 'Hunde im DRC - Suchkriterien';
var WTpagesize = 250;

Ext.onReady(function(){

  Ext.QuickTips.init();

  TbarObj = {
        text: 'Suche',
        tooltip: 'Erweiterte Suche',
        handler: startAdvancedSearch,  // search function
        iconCls:'search'               // we'll need to add this to our css
      };
	//TbarObj.text = "Hallo";
	//el.dom

  
  //-------------------------------------------------------------------------------------------    


  ColorDataStore = new Ext.data.Store({
      //id: 'RaceDataStore',
      proxy: new Ext.data.HttpProxy({
                url: 'hunde_suche.php', 
                method: 'POST'
            }),
            baseParams:{task: "GETRACES", breed: ''}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ {name: 'Color', type: 'string', mapping: 'cname'} ]),
      sortInfo:{field: 'Color', direction: "ASC"}
    });

    //-------------------------------------------------------------------------------------------    
    
  RaceDataStore = new Ext.data.Store({
      //id: 'RaceDataStore',
      proxy: new Ext.data.HttpProxy({
                url: '../wtresults/database.php', 
                method: 'POST'
            }),
            baseParams:{task: "GETRACES"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ {name: 'BreedName', type: 'string', mapping: 'LongName'} ]),
      sortInfo:{field: 'BreedName', direction: "ASC"}
    });

    //-------------------------------------------------------------------------------------------    

  WTtasksDataStore = new Ext.data.Store({
      id: 'WTtasksDataStore',
      //autoLoad: false,
      proxy: new Ext.data.HttpProxy({
                url: 'hunde_suche.php', 
                method: 'POST'
            }),
            baseParams:{task: "LISTING"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ 
        {name: 'HundID', type: 'int', mapping: 'Rkey'},
        {name: 'Hundename', type: 'string', mapping: 'Name'},
        {name: 'HZBNr', type: 'string', mapping: 'ZBNr'},
        {name: 'HRasse', type: 'string', mapping: 'Rasse'},
        {name: 'HGeschlecht', type: 'string', mapping: 'Geschlecht'},
        {name: 'HZuechter', type: 'string', mapping: 'Z_Name'},
        {name: 'HBesitzer', type: 'string', mapping: 'B_Name'},
        {name: 'HWurfdatum', type: 'date', mapping: 'Wurfdatum'},
        {name: 'HHD_Grad', type: 'string', mapping: 'HD_Grad'},
        {name: 'HED_Grad', type: 'string', mapping: 'ED_rechts'},
        {name: 'HAnzNachkommen', type: 'int', mapping: 'AnzNachkommen'},
        {name: 'HZW_HD', type: 'int', mapping: 'ZW_HD'},
	    {name: 'HZW_ED', type: 'int', mapping: 'ZW_ED'},
        {name: 'HZW_HC', type: 'int', mapping: 'ZW_HC'}
      ])
      //, sortInfo:{field: 'Hundename', direction: "ASC"}
    });

    WTtasksColumnModel = new Ext.grid.ColumnModel(
    [{
        header: 'ID',
        readOnly: true,
        dataIndex: 'HundID',
        width: 50,
        hidden: true,
        renderer: function(value, cell){ 
         cell.css = "readonlycell";
         return value;
        }
      },{
        header: 'Name',
        readOnly: true,
        dataIndex: 'Hundename',
        width: 200,
        hidden: false
       },{
        header: 'Wurfdatum',
        readOnly: true,
        dataIndex: 'HWurfdatum',
        width: 70,
        renderer: Ext.util.Format.dateRenderer('d.m.Y'),
        hidden: false
      },{
      	header: 'ZB-Nr',
        readOnly: true,
        dataIndex: 'HZBNr',
        width: 70,
        hidden: false
      },{
        header: 'Rasse',
        readOnly: true,
        dataIndex: 'HRasse',
        width: 70,
        hidden: false
      },{
        header: 'H/R',
        readOnly: true,
        dataIndex: 'HGeschlecht',
        width: 30,
        hidden: false
		},
		{
        header: 'Züchter',
        readOnly: true,
        dataIndex: 'HZuechter',//HBesitzer
        width: 80,
        hidden: false
      },
      {
        header: 'Besitzer',
        readOnly: true,
        dataIndex: 'HBesitzer',
        width: 80,
        hidden: false
      },
      {
        header: 'HD',
        readOnly: true,
        dataIndex: 'HHD_Grad',
        width: 30,
        hidden: false
      },    
      {
        header: 'ED',
        readOnly: true,
        dataIndex: 'HED_Grad',
        width: 50,
        hidden: false
      },    
      {
        header: 'ZW HD',
        readOnly: true,
        dataIndex: 'HZW_HD',
        width: 50,
        hidden: false
      },    
      {
        header: 'ZW ED',
        readOnly: true,
        dataIndex: 'HZW_ED',
        width: 50,
        hidden: false
      },
      {
        header: 'ZW HC',
        readOnly: true,
        dataIndex: 'HZW_HC',
        width: 50,
        hidden: false
      },
      {
        header: 'NK',
        readOnly: true,
        dataIndex: 'HAnzNachkommen',
        width: 30,
        hidden: false
      }
      
      
      ]
    );
    WTtasksColumnModel.defaultSortable= true;

/*
      tbar: [{
            text: 'Suche',
            tooltip: 'Erweiterte Suche',
            handler: startAdvancedSearch,  // search function
            iconCls:'search'               // we'll need to add this to our css
          }],

*/
        function openHelp() {
                NF1 = open("hilfe.html","Hilfe","width=650,height=500,menubar=no,resizable=yes,status=no,scrollbars=yes");
                NF1.moveBy(60, 40);
                NF1.focus();
        }


    
  WTtasksListingEditorGrid =  new Ext.grid.EditorGridPanel({
      id: 'WTtasksListingEditorGrid',
      store: WTtasksDataStore,
      cm: WTtasksColumnModel,
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
      
      //tbar: [TbarObj],
      bbar: new Ext.PagingToolbar({
                pageSize: WTpagesize,
                store: WTtasksDataStore,
                displayInfo: true,
                items: [
                '-',
                {
                    text: 'Hilfe',
                    handler: openHelp
                }
                ]
            })   
    });
    

 //add event handler   
 WTtasksListingEditorGrid.addListener('rowcontextmenu', onWTtaskGridContextMenu);

    
  WTtasksListingWindow = new Ext.Window({
      id: 'WTtasksListingWindow',
      header : true,
      closable:false,
      width:900,
      height:460,
      plain:true,
      layout: 'fit',
      x: 10,
      y: 20,
      items: WTtasksListingEditorGrid
    });
  
  WTtasksDataStore.load({params: {start: 0, limit: WTpagesize}});
  WTtasksListingWindow.show();
  startAdvancedSearch();
  
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // ++++++++++++++  start search window definitions +++++++++++++++++++++++
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  
   function startAdvancedSearch(){
      // local vars
      var WTtaskSearchForm;
      var WTtaskSearchWindow;
      var SearchNameItem;
      var SearchZBNrItem;
      var SearchOwnerItem;
      var SearchBreederItem;
      var SearchColorItem;
      var SearchBreedItem;
      var SearchGenderItem;
      var SearchMaxAgeItem;
      var SearchMinAgeItem;
      var SearchZZLItem;
      var SearchMaxZWHDItem;
      var SearchMaxZWEDItem;
      var SearchMaxZWHCItem;
      var SearchMinNKItem;
      var SearchConditionItem;
      var SearchChipCodeItem;
      
      
     function listSearch(){
         // change the store parameters
    		WTtasksDataStore.baseParams = {
   			task: 'SEARCH',
            Name: SearchNameItem.getValue(),
            ZBNr: SearchZBNrItem.getValue(),
            Owner: SearchOwnerItem.getValue(),
            Breeder: SearchBreederItem.getValue(),
            Breed: SearchBreedItem.getValue(),
            Color: SearchColorItem.getValue(),
            MaxAge: SearchMaxAgeItem.getValue(),
            MinAge: SearchMinAgeItem.getValue(),
            Gender: SearchGenderItem.getValue(),
            ZZL: SearchZZLItem.getValue(),
            ZWHD: SearchMaxZWHDItem.getValue(),
            ZWED: SearchMaxZWEDItem.getValue(),
            ZWHC: SearchMaxZWHCItem.getValue(),
            MinNK: SearchMinNKItem.getValue(),
            Cond: SearchConditionItem.getValue(),
            Chip: SearchChipCodeItem.getValue()
  		};

         // Cause the datastore to do another query : 
   		WTtasksDataStore.reload({params: {start: 0, limit: WTpagesize}});
	    WTtasksListingWindow.setTitle(WTdefaultListingTitle);

     }
     
     function resetSearch(){
     		// reset the store parameters
    		WTtasksDataStore.baseParams = {
   			task: 'LISTING'
   		};
         // Cause the datastore to do another query : 
   		WTtasksDataStore.reload({params: {start: 0, limit: WTpagesize}});
        //WTtaskSearchWindow.close();
        SearchColorItem.clearValue();
        SearchBreedItem.clearValue();
        SearchGenderItem.clearValue();
        SearchMaxAgeItem.clearValue();
        SearchMinAgeItem.clearValue();
        
		SearchZZLItem.reset();
        SearchNameItem.reset();
        SearchZBNrItem.reset();
        SearchOwnerItem.reset();
        SearchBreederItem.reset();
        SearchMaxZWHDItem.reset();
        SearchMaxZWEDItem.reset();
        SearchMaxZWHCItem.reset();
        SearchMinNKItem.reset();
        SearchConditionItem.reset();
        SearchChipCodeItem.reset();
     }
     
      SearchNameItem = new Ext.form.TextField({
          fieldLabel: 'Name',
          maxLength: 30,
          anchor : '95%'
          //maskRe: /([a-zA-Z0-9\s]+)$/  
            });
            
      SearchZBNrItem = new Ext.form.TextField({
          fieldLabel: 'ZBNr',
          maxLength: 30,
          anchor : '95%'   
          //maskRe: /([a-zA-Z0-9\s]+)$/  
            });

      SearchBreederItem = new Ext.form.TextField({
          fieldLabel: 'Züchter',
          maxLength: 30,
          anchor : '95%'   
          //maskRe: /([a-zA-Z0-9\s]+)$/  
            });
            
            
      SearchOwnerItem = new Ext.form.TextField({
          fieldLabel: 'Besitzer',
          maxLength: 30,
          anchor : '95%'   
          //maskRe: /([a-zA-Z0-9\s]+)$/  
            });

     SearchChipCodeItem = new Ext.form.TextField({
          fieldLabel: 'Chip-Code',
          maxLength: 30,
          anchor : '95%',
          maskRe: /([0-9\s]+)$/  
            });
            
     SearchGenderItem = new Ext.form.ComboBox({
     //id:'DogsGenderField',
     fieldLabel: 'Geschlecht',
     store:new Ext.data.SimpleStore({
       fields:['genderValue', 'genderName'],
       data: [['H','Hündin'],['R','Rüde']]
       }),
     mode: 'local',
     displayField: 'genderName',
     //allowBlank: false,
     valueField: 'genderValue',
     anchor:'95%',
     emptyText: '?',
     editable: false,
     triggerAction: 'all'
      });
            
            
     SearchBreedItem = new Ext.form.ComboBox({
     //id:'DogsBreedField',
     fieldLabel: 'Rasse',
     store:RaceDataStore,
     displayField: 'BreedName',
     //allowBlank: false,
     valueField: 'BreedName',
     anchor:'95%',
     emptyText: '?',
     editable: false,
     triggerAction: 'all'
      });
      
     SearchBreedItem.addListener('select', SearchBreedItemHandler);
      
   	function SearchBreedItemHandler ( combo, record, index ){
   		ColorDataStore.baseParams.breed = SearchBreedItem.getValue();
   		ColorDataStore.reload();
    }

      
     SearchColorItem = new Ext.form.ComboBox({
     fieldLabel: 'Farbe',
     store:ColorDataStore,
     displayField: 'Color',
     hidden: false,
     valueField: 'Color',
     anchor:'95%',
     emptyText: '?',
     editable: false,
     triggerAction: 'all'
      });

  	SearchMinAgeItem = new Ext.form.ComboBox({
    fieldLabel: 'min. Alter',
	store:new Ext.data.SimpleStore({
	fields:['MinAge'],
	data: [['1'],['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['11'],['12'],['13'],['14'],['15'],['16'],['17'],['18'],['19'],['20']]
	}),
    valueField:'MinAge',
    displayField:'MinAge',
    mode: 'local',
    triggerAction: 'all',
    emptyText:'?' , 
     editable: false,
    anchor:'95%'
	});
      
      
  	SearchMaxAgeItem = new Ext.form.ComboBox({
    fieldLabel: 'max. Alter',
	store:new Ext.data.SimpleStore({
	fields:['MaxAge'],
	data: [['1'],['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['11'],['12'],['13'],['14'],['15'],['16'],['17'],['18'],['19'],['20']]
	}),
    valueField:'MaxAge',
    displayField:'MaxAge',
    mode: 'local',
    triggerAction: 'all',
    emptyText:'?' , 
     editable: false,
    anchor:'95%'
	});

	 //adapted: adapter\ext\ext-base.js and source\core\Ext.js
	 //BLANK_IMAGE_URL:"http://localhost/drc/adr/ext221/examples/desktop/images/s.gif"
     SearchZZLItem = new Ext.form.Checkbox({
     fieldLabel: '   ',
     boxLabel: 'ZZL',
     hideLabel: false,
     labelSeparator : '',
     checked: false
      });
     SearchConditionItem = new Ext.form.Checkbox({
     fieldLabel: '   ',
     boxLabel: 'ohne Auflagen',
     hideLabel: false,
     labelSeparator : '',
     checked: false
      });
      
      SearchMaxZWHDItem = new Ext.form.TextField({
      fieldLabel: 'max.ZW HD',
      maxLength: 3,
      anchor : '95%',
      labelStyle: 'font-size:8pt;',
      maskRe: /([0-9\s]+)$/  
      });
      SearchMaxZWEDItem = new Ext.form.TextField({
      fieldLabel: 'max.ZW ED',
      maxLength: 3,
      anchor : '95%',
      labelStyle: 'font-size:8pt;',
      maskRe: /([0-9\s]+)$/  
      });
      SearchMaxZWHCItem = new Ext.form.TextField({
      fieldLabel: 'max.ZW HC',
      maxLength: 3,
      anchor : '95%',
      labelStyle: 'font-size:8pt;',
      maskRe: /([0-9\s]+)$/  
      });
      SearchMinNKItem = new Ext.form.TextField({
      fieldLabel: 'min.NK',
      maxLength: 3,
      anchor : '95%',
      labelStyle: 'font-size:8pt;',
      maskRe: /([0-9\s]+)$/  
      });

              
     WTtaskSearchForm = new Ext.FormPanel({
       labelAlign: 'top',
       bodyStyle: 'padding: 5px',
       width: 300,
       items: [{
         layout: 'form',
         border: false,
        items: [	SearchNameItem,
         			//SearchZBNrItem,
         			//SearchZZLItem,
         			{ 
	                layout: 'column',
	                border: false, 
	                items: [{columnWidth:.4,layout: 'form',border: false,items: [SearchZBNrItem]},
	                		{columnWidth:.2,layout: 'form',border: false,items: [SearchZZLItem]},
	                		{columnWidth:.4,layout: 'form',border: false,items: [SearchConditionItem]}]	                		
            		},
         			{ 
	                layout: 'column',
	                border: false, 
	                items: [{columnWidth:.5,layout: 'form',border: false,items: [SearchBreederItem]},
	                		{columnWidth:.5,layout: 'form',border: false,items: [SearchOwnerItem]}]
            		},
            		SearchBreedItem,
         			SearchColorItem,
         			{ 
	                layout: 'column',
	                border: false, 
	                items: [{columnWidth:.3,layout: 'form',border: false,items: [SearchMinAgeItem]},
	                		{columnWidth:.3,layout: 'form',border: false,items: [SearchMaxAgeItem]},
	                		{columnWidth:.4,layout: 'form',border: false,items: [SearchGenderItem]}]
            		},
            		{ 
	                layout: 'column',
	                border: false, 
    			    items: [{columnWidth:.25,layout: 'form',border: false,items: [SearchMaxZWHDItem]},
	                		{columnWidth:.25,layout: 'form',border: false,items: [SearchMaxZWEDItem]},
	                		{columnWidth:.25,layout: 'form',border: false,items: [SearchMaxZWHCItem]},
	                		{columnWidth:.25,layout: 'form',border: false,items: [SearchMinNKItem]}]
            		},
            		SearchChipCodeItem      
	                ],            	
         buttons: [{
               text: 'Such!',
               handler: listSearch
             },{
               text: 'Reset',
               handler: resetSearch
             }]
         }]
     });
      
     WTtaskSearchWindow = new Ext.Window({
         title: WTdefaultSearchTitle,
         closable:false,
         width: 300,
         height: 470,
         plain:true,
         layout: 'fit',
          x: 500,
          y: 80,
         items: WTtaskSearchForm
     });
     
     // once all is done, show the search window
     WTtaskSearchWindow.show();
     WTtasksListingWindow.setTitle(WTdefaultListingTitle);

   }  
  
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++ building context menu +++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  function onWTtaskGridContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    WTtaskListingContextMenu.rowRecord = grid.store.getAt(rowIndex);
    grid.selModel.selectRow(rowIndex);
    WTtaskListingSelectedRow=rowIndex;
    WTtaskListingContextMenu.showAt([coords[0], coords[1]]);
  }

  WTtaskListingContextMenu = new Ext.menu.Menu({
      id: 'WTtaskListingContextMenu',
      items: [
      { icon: '../ext221/docs/resources/tabs.gif', text: 'Details anzeigen', handler: WTtaskDetails },
      { icon: '../ext221/docs/resources/forum.gif', text: 'Nachkommen anzeigen', handler: HandlerResults }
      ]
   });    
   
	function openDetail(rid,gender,prace) {
		NF1 = open("../listen/show_druede.php?what=" + gender + "&rvid=" + rid + "&race=" + prace,"Detailanzeige","width=650,height=500,menubar=no,resizable=yes,status=no,scrollbars=yes");
		NF1.moveBy(60, 40);
		NF1.focus();
	}

  function WTtaskDetails(){
    var rowRecord = WTtaskListingContextMenu.rowRecord;
  	openDetail(rowRecord.get('HundID'),'Hunde',rowRecord.get('HRasse'));
  }

  function HandlerResults(){
  	var rowRecord = WTtaskListingContextMenu.rowRecord;
  	
	WTtasksDataStore.baseParams = {
		task: 'SUCCESSOR',
	    ZBNr : rowRecord.get('HZBNr'),
	    Breed: rowRecord.get('HRasse'),
	    Gender: rowRecord.get('HGeschlecht')
		};
	//reload datastore
	WTtasksDataStore.reload({params: {start: 0, limit: WTpagesize}});
	//display in the Header the name of the Parent
	WTtasksListingWindow.setTitle('Nachkommen von: ' + rowRecord.get('Hundename'));
  }
	
});
