google.load("maps", "2", { "other_params": "sensor=false" });
    

$(document).ready(function() {
        if ($("#contact_map").length == 1)
        {
          //Set up tabs
          $("#map_tab").click(function(event, onDone) {
             $(this).addClass("pin");
             $("#listing_tab").removeClass("pin");
             $("input#contact_tab").get(0).value="map_tab";
             if (typeof(onDone) !== 'function') {
               onDone = function() {};
             }
             $("#contact_listing").hide();
             //$("#contact_map").show(10, onDone);
             $("#contact_map").css("position", "relative").css("left",'');
             var backLinkHref = $("#node_only_filter a.back_to_list").attr("href");
             if (typeof(backLinkHref) !== 'undefined') {
                backLinkHref = backLinkHref.replace("tab=listing","tab=map");
                $("#node_only_filter a.back_to_list").attr("href", backLinkHref);
             }
             if ($("#contact_map_overlay span").text() !== "") {
               $("#contact_map_overlay").show();
             }
          });
          $("#listing_tab").click(function() {
             $(this).addClass("pin");
             $("#map_tab").removeClass("pin");
             $("input#contact_tab").get(0).value="listing_tab";
             //$("#contact_map").hide();
             $("#contact_map").css("position", "absolute").css("left",-10000);
             $("#contact_map_overlay").hide();
             $("#contact_listing").show(); 
             var backLinkHref = $("#node_only_filter a.back_to_list").attr("href");
             if (typeof(backLinkHref) !== 'undefined') {
                backLinkHref = backLinkHref.replace("tab=map","tab=listing");
                $("#node_only_filter a.back_to_list").attr("href", backLinkHref);
             }
          });



         initialize();

          if (window.location.href.match(/tab=listing/) !== null || $("input#contact_tab").get(0).value==="listing_tab") {
             //$("#map_tab").trigger('click',[function() { $("#listing_tab").click(); }]);
             $("#listing_tab").click();
          } else {
             $("#map_tab").click();
          }

          $("select#sector_filter, select#interest_filter, select#country_filter").change(function() {
             $("form#contact_search_form").submit();
          });

          $("input#node_only_filter_checkbox").click(function() {
             //also set the hidden field?
             if (this.checked) {
               $("#listing_list ul").hide();
             } else {
               $("div.node_country:visible").next("#listing_list ul").show();
               //$("#listing_list ul").each(function() {
               //   if($(this).prev("div.node_country:visible").length > 0) {
               //     $(this).show();
               //   }
               //});
             }
          });
          
/*
          $("select#country_filter").change(function() {
            var country_class = this.value;
            //alert($("#listing_list div." + country_class).position().top);
            $("#listing_list").scrollTop($("#listing_list").scrollTop() + $("#listing_list div." + country_class).position().top);
             // $("#listing_list div.node_country").each(function() {
               if ($(this).hasClass(country_class)) {
                  $(this).show();
                  $(this).next("ul").show();                  
               } else {
                  $(this).hide();
                  $(this).next("ul").hide();
               } // 
            });
          });
*/

          $("#show_hide_filters").click(function() {
           if ($(this).hasClass("hidden")) {
             $(this).text("Hide Filters");
             $(this).removeClass("hidden");
             $("#filters").animate({ 
                height: 75
             }, 500, "linear" );
           } else {
             $(this).text("ShowFilters");
             $(this).addClass("hidden");
             $("#filters").animate({ 
               height: 0
             }, 500, "linear" );
           }
          });

          if ($("#sector_filter").get(0).value != '' || $("#interest_filter").get(0).value != '' || $("#country_filter").get(0).value != ''  ||$("#search_filter_results").length > 0) {
            $("#show_hide_filters").click();
          }
        }
});

    $(window).unload(function() {
        google.maps.Unload();
    });


    function setToggle(b, show) {
        if (!$(b).hasClass("pin")) {
            $(b).addClass("pin");
            $(b).siblings().removeClass("pin");

            if (show) {
              for (var i = 0; i < contacts.length; i++) {
                 contacts[i].marker.show();
              }
            } else {
              for (var i = 0; i < contacts.length; i++) {
                 contacts[i].marker.hide();
              }
            }
        }
    }


    function hideContacts() {
        $("input#map_toggle").get(0).value= "node_contacts";
        setToggle(this, false);
    }

    function showContacts() {
        $("input#map_toggle").get(0).value = "all_participants";
        setToggle(this, true);
    }

    //All/Node control

    function ContactToggleControl() { 
    }

    //ContactToggleControl.prototype = google.maps.Control.prototype;

    ContactToggleControl.prototype.initialize = function(mapref) {
        var container = document.createElement("div");
        $(container).addClass("mapToggle")
        var nodeOnlyDiv = document.createElement("div");
        nodeOnlyDiv.id = "node_contacts_toggler";
        container.appendChild(nodeOnlyDiv);
        nodeOnlyDiv.appendChild(document.createTextNode("Node Contacts"));
        $(nodeOnlyDiv).click(hideContacts);

        var allDiv = document.createElement("div");
        allDiv.id = "all_participants_toggler";
        container.appendChild(allDiv);
        allDiv.appendChild(document.createTextNode("All Participants"));
        $(allDiv).click(showContacts);

        mapref.getContainer().appendChild(container);

        return container;
    }



    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    ContactToggleControl.prototype.getDefaultPosition = function() {
        return new google.maps.ControlPosition(1, new google.maps.Size(7, 7));
    }

    ContactToggleControl.prototype.printable = function() { return false; }
    ContactToggleControl.prototype.selectable = function() { return false; }
    ContactToggleControl.prototype.allowSetVisibility = function() { return true; }

    var map;


