var infoMargin = 326;
function handleSliderChange(e, ui) {
  var maxFScroll = $("#filters").attr("scrollHeight")-$("#filters").height();
  $("#filters").animate({scrollTop: -ui.value * (maxFScroll/100) },0);
}
function handleSliderSlide(e, ui) {
  var maxFScroll = $("#filters").attr("scrollHeight")-$("#filters").height();
  $("#filters").attr({scrollTop: -ui.value * (maxFScroll / 100)});
}

function displayPoint(marker, index) {
  $("#message").hide().empty();
  var closeButton = $(iconHTML("close"))
    .click(function() {
	     googleMap.map.panBy(new GSize(1,0));
	     $("#message").fadeOut();
	   })
    .css({ top:'5px', right:'5px' })
    .uiHover();

  var tabs = $('<div class="tabs" id="ctabs_'+marker.id+'"></div>');
  var ul = '<ul>';
  var bodies = "";
  for(var tab_i=0;tab_i<marker.tabs.length;tab_i++) {
    // create an li for each
    ul += '<li><a href="#ctab_'+marker.id + tab_i +'">'+ marker.tabs[tab_i][0] +'</a></li>';
    bodies += "<div id=\"ctab_"+ marker.id + tab_i +"\">"+ marker.tabs[tab_i][1] +"</div>"
  }
  ul += '</ul>';
  $(ul).appendTo(tabs);
  $(bodies).appendTo(tabs);
  tabs.appendTo('#message');
  tabs.tabs()
  closeButton.appendTo('#message');

  var moveEnd = GEvent.addListener(googleMap.map, "moveend", function(){
    var markerOffset = googleMap.map.fromLatLngToDivPixel(marker.marker.getPoint());
    $("#message")
      .css({ top:markerOffset.y, left:markerOffset.x })
      .show();
      GEvent.removeListener(moveEnd);
  });
  //yoff = ($("html").attr("scrollHeight")-$("html").height());
  // offset y to top of page minus pixel height of icon + some change
  yoff = $("html").attr("scrollHeight")/2 - 171;
  xoff = 450;
  var offset = XYToLL(xoff,yoff,marker.marker.getPoint().lng(),marker.marker.getPoint().lat(),googleMap.map.getZoom())
  googleMap.map.panTo(new GLatLng(offset.y,offset.x));
  //googleMap.map.panTo(marker.marker.getLatLng());
}

google.load("maps", "2.x");
google.load("jquery", "1.3.2");
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
        return i;
      }
    }
    return -1;
  }
}

