var map;
var geocoder;
var dirn1;
var dirn2;
var recentOverlay;
var minimumRes = 8;
var maximumRes = 17;
var mgr;
var jsondata;

function getPointerLocation(response)
{
    if (!response || response.Status.code != 200)
	{
        alert("gelieve een andere locatie te kiezen");
        if(recentOverlay){ map.removeOverlay(recentOverlay); }  
 	}
 	else
 	{
		place = response.Placemark[0];
	
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
      
        $("#pointer_location").empty();
		$("#pointer_location").append(place.address);
		
		$("#pointer_lat").val(place.Point.coordinates[1]);
		$("#pointer_lng").val(place.Point.coordinates[0]);
  }
}


var mapClick = function (overlay, latlng)
{
	$('.step1more').show();
	
    if(latlng)
    {
		if(recentOverlay){ map.removeOverlay(recentOverlay); }  
		
    	var point = new GLatLng(latlng.lat(), latlng.lng());
		if (!overlay)
		{
			dirn1.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
        }
    	var icon = new GIcon();
		icon.image = "http://verdwaaldvuil.be/images/icons/pinpoint.png";
		icon.shadow = "http://verdwaaldvuil.be/images/icons/pinpoint_shadow.png";
		icon.iconSize = new GSize(52.0, 59.0);
	    icon.shadowSize = new GSize(52.0, 59.0);
	    icon.iconAnchor = new GPoint(26.0, 59.0);
	    
		marker = new GMarker(point, icon);
		map.addOverlay(marker);
		
		geocoder.getLocations(point, getPointerLocation);
        
        recentOverlay = marker;
	}
};


function getAddressLocation(response)
{
	var street = "";
	var region = "";
	var city = "";
	var zip = "";
    
	if (!response || response.Status.code != 200)
	{
        //alert("gelieve een andere locatie te kiezen");
		//if(recentOverlay) map.removeOverlay(recentOverlay);
 	}
 	else
 	{
 		place = response.Placemark[0];
		
		country = place.AddressDetails.Country.CountryName;
		countryCode = place.AddressDetails.Country.CountryNameCode;
		
		if(countryCode == "BE")
		{
		
			if(place.AddressDetails.Country.AdministrativeArea != null)
			{
				region = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
				
				if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null)
				{
					if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null) 
					{
						city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
						
						if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode)
						{
							zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;	
						}
						
						if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare != null)
						{
							street = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
						}
						
						if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality != null)
						{
							city = (city == "") ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.DependentLocalityName : city;
							
							if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode != null)
							{
								zip = (zip == "") ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber : zip;	
							}
							
							if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare != null)
							{ 
								street = (street == "") ? place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName : street;
							}
						}
					}
				}
			}
			
	        point = new GLatLng(place.Point.coordinates[1],
	                            place.Point.coordinates[0]);
	      
	        $("#address_location").empty();
			$("#address_location").append(place.address);
			
			$("#address_lat").val(place.Point.coordinates[1]);
			$("#address_lng").val(place.Point.coordinates[0]);
			
			$("#address").val(place.address);
			
			$("#street_input").val(street);
			$("#city_input").val(city);
			$("#zip_input").val(zip);
		}
		else
		{
			alert("Gelieve een locatie in België te kiezen");
			if(recentOverlay){ map.removeOverlay(recentOverlay);}
		}
  	}
}

function getIcon(image)
{
	var icon = new GIcon();
	icon.image = "http://verdwaaldvuil.be/images/icons/ico_map_"+image+".png";
	icon.shadow = "http://verdwaaldvuil.be/images/icons/shadow.png";
	icon.iconSize = new GSize(30.0, 33.0);
    icon.shadowSize = new GSize(31.0, 33.0);
    icon.iconAnchor = new GPoint(13.0, 33.0);
    icon.infoWindowAnchor = new GPoint(10.0, 5.0);
	
	return icon;
}

function newMarker(point,icon,html)
{
	var marker = new GMarker(point,{icon: icon});
	GEvent.addListener(marker, "click",function() 
	{
		marker.openExtInfoWindow(
          map,
          "window",
          html,
          {beakOffset: 3}
  		);
	});
	
	return marker;
}

