// JavaScript Document
/// Copyright TRAX Business Solutions 2009

	var map;
	var gdir;
	var mgrToll;
	var mgrRSA;
	var mgrLB;
    var icons = {};
    var allmarkers = [];
	var gmarkersToll16 = [];      
	var gmarkersToll48 = [];  
	var gmarkersRSA16 = [];      
	var gmarkersRSA48 = [];   
	var gmarkersLB16 = [];      
	var gmarkersLB48 = [];   
		
		

function initialize() {
	
	

  if (GBrowserIsCompatible()) {      
      
	  //var map;
	  
  	  function createMap() {
		  
	  var om = new OverlayMessage(document.getElementById('map'));      
	  // display the loading message
	  om.Set('<b><img src=\"fileadmin/plusmaps/ajax-loader.gif\" /><\/b>');
	  
	  map = new GMap2(document.getElementById("map"));
	  
	  map.addControl(new GSmallMapControl());
	  map.addControl(new GMapTypeControl());
      
	  
      var n=0;

      var icon = new GIcon();
      icon.image = "fileadmin/plusmaps/image.png";
      //icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      icon.iconSize = new GSize(12, 20);
      //icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);      
		
	  //ICONS
	  //TOLL
      iconToll16 = new GIcon(icon,"fileadmin/plusmaps/toll16.png"); 
	  iconToll16.iconSize = new GSize(10, 16)
	  
	  iconToll48 = new GIcon(icon,"fileadmin/plusmaps/toll48.png"); 
	  iconToll48.iconSize = new GSize(30, 38)
	  
	  //RSA
      iconRSA16 = new GIcon(icon,"fileadmin/plusmaps/rsa16.png"); 
	  iconRSA16.iconSize = new GSize(10, 16)
	  
	  iconRSA48 = new GIcon(icon,"fileadmin/plusmaps/rsa48.png"); 
	  iconRSA48.iconSize = new GSize(30, 38)
	  
	  //LB
      iconLB16 = new GIcon(icon,"fileadmin/plusmaps/lb16.png"); 
	  iconLB16.iconSize = new GSize(10, 16)
	  
	  iconLB48 = new GIcon(icon,"fileadmin/plusmaps/lb48.png"); 
	  iconLB48.iconSize = new GSize(30, 38)


      function createMarker(point,name,html,icon) {
        var marker = new GMarker(point, {icon:icon});
        GEvent.addListener(marker, "click", function() {
          marker.openExtInfoWindow(
			map, 
            "custom_info_window_red",
			'<span>' + html + '</span>'
			);
        });
        return marker;
      }

      // read the markers from the XML
      GDownloadUrl(xmlfile, function (doc) {
				
        var gmarkersD = [];      
        var xmlDoc = GXml.parse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

          
        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new GLatLng(lat,lng);
          var name = markers[i].getAttribute("name");
		  var info = markers[i].firstChild.nodeValue;
          var type = markers[i].getAttribute("type");
		  var facility = markers[i].getAttribute("facility");
		  var direction = markers[i].getAttribute("direction");
          // split the markers into four arrays, with different GIcons
          if (parseInt(type) == 1) {
             var marker = createMarker(point,name,"<h5>"+name+"</h5>Services:<div class=\"services\">"+info+"</div>",iconToll16);
             gmarkersToll16.push(marker);
			 var markerBig = createMarker(point,name,"<h5>"+name+"</h5>Services:<div class=\"services\">"+info+"</div>",iconToll48);
			 gmarkersToll48.push(markerBig);
          }
          else if (parseInt(type) == 2) {
             var marker = createMarker(point,name,"<h5>"+name+"</h5>"+direction+"<div>Amenities:</div><div class=\"amenities\">"+info+"</div>",iconRSA16);
             gmarkersRSA16.push(marker);
			 var markerBig = createMarker(point,name,"<h5>"+name+"</h5>"+direction+"<div>Amenities:</div><div class=\"amenities\">"+info+"<br />",iconRSA48);
			 gmarkersRSA48.push(markerBig);
          }
          else if (parseInt(type) == 3) {
             var marker = createMarker(point,name,"<h5>"+name+"</h5>"+direction+"<div>Amenities:</div><div class=\"amenities\">"+info+"<br />",iconLB16);
             gmarkersLB16.push(marker);
			 var markerBig = createMarker(point,name,"<h5>"+name+"</h5>"+direction+"<div>Amenities:</div><div class=\"amenities\">"+info+"<br />",iconLB48);
			 gmarkersLB48.push(markerBig);
          }
          else {
             var marker = createMarker(point,name,"<h5>"+name+"</h5>Amenities:<br />"+info+"<br />",icon);
             gmarkersD.push(marker);
          }
        }

        // Display the map, with some controls and set the initial location 
		$('directions').set('text','');
        gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap, Esa
		map.setCenter(new GLatLng(4.02866,101.95313),7);	// inital setCenter()  added by Esa.
		map.clearOverlays();
		setDirections(start,ende);   //Startet Map Center
		map.hoverControls();
		
		mgrLB = new GMarkerManager(map, { });
		mgrLB.addMarkers(gmarkersLB16,0,12);
		mgrLB.addMarkers(gmarkersLB48,13,17);
		mgrLB.refresh();
		
		mgrToll = new GMarkerManager(map, { });
		mgrToll.addMarkers(gmarkersToll16,0,12);
		mgrToll.addMarkers(gmarkersToll48,13,17);
		mgrToll.refresh();
		
		mgrRSA = new GMarkerManager(map, { });
		mgrRSA.addMarkers(gmarkersRSA16,0,12);
		mgrRSA.addMarkers(gmarkersRSA48,13,17);
		mgrRSA.refresh();
		
        om.Clear(); // Clear the loading message
      });
	  
	  }
	  
        
      createMap();
	  
    }

    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

  
} //END initialize()

