// be-mobile (c) 2010
// This code is protected by copyright law. 

// v1.0 : Release Routeplanner Basic
// v1.1 : Add Google Traffic/ POI Logic



            var map;

            var tm_gdir;
			var tm_viaCount = 0;	
			var tm_mergedvias_array = []; // initialise array for via points 
			var tm_avoidhighway = false; // highways avoid initially
			var tm_traffic_on = false; // control is closed initially
			var tm_POI_on = false; // control is closed initially
            var geocoder = null;
			var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(50,10));
			var tm_printmap = false;
			
			// Routeplanner Phase2 variables			
			// Traffic Variables
			var traffic_overlays = [];
			// POI variables
			var poi_overlays = []
						
			// from index
            function tm_loadData() {
			
              if (GBrowserIsCompatible()) {      
                map = new GMap2(document.getElementById("map_container"));
				map.addControl(new GMapTypeControl(), topRight);
				tm_TrafficPreload();
				
				// Trafficbutton
				map.addControl (new TrafficControl());
				tm_TrafficInitialize(); // set up Trafficbutton elements
						
				// POI button
				map.addControl (new POIControl() ); 
				tm_POIInitialize();
								
				// add Google Controls
				map.addControl(new GLargeMapControl3D());
                map.setCenter(new GLatLng(50.4419, 4.2819), 8);
						
				//map.enableScrollWheelZoom();

                }// endif
                        
			
			tm_directions_panel =  document.getElementById("directions")
			tm_gdir = new GDirections(map, tm_directions_panel);

			// EventListener to add overlay
			GEvent.addListener (tm_gdir, "addoverlay", function() {
	
				// Fix tab width ie!!!
				getTds = document.getElementsByTagName('TD');
				for(vari=0;i<getTds.length;i++)
				{
					if(getTds[i].getAttribute("jseval"))
					{
						if(getTds[i].getAttribute("jseval").indexOf('descriptionHtml') != -1)
						{
							getTds[i].innerHTML = cutText(getTds[i].innerHTML);
						}
					}
				}
			
													
			}); //end eventlistener
			
			  
			  
			  // Eventlistener when error is received
			GEvent.addListener(tm_gdir,"error", function() {
			  
				// call handle Errors
				handleErrors()
				// 
				$('#tm_maps_status_message').append (tm_statusMessage );
				
			}); //end eventlistener
			
			  
			  // Eventlistener when everything went fine
			GEvent.addListener(tm_gdir,"load", function() {

			// getting the overall route information
			tm_RouteSummaryHTML =  tm_gdir.getSummaryHtml();
				
			// add summary
			$('.duration').append ('DUREE DU TRAJET : <strong> ' + tm_RouteSummaryHTML + '</strong> ');
			// enable access to print
			$('#Gmap_printMap').removeClass ('hide'); // show the print map button
			$('.Gmap_adsLinks').removeClass ('hide'); // show the ads when result
		   
			}); // end eventlistener
			  
			}// end loaddata
		   
		    function checkUncheck(oImg, sChkId){
				// Invert Img
				var oChk = document.getElementById(sChkId);
				oChk.checked = !oChk.checked;
				oImg.src = (oChk.checked) ? "../icons/crash.gif" : "../icons/incident.png";
				map.addOverlay(new GGeoXml(mypath))
				}
			
			
			function tm_TrafficPreload() {
				
				for (var tr_item in tm_traff_countries) {
					
					var country = tm_traff_countries[tr_item]
					
						for (i=0 ; i<tm_traff_options.length; i++) {
							var shortName = country + '.' +(i+1)+".kmz" ; //create keypair shortName array e.g. NL.2.kmz
							traffic_overlays[shortName] = new GGeoXml(buildTrafficOverlayName(shortName)); // build keypair array
											
						} // end for traff options
				} // end for var
			} // end Preload
				

			function tm_TrafficInitialize() {
				// Build TrafficControl + logic
				if (tm_debug == true) {
					GLog.write ("in tm_TrafficInitialize");
					}// end if
					
				
				for (i=0 ; i<tm_traff_options.length; i++) {
				
				// create input elements + box	
					traffic_box_height = traffic_box_height+20; 
					$('#container').append ( "<div id='mydiv" + i +"'>");
					$('#mydiv' + i).addClass('labelForStyler') // add class for divs 
									.append ( "<label for='" + tm_traff_options[i] + "'>" + tm_traff_options[i] + "</label><input id='" + tm_traff_options[i] + "' type='checkbox' name='" + tm_traff_options[i] + "' value='"+(i+1)+"' />" ) // // add elements and attributes
									.hide() ; // hide initially
					
				} // end for i

				// set attribute value to true for default traffActive options and active layer
				
				try {
						for (var traffitem in tm_traff_active_options) {
						//e.g tm_traff_active_options[item] ...this can be  files, accidents
						var inputname =tm_traff_active_options[traffitem]; //
							$('#'+inputname).attr('checked', 'true'); // set the checkboxes visually for user
							var inputvalue = document.getElementById(inputname).value // get the value
						
						// get all countries that have this value so we can put layer alive
						
							for (var index in tm_traff_countries) {
								var countryitem = tm_traff_countries[index];
								var full_link = countryitem + '.'+inputvalue + '.kmz'
								var layer_traff_obj = traffic_overlays[full_link]
								map.addOverlay(layer_traff_obj)  // add overlay to Google map obj "map"
							} //end for var index
						} // end for var traffitem
					
				} // end try
				
				
				catch (e) {"Error adding default overlay" + e;
							window.alert("Dear developer. Your item =>>> " + inputname + " was not found in list.  It will be deleted from default options. Correct the array tm_traffic_active_options and use the correct syntax. ");
							delete traffic_overlays[traffitem];
				} // end catch
				

			tm_TrafficListener();

	
			} // end trafficinit
			
			function buildTrafficOverlayName(layerName) {
				return tm_traffic_path + layerName + '?rand=' + (new Date()).valueOf();
			}
			
			function tm_TrafficListener() {

				$("#container :checkbox").click(function()  {
				// update the for example:
				
					if ($(this).is(':checked')) {
					// ADD THE CHECKED OVERLAY	
						var links = (this.value) // e.g. links = 4 >> means add 4th item (roadworks) //
						
						// create all objects that contain "links" in traffic_overlays[array] key name
						for (var identifier in traffic_overlays) {
							if (identifier.charAt(3) == links) {
								var layer_traff_obj = traffic_overlays[identifier] 	// define layer Object
								
								try {
									map.addOverlay(layer_traff_obj)  // add overlay to Google map obj "map"
									}
									
								catch (e) {
									window.alert("Problems adding layers. Error message : " + e + " in function  tm_TrafficListener. Please contact info@touring.be to report the issue to make this product even better. ")
									}
														
								
							} // end if 
						} // end for var
					} //end if 

	
					else {
					// REMOVE THE OVERLAY	
						var links = (this.value)
							for (var identifier in traffic_overlays) {
								if (identifier.charAt(3) == links) {
									var layer_traff_obj = traffic_overlays[identifier] 	// define layer Object
									map.removeOverlay(layer_traff_obj)  // add overlay to Google map obj "map"
								}// end if
							}// end for
					
					} // else

			   }) // end click

			}