function addMarkerData(data, categorie)
{ 
	mgr.clearMarkers();
	jQuery.each(data, function(){
		var markers = [];
		jQuery.each(this, function(){
			if(categorie == this.cat_url_title || categorie == "alle")
			{
				var image = (this.image == "") ? "<img src='/images/default.jpg' alt='img' />" : "<img src='/uploads/thumbs/"+this.image+"' alt='img' />";
				var html = "<ul class='marker_detail'><li class='picture'><span>"+image+"</span></li>"+"<li class='city'>"+this.city+"</li>"+"<li>"+this.street+"</li><li class='category'>in de categorie <a href='/overzicht/categorie/"+this.cat_url_title+"'>"+this.cat_name+"</a></li><li class='more'><a href='/overzicht/locatie/"+this.city_url_title+"#entry_"+this.report_id+"'><em>Meer info</em></a></li></ul>";
				point = new GLatLng(this.pointer_lat,this.pointer_long);
				var marker = newMarker(point, getIcon(this.cat_url_title), html);
				markers.push(marker);
			}
		});
		
		mgr.addMarkers(markers, 3);
	});
		
	mgr.refresh();
}

function getMarkers()
{
	 $.ajax({
	   url: "/map/get_map_data",
	   dataType: "json",
	   success: function(data){
	   	jsondata = data;
	    addMarkerData(data, "alle");
	   },
	   error: function(data){
	   	//console.log(data);
	   }
	 });
}

function searchPosition(data)
{
	$('.step1title').show();
	map.setZoom(15);
	map.panTo(new GLatLng(data.latitude, data.longitude));
}

function toggleField(field, defaultTxt)
{
	var location_input = defaultTxt;
	$(field).val(location_input);
	$(field).focus(function(){
		if($(this).val() == location_input){$(this).val("");}
	});
	$(field).blur(function(){
		if($(this).val() === ''){$(this).val(location_input);}
	});
}
function returnMinRes() { return minimumRes; }
function returnMaxRes() { return maximumRes; }

function init()
{
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());
	//map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(51.0481284,3.7720428), 8);
	map.removeMapType(G_HYBRID_MAP);
	map.addMapType(G_PHYSICAL_MAP);
	
	var mapTypes = map.getMapTypes();
	for (var i=0; i < mapTypes.length; i++) {
		mapTypes[i].getMinimumResolution = returnMinRes;
		mapTypes[i].getMaximumResolution = returnMaxRes;
	}
	
	mgr 	 = new MarkerManager(map);
	geocoder = new GClientGeocoder();
	dirn1 	 = new GDirections();
	dirn2 	 = new GDirections();
	
	GEvent.addListener(map, "click", mapClick, true);
	GEvent.addListener(map, "dblclick", function()
	{
		if(recentOverlay){ map.removeOverlay(recentOverlay);}
	}, true);
	GEvent.addListener(dirn1,"load", function() 
	{
		var p=dirn1.getPolyline().getVertex(0);
		var marker = new GMarker(p);
		geocoder.getLocations(p, getAddressLocation);
	});
	
	GEvent.addListener(dirn2,"load", function()
	{
        var p=dirn2.getPolyline().getVertex(0);
        geocoder.getLocations(p, getAddressLocation);
	});
	
	GEvent.addListener(dirn1,"error", function() 
	{
        alert("Gelieve een andere locatie te kiezen");
        if(recentOverlay){ map.removeOverlay(recentOverlay);}
	});
	GEvent.addListener(dirn2,"error", function()
	{
        if(recentOverlay){ map.removeOverlay(recentOverlay);}
	});
	
	getMarkers();
}

function doUpload()
{
	$('#uploadForm').ajaxSubmit({
		beforeSubmit: function(a,f,o) {
			//$('#uploadOutput').html('Submitting...');
			$("#loader").show();
		},
		success: function(data) {
			var jSon = JSON.parse(data);
			//$('#uploadOutput').html('<img src="/sluikstort/uploads/thumbs/'+ jSon.upload_data.file_name +'" alt="img"/>');
			$("#loader").hide();
			$("#loader_result").show();
			$("#picture").val(jSon.upload_data.file_name);
		}
	});
}

