﻿AV.Committee = {};

//========================== CommitteeForm ========================================================
AV.Committee.CommitteeForm = new function(){

  var frmCommitteePanel;     
  
  return {   
    
    getCommitteeForm: function() {                  
          
    if(!frmCommitteePanel)
    {                      
      frmCommitteePanel = new Ext.form.FormPanel({
        labelWidth:100,
        //url:'Committee2.asp?action=add',                  
        bodyStyle: 'padding:10px;background-color:#FFFFFF;',
        border: false,
        bodyBorder: false,
        autoDestroy: false,
        defaultType:'textfield',      
        method: 'GET',
        defaults: {
          labelSeparator: '',
          msgTarget: 'under',
          labelStyle: 'font-family:Arial,Helvetica; font-size: 11px; font-weight:bold;'   
        },

        items:[                                                                                                                   
                {
                  id: 'txtCommitteeName',
                  fieldLabel:'Committee Name',            
                  name:'txtCommitteeName',
                  allowBlank:false,   
                  blankText: 'This field is required.',          
                  width: 200
                }
              ]                           
        });                                           
      }      
      
      return frmCommitteePanel;
    },
    
    getCommitteeFormInstruction: function(title, instructions) {
      var formInstructions = '<div style="padding: 10px;"><div style="font-family:Arial,Helvetica; font-size: 20px; font-weight:bold;">' + title + '</div><div style="font-family:Arial,Helvetica; font-size: 10px; font-weight:normal;"><table><tr>';        
      formInstructions += '<td>' + instructions + '</td>';
      formInstructions += '</tr></table></div></div>';
      
      var frmInstructionPanel = new Ext.Panel({                    
          border: false,
          bodyBorder: false,                   
          header: false,
          html: formInstructions,
          bodyStyle: 'background-color:#FFFFFF;'
      });
      
      return frmInstructionPanel;
    },
    
    clearFormValues: function() { 
      if(Ext.getCmp('txtCommitteeName').getValue != '') { Ext.getCmp('txtCommitteeName').reset(); }
  
    }

  } //End return 
} //End object AV.Committee.CommitteeForm


//========================== OfficerForm ========================================================

