
var map, geocoder,directions,manager;
var centerLatitude = 43.670906;
var centerLongitude = -79.393331;
var startZoom = 9;
var products=[]
var farms=[]
var points=[]
var myLocation,directing
var markers=[]
var dateFilters=[];
var typeFilters=["farm","csa","market"];
var foodFilters=[];
var baseIcon,csaIcon,marketIcon,farmIcon,myIconBase,myIcon

var infoWindowHTML=$("<div><div class=\"title\"></div><div class=\"address\"></div><div class=\"phone\"></div><div class=\"products\"></div><div class=\"directions\"><button class=\"getdirections\">Get Directions</button><div class=\"lat\"></div><div class=\"lng\"></div></div></div>")
//console.log("")
//server:ABQIAAAAbKlxLGXNC2PH49P7rUhg8BSX7378GVX_wvm8ISAQItnVI7Ew8hTmMIZzghDc8El2IE9OHMwo4ioymg
//local:ABQIAAAAbKlxLGXNC2PH49P7rUhg8BS4uSxNcZeiHmsInBcucCK4dMkMwRRAfB8T30ehRK94-8S3IRmB1j4NUA
var MAPS_API_KEY="ABQIAAAAbKlxLGXNC2PH49P7rUhg8BSX7378GVX_wvm8ISAQItnVI7Ew8hTmMIZzghDc8El2IE9OHMwo4ioymg"
$(document).ready(function(){
  map = new GMap2($('#map')[0]);
  geocoder = new GClientGeocoder()
  directions = new GDirections(map,$("#getdirections")[0]);
  attachEvents()
  map.addControl(new GSmallMapControl());
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
  
  makeIcons()

	$("#allplaces li").each(function(i,n){
	  $this=$(this)
		if(parseInt($this.find(".lat").text())!=0){
			var point=new GLatLng(parseFloat($this.find(".lat").text()), parseFloat($this.find(".lng").text()))
			points.push(point)
		}
	})
	
	//var bounds=autoCenterAndZoom(points);
  //map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds)+2)
	

	manager = new GMarkerManager(map);
	$("#allplaces li").each(function(i,n){
	  $this=$(this)
		if(parseInt($this.find(".lat").text())!=0){
			var point=new GLatLng(parseFloat($this.find(".lat").text()), parseFloat($this.find(".lng").text()))
			var currentProducts=$this.find(".products").text().split(",")
			
			$.each(currentProducts,function(i,n){currentProducts[i]=$.trim(this);})
			$.each(currentProducts,function(i,n){if(currentProducts[i]=="") currentProducts.splice(i,1);})
			
			var identifier=$this.find(".identifier").text()
      
      if($this.hasClass("c-farm")){
        var marker=new GMarker(point,{icon:farmIcon})
        marker.Type="farm"
      }else if($this.hasClass("c-market")){
        var marker=new GMarker(point,{icon:marketIcon})
        marker.Type="market"
      }else{
        var marker=new GMarker(point,{icon:csaIcon})
        marker.Type="csa"
      }
			
			//manager.addMarker(marker,0)
			$this.data("marker",marker);
      
			marker.bindInfoWindowHtml(makeInfoWindow($this))
			marker.products=currentProducts
			marker.el=$this;
			markers.push(marker)
			products=products.concat(currentProducts)
		}
	})
	
	//setLocation("Toronto, Ontario")
	/* MAKE places */

	var tmpProducts={};
	$.each(products,function(i,val){
	   if(tmpProducts[val]){
	     tmpProducts[val].count++;
	   }else{
	     if(val!=""){
	       tmpProducts[val]={}
  	     tmpProducts[val].count=1;
  	     tmpProducts[val].data=getProductData(val);
       }
     }
	})
	products=tmpProducts;
	$.each(products,function(i,val){
		$("#allfood ul").append("<li class=\""+i+"\"><input type=\"checkbox\" /><span class=\"fooditem\">"+i+"</span><span>("+val.count+")</span></li>");
	})
	$.each(products,function(i,val){
	  if(val.data) $("#groups .group-"+val.data.Type).append("<li class=\""+i+"\"><input type=\"checkbox\" /><span class=\"fooditem\">"+i+"</span><span>("+val.count+")</span></li>");
	})

	$("#allfood li input[type=checkbox], #groups li input[type=checkbox]").click(function(){
	  //$("#allfood .active").removeClass("active")
		//$(this).toggleClass("active")
		if($(this).attr("checked")==true) addFoodFilter($(this).parent().find(".fooditem").text())
		else removeFoodFilter($(this).parent().find(".fooditem").text())
		updateMarkers()
	})
	$("#groups h3 input[type=checkbox]").click(function(){
	  $(this).parent().next().find("input[type=checkbox]").attr("checked",$(this).attr("checked"));
	  $(this).parent().next().find(".fooditem").each(function(i,n){
	    if($(this).prev().attr("checked")==true) addFoodFilter($(this).text())
  		else removeFoodFilter($(this).text())
	  })
	  updateMarkers()
	})
	$(".sources input[type=checkbox]").click(function(){
	  typeFilters=[]
	  $(this).parent().find("input[type=checkbox]").each(function(){
	    if($(this).attr("checked")==true) typeFilters.push($(this).attr("id").substr(5))
	  })
	  updateMarkers();
	})
	
  $("#groups h3 .title").click(function(){
    $(this).toggleClass("collapsed")
    $(this).next().toggle()
  });

  //$(".tabset").tabs()
  $(".tab-nav a").click(function(){
    $(this).parents(".tabset").find(".tab-contents").hide()
    $($(this).attr("href")).show()
    $(this).parents(".tab-nav").find(".tab-selected").removeClass("tab-selected")
    $(this).parent().addClass("tab-selected")
    return false;
  })
  $(".tab-nav a.groups").click();
  $(".tab-nav a.allplaces").click();
  
  $(".tab-foods").click(function(e){
    $("#foods").show()
    $("#places").hide()
    return false;
  })
  $(".tab-places").click(function(e){
    $("#foods").hide()
    $("#places").show()
    return false;
  })
  
  $("#allplaces li .title").click(function(){
    $(this).parents("ul").find(".active").removeClass("active")
    var item=$(this).parents("li")
    item.addClass("active")
    var marker=item.data("marker")
    marker.openInfoWindow(makeInfoWindow(item))
  })

  $('#allplaces li .getdirections').click(function(){
    var item=$(this).parents("li")
    getDirections(item)
  });
  $($(".foodandplaces li a")[0]).click()
  $('input[title!=""]').hint();
  $("#location_button").click(function(){
    setLocation($("#location").val())
  })
  $("#location").keydown(function(e){
    if(e.keyCode==13) $("#location_button").click();
  })
  $("a.info").click(function(){
    showProfile($(this).parents("li"))
    return false;
  })

  if($("#location").val()=="Where are you...") $("#location").val("Toronto, Ontario")
  
  $('#fresh').flash(
    { 
      src: '/images/fresh.swf',
      width: 380,
      height: 100,
      wMode:"transparent"
    },
    { version: 8 }
  );
  
  
  $(window).resize(function(){
    var newH=Math.max(300,$("#container").height()-$(".tab-contents").offset().top-$("#footer").height()-31)
    $(".tab-contents").each(function(){
      $(this).height(newH);
    })  
    $("#map").height(newH+30)
    $("#map").width($(window).width()-$("#map").offset().left-15)
    
    if($(window).width()<=910) $("#container").width(910)
    else $("#container").css("width","100%")
  })
  
  $(window).resize();

  setTimeout(function(){setLocation($("#location").val())},1)
});
function addFoodFilter(food){
  if(!$.inArray(food,foodFilters)>-1) foodFilters.push(food);
}
function removeFoodFilter(food){
  if($.inArray(food,foodFilters)>-1) foodFilters.splice($.inArray(food,foodFilters),1);
}
function updateMarkers() {
  map.clearOverlays();
  map.addOverlay(myLocation);
	//create the first 50 markers
	$("#allplaces li").hide()
	var i = 0;
	var showingMarkers=0;
	while(i<markers.length && showingMarkers<26) {
	  if(matchesFilters(markers[i])){
	    map.addOverlay(markers[i]);
  		markers[i].el.find(".identifier").text(showingMarkers+1)
  		markers[i].el.find(".distance").html(Math.round(markers[i].distance/100)/10+"<span>KM</span>");
  		$("#allplaces ul").append(markers[i].el);
  		markers[i].el.show()
  		showingMarkers++;
	  }
		i++;
	}
	
}
function getProductData(food){
  for(var i in productData){
    if(productData[i].Product==food) return productData[i];
  }
  return null;
}
function matchesFilters(marker){

  if($.inArray(marker.Type,typeFilters)<0) return false;
  if(foodFilters.length<1) return true;
  if(marker.products.length<1) return false;
  for(var i=0;i<foodFilters.length;i++){
    if($.inArray(foodFilters[i],marker.products)>-1) return true;
  };
  return false;
}
function inObjectKey(obj,val){
  var i =0;
  $.each(obj,function(k,n){
    if(k=val) return i;
    i++;
  })
  return -1
}
function setLocation(location){
  geocoder.getLatLng(location,function (gLatLng) {
    directing=false;
    if(gLatLng!=null){
      if(myLocation) map.removeOverlay(myLocation)
      map.setCenter(gLatLng,startZoom)
      if(!myLocation){
        myLocation=new GMarker(gLatLng,{ icon:myIcon, draggable: true })
        myLocation.bindInfoWindowHtml("<img src=\"/images/marker_me.png\" style=\"float:left;margin-right:10px;\"><h1 style=\"font-size:14px;line-height:21px;\">This is where you eat!</h1><p>"+$("#location").val()+"</p>")
			  manager.addMarker(myLocation,0)
			  
			}else{
			  myLocation.setLatLng(gLatLng)
			  myLocation.show()
			}
			
			GEvent.addListener(myLocation, "dragend", function() {
			  refreshProximity()
        updateMarkers()
        var reversegeocoder = new GReverseGeocoder(map);
        GEvent.addListener(reversegeocoder, "load",
          function(placemark) {
            $("#location").val(placemark.address);
          }
        );
        reversegeocoder.reverseGeocode(myLocation.getLatLng());
      });
      refreshProximity()
      updateMarkers()
    }
  });
}
function refreshProximity(){
  for (var k in markers) {
	  var point=markers[k].getLatLng();
		markers[k].distance=point.distanceFrom(myLocation.getLatLng())
	}
	//sort based on the distance
	markers.sort(function (a,b) {
		if(a.distance > b.distance) return 1
		if(a.distance < b.distance) return -1
		return 0
	});
}
function attachEvents(){
  GEvent.addListener(map, "infowindowopen", function() {
    $('.infobubble-content input[title!=""]').hint();
    $('.infobubble-content .getdirections').click(function(){
      getDirections($('.infobubble-content'))
    });
  });
  GEvent.addListener(directions, "load", function() {
      //myLocation.show();
      //myLocation.hide();
      //map.removeOverlay(myLocation)

      
  });
  
  GEvent.addListener(map, "addoverlay", function(overlay) {
    //if(map.isLoaded()) map.clearOverlays();

    //if(myLocation==overlay) myLocation.show()
  });
  GEvent.addListener(map, "load", function() {

  });
  
  
}
function getDirections(el){
  if(myLocation){

    var point=myLocation.getLatLng()
    directing=true;
    directions.loadFromWaypoints([point,new GLatLng(parseFloat(el.find(".lat").text()), parseFloat(el.find(".lng").text()))]);
    $(".tab-places").click()
    $(".tabset a[href=#getdirections]").click()
  }else{
    $("#location").val("").focus();
  }
}
function autoCenterAndZoom(points) {
	var lat_max = -90;
	var lat_min = 90;
	var lon_max = -180;
	var lon_min = 180;

	for (var i=0; i<points.length; i++) {
		lat = points[i].lat();
		lon = points[i].lng();
		if (lat > lat_max) {
			lat_max = lat;
		}
		if (lat < lat_min) {
			lat_min = lat;
		}
		if (lon > lon_max) {
			lon_max = lon;
		}
		if (lon < lon_min) {
			lon_min = lon;
		}
	}

	return new GLatLngBounds(new GLatLng(lat_min, lon_min), new GLatLng(lat_max, lon_max));
};
function makeInfoWindow(el){
  infoWindowHTML.find(".lat").text(el.find(".lat").text())
  infoWindowHTML.find(".lng").text(el.find(".lng").text())
  infoWindowHTML.find(".title").text(el.find(".title").text())
	infoWindowHTML.find(".address").text(el.find(".address").text())
	infoWindowHTML.find(".phone").text((el.find(".phone").text()=="") ? "Phone Unavailable" : el.find(".phone").text())
	
	return "<div class=\"infobubble-content\">"+infoWindowHTML.html()+"</div>"
}
function makeIcons(){
  baseIcon = new GIcon(G_DEFAULT_ICON);
  baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  csaIcon = new GIcon(baseIcon);
  csaIcon.image = "/images/marker_csa.png";
  marketIcon = new GIcon(baseIcon);
  marketIcon.image = "/images/marker_market.png";
  farmIcon = new GIcon(baseIcon);
  farmIcon.image = "/images/marker_farm.png";
  
  myIconBase = new GIcon(G_DEFAULT_ICON);
  myIconBase.shadow = "http://www.google.com/mapfiles/shadow50.png";
  myIconBase.iconSize = new GSize(30, 45);
  myIconBase.shadowSize = new GSize(60, 45);
  myIconBase.iconAnchor = new GPoint(15, 45);
  myIconBase.infoWindowAnchor = new GPoint(9, 2);
  myIcon = new GIcon(myIconBase);
  myIcon.image = "/images/marker_me.png";
}