function convertEmails() {
  $("#contact_map a.email, #profile_map a.email").each(function() {
       var url = $(this).attr('href');
       var urls = url.split("/");
       if (urls.length === 4) {
          var email = rotate_string(urls[2]) + "@" + rotate_string(urls[3]);
          $(this).attr('href', 'mailto:' + email);
          $(this).html(email);
          $(this).removeAttr('target');
       }
    });
}

var topNorth = 0;
var topSouth = 0;
var topEast = 0;
var topWest = 0;

function calcBounds(lat, long) {
  if (lat > topNorth || topNorth == 0) { 
    topNorth = lat; 
  } 
  if (lat < topSouth || topSouth == 0) { 
    topSouth = lat; 
  }
  
  if (long > topEast || topEast == 0) { 
    topEast = long; 
  } 
  if (long < topWest || topWest == 0) { 
    topWest = long; 
  }
}




function makeNodeMarker(idx, list, opts) {
  var doZoom = "zoom";
  if (showContacts) { doZoom = ""; }
  makeMarkerGen(idx, list, opts, doZoom);
}

function makeMarker(idx, list, opts) {
  makeMarkerGen(idx, list, opts, "");
}

function makeMarkerGen(idx, list, opts, click) {

    var point = new google.maps.LatLng(list[idx].location[1], list[idx].location[0]);
    calcBounds(list[idx].location[1], list[idx].location[0])
    var id = list[idx].marker;
    list[idx].marker = new google.maps.Marker(point,opts); //new LabeledMarker(point, opts);
    map.addOverlay(list[idx].marker);
    google.maps.Event.addListener(list[idx].marker, "click", function() {
       if (click == "zoom") {
          window.location = "/connect/the-iyc-network?show_node=" + id;
       } else {
          map.openInfoWindowHtml(list[idx].marker.getLatLng(), list[idx].infoWindow, {autoScroll:true, maxHeight:250, onOpenFn: function() { convertEmails(); } });
       }
     }); 
    /*if (click == "zoom") {
      google.maps.Event.addDomListener(list[idx].marker, "mouseover", function() {
         map.openInfoWindowHtml(list[idx].marker.getLatLng(), list[idx].infoWindow, {autoScroll:true, maxHeight:250, onOpenFn: function() { convertEmails(); } });     
      });
     }*/
}


function loadMarkers() {
    var largeIcon= new google.maps.Icon(google.maps.DEFAULT_ICON);
    largeIcon.image = "/images/markerLarge.png";
    largeIcon.iconSize = new google.maps.Size(30,48);
    largeIcon.iconAnchor = new google.maps.Point(15,48);
    largeIcon.shadow= null;
    var mediumIcon= new google.maps.Icon(google.maps.DEFAULT_ICON);
    mediumIcon.image = "/images/marker.png";
    mediumIcon.shadow= null;
    var smallIcon= new google.maps.Icon(google.maps.DEFAULT_ICON);
    smallIcon.image = "/images/markerSmall.png";
    smallIcon.iconSize = new google.maps.Size(15,25);
    smallIcon.iconAnchor = new google.maps.Point(8,25);
    smallIcon.shadow= null;
    var tinyIcon= new google.maps.Icon(google.maps.DEFAULT_ICON);
    tinyIcon.image = "/images/markerTiny.png";
    tinyIcon.iconSize = new google.maps.Size(12,12);
    tinyIcon.iconAnchor = new google.maps.Point(6,6);
    tinyIcon.shadow = null;
    var blueIcon = new google.maps.Icon(google.maps.DEFAULT_ICON);
    blueIcon.image = "/images/markerBlue.png";
    blueIcon.shadow= null;
    

    var nodeMarkerOpts = { icon: blueIcon };
    var opts = {icon: tinyIcon };
   


    for (var i = 0; i < contacts.length; i++) {
        var opts = {icon: smallIcon};
        if (contacts[i].count > 1) { opts.icon=mediumIcon; }
        if (contacts[i].count > 15) { opts.icon=largeIcon; }
        makeMarker(i, contacts, opts);
    }

    for (var i = 0; i < nodes.length; i++) {
        makeNodeMarker(i, nodes, nodeMarkerOpts);
    }
}


var maxContactsToShow = 300;
var contactsCount = 0;

function initialize() {
    map = new google.maps.Map2($("#contact_map").get(0));
    map.setCenter(new google.maps.LatLng(10, 0), 1);
      
    if (contactsCount <= maxContactsToShow ) {
      var customUI = map.getDefaultUI();
      customUI.controls.maptypecontrol = false;
      customUI.zoom.scrollwheel = false;
      map.setUI(customUI);

      loadMarkers();
      
      var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(topSouth-1.0,topWest-1.0), new google.maps.LatLng(topNorth+1.0,topEast+1.0));
      var zoom = map.getBoundsZoomLevel(bounds);
      map.setCenter(bounds.getCenter(),zoom);
   } else {
     $("#contact_map_overlay").show();
     $("#contact_map_overlay span").text("Your search matched over " + maxContactsToShow + " contacts.  Please narrow your search in order to display the results on the map");
   }

    /* 
    map.addControl(new ContactToggleControl());

    if ($("input#map_toggle").get(0).value == "all_participants") {
      $("#all_participants_toggler").click();
    } else {
      $("#node_contacts_toggler").click();    
    }
    */
}

