var map;
var regionsCollection = new Microsoft.Maps.EntityCollection();
var MM = Microsoft.Maps;
var options;
var pinInfobox = null;
var currentActivityId = 0;
var currentActivityName = null;
var userDidSelectedActivity = false;
var pinArray = new Array();
var customInfobox;
function OnPageLoad(latitude,longitude)
{

	map = new Microsoft.Maps.Map(document.getElementById("myMaps"), 
	{credentials: "ApqHjqky5yysTMuh0UXMMEGwHjHXHpdsB45R9ZzNMPXJnjIIf5ooAx-3pshzuNDD", // ////AlkgSEjnJ1aH-B0Y2LLA6CQmQHig3gTLwRljgpDhmaacbvy2qjUVFYeprsGrX-yQ
	center: new Microsoft.Maps.Location(latitude,longitude),//Location(46.45984,2.738281),
	mapTypeId: Microsoft.Maps.MapTypeId.road,
	disableUserInput: false,
	enableSearchLogo:false,
	showDashboard: true,
	showCopyright:false,
	showScalebar:false,
	disableZooming:false,
	zoom: 12});

	
	
	 Microsoft.Maps.registerModule("CustomInfoboxModule", "javascript/V7CustomInfobox.min.js");
	        Microsoft.Maps.loadModule("CustomInfoboxModule", { callback: function () {
	                //Create an instance of the custom infobox control
	                customInfobox = new CustomInfobox(map);
					customInfobox.setOptions({showArrow:true});
					customInfobox.setOptions({arrowColor:'#000000'});
					customInfobox.setOptions({showCloseButton:'false'});
	            }
	        });

			

			
		//Disable mouse wheel
      Microsoft.Maps.Events.addHandler(map, 'mousewheel', function(e) {
				if(e.targetType == 'map')
				{
					e.handled = true;
				}
			});

			
	// Hide the info box when the map is moved.
//	Microsoft.Maps.Events.addHandler(map, 'click', mapClicked);
	
	Microsoft.Maps.Events.addThrottledHandler(map, 'viewchangeend', mouseUpOnTheMap,1000);
	Microsoft.Maps.Events.addHandler(map, 'mouseout', pinMouseOut2);
	           
	//	ClickGeocode ();
}


function showPopupOnMap(pinNumber)
{
	displayInfobox2(pinArray[pinNumber],true);
}

function mapClicked(e)
{
	
		//var entityIndex = map.entities.indexOf(pinInfobox);
		//var entity = map.entities.get(pinInfobox);
		
	//	alert(pinInfobox.getHtmlContent());
}

function mouseUpOnTheMap(e)
{
		var loc = map.getCenter();
		var NW = map.getBounds().getNorthwest();
		var SE = map.getBounds().getSoutheast();
	
	   currentActivityName = $("#searchbar").attr("value")
	
		//this mean that the user did not select an item by clicking so we put it manually and refreshProfessionnels will fetch it manually
		if ( currentActivityName != '')
		{
			
			currentActivityName = $("#searchbar").attr("value");
			currentActivityId = -1;
			
		} else {
		     
			// The user did write anything we do not start a search
			return false
		}
	
		
		 $("#results").load("index.php/ajax/refreshProfessionnels", {'longitude':loc.longitude,'latitude':loc.latitude, 'radius':map.getMetersPerPixel(), 'currentActivityName':currentActivityName,'currentActivityId':currentActivityId,'lat2':NW.latitude,'lon1':NW.longitude,'lat1':SE.latitude,'lon2':SE.longitude});
		// $("#results").load("index.php/ajax/testSphinx", {'longitude':loc.longitude,'latitude':loc.latitude, 'radius':map.getMetersPerPixel(), 'currentActivityName':currentActivityName,'currentActivityId':currentActivityId,'lat2':NW.latitude,'lon1':NW.longitude,'lat1':SE.latitude,'lon2':SE.longitude});
		 
		/*$.post('index.php/ajax/refreshProfessionnels',
			{ 'longitude':loc.longitude,'latitude':loc.latitude, 'radius':map.getMetersPerPixel(), 'currentActivityName':currentActivityName,'currentActivityId':currentActivityId,'lat2':NW.latitude,'lon1':NW.longitude,'lat1':SE.latitude,'lon2':SE.longitude},
			function(result) {
				// if there is a result, fill the list div, fade it in 
				// then remove the loading animation
				
				if(result) {
							
						$('#results').html(result);
						
			}
		});*/

}

function displayInfobox2(e,isCalledFromPhp) {

			// build or display the infoBox
			var pin;
			
			//We need that because the function showPopupOnMap give the pin reference directly...
			if (isCalledFromPhp == true)
			{
				
				pin = e;
				
			} else {
				pin = e.target;
			}
			
            var latlong = pin.getLocation();

            //Define the layout contents in the infobox
	        var html = ["<div style='padding:10px'>"];
	        html.push("<b>", pin.title, "</b><br/>");
            html.push(pin.description, "<br/>");
	        html.push("</div>");

            //Display Infobox
            customInfobox.show(latlong, html.join(''));
			
			
			 
	    }
function pinMouseOut2(e) {
             customInfobox.hide();
        }

/***************************************************************/
 /* Add support for pop-up info boxes.
 /***************************************************************/

 // InfoBox class
 function InfoBox(title,content,html)
 {
  this.div;   // container div element
  this.title = title; // HTML to display inside the infobox  
  this.content = content;
  this.html = html;
 }


 // Extends the Pushpin class to add an InfoBox object.
 Microsoft.Maps.Pushpin.prototype.setInfoBox = function (infoBox)
 {
   this.infoBox = infoBox;

 }

