 
// reference local blank image
Ext.BLANK_IMAGE_URL = '/js/ext/resources/images/default/s.gif';
 
// create namespace
Ext.namespace('OCA');
 
// create application
OCA.app = function() {
  // do NOT access DOM from here; elements dont exist yet
 
  // private variables

  var grid;
  var resultsPanel;
  var gridFooter;
  var proxy;
  var httpProxy;
  var rsMetadata;
  var recordMetadata;
  var jsonReader;
  var dataStore;
  var columnModel;
  var searchForm;
  var searchFormPanel;
  var tabPanel;
  var pagingToolbar;
  var campTab;
  var activityFieldset;
  var searchResultsPerPage = 10;

  
  // private functions
  function initSearchForm(json) {
    var residentialStore = new Ext.data.SimpleStore({ fields: ['residential', 'residential_label'], data: [[0,'Any'],[1,'Day'],[2,'Resident']] });
    var residentialComboBox = new Ext.form.ComboBox({
      store: residentialStore,
      name: 'residential',
      id: 'residential',
      editable: false,
      disableKeyFilter: true,
      mode: 'local',
      triggerAction: 'all',
      fieldLabel: 'Day / Resident',
      value: 'Any',
      displayField: 'residential_label',
      anchor:'95%'

    });
    var genderStore = new Ext.data.SimpleStore({ fields: ['gender', 'gender_label'], data: [['any', 'Any'], ['boy', 'Boys Only'], ['girl','Girls Only'], ['coed', 'Coed'], ['family', 'Family']] });
    var genderComboBox = new Ext.form.ComboBox({
      store: genderStore,
      name: 'gender',
      id: 'gender',
      editable: false,
      mode: 'local',
      triggerAction: 'all',
      value: 'Any',
      fieldLabel: 'Camp Type',
      displayField: 'gender_label',
      anchor:'95%'
    });

    var regionStore = new Ext.data.JsonStore({
      url: '/regions_json',
      root: 'rows',
      fields: ['id', 'name']
    });
    var regionsComboBox = new Ext.form.ComboBox({
      store: regionStore,
      name: 'region',
      id: 'region',
      editable: false,
      triggerAction: 'all',
      emptyText: 'Select...',
      fieldLabel: 'Regions',
      displayField: 'name',
      valueField: 'id',
      value: 'Any',
      hiddenName: 'region_id',
      anchor:'95%',
      width: 270
    });
    var specialNeedsStore = new Ext.data.JsonStore({
      url: '/special_needs_json',
      root: 'rows',
      fields: ['id', 'name']
    });
    var specialNeedsComboBox = new Ext.form.ComboBox({
      store: specialNeedsStore,
      name: 'special_needs',
      id: 'special_needs',
      editable: false,
      triggerAction: 'all',
      emptyText: 'Select...',
      fieldLabel: 'Special Needs',
      displayField: 'name',
      valueField: 'id',
      value: 'Any',
      hiddenName: 'special_need_id',
      anchor:'95%',
      width: 270
    });

    activityFieldSet = new Ext.form.FieldSet({
      xtype:'fieldset',
      id: 'activities_fieldset',
      title: 'Activities',
      collapsible: true,
      autoHeight:true,
      defaults: {autoHeight: true},
      collapsed: true
    });
    initActivities(activities_json);
    searchFormPanel = new Ext.FormPanel({
      renderTo: 'search_form',
      frame: true,
      title: 'Find a Camp',
      bodyStyle:'padding:5px 5px 0',
      width: 710,
      items: [{ 
        layout: 'column',
        items: [{
          columnWidth: .45, 
          layout: 'form', 
		      items: [ { xtype: 'textfield', fieldLabel: 'Camp Name', name: 'name', id: 'name', width: 180, anchor: '95%' }, residentialComboBox, genderComboBox ]
        }, {
          columnWidth: .55, 
          layout: 'form', 
		      items: [ regionsComboBox, specialNeedsComboBox,  { layout: 'column', items: [{ columnWidth: .5, layout: 'form', items: [{ xtype: 'numberfield', fieldLabel: 'Age', name: 'age', id: 'age', width: 30, anchor: '95%'}]}, { columnWidth: .5, layout: 'form', items: [{ xtype: 'checkbox', fieldLabel: 'Has Subsidies', name: 'has_subsidies', itemCls: 'fix_checkbox'}]}]} ]
        }] 
      }, activityFieldSet ],
      buttons: [{ text: 'Search', handler: submitSearch }]
    });

    searchForm = searchFormPanel.getForm();
  }

  function initDataStore() {
    httpProxy = new Ext.data.HttpProxy({ url: '/camp_search/' });
    rsMetadata = { root:'rows', totalProperty:'count', id:'id' };
    recordMetadata = [ {name: 'id'}, {name: 'name'}, {name: 'region'}, {name: 'is_residential'}, {name: 'ages_served'}, {name: 'tagline' }, {name: 'gender_list'}, {name: 'activity_list'}, {name: 'capacity'}, {name: 'short_description'} ];
    jsonReader = new Ext.data.JsonReader(rsMetadata, recordMetadata);
    dataStore  = new Ext.data.Store({
      proxy: httpProxy,
      reader: jsonReader,
      remoteSort: true
    });
    dataStore.addListener('load', setBaseParams, OCA.app);
  }
  
  function initPager() {
    pagingToolbar = new Ext.PagingToolbar({
      pageSize: searchResultsPerPage,
      store: dataStore,
      displayInfo: true,
      displayMsg: 'Camps {0} - {1} of {2}',
      emptyMsg: 'No camps to display'
    });
  }
  
  function initCampPanel() {
    var tpl = new Ext.XTemplate(
      '<tpl for=".">',
        '<div class="search_line_item">',
      '<b><a href="#top" onclick="OCA.app.showCamp({id})">{name}</a></b>',
      '<tpl if="tagline">  &#149; {tagline}</tpl>',
      '<p>',
      '<tpl if="is_residential">Residential</tpl>',
      '<tpl if="is_residential == false">Day</tpl>',
      '<tpl if="region"> &#149; {region}</tpl>',
      '<tpl if="gender_list"> &#149; {gender_list}</tpl>',
      '<tpl if="ages_served"> &#149; ages {ages_served}</tpl>',
      '<tpl if="capacity"> &#149; capacity: {capacity}</tpl>',
      '<br>',
      '{activity_list}',
     '</p>',
        '</div>',
      '</tpl>',
      '<div class="x-clear"></div>'
    );
      
    var dataView = new Ext.DataView({
      store: dataStore,
      tpl: tpl,
      loadingText: 'Loading...',
      autoHeight:true,
      overClass:'x-view-over',
      itemSelector:'div.search-line-item'
    });
      
    resultsPanel = new Ext.Panel({
      frame:true,
      width:710,
      autoHeight:true,
      layout:'fit',
      title:'Camp Search Results',
      //items: dataView
      items: [ dataView, pagingToolbar ]
    });
  }
  
  function initTabPanel() {
    tabPanel = new Ext.TabPanel({
      //renderTo: Ext.getBody(),
      renderTo: 'tab_panel',
      autoHeight:true,
      defaults: { autoHeight: true, xautoScroll: true },
      frame: true,
      items: resultsPanel,
      resizeTabs: true,
      minTabWidth: 125,
      tabWidth: 145,
      enableTabScroll: true,
      plugins: new Ext.ux.TabCloseMenu(),
      activeTab: 0
    });
  }

  function initTabPanel2() {
    tabPanel = new Ext.TabPanel({
      //renderTo: Ext.getBody(),
      renderTo: 'tab_panel',
      //height: 100,
      defaults: { autoHeight: true },
      width: 710,
      frame: true,
      items: [ { title:'Camp Search Results', html:'<b>foo</b>'}, { title:'Camp Metarthythm', html:'<b>metarhythm</b>'} ],
      //items: [ {contentEl:'script', title: 'Short Text'}, {contentEl:'markup', title: 'Long Text'} ],
      activeTab: 0
    });
    //tabPanel.render('foo');
  }

  function setBaseParams() {
    var searchParams = getSearchParams();
    dataStore.baseParams = searchParams;
  }
  
  function getCheckedActivityIds() {
    var fieldSet = Ext.getCmp('activities_fieldset');
    var boxes = fieldSet.findByType('checkbox');
    var activityIds = new Array();
    var i = 0;
    Ext.each(
      boxes, 
      function(item, index, allItems) { 
        if (item.getValue()) { 
          activityIds[i++] = item.getId(); 
        }
      }
    ); 
    return activityIds;
  }
  
  function getSearchParams() {
    var searchParams = new Object();
    searchParams['name'] = searchForm.findField('name').getValue();
    searchParams['region'] = searchForm.findField('region').getValue();
    searchParams['special_needs'] = searchForm.findField('special_needs').getValue();
    searchParams['residential'] = searchForm.findField('residential').getValue();
    searchParams['gender'] = searchForm.findField('gender').getValue();
    searchParams['age'] = searchForm.findField('age').getValue();
    searchParams['has_subsidies'] = searchForm.findField('has_subsidies').getValue();
    var activityIds = getCheckedActivityIds();
    searchParams['activities'] = activityIds;
    return searchParams;
  }
  function submitSearch() {
    var searchParams = getSearchParams();
    searchParams['start'] = 0;
    searchParams['limit'] = searchResultsPerPage;
    dataStore.baseParams = searchParams;
    tabPanel.getComponent(0).show();
    dataStore.load();
  }
 
  function initActivities(json) {
    var numColumns = 4;
    //var activitiesPerColumn = parseInt((json.activities.size - 1) / numColumns); 
    for (i = 0; i < json.activities.length; i++) {
      var activityGroup = json.activities[i];
      if (activityGroup['name']) {
        var groupFieldSet = new Ext.form.FieldSet({
          xtype:'fieldset',
          title: activityGroup['name'],
          collapsible: true,
          collapsed: true,
          autoHeight:true,
          defaultType: 'checkbox',
          layout: 'column',
          width: 664,
          hideBorders: true          
        });
        var activities = activityGroup['activities'];
        var panels = [ 
          new Ext.form.FieldSet({ width: 160, border: false, autoHeight: true }), 
          new Ext.form.FieldSet({ width: 160, border: false }), 
          new Ext.form.FieldSet({ width: 160, border: false }), 
          new Ext.form.FieldSet({ width: 160, border: false })
        ];
        for (j = 0; j < activities.length; j++) {
          if (activities[j]['name']) {
            var k = j % numColumns;
            panels[k].add(new Ext.form.Checkbox({ id: activities[j]['id'], boxLabel: activities[j]['name'], labelSeparator: '' }));
          }
        }
        groupFieldSet.add(panels[0]);
        groupFieldSet.add(panels[1]);
        groupFieldSet.add(panels[2]);
        groupFieldSet.add(panels[3]);
        activityFieldSet.add(groupFieldSet);
      }
    }
  }
  

  
  // public space
  return {
    // public properties, e.g. strings to translate
          
    // public methods
    init: function() {
      //alert('Application successfully initialized');
      initDataStore();
      initPager();
      initCampPanel();
      initTabPanel();
      initSearchForm();
    },
    setSearchParams: function(params) {
      httpProxy.conn.extraParams = params;
    },
    showCamp: function(id) {
      //if (campTab) {
       // campTab.load({url: '/camps/', params: { id: id, no_wrap: 1 } });
        //campTab.setTitle(dataStore.getById(id).get('name'));
       // campTab.show();
      //}
      //else {
        var campTab = new Ext.Panel({
          title: dataStore.getById(id).get('name'),
          autoLoad: {url: '/camps/', params: { id: id, no_wrap: 1 }, callback: addCampSubmenuHandler },
          closable: true
        });
        tabPanel.add(campTab).show();
        

      //}
    }
  };
}(); // end of app

Ext.onReady(OCA.app.init, OCA.app);

