mainVenue = function() {
  return {

    // ========
    // = Vars =
    // ========

    map                        : {},            // Hash containing references to the Google Maps objects
    when                       : '7days',       // Starting day for data retrieval
    page                       : 1,             // Default page for results
    sport                      : 'all',         // Default sports
    city                       : null,          // Current city
    conn                       : null,          // Connection obj
    eventData                  : null,          // Event data
    perPage                    : 10,            // Events per page
    categories                 : null,          // List of Sports
    mapData                    : null,          // List of icons for the map
    photoSmall                 : null,          // Empty profile photo (small)
    pastGames                  : false,         // Searching for past events?
    showCreateAccountDialog    : false,         // Show create account dialog?
    emailFrom                  : null,          // Email sent from?

    // ===========
    // = Methods =
    // ===========

    initMainIndex : function() {
      
      // Init the map
      
      main.initMap();
      
      // Init the tabs
      
      $('#dayTabs li a').click(function(e) {
        e.preventDefault();
        e.target.blur();        

        $('#dayTabs li').removeClass('selected');
        if (main.when != e.target.parentNode.className) {
          main.page = 1;
          main.when = e.target.parentNode.className;
          main.getData();
          
          // Set the hash
          window.location.hash = main.when
        }
        $(e.target.parentNode).addClass('selected');
      });
      
      // See if tab is passed in the hash
      
      var hash = window.location.hash;
      if (hash == '#today' || hash == '#tomorrow' || hash == '#weekend' || hash == '#7days') {
        main.when = hash.replace('#', '');
      }
      
      // Select the selected tab
      
      $('#dayTabs li.' + main.when).addClass('selected');
      
      // Get the initial data

      main.getData();
      
      // Init Pagination
      
      $('div.eventResults div.pagination div.second p').click(function(e) {
        if (e.target.tagName != 'A') {
          return;
        }

        e.preventDefault();
        var page = $(e.target).blur().text();
        
        switch (page) {
          case 'Previous':
            main.page--;
            break;
          case 'Next':
            main.page++;
            break;
          default:
            main.page = page * 1;
        }
        
        main.getData();
      });
      
      // Init Sports drop down
      
      $('div.eventResults div.title div.second select').change(function(e) {
        var val = $(this).blur().val();
        main.sport = (val == 'all') ? val : (val * 1);
        main.page = 1;
        main.getData();
      });
      
      // Init the switch city drop down
      
      $('#cityTitle span').mouseover(function(e) {
        $(this).addClass('hover');
      }).mouseout(function(e) {
        $(this).removeClass('hover');
      }).click(function(e) {
        main.showCityDD();
      });
      $('#cityDD h3').click(function(e) {
        main.hideCityDD();
      });
      
      // Show account creation dialog?
      
      if (main.showCreateAccountDialog === true) {
        main.initCreateAccountDialog();
      }

    },

    initMainSteelcity : function() {
      main.sport = 41;
      main.initMainIndex();
    },
    
    initMainPastGames : function() {
      
      main.pastGames = true;
      
      // Init the map
      
      main.initMap();
      
      // Get the initial data

      main.getData();
      
      // Init Pagination
      
      $('div.eventResults div.pagination div.second p').click(function(e) {
        if (e.target.tagName != 'A') {
          return;
        }

        e.preventDefault();
        var page = $(e.target).blur().text();
        
        switch (page) {
          case 'Previous':
            main.page--;
            break;
          case 'Next':
            main.page++;
            break;
          default:
            main.page = page * 1;
        }
        
        main.getData();
      });
      
      // Init Sports drop down
      
      $('div.eventResults div.title div.second select').change(function(e) {
        var val = $(this).blur().val();
        main.sport = (val == 'all') ? val : (val * 1);
        main.page = 1;
        main.getData();
      });

    },
    
    initMap : function() {
      if (GBrowserIsCompatible()) {
        main.map.map = new GMap2(document.getElementById("resultsMap"));
        main.map.map.setCenter(new GLatLng(main.city.latitude, main.city.longitude), 13);
        main.map.map.setUIToDefault();

        main.map.markerMgr = new MarkerManager(main.map.map, { 'trackMarkers' : true });
        main.map.geocoder = new GClientGeocoder();
        main.map.mapIcon = new GIcon(G_DEFAULT_ICON);
      }
    },
    
    addressSearch : function(e) {
      $(e.target).attr('disabled', true).val('Searching...').blur();

      main.map.geocoder.getLatLng($('#location input[type=text]').val(), function(point) {
        $(e.target).attr('disabled', false).val('Lookup the Address');
        $('#location p span.error').remove();

        if (!point) {
          $('#location p').append($('<span/>').addClass('error').html('Could not find the address'));
        } else {
          main.map.map.setCenter(new GLatLng(point.lat(), point.lng()), 15);
        }
      });
    },
    
    getData : function() {
      
      // Hide divs
      
      $('div.eventResults div.pagination, div.eventResults ul.results').css('display', 'none');
      $('div.eventResults h4.title').text('Loading...').addClass('loading');
      
      // Get params
      
      var params = {
        'limit' : main.perPage,
        'page' : main.page,
        'sport' : main.sport,
        'includePlayers' : 'true'
      };
      
      if (main.pastGames === true) {
        params['pastGames'] = 'true';
      } else {
        params['when'] = main.when;
      }
      
      var url = main.links.getEventsLink;
      
      // Make the call
      
      if (main.conn) {
        main.conn.abort();
      }
      
      main.conn = $.getJSON(url, params, function(data) {
        if (data.error) {
          return;
        }
        main.eventData = data;
        
        main.processPagination();
        main.processResults();
      });
      
    },
    
    processPagination : function() {
      
      // Results
      
      if (main.eventData.totalResults === 0) {
        $('div.eventResults div.pagination div.first p').html('No pickup games found. <a href="' + main.links.createEventLink + '">Start a game now!</a>');
        $('div.eventResults div.pagination').css('display', 'block');
        return;
      }

      var start = (this.page - 1) * this.perPage + 1;
      var end = Math.min(start + this.perPage - 1, main.eventData.totalResults);
      var title = 'Showing ' + start + '-' + end + ' of ' + main.eventData.totalResults;
      $('div.eventResults div.pagination div.first p').html(title);
      
      // Pages

      var parts = [];
      var totalPages = Math.ceil(main.eventData.totalResults / main.perPage);

      if (main.page === 1) {
        parts[parts.length] = '<span>Previous</span>';
      } else {
        parts[parts.length] = '<a href="#" class="previous">Previous</a>';
      }

      var i, pages = [];
      if (totalPages <= 6) { // Ex: 1, 2, 3, 4, 5
        for (i=1; i<=totalPages; i++) {
          pages[pages.length] = i;
        }
      } else if (totalPages > 6 && (main.page <= 2 || main.page >= (totalPages - 3))) { // Ex: 1, 2, 3, ... 70, 71, 72
        pages[pages.length] = 1;
        pages[pages.length] = 2;
        pages[pages.length] = 3;
        pages[pages.length] = "sep";
        pages[pages.length] = totalPages - 2;
        pages[pages.length] = totalPages - 1;
        pages[pages.length] = totalPages;
      } else { // Ex: 1, ... 13, 14, 15, ... 72
        pages[pages.length] = 1;
        pages[pages.length] = "sep";
        pages[pages.length] = main.page;
        pages[pages.length] = main.page + 1;
        pages[pages.length] = main.page + 2;
        pages[pages.length] = "sep";
        pages[pages.length] = totalPages;
      }

      for (i=0; i<pages.length; i++) {
        if (pages[i] == "sep") {
          parts[parts.length] = '<span>...</span>';
        } else {
          if (pages[i] == main.page) {
            parts[parts.length] = '<span>' + pages[i] + '</span>';
          } else {
            parts[parts.length] = '<a href="#">' + pages[i] + '</a>';
          }
        }
      }

      if (main.page == totalPages) {
        parts[parts.length] = '<span>Next</span>';
      } else {
        parts[parts.length] = '<a href="#" class="next">Next</a>';
      }
      
      if (parts.length > 3) {
        $('div.eventResults div.pagination div.second p').html(parts.join(''));
      }
      $('div.eventResults div.pagination').css('display', 'block');
    },
    
    processResults : function() {
      
      // Process the title
      
      $('div.eventResults h4.title').removeClass('loading').html(main.getResultsTitle());
      
      // Process each event
      
      $('div.eventResults ul.results').empty();
      
      main.mapData = {};
      
      var event, li, div, div2, players, o;
      for (var i=0; i<main.eventData.results.length; i++) {
        
        event = main.eventData.results[i];

        // Add to HTML
        
        li = $('<li/>').attr('id', 'event_' + event.id).addClass('clearfix');
        if (event.category_id == 41) {
          li.addClass('steelcity');
        }
        div = $('<div/>').addClass('info').appendTo(li);
        div.append($('<p/>').addClass('category').html(event.category.name));
        div.append($('<p/>').addClass('venue').html($('<a/>').attr('href', main.links.showVenueLink.replace('/ID', '/' + event.venue_id)).text(event.venue.name)));
        div.append($('<p/>').addClass('neighborhood').text(event.neighborhood.name));
        
        div2 = $('<div/>').addClass('when').appendTo(li);
        div2.append($('<p/>').addClass('time').html(event.happening_at_time));
        if (event.happening_today === true) {
          div2.addClass('today');
          div2.append($('<p/>').addClass('weekday').html('Today!'));
        } else {
          div2.append($('<p/>').addClass('weekday').html(event.happening_at_weekday));
        }
        div2.append($('<p/>').addClass('day').html(event.happening_at_day));
        div2.append($('<p/>').addClass('month').html(event.happening_at_month));
        
        li.append($('<h5/>').append($('<a/>').attr('href', main.links.showEventLink.replace('/ID', '/' + event.id)).text(event.title)));
        // li.append($('<p/>').addClass('date').text(event.happening_at));
        li.append($('<p/>').addClass('description').html(event.description));

        players = $('<p/>').addClass('players').addClass('clearfix');
        for (o=0; o<event.player_count; o++) {
          if (event.players[o].id !== null) {
            players.append($('<a/>').addClass('profileSmallLink').attr('username', event.players[o].username).attr('href', main.links.showProfileLink.replace('ID', event.players[o].id)).append($('<img/>').attr('src', (event.players[o].photo_small === null ? main.photoSmall : event.players[o].photo_small)).attr('height', 42).attr('width', 42)));
          } else {
            players.append($('<span/>').append($('<img/>').attr('src', main.photoSmall).attr('height', 42).attr('width', 42)));
          }
        }
        li.append(players);
        
        $('div.eventResults ul.results').append(li);
        
        // Add market to map
        
        if (typeof main.mapData[event.venue_id] != 'undefined') {
          main.mapData[event.venue_id].count = main.mapData[event.venue_id].count + 1;
        } else {
          main.mapData[event.venue_id] = {
            'count' : 1,
            'id' : event.venue_id,
            'name' : event.venue.name,
            'description' : event.venue.description,
            'latitude' : event.venue.latitude,
            'longitude' : event.venue.longitude
          };
        }
        
      }
      
      // Add results to the map
      
      main.map.markerMgr.clearMarkers();
      var bounds = new GLatLngBounds();
      var marker, point;
      
      for (var venueId in main.mapData) {
        if (typeof(main.mapData[venueId]) != 'function') {
          point = new GLatLng(main.mapData[venueId].latitude, main.mapData[venueId].longitude);
          marker = main.addMapMarker(main.mapData[venueId], point);
  				main.map.markerMgr.addMarker(marker, 3);
  				bounds.extend(point);
        }
      }
      
			// Show the markers, re-center and zoom out enough to show them all

      if (main.eventData.results.length === 0) {
        main.map.map.setCenter(new GLatLng(main.city.latitude, main.city.longitude), 13);
      } else {
        main.map.markerMgr.refresh();
        main.map.map.setZoom(main.map.map.getBoundsZoomLevel(bounds) - 1);
        main.map.map.setCenter(bounds.getCenter());
      }
      
      $('div.eventResults ul.results').css('display', 'block');
      
    },
    
    getResultsTitle : function() {
      
      var title = main.eventData.totalResults;
      title = title + ' ' + (main.sport == 'all' ? 'pickup' : main.categories[main.sport]) + ' ' + (main.eventData.totalResults == 1 ? 'game' : 'games');
      if (main.pastGames === false) {
        switch (main.when) {
          case 'today':
            title = title + ' Today';
            break;
          case 'tomorrow':
            title = title + ' Tomorrow';
            break;
          case 'weekend':
            title = title + ' this Weekend';
            break;
          case '7days':
            title = title + ' Next 7 days';
            break;
        }
      } else {
        title = title + ' played';
      }
      
      title = title + ' in ' + main.city.name;
      
      return title;
      
    },
    
    addMapMarker : function(venue, point) {
			var marker = new GMarker(point, { 'title' : venue.name, 'icon' : main.map.mapIcon, 'draggable' : false });

      GEvent.addListener(marker, 'click', function() {
       var url = main.links.showVenueLink.replace('ID', venue.id);
       marker.openInfoWindow('<span class="gmap-info"><strong>' + venue.name + '</strong><br />' + venue.count + ' ' + (venue.count == 1 ? 'game' : 'games') + '<br/><a href="' + url + '">&raquo; Venue Details</a></span>');
      });
			
			return marker;
		},
		
		showCityDD : function() {
      var offset = $('#cityTitle span').offset();
      var top;
      if (jQuery.browser.safari !== false) {
        top = offset.top - 6;
      } else {
        top = offset.top - 7;
      }
      var left = offset.left - 11;
      $('#cityDD').stop().css({
        'top' : top + 'px',
        'left' : left + 'px',
        'opacity' : 0,
        'display' : 'block'
      }).animate({opacity:1}, 200);
      setTimeout(function() {
        $(document.body).click(main.hideCityDD);
      }, 10);
    },
    
    hideCityDD : function() {
      $(document.body).unbind('click', main.hideCityDD);
      $('#cityDD').stop().animate({opacity:0}, 200, function() {
        $('#cityDD').css({
          'opacity' : 1,
          'display' : 'none'
        });
      });
    },
    
    initMainPlayers : function() {
      $('#players .player .img-container .stats').each(function(index, item) {
        $(this).css('height', ($('img', item.parentNode).height() - 10) + 'px').css('opacity', .9);
      }).mouseout(function(e) {
        var parents = $(e.relatedTarget).parents();
        for (var i=0; i<parents.length; i++) {
          if (parents[i] == this.parentNode) {
            return;
          }
        }
        $(this).css('display', 'none');
      }).click(function(e) {
        var id = $(this.parentNode.parentNode).attr('id').replace('player_', '');
        window.location = main.links.showProfileLink.replace('ID', id);
      });
      
      $('#players .player .img-container img').mouseover(function(e) {
        $('.stats', e.target.parentNode.parentNode).css('display', 'block');
      });
      
      // Order Dropdown
      
      $('#order').change(function(e) {
        window.location = main.links.playersLink + '?o=' + $('#order').val();
      });

    },
    
    initCreateAccountDialog : function() {
      $('<div/>').html('<h4>Congratulations! Your player account has been created</h4><p>You can now browse and join any of the pickup sports games!</p><p><strong>However, you must verify your account to be able to do things like:</strong></p><ul><li>Create your own pickup games</li><li>Receive daily or weekly alerts to be notified of new games</li><li>Receive notifications of new comments on games you\'ve joined and on your profile</li></ul><p>You can verify your account by clicking the verification link in an email that we\'ve sent to you from <strong>' + main.emailFrom + '</strong></p><p>Please check your <em>SPAM</em> folder if you don\'t receive the Welcome email.</p>').dialog({
        'modal' : true,
        'title' : 'Welcome to Pickupalooza.com',
        'dialogClass' : 'dialogCreateAccount',
        'width' : '500px',
        'buttons' : {
          'Start playing games!' : function() {
            $(this).dialog("close");
          }
        }
      });
    }
    
  };
}();

jQuery.extend(main, mainVenue);