var map = null;
var selectedLocation = null;
var locations = [];
var teams = {};
var curTeam = null;
var curLoc = null;

Function.prototype.bind = function() {
  if (arguments.length < 2 && arguments[0] === undefined) return this;
  var __method = this, args = $.makeArray(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($.makeArray(arguments)));
  }
};

$(function() {
  map = new TbiMap('#map', locations);
  
  /* jump to texas */
  $('#texas_link').click(function() {
    map.showTexas();
    
   selectTexasToggle();
          
    return false;
  });
  
  /* jump to zona */
  $('#arizona_link').click(function() {
    map.showArizona();
    
    selectArizonaToggle();
    
    return false;
  });
  
  $('#map_teams').click(function(event) {
    var element = $(event.target);
    
    if(element.attr('nodeName') == 'SPAN') {
      if(element.parent('span')) {
        element = element.parent('span').parent('a');
      }
      else {
        element = element.parent('a');
      }
    }
    
    /* when we click a team name... */
    if(element.attr('nodeName') == 'A') {var team = element.attr('id').split('_')[1];
      
      /* if the location is selected, then show the doctors popup */
      if(element.hasClass('enabled')) {        
        var location = selectedLocation == null ? 'all' : selectedLocation.id;      
        
        showPopupForTeamAndLocation(team, location);
      }
      else if(element.hasClass('closer')) {
        closeTeamInfo();
      }
      else if(element.hasClass('location')) {
        var i = element.attr('href').split('#')[1];
        var location = locations[i];
        var address = '<dl class="address">' + $('#location_' + location.id).html() + '</dl>';
        
        address += ' <a href="#" class="view_doctors">View ' + location.name + ' ' + $('#team_locations_note').text() + '</a>';
        
        map.showLocationBubble(location, location.marker);
  
        curLoc = location.id;
      }
      /* if a location is not selected, show the locations that have this team */
      else if(!element.hasClass('disabled')) {
        var texasLocations = [];
        var arizonaLocations = [];
        
        map.showTexas();
        
        element.blur();
                
        if(curTeam != null) {
          if(curTeam == team) {
            closeTeamInfo();
            
            return false;
          }
          else {
            $('#team_' + curTeam).removeClass('open');
            $('#special_' + curTeam).slideUp(300);
          }
        }
        
        map.closePopup();
        
        for(var i=0;i<locations.length;i++) {
          if(locations[i].doctors[team] > 0 ) {
            locations[i].state == 'AZ' ? arizonaLocations.push([i, locations[i]]) : texasLocations.push([i, locations[i]]);
            
            locations[i].marker.show();
          }
          else {
            locations[i].marker.hide();
          }
        }
        
        curTeam = team;
        
        element.addClass('open');
        
        var locationsHtml = "";
        
        if(texasLocations.length > 0) {
          locationsHtml += buildLocationList('Texas', texasLocations);
        }
        
        if(arizonaLocations.length > 0) {
          locationsHtml += buildLocationList('Arizona', arizonaLocations);
        }
        
        if(locationsHtml == "") {
          locations += '<p>There are no locations with this specialty available.</p>';
          locationsHtml += '<p><a href="#" class="closer">Ok</a></p>';
        }
        
        $('#special_' + team).html(locationsHtml).slideDown();
      }
      
      return false;
    }
  });
});

function buildLocationList(name, arr) {
  var result = "";
  
  result += ' <h4>' + name + '</h4>';
  
  if(arr.length > 0) {
    result += "<ul>";
    
    for(var i=0;i<arr.length;i++) {
      result += '<li><a href="#' + arr[i][0] + '" class="location">' + arr[i][1].name + '</a></li>';
    }
    
    result += "</ul>";
  }
  else {
    result += "<p>No Locations Found</p>";
  }
  
  return result;
}

function showPopupForTeamAndLocation(team, location) {
  $('#viewDoctorsPopup').html('<a href="#" onclick="tb_remove(); return false;" class="popup_close_link"><span>Close</span></a> <div class="loading">Loading specialists. Please wait&#8230;</div>');

  tb_show("", "#TB_inline?height=350&width=500&inlineId=viewDoctorsPopup&modal=true");

  $.ajax({ 
    type: 'POST', 
    dataType: 'script', 
    url: '/locations/doctors/' + team + '/' + location
  });
}

function closeTeamInfo() {
  if(curTeam != null) {
    $('#special_' + curTeam).slideUp();
    
    for(var i=0;i<locations.length;i++) {
      locations[i].marker.show();
    }
    
    $('#team_' + curTeam).removeClass('open');
    
    curTeam = null;
  }
}

function selectTexasToggle() {
  $('#texas_link').addClass('selected').next('div').removeClass('selected');
}

function selectArizonaToggle() {
  $('#arizona_link').addClass('selected').prev('div').removeClass('selected');
}

