var marker;
var map;
var geocoder;	
var infowindow;
var provincie;
var land_short;
var range = -1;
var series= "";
var type = "";
var eerstekeer = true;

var centerlat = 51.54176111744289;
var centerlong = 5.042155981063843;

var loc_choosen = 0;
var equip_choosen = 0;
var loc_available = 1;


// detect enter!
$(function(){
   var  testTextBox = $('.input-field');
    var code =null;
    testTextBox.keypress(function(e)
    {
        code= (e.keyCode ? e.keyCode : e.which);
        if (code == 13){
	        $("#searchbutton").click();
	        e.preventDefault();
        }
    });

});

$(document).ready(function(){

	// equipment select set to defaults (for firefox)
	$("#series_selection").val("");
	$("#type_selection").val("");

	// hide objects
	$("#output-container").hide();
	$("#notfound-container").hide();
	$("#loading-equip").hide();
	$("#loading-freq").hide();
	$(".equip-instructions").hide();
	$("#printbutton").hide();	
		
	// set initial map	
	map = loadMapOnCoordinates(centerlat, centerlong);
	
	google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); });

	geocoder = new google.maps.Geocoder();

	$("#printbutton").click(function(){
		window.open("print.php?lat="+$("#coordinateslat").val()+"&long="+$("#coordinateslong").val()+"&postal="+$("#postalcode").val()+"&town="+$("#town").val()+"&state="+$("#state_province").val()+"&country="+$("#country").val()+"&loc_available="+loc_available+"&loc_choosen="+loc_choosen+"&equip_choosen="+equip_choosen+"&serie="+series+"&type="+type+"&search_state="+provincie+"&search_country="+land_short+"&range="+range+"");
	});
	
	$("#resetbutton").click(function(){
		resetView();	
	});

	$("#resetbutton-header").click(function(){
		resetView();
	});

	$("#coordinateslat").click(function(){		
	 	if($("#coordinateslat").val() == "Lat"){
	 		$("#coordinateslat").val("");
	 		$("#coordinateslat").removeClass("grijs");
			$("#coordinateslat").addClass("blauw");
		}
	});
	
	$("#coordinateslong").click(function(){
	 	if($("#coordinateslong").val() == "Long"){
	 		$("#coordinateslong").val("");
	 		$("#coordinateslong").removeClass("grijs");
			$("#coordinateslong").addClass("blauw");
		}
	});
	
	
	//equipment drop down lists
	$("#series_selection").change(function(){
		range = -1;
		series = $("#series_selection").val();	
		
		if(series != "" && type != ""){
			equip_choosen = 1;
			
			$("#loading-equip").show();
			$("#pleaseselect-equipm-container").hide();
			

			$("#equipment-output-body").load("ajaxphp/equipmentfreq.php", {prov: provincie, land: land_short, range: range, series: series, type: type}, function() {
				$("#loading-equip").hide();
				$(".equip-instructions").show();
			});
			
		}
	});
	
	$("#type_selection").change(function(){
		type = $("#type_selection").val();	
		
		if(series != "" && type != ""){
			equip_choosen = 1;
			
			$("#loading-equip").show();
			$("#pleaseselect-equipm-container").hide();
			
			$("#equipment-output-body").load("ajaxphp/equipmentfreq.php", {prov: provincie, land: land_short, range: range, series: series, type: type}, function() {
				$("#loading-equip").hide();
				$(".equip-instructions").show();
			});
		}
	});
		
		
	//ZOEKEN	
	$("#searchbutton").click(function(){			
		loc_choosen = 1;
		
		//first clear the marker
		if(marker != null){
			marker.setMap(null);
		}
		
		//first clear the marker
		if(infowindow != null){
			infowindow.close();
		}
		
		
		//ZOEKEN OP COORDINATES
		if($("#coordinateslong").val() != "" && $("#coordinateslat").val() != "" && $("#coordinateslat").val() != "Lat" && $("#coordinateslong").val() != "Long"){
			
			
			/* From the goog API
			Notice that although usual map projections associate longitude with the x-coordinate of the map, and latitude with the y-coordinate, 
			the latitude coordinate is always written first, followed by the longitude
			*/
			var myLatlng = new google.maps.LatLng($("#coordinateslat").val(),$("#coordinateslong").val());
			
			if (geocoder) {
		      geocoder.geocode({'latLng': myLatlng}, function(results, status) {
		      	postcode = ""; stad = ""; land = ""; 
		        if (status == google.maps.GeocoderStatus.OK) {
		          if (results[1]) {
		            marker = new google.maps.Marker({
		                position: myLatlng, 
		                map: map
		            }); 
		            
		            //console.dir(results[0].address_components);
		            
		            $.each(results[0].address_components, function(){
		            	if(this.types[0] == "country"){
		            		land = this.long_name;
		            		land_short = this.short_name;
		            	}
		            	
		            	if(this.types[0] == "postal_code"){
		            		postcode = this.long_name;
		            	}
		            	
		            	if(this.types[0] == "locality"){
		            		stad = this.long_name;
		            	}               	
                	});
                
	                //provincie is afhankelijk van land
	                $.each(results[1].address_components, function(){
	     			    if(this.types[0] == "administrative_area_level_1" && land_short == "NL"){
		            		provincie = this.long_name;
		            	}
		            	
		            	if((this.types[0] == "administrative_area_level_2" || this.types[0] == "administrative_area_level_1") && land_short == "BE"){
		            		//console.log(this.lon)
		            		if(this.long_name == "Bruxelles"){
		            			provincie = this.long_name;
		            		}else if(this.types[0] == "administrative_area_level_2"){	            		
		            			provincie = this.long_name;	 	            		
		            		}
		            	}		
		            	
		            	if(this.types[0] == "administrative_area_level_1" && land_short == "LU"){
	            			provincie = this.long_name;	 	            		
	            		}
		            });
	                
	                $("#postalcode").val(postcode);
	                $("#country").val(land);
	                $("#town").val(stad);
	                $("#state_province").val(provincie);
			          
			        /* Geen infowindow    
			        infowindow = new google.maps.InfoWindow();
			        infowindow.setContent(results[1].formatted_address);
			       	infowindow.open(map, marker);
			       	*/
			            
			        map.setCenter(myLatlng); 
					map.setZoom(9);	
		          }
		          
		          loadAjax();
		          
		        } else {
		          alert("No results for coordinate "+$("#coordinateslat").val()+", "+$("#coordinateslong").val());
		          
		        }
		      });
		    }
	   	//ZOEKEN OP ADRES GEGEVENS
   		}else{
   			
	   		var address = $("#town").val()+', '+$("#postalcode").val()+', '+$("#state_province").val()+', '+$("#country").val();
	   		//console.dir(address);
	   		if (geocoder) {
		      geocoder.geocode( { 'address': address}, function(results, status) {
		     	
		     	postcode = ""; stad = ""; land = ""; leeg = false;
		     	if (status == google.maps.GeocoderStatus.OK) {
		      	  //console.dir(results[0].address_components);
		      	  $.each(results[0].address_components, function(){
	            	if(this.types[0] == "country"){
	            		land = this.long_name;
	            		land_short = this.short_name;
	            	}
	            	
	            	if(this.types[0] == "postal_code"){
	            		postcode = this.long_name;
	            	}
	            	
	            	if(this.types[0] == "locality"){
	            		stad = this.long_name;
	            	}   
	            	
	            	// hier niks mee doen!
	            	if(this.types[0] == "natural_feature"){
	            		leeg = true;
	            	}
                });
                
                
                
                //provincie is afhankelijk van land
                $.each(results[0].address_components, function(){
     			    if(this.types[0] == "administrative_area_level_1" && land_short == "NL"){
	            		provincie = this.long_name;
	            		leeg = false;
	            	}
	            	
	            	if((this.types[0] == "administrative_area_level_2" || this.types[0] == "administrative_area_level_1" || this.types[0] == "administrative_area_level_3") && land_short == "BE"){
	            		//console.log(this.lon)
	            		if(this.long_name == "Bruxelles"){
	            			provincie = this.long_name;
	            			leeg = false;
	            		}else if(this.types[0] == "administrative_area_level_2"){	            		
	            			provincie = this.long_name;	 	            		
	            			leeg = false;
	            		}
	            	}	 
	            	
	            	if(this.types[0] == "administrative_area_level_1" && land_short == "LU"){
	            		provincie = this.long_name;	 	            		
	            		leeg = false;
	            	}   
	            	
	            	if(this.types[0] == "administrative_area_level_1" && land_short == "DE"){
	            		provincie = this.long_name;	 	            		
	            		leeg = false;
	            	}      	
	            		
	            });
                
                $("#coordinateslat").val("");
		 		$("#coordinateslat").removeClass("grijs");
				$("#coordinateslat").addClass("blauw");
		
				$("#coordinateslong").val("");
 				$("#coordinateslong").removeClass("grijs");
				$("#coordinateslong").addClass("blauw");
                
                if(postcode != ""){
                	$("#postalcode").val(postcode);
                }
                $("#country").val(land);
                $("#town").val(stad);
                $("#state_province").val(provincie);                  		      	  		          
		          marker = new google.maps.Marker({
		              map: map, 
		              position: results[0].geometry.location
		          });
		          
		          /* Geen infowindow
		          infowindow = new google.maps.InfoWindow();
		          infowindow.setContent(results[0].formatted_address);
	           	  infowindow.open(map, marker);
		          */
		          
		          if(!leeg){
		          	map.setCenter(results[0].geometry.location);
		          	map.setZoom(9);			          	
		          	loadAjax();
		          }else{
		          	alert("No results found for given address.");
		          }
		          
		        } else {
		          alert("No results found for given address.");
		        }
		      });
		    }
		    
		}
	});
	
	
	//load php content
	function loadAjax(){
		
		$("#loading-freq").show();
		$.ajax({
			url: "ajaxphp/freqchannels.php",
			cache: false,
			type: "POST",
			dataType: "html",
			data: ({prov: provincie, land: land_short}),
  			success: function(html){
  				
  				$("#loading-freq").hide();
  				$("#pleaseselect-container").hide();
  				
  				if(html.search("NOT FOUND") == -1){
  					$("#notfound-container").hide();
  					
 	 				$("#table-frequency-ajax").html(html);  					
  					$("#output-container").slideDown("slow");
  					$("#printbutton").show();
  					loc_available = 1;
  					
  					$("#legenda-output-body").load("ajaxphp/legenda.php", {prov: provincie, land: land_short}, function() {
				
					});

    			}else{
					$("#pleaseselect-container").hide();
					$("#printbutton").hide();
					
					$("#output-container").slideUp("slow",function() {
						$("#notfound-container").show();
						loc_available = 0;
					});
    			}    			
  			}
		});
		
		
		if(type != "" && series != ""){
			
			$("#loading-equip").show();
			$("#pleaseselect-equipm-container").hide();
			
			$("#equipment-output-body").load("ajaxphp/equipmentfreq.php", {prov: provincie, land: land_short, range: range, series: series, type: type}, function() {
				$("#loading-equip").hide();
				$(".equip-instructions").show();
			});
		}
	}
	
	// Reset view
	function resetView(){
		$("#postalcode").val("");
		$("#country").val("");
		$("#town").val("");
		$("#state_province").val("");
		$("#coordinateslong").val("");
		$("#coordinateslat").val("");
		
		$("#coordinateslat").removeClass("blauw");
		$("#coordinateslat").addClass("grijs");
		$("#coordinateslong").removeClass("blauw");
		$("#coordinateslong").addClass("grijs");
		
		$("#coordinateslat").val("Lat");
		$("#coordinateslong").val("Long");
		
		provincie = "";
		
		// hide objects
		$("#output-container").slideUp("slow", function(){
			$("#pleaseselect-container").show();		
		});
		
		$("#notfound-container").hide();
		$("#loading-equip").hide();
		$("#loading-freq").hide();
		$(".equip-instructions").hide();
		$("#printbutton").hide();
		
		
		loc_choosen = 0;
		loc_available = 1;
		
		//first clear the marker
		if(marker != null){
			marker.setMap(null);
		}
		
		var myLatlng = new google.maps.LatLng(centerlat, centerlong);
		map.setCenter(myLatlng); 
		map.setZoom(6);
	}
	
	
	
	//CLICK OP KAART
	function placeMarker(location) {
		loc_choosen = 1;
		
		postcode = "";
		
		$("#coordinateslat").val("");
		$("#coordinateslat").removeClass("grijs");
		$("#coordinateslat").addClass("blauw");
		
		$("#coordinateslong").val("");
 		$("#coordinateslong").removeClass("grijs");
		$("#coordinateslong").addClass("blauw");
				
		var clickedLocation = new google.maps.LatLng(location);
		
		//first clear the marker
		if(marker != null){
			marker.setMap(null);
		}
		
		//first clear the marker
		if(infowindow != null){
			infowindow.close();
		}
		
		if (geocoder) {
	      geocoder.geocode({'latLng': location}, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	          if (results[1]) {
	            marker = new google.maps.Marker({
	                position: location, 
	                map: map
	            }); 
	           
	            $.each(results[0].address_components, function(){
	            	if(this.types[0] == "country"){
	            		land = this.long_name;
	            		land_short = this.short_name;
	            	}
	            	
	            	if(this.types[0] == "postal_code"){
	            		postcode = this.long_name;
	            	}
	            	
	            	if(this.types[0] == "locality"){
	            		stad = this.long_name;
	            	} 
	            	
	            	
                });
                
				//console.dir(results[1].address_components)				
               
                //provincie is afhankelijk van land
                $.each(results[1].address_components, function(){
     			    if(this.types[0] == "administrative_area_level_1" && land_short == "NL"){
	            		provincie = this.long_name;
	            	}
	            	
	            	if((this.types[0] == "administrative_area_level_2" || this.types[0] == "administrative_area_level_1") && land_short == "BE"){
	            		//console.log(this.lon)
	            		if(this.long_name == "Bruxelles"){
	            			provincie = this.long_name;
	            		}else if(this.types[0] == "administrative_area_level_2"){	            		
	            			provincie = this.long_name;	 	            		
	            		}
	            	}	
	            	
	            	if(this.types[0] == "administrative_area_level_1" && land_short == "LU"){
	            		provincie = this.long_name;	 	            		
	            	}
	            	
	            	if(this.types[0] == "administrative_area_level_2" && land_short == "DE"){
	            		provincie = this.long_name;	 	            		
	            	}
	            });
                
                $("#postalcode").val(postcode);
                $("#country").val(land);
                $("#town").val(stad);
                $("#state_province").val(provincie);
                
                $("#coordinateslong").val(location.lng());
                $("#coordinateslat").val(location.lat());
                
           
	            /* Geen infowindow
	            infowindow = new google.maps.InfoWindow();
	            infowindow.setContent(results[1].formatted_address);
	            infowindow.open(map, marker);
	            */
	            
	            map.setCenter(location); 
			   	//map.setZoom(9);	
			   	
			   	loadAjax();			   	
	          }
	        } else {
	          alert("No results for coordinate "+location.lat()+", "+location.lng());
	        }
	      });
	    }		
	}	
});

function selectRange(_range){
	range = _range;
	$("#loading-equip").show();
	$("#equipment-output-body").load("ajaxphp/equipmentfreq.php", {prov: provincie, land: land_short, range: range, series: series, type: type}, function() {
		$("#loading-equip").hide();
	});

}

function loadMapOnCoordinates(latitude, longitude){
	var myLatlng = new google.maps.LatLng(latitude,longitude);
    var myOptions = {
      zoom: 6,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false,
      scrollwheel: true,
	  mapTypeControlOptions: {
	  	style: google.maps.NavigationControlStyle.SMALL,
	  	position: google.maps.ControlPosition.BOTTOM_LEFT
	  },
	  streetViewControl: false,
	  navigationControl: true,
	  navigationControlOptions: {
	  	style:google.maps.NavigationControlStyle.SMALL,
	  	position: google.maps.ControlPosition.TOP_RIGHT
	  }   
	}
    
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);    
    
    return map;  
}