$(document).ready(function() 
{
	var formTitle = $('#input h2').text();
	var successTitle = "Uw melding is verzonden";
	var defaultText = "Geef een korte beschrijving van het probleem.";
	
	toggleField($("#text_input"), defaultText);
	
	init();
	
	var prev = $("#prev");
	var next = $("#next");
	var end = $("#end");
	end.hide();
	
	$("#input_view").scrollable({ 
		size: 1, 
		items: '#input_wrapper', 
		hoverClass: 'hover',
		keyboard: false,
		onSeek: function(){
			if(this.getPageIndex() == 0)
			{
				prev.show();
				prev.attr("class","disabled");
			}else{
				prev.attr("class","input_nav");
			}
			
			if(this.getPageIndex() == 2)
			{
				next.hide().attr("class","disabled");
				end.show();
				prev.show();
			}else{
				end.hide();
				next.show().attr("class","input_nav");
			}
			
			if(this.getPageIndex() == 3)
			{
				$('#input h2').text("Uw melding is verzonden");
				next.hide();
				prev.hide();
				end.hide();
			}
			
		} });
	var input_view = $("#input_view");
	var txt=new RegExp(defaultText);
	
	$(".input_nav").click(function(){
		switch(this.id)
		{
			case "prev":
				input_view.scrollable().prev();
				break;
			case "next":
				input_view.scrollable().next();
				break;
			case "begin":
				input_view.scrollable().begin();
				break;
			case "end":
				$("#street").val($("#street_input").val());
        		$("#zip").val($("#zip_input").val());
        		$("#city").val($("#city_input").val());
        		if($("#cat_input").val()!= 0){$("#categorie").val($("#cat_input").val());}
        		
        		if(defaultText == $("#text_input").val())
				{
        			$("#text").val("");
				}else{
					$("#text").val($("#text_input").val());
				};
        		$("#name").val($("#name_input").val());
        		$("#email").val($("#email_input").val());
        		
				$('#report_form').submit();
				
				break;	
		}
	});
	
	var report_form = $("#report_form").validate({
		rules: {
			street: "required",
			zip: "required",
			categorie: "required",
			city: {
				required: true,
				minlength: 2
			},
			name: "required",
			email: {
				required: true,
				email: true
			},
			pointer_lat: "required"
		},
		messages: {
			street: " - Straat niet ingevuld",
			zip: " - Postcode niet ingevuld",
			categorie: " - Geen Categorie gekozen",
			city: " - Stad niet ingevuld",
			name: " - Naam niet ingevuld",
			email: {
		       required: " - E-mail niet ingevuld",
		       email: " - E-mail verkeerd ingevuld"
		     },
		     pointer_lat: " - Je hebt de plaats nog niet aangeduid op de kaart",
		     pointer_long: ""

	   },
		errorPlacement: function(error, element) {
			//error.appendTo( $('#error') );
	   	},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message;
				if(errors == 1)
				{
					message = 'Oops, je formulier heeft nog een foutje,'+"\n"+'gelieve dit probleem nog te corrigeren:'+"\n"+"\n";
				}else
				{
					message = 'Oops, je formulier heeft nog enkele foutjes,'+"\n"+'gelieve deze problemen nog te corrigeren:'+"\n"+"\n";
				}
			
				for(var i=0; i<errors;i++){
					if(validator.errorList[i].message != "")
					{
						message += validator.errorList[i].message +"\n";
					}
				}
				
			alert(message);
			}
		},
		submitHandler: function(form) {
			jQuery(form).ajaxSubmit({
	        	dataType:  'json',
	        	beforeSubmit: function(a,f,o){
	        		//console.log(a);
	        	},
	            success: function(data){
					//console.log(data);
					input_view.scrollable().next();
					$('#report_form :hidden').val("");
					$('#uploadForm :file').val("");
					$('input').val("");
	            },
	            error: function(data){
	            	//console.log("error");
	            	//console.log(data);
	            }
	    	});
		}
	});
	
	$('.opnieuw').click(function(){
		$("#loader_result").hide();
		input_view.scrollable().begin();
	});
    
    $('#locate_form').ajaxForm({
    	dataType:  'json',
        success: function(data){
			searchPosition(data);
        }
	});
	
	$('.vote').click(function(){
		var urlSeg = this.name;
		var voteBtn = $(this);
		$.ajax({
			type:"GET",
			url:'/map/add_vote/'+urlSeg.replace(/_/, "/"),
			error:function(data){
				//console.log(data);
			},
			success:function(data){
				voteBtn.prevAll(".count").html(data);
				voteBtn.text("Bedankt voor je stem");
			}
		});
	});
	
	$('.step1title').hide();
	$('.step1more').hide();
	
	$('#legende li a').click(function(){
		addMarkerData(jsondata,this.id);
	});
	
	$('#legende li a').tooltip({
	    delay: 0, 
	    showURL: false,
	    top: -50,
	    left: -55
	});
	
	$("#prev").show().attr("class","disabled");
	$("#next").show();
});
