$(function() { 
	      	var Maps = new function() {
	      	  var priv = {
				settings: {
				  root: $('#logo').attr('href'),
				  map: null,
				  defaultPos: [37.3, -96.5],
				  selectors: { map: '#search-map' },
				  handler: 'extensions/com/adverts/AdvertAjaxGateway.cfc',
				  locations: {},
				  used: [],
				  ids: []
				},	      	    
	      	    
	      	    init: function() {	      	
		      	  try {
				    if (GBrowserIsCompatible && GBrowserIsCompatible() && $(this.settings.selectors.map).length) {

		      	  	  this.settings.$map = $(this.settings.selectors.map).html('<h1><span class="e">Loading map...</span></h1>');
		      	  	  this.settings.$form = this.settings.$map.next();
		      	  	  this.settings.$results = $(this.getResultsHTML());
		      	  	  this.settings.$map.after(this.settings.$results);
			        
			          $(window).bind('unload', GUnload);
			        }
				  } catch (e) { };
	      	    },
	      	    build: function() {	      	      
	      	      this.settings.map = new GMap2(this.settings.$map[0]);

	      	      this.settings.map.enableDoubleClickZoom();
	      	      this.settings.map.enableScrollWheelZoom();

	      	      this.settings.map.addControl(new GLargeMapControl());
	      	      this.settings.map.addControl(new GMapTypeControl());
			      this.settings.map.setCenter(new GLatLng(this.settings.defaultPos[0], this.settings.defaultPos[1]), 4);
			      
			      this.initControls();			      
			      this.getLocations();
	      	    },      	    
	      	    plot: function(d) {
	      	      $.each(
	      	        d,
	      	        function(i, n) {				      
				      var k = n.city_latitude + ',' + n.city_longitude;
				      
				      if (!priv.settings.locations[k]) {
				        priv.settings.locations[k] = [];
				      }
				      
				      priv.settings.locations[k].push(n);
	      	        }
	      	      );
	      	      
	      	      $.each(
	      	        this.settings.locations,
	      	        function(i, n) {
	      	          var j = 0;
	      	          var p = i.split(',');
	      	          var m = new GMarker(new GLatLng(p[0], p[1]));
	      	          var s = '';
	      	          var o = null;
	      	          
	      	          for (; j < this.length; j++) {
	      	            o = this[j];
	      	            if (!j) {
	      	              s += '<h1>' + o.city_name + ', ' + o.county_name + ', ' + o.state_name + ', ' + o.country_name + '</h1>';
	      	            }
	      	            s += '<p' + (j == this.length - 1 ? ' style="margin:0px; padding:0px;"' : '') + '>' + o.advert_title + '<br /><a href="javascript:;" class="search-map-add-link" rel="' + i + '|' + j + '">Click here</a> to add to search group.</p>';
	      	          }
	      	           
	      	          priv.settings.map.addOverlay(m);
		      	          
		      	      GEvent.addListener(m, 'click', function() {
					    m.openInfoWindowHtml(s);
					    
					    priv.initAdd();
					  });	      	            
	      	        }
	      	      );
	      	    },
	      	    initControls: function() {
	      	      this.settings.$form.html('<div><input type="hidden" name="advert_id" /><input type="submit" value="Display Results" class="btn" /></div>');
	      	      this.settings.$message = $('span.e-m', $('input[@type=submit]', this.settings.$form).after('<span class="e-m"></span>').end()).hide();
	      	      this.settings.$form.bind(
	      	        'submit',
	      	        function(e) {
	      	          var er = true;
	      	          
	      	          $('input[@name="advert_id"]').val(priv.settings.ids.join(','));
	      	          
	      	          er = priv.settings.used.length == 0;
					  er ? priv.settings.$message.html('Please select at least one listing').fadeIn('fast') : priv.settings.$message.fadeOut('fast');
					  return !er;  	      	          
	      	        }
	      	      );	
	      	    },
	      	    initAdd: function() {
	      	      $('a.search-map-add-link', this.settings.map).bind(
	      	        'click', 
	      	        function(e) { 
	      	          priv.add(this);
	      	          return false;   
	      	        }
	      	      );
	      	    },
	      	    initRemove: function(el) {
	      	      el.onclick = function(e) { 
	      	        priv.remove(el);
	      	        return false;   
	      	      };
	      	    },	      	    
	      	    add: function(el) {
	      	      var p = el.rel.split('|');
	      	      var i = this.settings.locations[p[0]][p[1]];
	      	      var $r = null;

	      	      if (this.isUsed(el.rel) == -1) {	      	      	
	      	        this.fixResultHTML('add');
	      	        this.addUsed(el.rel, i.advert_id);	      	        
	      	        	      	      	
	      	        $r = $(this.getRow('row')).html('<h1>' + i.advert_title + '</h1><p>' + i.advert_short_description + '<br /><a href="javascript:;" class="search-map-remove-link" rel="' + el.rel + '">Click here</a> to remove from search group.</p>');
	      	      
	      	        this.settings.$results.append($r);
	      	        this.initRemove($('a.search-map-remove-link', $r)[0]);	      	        
	      	      }
	      	    },
	      	    remove: function(el) {
	      	      var p = el.rel.split('|');
	      	      var i = this.settings.locations[p[0]][p[1]];

	      	      if (confirm('Are you sure you want to remove this from your search selections?')) {
	      	        this.removeUsed(el.rel, i.advert_id);	      	      	
	      	        this.fixResultHTML('remove');
	      	        
	      	        try {
	      	          $(el).parent().parent().remove();
	      	        } catch (e) {}
	      	        
	      	        this.fixRowsColors();	      	      
	      	      }
	      	    },
	      	    isUsed: function(k) {
	      	      return $.inArray(k, this.settings.used);
	      	    },
	      	    addUsed: function(k, id) {
	      	      if (this.isUsed(k) == -1) {
	      	      	this.settings.used.push(k);
	      	      	this.settings.ids.push(id);
	      	      }
	      	    },
	      	    removeUsed: function(k, id) {
	      	      var p = this.isUsed(k); 
	      	      if (p != -1) {
	      	        this.settings.used.splice(p, 1);
	      	        this.settings.ids.splice(p, 1);
	      	      }
	      	    },
	      	    fixRowsColors: function() {
	      	      $('> div', this.settings.$results).attr('class', '').filter(':even').addClass('one').end().filter(':odd').addClass('two');
	      	    },	
	      	    fixResultHTML: function(t) {
	      	      switch (t) {
	      	        case 'add': {
	      	          if (!this.settings.used.length) {
	      	            this.settings.$results.html('');
	      	          }	      	        	
	      	          break;
	      	        }
	      	        case 'remove': {
	      	          if (!this.settings.used.length) {
	      	            this.settings.$results.html(this.getRow('init'));
	      	          }	      	        	
	      	          break;
	      	        }	      	        
	      	      }	      	      
	      	    },      	    
	      	    getResultsHTML: function(t) {
	      	      return '<div class="recordset">' + this.getRow('init') + '</div>';
	      	    },
	      	    getRow: function(t) {
	      	      switch (t) {
	      	        case 'row': {
	      	          return '<div class="' + ($('div.one, div.two', this.settings.$results).length % 2 == 0 ? 'one' : 'two') + '"></div>';
	      	        }
	      	        case 'init': {
	      	          return '<div class="one"><h1>Waiting...</h1><p>Please browse the map to add desired loactions to your result set.</p></div>';
	      	        }
	      	        default: {
	      	          return '<div class="one"></div>';
	      	        }	      	        
	      	      }
	      	    },
	      	    getLocations: function() {
	      	      $.getJSON(
	      	        this.settings.root + this.settings.handler + '?method=init&methodname=map',
	      	        function(JSON) {
	      	          priv.plot(JSON);
	      	        }
	      	      );
	      	    }
	      	  };
	      	  
	      	  this.init = function() {
	      	    priv.init();
	      	  
	      	    $('ul.tabs-nav > li a:eq(2)').one('click', function() {
	      	      setTimeout(function() { priv.build(); }, 1000);
	      	    });

	      	    return this;
	      	  };	
	      	};

	      	Maps.init();
	      });