var map             = null;
var geocoder        = null;
var geoxml          = null;
var requesttype     = '';
var loaded          = 0; 
var citydata        = '';
var startProvince   = '';
var startProvinceCode   = '';
var startCityName       = '';
var cityInit		= false;
var initCityName 	= ''; 
var siteRoot        = '';
var zoomlevel		= 7;

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

function GUnload() {
	//dummy	
}

function initialize() {
	
	var baseURL = location.href;
   	//siteRoot = baseURL.substring(0, baseURL.indexOf('/', 7));
   	siteRoot = "http://www.trosradar.nl";
  	
  	geocoder = new google.maps.Geocoder();

	var latlng = new google.maps.LatLng(52.13568,5.555878);

	var myOptions = {
		zoom: zoomlevel,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.SATELLITE
	};
  	map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    
	showAllDelayed();
}

function provinceSelect(sProvinceName) {
	// bij kiezen van een provincie de gemeente op null zetten
	setSelect(document.forms['geoform'].cityselect,'');
	if (sProvinceName == '') {
		document.getElementById('cityselectdiv').style.display = "none";
	    showAllDelayed();
		return;
	}
	var provinceName   = sProvinceName;

	showLocation(provinceName,'province');
	requesttype = 'province';

	getCities(provinceName);
}

function provinceActivate(sProvinceCode) {
	var theForm = document.forms['geoform'];
	var provinceSelect = theForm.provincieselect;
	for (i = 0;i < provinceSelect.length; i++) {
		if (provinceSelect[i].value.split(",")[0] == sProvinceCode) {
			provinceSelect[i].selected = "1";
			return provinceSelect[i].value.split(",")[2];
		}
	}
	return false;
}

function cityActivate() {
	var theForm = document.forms['geoform'];
	var citySelect = theForm.cityselect;
	for (i = 0;i < citySelect.length; i++) {		
		if (citySelect[i].value == initCityName) {
			citySelect[i].selected = "1";			
		}
	}
}

function citySelect(sCity) {
	if (sCity == '') {
		if(getProvince() != '') {
			showLocation(getProvince(),'province');
			requesttype = 'province';
		}
	} else {
		showLocation(sCity,'city');
		requesttype = 'city';
	}
}

function douchetypeSelect(doucheType){
	if (getCity() != '') {
		citySelect(getCity());
	} else if (getProvince() != '') {
		provinceSelect(getProvince());
	} else {
		showAll(doucheType);
	}
}

function doucheamountSelect(amount){
	if (amount != '') {
		if (getCity() != '') {
			citySelect(getCity());
		} else if (getProvince() != '') {
			provinceSelect(getProvince());
		} else {
		    loadCityView();			
		}
	}
}

function showAllDelayed() {
	showLocation('','nederland');
	requesttype = 'nederland';
}

function showLocation(sLocation,requesttype) {
	if (requesttype == "city") {
		zoomlevel = 12;
	} else if (requesttype == "province") {
		zoomlevel = 8;
	} else {
		zoomlevel = 7;
	}

	if (requesttype != "nederland") {
		var fixedAddress = sLocation+",netherlands";
	} else {
		var fixedAddress = 'netherlands';
	}

  	if (geocoder) {
		geocoder.geocode( { 'address': fixedAddress}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				map.setZoom(zoomlevel);

				if (requesttype != 'nederland') {
      			    getGEO();
      			} else {
      			    showAll();
      			}
			} else {
				return;
				//alert("Geocode was not successful for the following reason: " + status);
			}
		});  		
  	}
}

function showAll() {
    var douchetype = getDouchetype();

    if (geoxml != null) {
    	geoxml.setMap(null);	
    }    
    	
	geoxml = new google.maps.KmlLayer(siteRoot+"/index.php?id=generate_kml&mode=all&doucheType="+douchetype,{ preserveViewport : true });
 	geoxml.setMap(map);
 	map.setZoom(zoomlevel);
}

function getGEO () {
   	var provinceName   = getProvince();
	
	if(startCityName == '') {
        var city = getCity();
	} else {
	    var city = startCityName;
	    startCityName = '';
	}
    var douchetype     = getDouchetype();
	var doucheAmount = getAmount();
    //alert("douchetype =" + douchetype);

    locationtype = requesttype;
    
	geoxml.setMap(null);
    delete geoxml;
	if (locationtype == 'province') {
		geoxml = new google.maps.KmlLayer(siteRoot+"/index.php?id=generate_kml&mode=province&provinceName="+provinceName+"&doucheType="+douchetype+"&doucheAmount="+doucheAmount,{ preserveViewport : true });
	} else if (locationtype == 'city') {
		geoxml = new google.maps.KmlLayer(siteRoot+"/index.php?id=generate_kml&mode=city&city="+city+"&doucheType="+douchetype+"&doucheAmount="+doucheAmount,{ preserveViewport : true });	
	}
	geoxml.setMap(map);
	map.setZoom(zoomlevel);
}

function getDouchetype() {
	var theForm = document.forms['geoform'];
	var doucheType = theForm.soort.options[theForm.soort.selectedIndex].value;
	return doucheType;
}
function getProvince() {
	var theForm = document.forms['geoform'];
	var province = theForm.provincieselect.options[theForm.provincieselect.selectedIndex].value;
	return province;
}
function getCity() {
	var theForm = document.forms['geoform'];
	var city = theForm.cityselect.options[theForm.cityselect.selectedIndex].value;
	return city;
}
function getAmount() {
	var theForm = document.forms['geoform'];
	var amount = theForm.doucheamount.options[theForm.doucheamount.selectedIndex].value;
	return amount;
}
function getCities(provinceName) {
	$.getJSON('/index.php?id=douche_citylist&province=' + provinceName,
		function(citiesData) {
			buildCities(citiesData);
		}
    );
}

function buildCities(citiesObj) {
	var cityListObj = citiesObj[0].cities;
	var citieslength = cityListObj.length;	
		
	//refill select
	var formselect = document.getElementById('cityselect');
	formselect.length = 1;
	formselect.options[0].text = 'Alle gemeenten';
	for (i = 0;i < (citieslength);i++) {
		if (cityListObj[i]) {
			var elOptNew = document.createElement('option');
				elOptNew.text = urldecode(cityListObj[i].city);
				elOptNew.value = cityListObj[i].city;
			try {
				formselect.add(elOptNew, null); // standards compliant; doesn't work in IE
			}
			catch(ex) {
				formselect.add(elOptNew); // IE only
			}
		}
	}
	document.getElementById('cityselectdiv').style.display = "block";
	//document.getElementById('doucheamountselect').style.display = "block";

	if (cityInit == true) {
		cityActivate();			
		cityInit = false;
	}

}

function urldecode( str ) {
	ret = unescape(str);
	ret = ret.replace("+"," ");
	return ret;
}

function setSelect(selectBox, sValue) {
	for (i = 0 ;i < selectBox.options.length;i++) {
		if (selectBox.options[i].value == sValue) {
			selectBox.selectedIndex = i;
			return;
		}
	}
}
