

// -----------------------------------------------------------------------------
// initialize the map
// -----------------------------------------------------------------------------

locationOrigin = {};
var locationDestination;
var SelectValue, selectOrigin, myMapOptions
var valOrigin, valDestination
var iOrigin, iDestination;
var latlng, geocoder, map;
var distance, directionDisplay;
var scriptRun;
var markerArray = [];


function initRouteElements() {
  if ($(".m_Google_Route").length > 0) {
    // init the click elements
  
    $(".reverseSearch").click(function(){
      valOrigin = $("#iOrigin").val();
      valDestination = $("#iDestination").val();
      
      if ($.trim(valOrigin) == '' || $.trim(valDestination) == ''){
        alert("Please fill in your address.");
      }
      
      if ($.trim(valOrigin) != '' && $.trim(valDestination) != ''){
        $("#iOrigin").val(valDestination);
        $("#iDestination").val(valOrigin);
        valOrigin = $("#iOrigin").val();
        valDestination = $("#iDestination").val();
        
        if ($("#iOrigin").hasClass("lindeAdress")) {
          $(".lindeAdress").removeClass("lindeAdress");
          $("#iDestination").addClass("lindeAdress");
        }

        if ($("#iDestination").hasClass("lindeAdress")) {
          $(".lindeAdress").removeClass("lindeAdress");
          $("#iOrigin").addClass("lindeAdress");
        }
        reloadRouteSearch();
        return false;
      }
    });
    
    $(".m_Google_Route .submitButton").click(function(){
      valOrigin = $("#iOrigin").val();
      valDestination = $("#iDestination").val();
      
      if ($.trim(valOrigin) == '' || $.trim(valDestination) == ''){
        alert("Please fill in your address.");
        return false;
      }
      if ($.trim(valOrigin) != '' && $.trim(valDestination) != ''){
        routeSearch();
        return false;
      }
    });

  }
}

function fillInput() {
	// getting the linde address value and fill it into input element
  SelectValue = $(".contactSelect").val();
  selectOrigin = $(".contactInformation div#" + SelectValue +" .googleAddress").text();
  $(".lindeAdress").addClass("filled").val(selectOrigin);  
}

function showLocation() {

  geocoder = new google.maps.Geocoder(); // creating a new geocode object

	// if - service teaser
  if ($("#m_contactMap").length > 0 ) { 
    selectServiceOrigin = $(".m_Contact_Map .googleAddress").text(); 
    // finding out the linde coordinates
  	if (geocoder) {
  		geocoder.geocode( { 'address': selectServiceOrigin}, function(results, status) {
  			if (status == google.maps.GeocoderStatus.OK) {
  				//location of first address (latitude + longitude)
  				locationOrigin = results[0].geometry.location;
          loadMap();
  			}
  			else {
  			  alert("We are sorry but we couldn't find the address.");}
  		});
  	}
  }
  
  // else - map in Content Area + print version
	else { 
	  fillInput();
	  // finding out the linde coordinates
  	if (geocoder) {
  		geocoder.geocode( { 'address': selectOrigin}, function(results, status) {
  			if (status == google.maps.GeocoderStatus.OK) {
  				//location of first address (latitude + longitude)
  				locationOrigin = results[0].geometry.location;
          loadMap();
  			}
  			else {
  			  alert("We are sorry but we couldn't find the address.");}
  		});
  	}
	}

	// load location inside map - set marker
	function loadMap() {
		var latlng = new google.maps.LatLng(locationOrigin.lat(),locationOrigin.lng());

		if ($("#m_googleMap").length > 0) {
  		myMapOptions = {
  			zoom: 16,
  			center: latlng,
  			mapTypeId: google.maps.MapTypeId.ROADMAP
  		};
  		var map = new google.maps.Map(document.getElementById("m_googleMap"), myMapOptions);
  	}
  	
  	// get Service Teaser variable
  	if ($("#m_contactMap").length > 0) {
  		myMapOptions = {
  			zoom: 12,
  			disableDefaultUI: true,
  			center: latlng,
  			mapTypeId: google.maps.MapTypeId.ROADMAP
  		}
  		var map = new google.maps.Map(document.getElementById("m_contactMap"), myMapOptions);
  	}

		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title: iOrigin
		});
	}
}