var GoogleMap = function() {};
GoogleMap.prototype = {
  initialize: function(options) {
    this.setOptions(options);
    this.mapframe = $('#google_map');
    this.resize();
    this.map = new google.maps.Map2(document.getElementById('google_map'));
    this.map.setCenter(new google.maps.LatLng(this.initial_latitude(), this.initial_longitude()), this.initial_zoom());
    var customUI = this.map.getDefaultUI();
    customUI.controls.largemapcontrol3d = false;
    customUI.scalecontrol = false;
    customUI.zoom.scrollwheel = true;
    customUI.zoom.doubleclick = false;
    customUI.keyboard = false;
    this.map.setUI(customUI);
    this.geocoder = new google.maps.ClientGeocoder();
    this.setupMarker();
    this.loadFilters();
    //this.loadSelectFilters();
    //this.loadRadioFilters();
    $('#loading').hide();
  },

  setOptions: function(options) {
    this.options = options;
  },

  initial_latitude: function() {
    if (this.options.latitude) { return this.options.latitude;} else {return 29.97;}
  },

  initial_longitude: function () {
    if (this.options.longitude) { return this.options.longitude;} else {return -98.35;}
  },

  initial_zoom: function() {
    if (this.options.zoom) { return this.options.zoom;} else {return 10;}
  },

  resize: function() {
    options = this.options;
    if(options == undefined) {
      this.mapframe.css({width: $(document).width()-infoMargin+'px', height: $(document).height()+'px'});
    } else {
      if(options.width) {
        this.mapframe.css({width: options.width});
      } else {
        this.mapframe.css({width: $(document).width()-infoMargin});
      }
      if(options.height) {
        this.mapframe.css({height: options.height});
      } else {
        this.mapframe.css({height: $(document).height()});
      }
    }
  },

  // tabs is an array of arrays Array([title, copy], [title, copy])
  mark: function(id, slug, tlat, tlong, tabs) {
    if (tabs[0]) {
      var point = new google.maps.LatLng(tlat, tlong);
      var marker = new google.maps.Marker(point, {icon:this.baseIcon, title:tabs[0][0]});
      this.map.addOverlay(marker);
      this.markers[this.markers.length] = {'marker': marker, 'id':id, 'slug':slug};
    }
  },

  closeOverlay: function() {
    if (this.currentMarker) {
      this.map.removeOverlay(this.currentMarker.overlay);
    }
  },

  setupMarker: function() {
    this.baseIcon = new google.maps.Icon();
    this.baseIcon.image = '/images/icons/markers/image.png';
    this.baseIcon.printImage = '/images/icons/markers/printImage.gif';
    this.baseIcon.mozPrintImage = '/images/icons/markers/mozPrintImage.gif';
    this.baseIcon.iconSize = new GSize(20,20);
    this.baseIcon.shadow = '/images/icons/markers/shadow.png';
    this.baseIcon.transparent = '/images/icons/markers/transparent.png';
    this.baseIcon.shadowSize = new GSize(30,20);
    this.baseIcon.printShadow = '/images/icons/markers/printShadow.gif';
    this.baseIcon.iconAnchor = new GPoint(10,20);
    this.baseIcon.infoWindowAnchor = new GPoint(10,0);
    this.baseIcon.imageMap = [19,0,19,1,19,2,19,3,19,4,19,5,19,6,19,7,19,8,19,9,19,10,19,11,19,12,19,13,19,14,19,15,19,16,19,17,19,18,19,19,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,0,0];
  },

  openMarkerById: function(id) {
    for(x in this.markers) {
      if(this.markers[x].id == id) {
        displayPoint(this.markers[x], 0);
        break;
      }
    }
  },

  centerMarker: function(id) {
    for(x in this.markers) {
      if(this.markers[x].id == id) {
        this.map.setCenter(this.markers[x].marker.getLatLng());
        break;
      }
    }
  },

  loadFilters: function() {
    var map = this;
    //on load, look at all radio buttons
    this.filters = $('#filters .filter_change select').add('#filters .filter_change input[type=radio]').add('#filters .filter_change input[type=checkbox]');
    this.filters.each(function(index){
      // uncomment if browser issues arise
      //var evt = $.browser.msie? 'click': 'change';
      $(this).bind('click', function () {
	if (this.type == 'radio' || this.type == 'checkbox') {
	  map.filter(this.value);
	} else {
	  map.filter(this.options[this.selectedIndex].value);
	}
      });
    });
  },

  resetFilters: function() {
    var map = this;
    //reset all select and radio buttons
    this.filters =$('#filters .filter_change select').add('#filters .filter_change input[type=radio]').add('#filters .filter_change input[type=checkbox]');
    this.filters.each(function(index){
      if (this.type == "radio" || this.type == "checkbox") {
	this.checked = false;
      } else {
	this.value = "";
      }
      //reset map icons
      map.filter(undefined);
    });
  },

  filter: function(filter_option_id) {
    var self = this;
    //filter out unchecked radio buttons
    var allFilters = $('#filters .filter_change select').add('#filters .filter_change input:radio:checked').add('#filters .filter_change input:checked');
    $.getJSON('/communities.js', allFilters, function(json) {
      var community_ids = [];
      $.each(json.communities, function(i, comm) {
        community_ids[community_ids.length] = comm.community.id;
      });
      // now we have ids, need to dim and brighten
      $.each(self.markers, function(i, marker) {
        if (community_ids.indexOf(marker.id) > -1) {
	  marker.marker.show();
	  $('#community_'+marker.id).removeClass('inactive');
        } else {
	  marker.marker.hide();
	  $('#community_'+marker.id).addClass('inactive');
        }
      });
    });

  },

  // Look up an address, create a mark, then save it over Ajax
  geocode: function(address, text) {
    var self = this;
    this.geocoder.getLatLng(
      address,
      function(point) {
        if (point) {
          var marker = new google.maps.Marker(point, {icon:this.baseIcon});
          self.map.addOverlay(marker);
          self.markers[self.markers.length] = {'marker': marker, 'text': text};
        }
      }
    );
  },

  map: null,
  mapControl: null,
  geocoder: null,
  filters: [],
  markers: [],
  options: {},
  baseIcon: null,
  currentMarker: null,
  mapframe: 'google_map',
  contentframe: 'map_content'
};