(function($) {
  function StateToggleControl() { }
  
  StateToggleControl.prototype = new GControl();

  StateToggleControl.prototype.initialize = function(gmap) {
    var container = document.createElement("div");
    
    container.id = 'map_state_toggle';
    
    var texasDiv = document.createElement("div");
    texasDiv.id = 'texas_link';
    texasDiv.className = 'selected';
    container.appendChild(texasDiv);
    
    var inner = document.createElement('span');
    inner.appendChild(document.createTextNode("Texas"));
        
    texasDiv.appendChild(inner);

    var arizonaDiv = document.createElement("div");
    arizonaDiv.id = 'arizona_link';
    container.appendChild(arizonaDiv);
    
    inner = document.createElement('span');
    inner.appendChild(document.createTextNode("Arizona"));
    
    arizonaDiv.appendChild(inner);

    gmap.getContainer().appendChild(container);
    
    return container;
  };

  StateToggleControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
  };
  
  TbiMap = Class.create({
    initialize: function(elements, locations) {
      this.elements = $(elements);
      this.locations = $.makeArray(locations);

      if(this.elements.length == 0)
        return;
        
      this.element = this.elements.get(0);

      this.map = new GMap2(this.element);
      this.map.addControl(new StateToggleControl());
      this.map.addControl(new GLargeMapControl3D());

      var options = {
        texas: { lat: 33.330528249028085, lng: -97.53662109375, zoom: 8 },                      
        arizona: { lat: 33.445193134508465, lng: -111.90536499023438, zoom: 10 }
      };

      this.map.setCenter(new GLatLng(options.texas.lat, options.texas.lng), options.texas.zoom);

      this.addMarkers();

      $(window).bind('unload', function() {
        GUnload();
      });
        
      this.options = options;
    },

    showTexas: function() {
      this.map.setCenter(new GLatLng(this.options.texas.lat, this.options.texas.lng), this.options.texas.zoom);
    },

    showArizona: function() {
      this.map.setCenter(new GLatLng(this.options.arizona.lat, this.options.arizona.lng), this.options.arizona.zoom);
    },
    
    addMarkers: function() {
      var icon = new GIcon();
      icon.image = "/_images/map_icon.png";
      icon.shadow = "/_images/map_icon_shadow.png";
      icon.iconSize = new GSize(32, 32);
      icon.shadowSize = new GSize(59, 32);
      icon.iconAnchor = new GPoint(16, 32);
      icon.infoWindowAnchor = new GPoint(5, 1);

      var map = this.map;
      var onClick = this.onClick.bind(this);
      var closeWindows = this.closeWindows.bind(this);
      
      for(var i=0;i<this.locations.length;i++) {
        var location = locations[i];            
        var point = new GLatLng(location.coordinates[0], location.coordinates[1]);            
        var marker = new GMarker(point, { icon: icon });
        
        marker._locationInfo = location;
        location.marker = marker;
        
        GEvent.addListener(marker, "click", function() {
          onClick(this._locationInfo, this);
        });
        
        GEvent.addListener(marker, "infowindowclose", function() {
          closeWindows();
        });
        
        this.map.addOverlay(marker);
      }
    },
    
    onClick: function(location, marker) {          
      this.showLocationBubble(location, marker);
      selectedLocation = location;
    },
    
    focusOnLocation: function(location) {
      this.map.setCenter(new GLatLng(location.coordinates[0], location.coordinates[1]));
    },
    
    showLocationBubble: function(location, marker) {
      var html = '<dl class="address">' + $('dl#location_' + location.id).html() + '</dl>';
      
      if(curTeam != null) {
        html += '<div style="margin-top: 8px;"><a href="#" onclick="showPopupForTeamAndLocation(' + curTeam + ', ' + location.id + '); return false;" style="font-weight:bold;">View ' + teams[curTeam].name + '</a></div?';
      }
      else {
        var specialistsHtml = '';
        
        $('#map_teams a.team').each(function() {
          var id = this.id.split('_')[1];
        
          if(location.doctors[id] != 0) {
            specialistsHtml += '<div style="margin-bottom: 3px;"><a href="#" onclick="showPopupForTeamAndLocation(' + id + ', ' + location.id + '); return false;">' + teams[id].name + '</a></div>';
          }
        });
        
        if(specialistsHtml != '') {
          html += '<h5>Specialists in ' + location.name + '</h5>';
          
          html += specialistsHtml;
        }
      }
      
      if(location.state == "TX") {
        selectTexasToggle();
      }
      else {
        selectArizonaToggle();
      }
      
      marker.openInfoWindowHtml(html);  
    },
    
    closePopup: function() {
      this.map.closeInfoWindow();      
      selectedLocation = null;
    },
    
    closeWindows: function() {
      $('#map_note').html('Find a Specialist');
      
      $('#map_teams a.team').each(function() {
        $(this).removeClass('disabled enabled');
      });
    }
  });
})(jQuery);

/* some rjs fakeout */
var Element = {};

Element.update = function(element, contents) {
  $('#' + element).html(contents);
};