function reloadRouteSearch() {
  $(".lindeAdress").addClass("filled").val(iOrigin);
  // debugging $("h1").append(" r");
  routeSearch();
}
function dropdownReloadRouteSearch() {
  fillInput();
  routeSearch();
}


// -----------------------------------------------------------------------------
// search for the route
// -----------------------------------------------------------------------------

function showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  $("#directions").append('<div id="steps"></div>');
  var myRoute = directionResult.routes[0].legs[0];

  for (var i = 0; i < myRoute.steps.length; i++) {
    //alert(myRoute.steps[i].distance.text);
    $("#directions #steps").append('<div><span class="col_distance">' + myRoute.steps[i].distance.text + '</span><span class="col_number">' + (i+1) + '.</span>' + myRoute.steps[i].instructions + '</div>');
  }
  $("#directions #steps div:odd").addClass("odd");
  $("#directions #steps div:first").addClass("firstElement");
}



// creates and shows the map
function routeSearch() {
	// disable click elements during route request
  $('.reverseSearch').unbind('click').click(function(){ return false; });
  $('.m_Google_Route .submitButton').unbind('click').click(function(){ return false; });
  // debugging $('h1').css('color','red');
  
  // reset error alert
	errorAlert = 0;
	
	// reset last search
	$("#directions").empty();
  
  // get address variables
  var iOrigin = $("#iOrigin").val();
  var iDestination = $("#iDestination").val();
  
	// set map options: zoom level - center - type
	var myMapOptions = {
		zoom: 10,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	// create a new map object
	var map = new google.maps.Map(document.getElementById("m_googleMap"), myMapOptions);

	// Create a renderer for directions and bind it to the map.
  var rendererOptions = {
    map: map,
    suppressMarkers: false,
    suppressInfoWindows: false
  }
  
  // show route between the points
	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

	directionsDisplay.setMap(map);
	//directionsDisplay.setPanel(document.getElementById("directions"));
  
	var request = {
		origin:iOrigin, 
		destination:iDestination,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

  // Request for the Route Directions
	directionsService.route(request, function(response, status) {

		if (status == google.maps.DirectionsStatus.OK) {
			
			// this load the Route Directions
			directionsDisplay.setDirections(response);
      
			//add distance to Header
			$("#m_googleDirections").show();
      $("#m_googleDirections h3 span").remove();
			distance = " <span> "+response.routes[0].legs[0].distance.text;
      distance += " - "+response.routes[0].legs[0].duration.text+"</span>";
      $("#m_googleDirections h3").append(distance);
      $(".m_printPage .cssButton").show();
      
      // add Start and End Points
      $("#directions").prepend("<div class='adp-placemark'>" + response.routes[0].legs[0].start_address + "</div>");
      
      // and add the steps
      showSteps(response);
      
      //finally add the copyright
      $("#directions").append("<div class='adp-placemark'>" + response.routes[0].legs[0].end_address + "</div>");
      $("#directions").append("<div class='adp-legal'>" + response.routes[0].copyrights + "</div>");
      
      //Resize Container on print page
      if ($("#print_Header").length > 0) {
        // $("#MainContainer").css("height","auto");
        //         $("#pagewrapper").css("height","auto");
        $(".grid_6_container").css("height","auto");
        window.setTimeout(function() {
          // setMainContainerHeight = $("#MainContainer").height();
          //           $("#MainContainer").height(setMainContainerHeight);
          //           setMainContainerHeight = $("#pagewrapper").height();
          //           $("#pagewrapper").height(setMainContainerHeight);
          $(".grid_6_container").each(function() {
            containerHeight = $(this).height();
            if ($(".ie").length > 0) {}
            else {$(this).height(containerHeight);}
          });
        }, 600);
      }

		}

		else {
		  showLocation();
		  if (errorAlert == 0) {
		    errorAlert = 1;
		    alert("We are sorry but we couldn't find the address. Please try to be more specific.");
		  }
		}

	});

  // reenable click elements after route request
  window.setTimeout(function() { initRouteElements(); }, 600);

}






// ----------------------------------------------------------------------------
// --- DOCUMENT READY ---------------------------------------------------------
// ----------------------------------------------------------------------------

$(document).ready(function(){
  initRouteElements();
});

