
Ext.ns('Metrosplash', 'Metrosplash.component');
Metrosplash.component.map = Ext.extend(Ext.Panel, 
{
   dataUrl: '/util/dumpLocations-new.php',
   locationTypeUrl: '/generic-requests/mapping.php',
   locationTypeParam: 
   {
      searchType: '1,2,3,4,5,6,7,8'
   },
   initComponent: function()
   {
      Ext.QuickTips.init();
      
      var locationTypes = [];
      var locationMap = [];
      var locations = [];
      
      var gmapPanel = 
      {
         bodyStyle: 'border:1px #D0D0D0 solid; border-top: 0;',
         title: false,
         header: false,
         xtype: 'gmappanel',
         height: 380,
         zoomLevel: 4,
         gmapType: 'map',
         autoWidth: true,
         collapsible: true,
         mapConfOpts: ['disableScrollWheelZoom', 'enableDoubleClickZoom', 'enableDragging'],
         mapControls: ['GSmallMapControl'],
         setCenter: 
         {
            lat: 38,
            lng: -97
         },
         markers: [],
         listeners: 
         {
            gmapuxloaded: 
            {
               scope: this,
               fn: function(gmapPanel)
               {
                  var dataUrl = this.dataUrl;
                  var locationTypeParam = this.locationTypeParam;
                  var callback = gmapPanel.addPointsFromUrl.createDelegate(gmapPanel, [dataUrl, locationTypeParam, true]);
                  this.on('locationtypesloaded', callback, this);
                  
                  // add points
                  var gmap = gmapPanel.getMap();
                  GEvent.bind(gmap, 'zoomend', gmap, function()
                  {
                    gmapPanel.clearAll();
                    callback();
                  });
                  GEvent.bind(gmap, 'dragend', gmap, callback);
               }
            },
            locationsloaded: 
            {
               scope: this,
               fn: function(map, locs)
               {
                  var recordInfo = Ext.data.Record.create(['lat', 'lng', 'html', 'title', 'location_id', 'marker']);
                  var locationCount = locs.length;
                  var gridStore = this.findByType('grid')[0].getStore();
                  gridStore.removeAll();
                  gridStore.proxy.data = [];//locs;
                  for (var x = 0; x < locationCount; x++) 
                  {
                     var record = locs[x].data;
                     gridStore.proxy.data.push([record.lat, record.lng, record.html, record.title, record.location_id, locs[x]]);
                  }
                  gridStore.load(
                  {
                     params: 
                     {
                        start: 0,
                        limit: 5
                     }
                  });
                  this.doLayout();
                  
                  
               }
            }
         }
      
      };
      
      var locationTemplate = Ext.XTemplate.from('location-entry').compile();
      
      var gridStore = new Ext.data.Store(
      {
         proxy: new Ext.ux.data.PagingMemoryProxy(locations),
         reader: new Ext.data.ArrayReader(
         {
            id: 'location_id'
         }, ['lat', 'lng', 'html', 'title', 'location_id', 'marker'])
      });
      
      var locationGrid = 
      {
         bodyStyle: 'border:1px #D0D0D0 solid; border-top: 0;',
         title: false,
         header: false,
         height: 463,
         scrollable: false,
         collapsible: true,
         collapsed: true,
         xtype: 'grid',
         id: 'locationsFound',
         trackMouseOver: false,
         store: gridStore,
         sm: new Ext.grid.RowSelectionModel(
         {
            singleSelect: false
         }),
         viewConfig: 
         {
            forceFit: true
         },
         bbar: new Ext.PagingToolbar(
         {
            store: gridStore,
            pageSize: 5,
            displayInfo: true,
            displayMsg: 'Locations {0} - {1} of {2}',
            emptyMsg: "No locations to display"
         }),
         columns: [
         {
            header: "Merchant",
            dataIndex: 'title',
            align: 'left',
            renderer: function(value, p, record)
            {
               var data = record.data.html.split("|");
               var dataObj = {};
               var fieldCount = data.length;
               var dataItem;
               for (var x = 0; x < fieldCount; x++) 
               {
                  dataItem = data[x].split("=");
                  dataObj[dataItem[0]] = dataItem[1];
               }
               dataObj.location_type = dataObj.location_type_desc;
               var icons = [];
               if (dataObj.can_rollback == "T") 
               {
                  icons.push('<img src="/images/skin2/search/icon-cpg-redemption.gif" />');
               }
               if (dataObj.can_issue == "T") 
               {
                  icons.push('<img src="/images/skin2/search/icon-reward-issue.gif" />');
               }
               if (dataObj.can_redeem == "T") 
               {
                  icons.push('<img src="/images/skin2/search/icon-c4g-redemption.gif" />');
               }
               dataObj.icons = icons.join("&nbsp;&nbsp;&nbsp;");
               dataObj.mapDestination = dataObj.address + " " + dataObj.city + ", " + dataObj.state + " " + dataObj.zipcode;
               dataObj.mapDestination = Ext.urlEncode(dataObj.mapDestination);
               return locationTemplate.apply(dataObj);
            }
         }, 
         {
            dataIndex: 'lat',
            hidden: true
         }, 
         {
            dataIndex: 'lng',
            hidden: true
         }]
      };
      
      var legend = 
      {
         bodyStyle: 'border: 1px #D0D0D0 solid; border-top: 0; padding-bottom: 15px; padding-top: 15px;',
         title: false,
         header: false,
         items: [
         {
            html: '<img src="/images/skin2/search/new-legend-plain.png" title="Legend" />'
         }]
      };
      
      var changeShowHideText = function(button)
      {
         if (button.pressed) 
         {
            button.oldText = button.getText();
            button.setText(button.getText().replace("Show", "Hide"));
         }
         else if (button.oldText != "") 
         {
            button.setText(button.oldText);
         }
      };
      
      var defaultConfig = 
      {
         stateful: true,
         frame: true,
         items: [legend, gmapPanel, locationGrid],
         tbar: ['Find near:', '  ', 
         {
            id: 'locationString',
            xtype: 'textfield',
            name: 'location',
            width: 200,
            style: 'font-size: 11px;',
            selectOnFocus: true,
            disableKeyFilter: true,
            enableKeyEvents: true,
            emptyText: 'Type in your address or zipcode here.',
            listeners: 
            {
               specialkey: 
               {
                  scope: this,
                  fn: function(el, event)
                  {
                     if (event.getKey() == Ext.EventObject.ENTER) 
                     {
                        this.doSearch();
                     }
                  }
               }
            }
         }, ' ', 
         {
            text: 'Find',
            handler: this.doSearch,
            scope: this
         
         }, '->', 
         {
            text: 'Show Legend',
            id: 'legendToggler',
            iconCls: 'legendIcon',
            enableToggle: true,
            pressed: true,
            stateful: true,
            listeners: 
            {
               render: function(button)
               {
                  button.oldText = button.getText();
                  changeShowHideText(button);
               },
               toggle: changeShowHideText
            },
            handler: function(button)
            {
               this.findByType('panel')[0].toggleCollapse(true);
               this.findByType('panel')[0].doLayout();
               if (button.pressed) 
               {
                  this.getTopToolbar().getEl().applyStyles(
                  {
                     "border-bottom": "0"
                  });
               }
               else 
               {
                  this.getTopToolbar().getEl().applyStyles(
                  {
                     "border-bottom": "1px #D0D0D0 solid"
                  });
               }
            },
            scope: this
         }, '  ', 
         {
            text: 'Show Map',
            enableToggle: true,
            id: 'mapToggler',
            iconCls: 'mapIcon',
            pressed: true,
            stateful: true,
            listeners: 
            {
               render: function()
               {
                  this.oldText = this.getText();
                  changeShowHideText(this);
               },
               toggle: changeShowHideText
            },
            handler: function(button)
            {
               this.findByType('gmappanel')[0].toggleCollapse(true);
               this.findByType('gmappanel')[0].doLayout();
            },
            scope: this
         }, '  ', 
         {
            text: 'Show List',
            id: 'listToggler',
            enableToggle: true,
            pressed: false,
            iconCls: 'listIcon',
            stateful: true,
            listeners: 
            {
               render: function(button)
               {
                  button.oldText = button.getText();
                  changeShowHideText(button);
               },
               toggle: changeShowHideText
            },
            handler: function(button)
            {
               this.findByType('grid')[0].toggleCollapse(true);
               this.findByType('grid')[0].doLayout();
            },
            scope: this
         }, ' ', ' ', ' ', '->', 
         {
            text: 'Location Types:',
            tooltip: 'By clicking on this button, you are able to choose the locations you want/don\'t want to see on the map',
            tooltipType: 'qtip',
            menu: 
            {
               items: []
            },
            listeners: 
            {
               render: 
               {
                  scope: this,
                  delay: 100,
                  fn: function(button)
                  {
                     Ext.Ajax.method = 'GET';
                     Ext.Ajax.request(
                     {
                        url: this.locationTypeUrl,
                        callback: function(request, success, response)
                        {
                           var resultObject = Ext.decode(response.responseText);
                           var menu = button.menu;
                           var typeCount = resultObject.data.length;
                           var locationType;
                           for (var x = 0; x < typeCount; x++) 
                           {
                              locationType = resultObject.data[x];
                              var image = '/images/google/icons/icon-' + locationType.location_value + '.png';
                              menu.add(
                              {
                                 text: locationType.display_name, // + '</span>',
                                 checked: true, // when checked has a boolean value, it is assumed to be a CheckItem
                                 id: 'loc-type-' + locationType.location_value,
                                 listeners: 
                                 {
                                    checkchange: 
                                    {
                                       fn: this.onItemCheck,
                                       scope: this
                                    }
                                 },
                                 cls: 'location-type-' + locationType.location_value,
                                 style: 'float: left'
                              });
                              locationTypes.push(locationType.location_value);
                              locationMap[locationType.location_value] = 
                              {
                                 name: locationType.display_name,
                                 short_name: locationType.short_name
                              };
                              
                           }
                           if (this.defaultValue.trim() != "") 
                           {
                              this.setSearchValue(this.defaultValue);
                              this.doSearch();
                           }
                           else 
                           {
                              this.fireEvent('locationtypesloaded', this);
                           }
                           
                        },
                        scope: this,
                        params: 
                        {
                           type: 'location_types'
                        }
                     });
                  }
               }
            }
         }]
      };
      Ext.applyIf(this, defaultConfig);
      Metrosplash.component.map.superclass.initComponent.call(this);
      this.addEvents('locationtypesloaded');
   },
   setSearchValue: function(value)
   {
      var textFieldIndex = 2;
      Ext.getCmp(this.getTopToolbar().items.items[textFieldIndex].id).setValue(value);
   },
   doSearch: function()
   {
      var textFieldIndex = 2;
      var searchString = Ext.getCmp(this.getTopToolbar().items.items[textFieldIndex].id).getValue();
      if (searchString != "") 
      {
         var gmapPanel = this.findByType('gmappanel')[0];
         gmapPanel.centerOnSearch(searchString);
         this.findByType('grid')[0].expand(true);
         Ext.getCmp('listToggler').toggle(true);
      }
   },
   changeShowHideText: function(button)
   {
      if (button.pressed) 
      {
         button.oldText = button.getText();
         button.setText(button.getText().replace("Show", "Hide"));
      }
      else if (button.oldText != "") 
      {
         button.setText(button.oldText);
      }
   },
   // Request more data.
   onItemCheck: function(item, checked)
   {
      //Ext.getCmp('locationMenu').menu.items.items[0].checked
      var items = item.parentMenu.items.items;
      //var items = item.findParentByType('menu').items.items;
      
      var length = items.length;
      var value;
      var checkItem;
      
      locationTypes = [];
      
      var tmp = [];
      
      tmp.push(
      {
         id: item.getId(),
         checked: checked
      });
      
      if (item.checked) 
      {
         locationTypes.push(item.getId().split("-")[2]);
      }
      
      for (var x = 0; x < length; x++) 
      {
         checkItem = items[x];
         value = checkItem.getId().split("-")[2];
         tmp.push(
         {
            id: checkItem.getId(),
            checked: checkItem.checked
         });
         if (checkItem.getId() != item.getId() && checkItem.checked) 
         {
            locationTypes.push(value);
         }
      }
      
      this.locationTypeParam.searchType = locationTypes.join(",");
      var gmapPanel = this.findByType('gmappanel')[0];
      gmapPanel.clearAll();
      gmapPanel.addPointsFromUrl(this.dataUrl, this.locationTypeParam, true);
   }
   
});
Ext.reg('mssggmap', Metrosplash.component.map);

//Ext.extend(Metrosplash.component.map, Ext.Panel);

