/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var destinations = [
  ['UC Health Surgical Hospital', 39.361276,-84.365777, 1],
  ['Imaging Center',39.360744,-84.366779],
  ['Sleep Medicine Center',39.356231,-84.366788]
];

var startingPoints = [
  ['I-75 South', 39.389244, -84.363971],
  ['I-75 North', 39.10028816961876, -84.521244764328],
  ['I-71 South', 39.27720593612153, -84.34150457382202],
  ['I-71 North', 39.09721967940193, -84.51956033706665],
  ['I-471 North', 39.090824711918785, -84.47582960128784]
];
var directionsService;
var map;
var directionsDisplay;
var initializing;

function initializeMaps()
{

	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer();
        initializing = true;
        //alert(initializing);
        
	var myLatlng = new google.maps.LatLng(39.359298,-84.36541);
    
	var myOptions = {
          scrollwheel:false,
          zoom: 15,
          zoomControlOptions: {
              style: google.maps.ZoomControlStyle.LARGE
            },
            center: myLatlng,
          mapTypeId: google.maps.MapTypeId.HYBRID,
          unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
          navigationControl: true,
          mapTypeControl: false,
          scaleControl: true

    }
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    //directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));

    var markers = [];
    for (var i = 0; i < destinations.length; i++) {
        var beach = destinations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3]});
        markers[i] = marker;
      }
    
   // $("#map-message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
    
    $(markers).each(function(i,marker){ 
    	var beach = destinations[i];
    	 $("<li />") 
 	    	.html("<h3>"+beach[0].toString()+"</h3>") 
 	    	.click(function(){ 
 	    		map.panTo(marker.position);
 	    		//displayPoint(marker, i);
 	    }) 
 	    .appendTo("#map-list");
    });
    
    // Hide a map label, location name has changed but Google Maps has not updated yet.
    //drawCover(map);
    
    // Add an information window the marker with correct name and address.
    var contentString = '<div id="infoWin"><div id="bodyContent"><p><strong>UC Health Surgical Hospital</strong><br />7750 University Court<br/>West Chester, Ohio 45069</p></div></div>';
    addMarkerWindow(map, markers[0],contentString);

    contentString = '<div id="infoWin"><div id="bodyContent"><p><strong>Imaging Center</strong><br />7700 University Court, Suite 1800<br/>West Chester, Ohio 45069</p></div></div>';
    addMarkerWindow(map, markers[1],contentString);

    contentString = '<div id="infoWin"><div id="bodyContent"><p><strong>Sleep Medicine Center</strong><br />7777 University Drive, Suite A<br/>West Chester, Ohio 45069</p></div></div>';
    addMarkerWindow(map, markers[2],contentString);
    
    calcDirections();
}  


function calcDirections()
{
	var startIndex = document.getElementById("start").value;
	var endIndex = document.getElementById("end").value;
	//var endIndex = 0;
	
	//var startLoc = start.split(",");
	//var endLoc = end.split(",");

	directionsDisplay.setPanel(document.getElementById("directionsPanel"));
	
	var start = new google.maps.LatLng(startingPoints[startIndex][1],startingPoints[startIndex][2]);
	var end = new google.maps.LatLng(destinations[endIndex][1],destinations[endIndex][2])

        if (!initializing)
        {
            map.panTo(end);
        }
        else
        {
            initializing = false;
        }

	var request = {
		origin:start, 
		destination:end,
		unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
   
	directionsService.route(request, function(result, status)
			{
				if (status == google.maps.DirectionsStatus.OK)
	   			{
	   				myDisplaySteps(result, startIndex, endIndex);
	   			}
			});
}

function generateRow(stepMarkup, num, txt, dist)
{
    stepMarkup = stepMarkup.replace(/\%dirsegtext\%/, txt);
    stepMarkup = stepMarkup.replace(/\%num\%/, num);
    stepMarkup = stepMarkup.replace(/\%sdist\%/, dist);
    stepMarkup = applyFilters(stepMarkup);
    return stepMarkup;
}

/**
 * Applies surgical hospital-specific filters to the directions markup
 */
function applyFilters(stepText)
{
        var endIndex = document.getElementById("end").value;
        if (endIndex == 0 && stepText.indexOf('University Dr')>-1)
        {
            stepText = stepText.replace('University Dr','University Court. The Surgical Hospital is on the right.');
        }
        else if (endIndex == 1 && stepText.indexOf('University Dr')>-1)
        {
            stepText = stepText.replace('University Dr','University Court. The Imaging Center is at the end of the court.');
        }
        return stepText;
}

function myDisplaySteps(route, start, end)
{
	var myRoute = route.routes[0].legs[0];
	var directionsPanel = $("#directionsPanel");
	var stepBody = $('#directionsPanel .stepBody');
	var stepCounter = 1;
	
	var startingPoint = startingPoints[start];
	var destination = destinations[end];

	// Builds header of directions
	$('#directionsHead').html('Driving Directions to ' + destination[0].toString());
	
	if (typeof(myRoute.start_address) != 'undefined')
	{
		$('#directionsPanel .tripSource').html("From " + startingPoint[0].toString());
	}
	else
	{
		$('#directionsPanel .tripSource').html('');
	}
  
	$('#directionsPanel .totalDuration').html(myRoute.duration.text);
	$('#directionsPanel .totalDistance').html('('+myRoute.distance.text+')');
	
	// Building body of directions    
	var stepRow = $(stepBody).html();
    for (var i = 0; i < myRoute.steps.length; i++)
    {
        var step = myRoute.steps[i];
        var stepMarkup = stepRow;

        // By default, use what Google supplied.
        var stepText = step.instructions;
        var stepDist = step.distance.text;
        
        $(stepBody).append(generateRow(stepMarkup, stepCounter++, stepText, stepDist)); 
    }
	
    $(stepBody).find('tr:not(:first)').removeAttr('style');
    
    var putDirectionsHere = $("#putDirectionsHere");
    var newIndex = putDirectionsHere.children().length;
    var newHtml = ("<div id=\"ddr_route_" + newIndex + "\">" + directionsPanel.html() + "</div>");
    putDirectionsHere.html(newHtml);
    directionsPanel.find("tr").slice(1).remove();
    $('#drivingdirectionsResults').show();
    
    $('table.striped tr:even').addClass('map-alternate-step');
    
}

function addMarkerWindow(map, marker, content)
{
	
	var infowindow = new google.maps.InfoWindow({
		content: content
	});
	
	//infowindow.open(map,marker);
	
	google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); });
}


function drawCover(map)
{
	var rectCoords = [
                      new google.maps.LatLng(39.361871,-84.366642),
                      new google.maps.LatLng(39.361821,-84.364218),
                      new google.maps.LatLng(39.361108,-84.36426),
                      new google.maps.LatLng(39.361141,-84.366578),
                      new google.maps.LatLng(39.361871,-84.366642)
                    ];
	 var coverRect = new google.maps.Polygon({
	        paths: rectCoords,
	        strokeColor: "#e5c6c3",
	        strokeOpacity: 1,
	        strokeWeight: 2,
	        fillColor: "#e5c6c3",
	        fillOpacity: 1
	      });

	 coverRect.setMap(map);
}