function showToll() {
        //var c=0;
		GUnload();
		map = $empty;
		//gdir = $empty;
		mgrToll = $empty;
		mgrRSA = $empty;
		mgrLB = $empty;
		/*
		gmarkersToll16 = $empty;      
		gmarkersToll48 = $empty; 
		*/
		gmarkersRSA16 = [];      
		gmarkersRSA48 = [];   
		gmarkersLB16 = [];      
		gmarkersLB48 = [];
		
		xmlfile = 'fileadmin/plusmaps/tollstations.xml';
		initialize();
  		
}

function showRSA() {
        //var c=0;
		GUnload();
		map = $empty;
		//gdir = $empty;
		mgrToll = $empty;
		mgrRSA = $empty;
		mgrLB = $empty;
		
		gmarkersToll16 = [];      
		gmarkersToll48 = []; 
		/*
		gmarkersRSA16 = $empty;      
		gmarkersRSA48 = $empty; 
		*/
		gmarkersLB16 = [];      
		gmarkersLB48 = []; 
		
		xmlfile = 'fileadmin/plusmaps/rsas.xml';
		initialize();
  		
}

function showLB() {
        //var c=0;
		GUnload();
		map = $empty;
		//gdir = $empty;
		mgrToll = $empty;
		mgrRSA = $empty;
		mgrLB = $empty;
		
		gmarkersToll16 = [];      
		gmarkersToll48 = []; 
		gmarkersRSA16 = [];      
		gmarkersRSA48 = [];  
		/*
		gmarkersLB16 = $empty;      
		gmarkersLB48 = $empty;
		*/
		xmlfile = 'fileadmin/plusmaps/laybys.xml';
		initialize();
  		
}

function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
  { "locale": locale , "getSteps":true});
}

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
  else alert("An unknown error occurred.");
}


//to hide and show the viewer type and zoom in/out capabilities
GMap2.prototype.hoverControls = function(){
  var theMap = this;
  theMap.hideControls();
  GEvent.addListener(theMap, "mouseover", function(){
    theMap.showControls();
  });
  GEvent.addListener(theMap, "mouseout", function(){
    theMap.hideControls();
  });
  theMap.libraryCard = 19162;
}
GMap.prototype.hoverControls = GMap2.prototype.hoverControls;
  
///////////////////////////////////////////////////////////////////////

/**
* The add-on code for draggable markers
* @author Esa 2008
*/
var newMarkers = [];
var latLngs = [];
var icons = [];

// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used

function onGDirectionsAddOverlay(){ 
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }

  // Loop through the markers and create draggable copies
  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], clickable: false, draggable:false, title:'Plus Highway'});
    map.addOverlay(newMarkers[i]);

    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragend", function(){
      var points = [];
      for (var i=0; i<newMarkers.length; i++){
        points[i]= newMarkers[i].getLatLng();
      }
      gdir.loadFromWaypoints(points);
    });

    //Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
  }

  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      GEvent.trigger(oldMarker,'click');
    });
  }
}


   window.addEvent('load', function() {
      initialize();
   });

  window.addEvent('unload', function() {
      GUnload();
   });
   
   window.addEvent('domready', function() {
		
	  $('fromAddress').set('value',window.start);
	  $('toAddress').set('value',window.ende);
      
	  var thisSlider = new Fx.Slide($('directionsDIV'), { duration: 500, transition: Fx.Transitions.Sine.easeOut } );
	  thisSlider.hide();
	  	  
	  $('showDirections').addEvent( 'click', function(){ 
	
		thisSlider.slideIn();
		$('showDirections').setStyles({'display':'none'});
		$('hideDirections').setStyles({'display':'block'});
		$('fromAddress').setStyles({'display':'block'});
		$('toAddress').setStyles({'display':'block'});
	  });
	  
	  $('hideDirections').addEvent( 'click', function(){ 

		thisSlider.slideOut();
		$('hideDirections').setStyles({'display':'none'});
		$('showDirections').setStyles({'display':'block'});
		$('fromAddress').setStyles({'display':'none'});
		$('toAddress').setStyles({'display':'none'});
	  });
	  
	  	$('changeLOC').addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			window.start = this.from.value;
			window.ende = this.to.value;
			window.setDirections(this.from.value, this.to.value); return false;
			this.send();
		});
		
		$('TOLL').addEvent( 'click', function(){
			 //map.clearOverlays(); 							 
			 showToll();
		 }); //reststops click
		
		$('RSA').addEvent( 'click', function(){
			 //map.clearOverlays(); 							 
			 showRSA();
		 }); //reststops click
		
		$('LB').addEvent( 'click', function(){
			 //map.clearOverlays(); 							 
			 showLB();
		 }); //reststops click


   }); //domready end