/*
//			Functions to add POI control to stage and add logic (eventListeners and handling)
//
*/

			function tm_POIInitialize(){
			
			if (tm_debug == true) {
			GLog.write ("in tm_POIInitialize");
			}// end if
					
			for (i=0 ; i<tm_poi_options.length; i++) {
				
				// create input elements + box	
					poi_box_height = poi_box_height+20; 
					$('#poi_container').append ( "<div id='poidiv" + i +"'>");
					$('#poidiv' + i).addClass('labelPOIStyler') // add class for divs 
									.append ( "<label for='" + tm_poi_options[i] + "'>" + tm_poi_options[i] + "</label><input id='" + tm_poi_options[i] + "' type='checkbox' name='" + tm_poi_options[i] + "' + value='"+tm_poi_options[i]+ "' />" ) // // add elements and attributes
									.hide() ; // hide initially
				
					var shortName = tm_poi_options[i]+tm_poi_fileext ; //create keypair shortName array (e.g. 'Hotels'+'_nl.kmz' = Hotels_nl.kmz)
					poi_overlays[shortName] = new GGeoXml(buildPOIOverlayName(shortName)); // build keypair array
					
				
				} // end for

				// set attribute value to true for default traffActive options and activate layer
				
				try {	
						for (var tm_poi in tm_poi_active_options) {
							//e.g tm_poi_active_options[item] ...this can be hotels, restaurants
							
							var poi_name = tm_poi_active_options[tm_poi];
							$('#'+poi_name).attr('checked', 'true'); // set the checkboxes visually for user
							// get Obj by referring to Link so we can add Layer
							var p_link = document.getElementById(poi_name).name; // get Link by referring to name
							var poi_link = p_link+tm_poi_fileext // add language identifier and file extension
							layer_poi_obj = poi_overlays[poi_link] // create object
							
							map.addOverlay(layer_poi_obj)	// add overlay to Google map obj "map"
							} // end for  var item
					} // end try
					
				catch (e) { "Error adding default overlay" + e;
							window.alert("Dear developer. Your item =>>> " + tm_poi_active_options[tm_poi] + " was not found in list . It will be deleted from default options. Correct the array tm_poi_active_options and use the correct syntax. ");
							delete poi_overlays[poi_link];	
				} // end catch
							
				POIListener()
				
				
			
			} // end poi init
			
			function buildPOIOverlayName(layerName) {
				return tm_poi_path + layerName + '?rand=' + (new Date()).valueOf();
			}
			
			function POIListener () {

				$("#poi_container :checkbox").click(function()  {
						// update the for example:
						
				  if ($(this).is(':checked')) {
					  // there is a new layer to be added
					  var links = (this.value)+ tm_poi_fileext //
					  var layer_poi_obj = poi_overlays[links];// activate the layer
					  
						  try 	{	
							  map.addOverlay(layer_poi_obj)	
								} // end try
						  catch (e) {
									  window.alert("Problems adding layers. Error message : " + e + " in function  tm_POIListener Please contact info@touring.be to report the issue to make this product even better. . ")
							} // end catch
						  
				  }// if 
	
				  else {
					  
					  var links = (this.value)+ tm_poi_fileext
					  var layer_poi_obj = poi_overlays[links];
					  //delete traffic_overlays[links]
					  map.removeOverlay(layer_poi_obj)
				  } // else
	
				})            // end click	
				
			}

			function tm_checkClasses() {
				
			if (tm_debug == true) {
				GLog.write ("in tm_checkClasses");
			
				if ($('.gm-steps').length == 0 ) {
					alert ("Missing class gm-steps. This error should not occur. ");
					};
	
				if ($('#Gmap_printMap').length == 0 ) {
					alert ("Missing class printMap. This error should not occur. ");
					};
					
				if ($('#tm_maps_status_message').length == 0 ) {
					alert ("Missing class printMap. This error should not occur. ");
					};
	
					
				} // end tm_checkClasses
			}

			
            function tm_setDirections() {
				
				// combined the start , via ways and end point by pushing into array
			
				// hide print icon
				$('#Gmap_printMap').addClass ('hide');
			
				var fromAd = document.getElementById('startAddress').value;
				var toAd = document.getElementById('endAddress').value;
				
				
				//clear previous status message and hide div
				$('#tm_maps_status_message').empty().hide();
				
				// clear duration message
				$('.duration') .empty();
				
				// clear the array
				tm_mergedvias_array= []; // clear the array
				
				// push start address
				tm_mergedvias_array.push (fromAd);
						
				// push via's
				for (i=1; i < tm_viaCount+1; i++) 
					{
						tm_mergedvias_array.push (document.getElementById('step_' +i).value);
					}// end for loop
				
				// add endAddress
				tm_mergedvias_array.push (toAd);
				
				// submit Query
				tm_gdir.loadFromWaypoints(tm_mergedvias_array,{"avoidHighways": tm_avoidhighway, "travelMode":CURRENT_TRAVEL_MODE, getSteps:true, "locale":localeBE}); 

				// show n' hide options
				tm_shownHide();
				
				//alert($('.googledir').html());
				//document.getElementById('directions').innerHTML = cutText(document.getElementById('directions').innerHTML);

				
            } // end function setDirections
            
			function cutText(string){
				return string.replace(/[a-zA-Z0-9]\//g, " / ");
			}


			function tm_shownHide() {
				// show/hide div when direction result is positive
				
				if (tm_viaCount>0) {$('.duration').removeClass ('hide');
					// show duration div only when via > 1 - Google already shows the result -
					} else {$('.duration').addClass ('hide');}
				
				$('#iab_banner_big').hide(); // hide big
				$('#iab_banner_small').removeClass ('hide'); // show small
												
				}
				
			function tm_printGMap() {
				// print the map and route description when print button is clicked
				print();
				}
		
		
            function handleErrors(){
				
				// clear statusMessage				
				tm_statusMessage ="";
				$('#tm_maps_status_message').show()
							
				switch(tm_gdir.getStatus().code) {
					
					case  G_GEO_BAD_REQUEST: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Adres is niet gekend. Verifieer of alle velden zijn ingevuld. ";
							}
							else {tm_statusMessage= "L'adresse n'est pas connue. V&eacute;rifiez si toutes les donn&eacute;es sont correctes. ";}
							
						break;
						} // end case
						
				
					case G_GEO_SERVER_ERROR: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Adres is niet gekend. Kies een andere vertrekplaats of bestemming.  ";
							}
							else {tm_statusMessage="L'adresse n'est pas connue. Choissisez un autre d&eacute;part ou une autre destination. ";}
							
						break;
						} // end case
	
					case (G_GEO_MISSING_QUERY && G_GEO_MISSING_ADDRESS): {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Adres is niet gekend. Kies een andere vertrekplaats of bestemming.  ";
							}
							else {tm_statusMessage="L'adresse n'est pas connue. Choissisez un autre d&eacute;part ou une autre destination. ";}
							
						break;
						} // end case
	
					case  G_GEO_UNKNOWN_ADDRESS: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Adres is niet gekend of via-punt is niet ingevuld . Kies een andere vertrekplaats of bestemming en verifieer of het via-punt is ingevuld.  ";
							}
							else {tm_statusMessage="L'adresse n'est pas connue ou l'etape n'est pas remplie. Choissisez un autre d&eacute;part ou destination et v&eacute;rifiez si l'&eacute;tape est correctement remplie. ";}
							
						break;
						} // end case
						
					case G_UNAVAILABLE_ADDRESS: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Adres is niet gekend. Kies een andere vertrekplaats of bestemming. ";
							}
							else {tm_statusMessage="L'adresse n'est pas connue. Choissisez un autre d&eacute;part ou une autre destination. ";}
							
						break;
						} // end case
	
	
					case G_UNKNOWN_DIRECTIONS: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="De route kon niet worden berekend. Kies een andere vertrekplaats of bestemming. ";
							}
							else {tm_statusMessage="La route n'a pas pu &ecirc;tre calcul&eacute;e. Choissisez un autre d&eacute;part ou une autre destination. ";}
							
						break;
						} // end case
							
	
					case G_GEO_BAD_KEY: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Systeem fout. API sleutel is niet korrekt. ";
							}
							else {tm_statusMessage="Erreur de syst&egrave;me. Cl&eacute; API n'est pas correcte. ";}
						break;
						} // end case
						
					case G_GEO_TOO_MANY_QUERIES: {
						
						if (localeBE=="nl_BE") {
							tm_statusMessage ="Systeem fout. Teveel aanvragen. ";
							}
							else {tm_statusMessage="Erreur de syst&egrave;me. Trop de demandes. ";}
						break;
						} // end case
	
					default:
						tm_statusMessage="";
						break;
	
					} // end switch
              
			} // end function
			

			