// This function will create an infobox and then display it for the pin that triggered the hover-event.
        function displayInfobox(e,isCalledFromPhp) {
            // make sure we clear any infoBox timer that may still be active
            //stopInfoboxTimer(e);
		
            // build or display the infoBox
			var pin;
			
			//We need that because the function showPopupOnMap give the pin reference directly...
			if (isCalledFromPhp == true)
			{
				pin = e;
				
			} else {
				pin = e.target;
			}
            
            if (pin != null) {

                // Create the info box for the pushpin
                var location = pin.getLocation();
                var options = {
                    id: 'infoBox1',
                    title: pin.infoBox.title,
                    description: pin.infoBox.content,
                    htmlContent: pin.infoBox.html,
                    height: 100,
                    width: 180,
                    visible: true,
                    showPointer: true,
                    showCloseButton: true,
                    offset: new Microsoft.Maps.Point(0, pin.getHeight()),  // offset the infobox enough to keep it from overlapping the pin.
                    zIndex: 999
                };
                // destroy the existing infobox, if any
                // In testing, I discovered not doing this results in the mouseleave
                // and mouseenter events not working after hiding and then reshowing the infobox.
                if (pinInfobox != null) {
                    map.entities.remove(pinInfobox);
                    if (Microsoft.Maps.Events.hasHandler(pinInfobox, 'mouseleave'))
                        Microsoft.Maps.Events.removeHandler(pinInfobox.mouseLeaveHandler);
                    if (Microsoft.Maps.Events.hasHandler(pinInfobox, 'mouseenter'))
                        Microsoft.Maps.Events.removeHandler(pinInfobox.mouseEnterHandler);
                    pinInfobox = null;
                }
				
				
				    pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Point(0, pin.getHeight()), options);
				
				   /* var buffer = 25;

 
				
                  var infoboxOffset = pinInfobox.getOffset();

                  var infoboxAnchor = pinInfobox.getAnchor();

                  var infoboxLocation = map.tryLocationToPixel(pin.getLocation(), Microsoft.Maps.PixelReference.control);

 

                  var dx = infoboxLocation.x + infoboxOffset.x - infoboxAnchor.x;

                  var dy = infoboxLocation.y - 25 - infoboxAnchor.y;

 

                  if (dy < buffer) {    //Infobox overlaps with top of map.

                      //Offset in opposite direction.

                      dy *= -1;
					  pinInfobox = new Microsoft.Maps.Infobox(location, options);
 

                      //add buffer from the top edge of the map.

                      dy += buffer;

                  } else {

                      //If dy is greater than zero than it does not overlap.

                      dy = 0;

                  }

 

                  if (dx < buffer) {    //Check to see if overlapping with left side of map.

                      //Offset in opposite direction.

                      dx *= -1;

 

                      //add a buffer from the left edge of the map.

                      dx += buffer;

                  } else {              //Check to see if overlapping with right side of map.

                      dx = map.getWidth() - infoboxLocation.x + infoboxAnchor.x - pinInfobox.getWidth();

 

                      //If dx is greater than zero then it does not overlap.

                      if (dx > buffer) {

                          dx = 0;

                      } else {

                          //add a buffer from the right edge of the map.

                          dx -= buffer;

                      }

                  }*/

 

                 
				  
                // create the infobox
                pinInfobox = new Microsoft.Maps.Infobox(location, options);
                // hide infobox on mouseleave
                pinInfobox.mouseLeaveHandler = Microsoft.Maps.Events.addHandler(pinInfobox, 'mouseleave', pinInfoboxMouseLeave);
                // stop the infobox hide timer on mouseenter
                pinInfobox.mouseEnterHandler = Microsoft.Maps.Events.addHandler(pinInfobox, 'mouseenter', pinInfoboxMouseEnter);
                // add it to the map.
                map.entities.push(pinInfobox);
				
				/* //Adjust the map so infobox is in view

                  if (dx != 0 || dy != 0) {

                      map.setView({ centerOffset: new Microsoft.Maps.Point(dx, dy), center: map.getCenter() });

                  }*/
            }
        }

        function hideInfobox(e) {
            pinInfobox.setOptions({ visible: false });
        }

        // This function starts a count-down timer that will hide the infoBox when it fires.
        // This gives the user time to move the mouse over the infoBox, which disables the timer
        // before it can fire, thus allowing clickable content in the infobox.
        function startInfoboxTimer(e) {
            // start a count-down timer to hide the popup.
            // This gives the user time to mouse-over the popup to keep it open for clickable-content.
            if (pinInfobox.pinTimer != null) {
                clearTimeout(pinInfobox.pinTimer);
            }
            // give 300ms to get over the popup or it will disappear
            pinInfobox.pinTimer = setTimeout(timerTriggered, 300);
        }

        // Clear the infoBox timer, if set, to keep it from firing.
        function stopInfoboxTimer(e) {
            if (pinInfobox != null && pinInfobox.pinTimer != null) {
                clearTimeout(pinInfobox.pinTimer);
            }
        }

        function mapViewChange(e) {
            //stopInfoboxTimer(e);
            hideInfobox(e);
        }
        function pinMouseOver(e) {
            displayInfobox(e,false);
        }
        function pinMouseOut(e) {
            // TODO: detect if the mouse is already over the infoBox
            //  This can happen when the infobox is shown overlapping the pin where the mouse is at
            //    In that case, we shouldn't start the timer.
            //startInfoboxTimer(e);
        }
        function pinInfoboxMouseLeave(e) {
            hideInfobox(e);
        }
        function pinInfoboxMouseEnter(e) {
            // NOTE: This won't fire if showing infoBox ends up putting it under the current mouse pointer.            
            //stopInfoboxTimer(e);
        }
        function timerTriggered(e) {
            hideInfobox(e);
        }

 /***************************************************************/