AV.Committee.OfficerForm = new function(){

  var frmOfficerPanel;
  var frm_data;
  
  function getOfficerIdFromSort(sortValue)
  {
    var officer_id = '-1';
    
    Ext.getCmp('comboDisplayBefore').store.each(function(row) {                                                                  
                                                                  if(row.data.av_sort == sortValue)
                                                                  {
                                                                    officer_id = row.data.officer_id;                                                                    
                                                                    return false //aborts loop after successfull setting of value
                                                                  }                
                                                                });                                                                                                                            
    return officer_id;
  }
  
  function populateFromNameSelection(officer_title, security_role, sort, committee_id, action)  
  {        
    if(action == 'edit')
    {
      //populate officer title box
      if(officer_title == '')
        { Ext.getCmp('txtPosition').setRawValue(officer_title); } //use raw value to avoid validation
      else
        { Ext.getCmp('txtPosition').setValue(officer_title); }      
        
      //if there is more than one committee, try to find it in the combobox     
      if(frm_data.Arrays.Committees.length != 1)
      { 
        Ext.getCmp('comboSelectCommittee').store.each(function(row) {                                                                  
                                                                    if(row.data.committee_id == committee_id)
                                                                    {
                                                                      //Set the value
                                                                      Ext.getCmp('comboSelectCommittee').setValue(committee_id); 
                                                                      //filter comboDisplayBefore based on set value
                                                                      committeeSelected(Ext.getCmp('comboSelectCommittee'),row);
                                                                      return false //aborts loop after successfull setting of value
                                                                    }                
                                                                  });  
      }      
                    
      //select the display before value (if any) of the selected contact    
      var sortValueId = '-1';
      var displayBeforeOfficerID = '-1';
        
      //BECAUSE the DisplayBefore combo has possibly been filtered, the av_sort values are no longer necessarily
      //consecutively incremented (i.e. they could be 1, 4, 5 instead of 1, 2, 3), so find the next valid value
      //The av_sort values will still be in order
      Ext.getCmp('comboDisplayBefore').store.each(function(row) {
                                                                  if(row.data.av_sort > sort)
                                                                  {
                                                                    sortValueId = row.data.av_sort;
                                                                    return false; //aborts loop
                                                                  }
                                                                  
                                                                });
       
      var displayBeforeOfficerID = getOfficerIdFromSort(sortValueId); 
      
      if(displayBeforeOfficerID != '-1' && sort != '')
        { Ext.getCmp('comboDisplayBefore').setValue(displayBeforeOfficerID); }           
    }
    
    //select the security role of the selected contact (for EDIT or when a contact is selected During the ADD process)
    Ext.getCmp('comboSecurityRole').setValue(security_role); 
    
    //if only one committee exists, select it
    if(frm_data.Arrays.Committees.length == 1)     
        { Ext.getCmp('comboSelectCommittee').setValue(frm_data.Arrays.Committees[0][0]); }      
        
   checkDisplayBeforeForOne();
   
  }
  
  function checkDisplayBeforeForOne()
  {
    //if only one item exists in the Display Before combobox, select it  
    //Basically, if only "-- At End --" exists, select it
    if(Ext.getCmp('comboDisplayBefore').getValue() == '' && Ext.getCmp('comboDisplayBefore').store.getCount() == 1)
      { Ext.getCmp('comboDisplayBefore').setValue(Ext.getCmp('comboDisplayBefore').store.getAt(0).data.officer_id); }    
  }
  
  function nameSelected(combo, row, index)
  {
    populateFromNameSelection(row.data.officer_title, row.data.sec_role_id, row.data.av_sort, row.data.committee_id);
  }
  
  function committeeSelected(combo, row, index)
  {
    //in case a DisplayBefore value has been selected that does not exist for the committee
    Ext.getCmp('comboDisplayBefore').clearValue(); 
    
    //filter "Display Before" combo by the selected committee
    if(combo.store.getCount() > 1)
    {
      Ext.getCmp('comboDisplayBefore').store.filterBy(function(record, id) {  //returning true keeps the record...returning false filters the record out
                                                                              //committee_id = 0 is for the "-- At End --" record                                                                              
                                                                              if(record.data.committee_id == row.data.committee_id || record.data.committee_id == '0')
                                                                                { return true; }
                                                                              else
                                                                                { return false; }
                                                                            });
    }
    
    checkDisplayBeforeForOne();
   
  }
  
  return {
    //should only be used when the form has already been created
    getForm: function() {    
    
      if(frmOfficerPanel) { return frmOfficerPanel; }      
    },
    
    getNewOfficerForm: function(data) {                  
      
    //Because contacts can belong to more than one committee, I have to reload the window each time
    //if(!frmOfficerPanel)
    //{
        if(data != '') { frm_data = data; }
        
        //Ticket 70658 3/19/2010  used to counteract a known bug in EXT
        var selectedContactID = "";
        
        frmOfficerPanel = new Ext.form.FormPanel({
          labelWidth:110,
          //url:url,       
          bodyStyle: 'padding:10px;background-color:#FFFFFF;',
          border: false,
          bodyBorder: false,
          autoDestroy: false,
          defaultType:'textfield',      
          method: 'GET',
          defaults: {
            labelSeparator: '',
            msgTarget: 'under',
            labelStyle: 'font-family:Arial,Helvetica; font-size: 11px; font-weight:bold; white-space: nowrap;'   
          },

          items:[                                                                                             
                new Ext.form.ComboBox({
                  id: 'comboSelectName',
                  fieldLabel:'Select Name',              
                  name:'comboSelectName',                       
                  hiddenName:'value_name_contact_id',    //Required for the combo's value to automatically post during a form submission
                  width: 200,
                  allowBlank: false,
                  editable: true,          
                  mode: 'local',
                  typeAhead: true,            
                  store: new Ext.data.ArrayStore({                  
                                                    fields: ['contact_id','full_name', 'officer_title', 'av_sort', 'sec_role_id', 'committee_id'],
                                                    data:frm_data.Arrays.Contacts,
                                                    id: 0   //set to first field.  required to be able to select by Id
                                                  }),
                  valueField: 'contact_id',   
                  displayField: 'full_name',                                               
                  triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly                  
                  forceSelection: true,
                  listeners: {
                    scope: this,
                    'select': function(combo, record, index) {                           
                        //alert(combo.getValue()); //TESTING
                        selectedContactID = combo.getValue();
                    },
                    'blur': function(combo) {                            
                        combo.setValue(selectedContactID);
                        //alert(combo.getValue());  //TESTING
                    },
                        'change': function(combo) {
                        //alert(combo.getValue());  //TESTING
                    }       
                  }                                
                }), 
                new Ext.form.ComboBox({
                  id: 'comboSelectCommittee',
                  fieldLabel:'Select Group',              
                  name:'comboSelectCommittee',                       
                  hiddenName:'value_committee_id',    //Required for the combo's value to automatically post during a form submission
                  width: 200,
                  allowBlank: false,
                  editable: true,          
                  mode: 'local',
                  //typeAhead: true,          
                  store: new Ext.data.SimpleStore({                  
                                                    fields: ['committee_id','committee_name'],
                                                    data:frm_data.Arrays.Committees,
                                                    id: 0   //set to first field.  required to be able to select by Id
                                                  }),
                  valueField: 'committee_id',   
                  displayField: 'committee_name',                                               
                  triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly                  
                  forceSelection: true              
                }),                   
                {
                id: 'txtPosition',
                fieldLabel:'Position',              
                name:'txtPosition',
                allowBlank:false,   
                blankText: 'This field is required.',          
                width: 200
                },    
                new Ext.form.ComboBox({
                  id: 'comboSecurityRole',
                  fieldLabel:'Security Role',              
                  name:'comboSecurityRole',                
                  hiddenName:'value_role_id',    //Required for the combo's value to automatically post during a form submission      
                  width: 200,
                  allowBlank: false,
                  editable: false,
                  mode: 'local',
                  store: new Ext.data.SimpleStore({
                                                    fields: ['sec_role_id','sec_role_desc'],
                                                    data: frm_data.Arrays.Roles, 
                                                    id: 0  //set to first field.  required to be able to select by Id
                                                  }),
                  valueField: 'sec_role_id',   
                  displayField: 'sec_role_desc',                                                     
                  triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly
                  forceSelection: true              
                }),
                new Ext.form.ComboBox({
                  id: 'comboDisplayBefore',
                  fieldLabel:'Display Before',              
                  name:'comboDisplayBefore',       
                  hiddenName:'value_display_before_officer_id',    //Required for the combo's value to automatically post during a form submission               
                  width: 200,
                  allowBlank: false,
                  editable: false,
                  mode: 'local',
                  store: new Ext.data.SimpleStore({
                                                    fields: ['officer_id','officer_title', 'officer_sort', 'av_sort', 'contact_id', 'committee_id'],
                                                    data: frm_data.Arrays.Officers,
                                                    id: 0  //set to first field.  required to be able to select by Id
                                                  }),
                  valueField: 'officer_id',   
                  displayField: 'officer_title',  
                  triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly
                  forceSelection: true,
                  lastQuery: ''            //**** THIS IS REQUIRED (WHY??) to all the combo to be filtered***  
                })
             ]                           
        });                       
        
        Ext.getCmp('comboSelectName').on('select', nameSelected);
        Ext.getCmp('comboSelectCommittee').on('select', committeeSelected);
      
      //}      
      
      return frmOfficerPanel;
    },
    
    getOfficerFormInstruction: function(title, instructions) {
      var formInstructions = '<div style="padding: 10px;"><div style="font-family:Arial,Helvetica; font-size: 20px; font-weight:bold;">' + title + '</div><div style="font-family:Arial,Helvetica; font-size: 10px; font-weight:normal;"><table><tr>';        
      formInstructions += '<td>' + instructions + '</td>';
      formInstructions += '</tr></table></div></div>';
      
      var frmInstructionPanel = new Ext.Panel({                    
          border: false,
          bodyBorder: false,     
          width: 340,					//shortened to prevent the message from rewrapping when the horiz scroll appears.
          header: false,
          html: formInstructions,
          bodyStyle: 'background-color:#FFFFFF;'
      });
      
      return frmInstructionPanel;
    },
    
    clearFormValues: function() { 
      Ext.getCmp('comboSelectName').clearValue();
      Ext.getCmp('comboSelectCommittee').clearValue();
      Ext.getCmp('txtPosition').reset();
      Ext.getCmp('comboSecurityRole').clearValue();
      Ext.getCmp('comboDisplayBefore').clearValue();    
    },
    
    initFormValues: function(contact_id, action) {      
      
      if(Ext.getCmp('comboDisplayBefore').store.isFiltered())
        { Ext.getCmp('comboDisplayBefore').store.clearFilter(); }
      
      
      //if an officer is being editted, pre-populate form and lock the Select Name and select committee combos
      if(contact_id != '' && contact_id != '0' && action == 'edit')
      {        
        //select the officer being edditted from the contact list (onselect event not fired)
        Ext.getCmp('comboSelectName').setValue(contact_id);

        //populate the rest of the fields based on the selected name
        populateFromNameSelection(Ext.getCmp('comboSelectName').store.getById(contact_id).data.officer_title,
                    Ext.getCmp('comboSelectName').store.getById(contact_id).data.sec_role_id,
                    Ext.getCmp('comboSelectName').store.getById(contact_id).data.av_sort,
                    Ext.getCmp('comboSelectName').store.getById(contact_id).data.committee_id,
                    action);
        
        Ext.getCmp('comboSelectName').setDisabled(true);          
        Ext.getCmp('comboSelectCommittee').setDisabled(true);             
      }                 
    }
         
          
  } //End return 
} //End object AV.Committee.OfficerForm
