var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.iconSize = new GSize(20, 30);

var maleFlag = new GIcon(baseIcon);
maleFlag.image = "/images/male_flag.png";
maleFlag.shadow = "/images/flag_shadow.png"

var femaleFlag = new GIcon(baseIcon);
femaleFlag.image = "/images/female_flag.png";
femaleFlag.shadow = "/images/flag_shadow.png"

var unisexFlag = new GIcon(baseIcon);
unisexFlag.image = "/images/unisex_flag.png";
unisexFlag.shadow = "/images/flag_shadow.png"

var liteFlags = false;

var maleFlagLite = new GIcon(baseIcon);
maleFlagLite.image = "/images/male_flag_lite.png";
maleFlagLite.shadow = "/images/flag_shadow.png"

var femaleFlagLite = new GIcon(baseIcon);
femaleFlagLite.image = "/images/female_flag_lite.png";
femaleFlagLite.shadow = "/images/flag_shadow.png"

var unisexFlagLite = new GIcon(baseIcon);
unisexFlagLite.image = "/images/unisex_flag_lite.png";
unisexFlagLite.shadow = "/images/flag_shadow.png"

var aroundMap;

function loadAroundMap(lat, lng)
{
	if(GBrowserIsCompatible())
	{
		window.onunload = GUnload;

        aroundMap = new GMap2(document.getElementById("aroundMap"));
		aroundMap.enableScrollWheelZoom();
		aroundMap.addControl(new GMapTypeControl());
		aroundMap.addControl(new GSmallMapControl());

        var point = new GLatLng(lat, lng);
        aroundMap.setCenter(point, 13);
        drawToilets(aroundMap);

        if (typeof navigator.geolocation == 'object')
        {
            document.getElementById('aroundMapInfo').innerHTML = allowGeolocate;
            document.getElementById('aroundMapInfo').style.display = 'block';
            navigator.geolocation.getCurrentPosition(loadAroundMapGeolocation, function()
            {
                document.getElementById('aroundMapInfo').style.display = 'none';
                getAroundPointToilets(lat, lng, aroundMap, '');
            });
        }
        else
        {
            getAroundPointToilets(lat, lng, aroundMap, '');
        }

		GEvent.addListener(aroundMap, "dragstart", function()
		{
			pauseMapTour();
		});

		GEvent.addListener(aroundMap, "moveend", function()
		{
			drawToilets(aroundMap);
		});

		GEvent.addListener(aroundMap, "click", function(overlay, point)
		{
			pauseMapTour();

			if(typeof(addToiletInfo) == 'function')
			{
				mapAddToilet(point, aroundMap);
			}
		});

        var adsense = new GAdsManager(aroundMap, 'pub-3324372363162137');
		adsense.enable();
	}
}

function mapAddToilet(point, map)
{
    if(typeof(addToiletInfo) == 'function')
    {
        var geocoder = new GClientGeocoder();

        geocoder.getLocations(point, function(Placemark)
        {
            if (Placemark.Status.code == 200)
            {
                var place = Placemark.Placemark[0];
                var geo = new Object();

                geo['string'] = place.address;

                if(place.AddressDetails.Country)
                {
                    geo['country'] = place.AddressDetails.Country.CountryNameCode;

                    if(place.AddressDetails.Country.AdministrativeArea)
                    {
                        geo['state'] = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;

                        if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality)
                        {
                            geo['city'] = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;

                            if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare)
                                geo['street'] = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;

                            if(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode)
                                geo['zip'] = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                        }
                    }
                }

                map.openInfoWindowHtml(point, addToiletInfo(point, geo));
            }
        });
    }
}

var geolocation = true;

function loadAroundMapGeolocation(position)
{
    if (geolocation)
    {
        document.getElementById('aroundMapInfo').style.display = 'none';

        geolocation = false;
        counter = 0;
        counterRecords = 0;
        selectedPoint = -1;
        markers = new Array();

        aroundCitys = new Object();
        aroundStates = new Object();
        aroundCountries = new Object();

        var point = new GLatLng(position.coords.latitude, position.coords.longitude);

        aroundMap.setCenter(point, 13);
        getAroundPointToilets(position.coords.latitude, position.coords.longitude, aroundMap, '');

        var geocoder = new GClientGeocoder();
        geocoder.getLocations(point, function(Placemark)
        {
            if (Placemark.Status.code == 200)
            {
                var place = Placemark.Placemark[0];
                var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
                document.getElementById('aroundMapSearch').value = city;
            }
        });
    }
}

function loadAroundMapPosition(geoString)
{
	stopMapTour();

	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(geoString,
	function(point)
	{
		if(point)
		{
			counter = 0;
			counterRecords = 0;
			selectedPoint = -1;
			markers = new Array();

            aroundCitys = new Object();
            aroundStates = new Object();
            aroundCountries = new Object();

   			aroundMap.setCenter(point, 13);
			getAroundPointToilets(point.lat(), point.lng(), aroundMap, '');
		}
	});

	return false;
}

function doNothing()
{
    return true;
}

var tourPoints = 0;
var tourMap = 0;
var selectedPoint = -1;
var tourInterval = 0;

function mapTour(points, map)
{
	tourMap = map;
	tourPoints = points;

	document.getElementById('amountMapTourToilet').innerHTML = tourPoints.length;
	document.getElementById('aroundMapToolbar').style.visibility = 'visible';

    if(document.getElementById('amtc_option_custom')==null)
        map.addControl(new MoreControl());

	startMapTour();
}

function pauseMapTour()
{
	clearInterval(tourInterval);

	document.getElementById('mapTourPause').style.visibility = 'hidden';
	document.getElementById('mapTourPause').style.width = '0px';
	document.getElementById('mapTourStart').style.visibility = 'visible';
	document.getElementById('mapTourStart').style.width = '16px';
}

function stopMapTour()
{
	pauseMapTour();
	firstMapTourPoint();
}

function startMapTour()
{
	nextMapTourPoint();
	tourInterval = setInterval("nextMapTourPoint()", 5000);

	document.getElementById('mapTourPause').style.visibility = 'visible';
	document.getElementById('mapTourPause').style.width = '16px';
	document.getElementById('mapTourStart').style.visibility = 'hidden';
	document.getElementById('mapTourStart').style.width = '0px';
}

function firstMapTourPoint()
{
	selectedPoint = 0;
	setMapTourPoint();
}

function prevMapTourPoint()
{
	if(selectedPoint > 0)
	{
		selectedPoint--;
		setMapTourPoint();
	}
}

function nextMapTourPoint()
{
	if(selectedPoint < tourPoints.length-1)
	{
		selectedPoint++;
		setMapTourPoint();
	}
	else
		stopMapTour();
}

function lastMapTourPoint()
{
	stopMapTour();
	selectedPoint = tourPoints.length-1;
	setMapTourPoint();
}

function prevMapTourPoint()
{
	selectedPoint--;
	setMapTourPoint();
}

function setMapTourPoint()
{
	tourMap.openInfoWindow(tourPoints[selectedPoint][0].getLatLng(), '<div style="width: 196px;">' + toiletInfoHtml(tourPoints[selectedPoint][1]) + '</div>');
	document.getElementById('selectedMapTourToilet').innerHTML = (selectedPoint + 1);
}

function loadLittleMap(type)
{
	if(lat != 0 && lng != 0)
	{
		if(GBrowserIsCompatible())
		{
			window.onunload = GUnload;

            var littleMap = new GMap2(document.getElementById("littleMap"));
			littleMap.setMapType(G_HYBRID_MAP);
            littleMap.disableDragging();
            littleMap.addControl(new GMapTypeControl());

			var point = new GLatLng(lat, lng);
			var markerOptions = getFlag(type);

			littleMap.setCenter(point, 14);
			var marker = new GMarker(point, markerOptions);
			littleMap.addOverlay(marker);

			center = littleMap.getCenter();

			GEvent.addListener(marker, "click", function()
			{
				document.location.href = document.location.href.replace(/#.*$/, '') + "map/";
			});
		}
	}
}

var bigMap;

function loadBigMap()
{
	if(GBrowserIsCompatible())
	{
		window.onunload = GUnload;

        bigMap = new GMap2(document.getElementById("bigMap"));

		bigMap.enableScrollWheelZoom();
        bigMap.addMapType(G_SATELLITE_3D_MAP);
		bigMap.setMapType(G_HYBRID_MAP);
		bigMap.addControl(new GMapTypeControl());
		bigMap.addControl(new GSmallMapControl());

		rect = new GLatLngBounds(new GLatLng(swLat, swLng), new GLatLng(neLat, neLng));

		if(geoString)
		{
			var geocoder = new GClientGeocoder();
			geocoder.getLatLng(geoString,
			function(point)
			{
				if(point)
				{
					bigMap.setCenter(point, 14);
				}
			});
		}
		else
		{
			bigMap.setCenter(rect.getCenter(), bigMap.getBoundsZoomLevel(rect));
			drawToilets(bigMap);
		}

		GEvent.addListener(bigMap, "moveend", function()
		{
			drawToilets(bigMap);
		});

		GEvent.addListener(bigMap, "click", function(overlay, point)
		{
            if(typeof(addToiletInfo) == 'function')
            {
                mapAddToilet(point, bigMap);
                //aroundMap.openInfoWindowHtml(point, addToiletInfo(point));
            }
		});

		var adsense = new GAdsManager(bigMap, 'pub-3324372363162137');
		adsense.enable();
	}
}

function drawToilets(map)
{
	bounds = map.getBounds();
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();

	distance = 0.017 / map.getZoom();

	getMapToilets(sw.lng(), ne.lng(), sw.lat(), ne.lat(), map);
}

var webDrawed = false;

function drawWeb(map, xml)
{
    map.clearOverlays();

    if(typeof(posMarker) == 'object')
        map.addOverlay(posMarker);

    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();

    var boundLat = ne.lat()-sw.lat();
    var boundLng = ne.lng()-sw.lng();

    var boundLatBox = boundLat/3;
    var boundLngBox = boundLng/3;

    var x = 0;

    for(var i = 1;i <= 3;i++)
    {
        for(var j = 1;j <= 3;j++)
        {
            if (xml.getElementsByTagName('tc')[x].getAttribute('v') > 0)
            {
            var coords = new Array(new GLatLng(sw.lat()+(boundLat-(i*boundLatBox)), sw.lng()+(boundLng-(j*boundLngBox))),
                                   new GLatLng(sw.lat()+(boundLat-(i*boundLatBox)+boundLatBox), sw.lng()+(boundLng-(j*boundLngBox))),
                                   new GLatLng(sw.lat()+(boundLat-(i*boundLatBox)+boundLatBox), sw.lng()+(boundLng-(j*boundLngBox)+boundLngBox)),
                                   new GLatLng(sw.lat()+(boundLat-(i*boundLatBox)), sw.lng()+(boundLng-(j*boundLngBox)+boundLngBox)),
                                   new GLatLng(sw.lat()+(boundLat-(i*boundLatBox)), sw.lng()+(boundLng-(j*boundLngBox))));

            var field = new webField(coords, xml.getElementsByTagName('tc')[x].getAttribute('v'));
            map.addOverlay(field);
            }
            x++;
        }
    }

    webDrawed = true;

    if ( undefined !==window.id)
        ignoreIds = id;
    else
        ignoreIds = '';
}

var setMap;
var posMarker;

function loadSetMap(toiletID)
{
	if (GBrowserIsCompatible())
	{
		liteFlags = true;

        window.onunload = GUnload;

        setMap = new GMap2(document.getElementById("setMap"));
		setMap.enableScrollWheelZoom();
		setMap.addControl(new GMapTypeControl());
		setMap.addControl(new GSmallMapControl());

        if(lat && lng)
		{
			var point = new GLatLng(lat, lng);
			setMap.setCenter(point, 14);
			posMarker = new GMarker(point, getFlag(wcType));
			setMap.addOverlay(posMarker);
		}
		else
			getAddress();

        ignoreIds += ',' + toiletID;
		drawToilets(setMap);

        GEvent.addListener(setMap, "click", function(overlay, point)
		{
            posMarker.setLatLng(point);
			saveCoords(id, point.lat(), point.lng());
		});

        GEvent.addListener(setMap, "moveend", function()
        {
            drawToilets(setMap);
        });
	}
}

function getAddress()
{
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(street + ' ' + postcode + ' ' + city + ' ' + state + ' ' + country,

    function(point)
	{
		if(point)
		{
            setMap.setCenter(point, 14);
			posMarker = new GMarker(point, getFlag(wcType));
			setMap.addOverlay(posMarker);
			saveCoords(id, point.lat(), point.lng());
		}
		else
		{
            if(street == '')
				postcode = '';
			else
				street = '';

			getAddress();
		}
	});
}

function setMarker(point, record)
{
	if(liteFlags)
        var markerOptions = getFlagLite(record.getElementsByTagName('wc_type')[0].getAttribute('v'));
    else
        var markerOptions = getFlag(record.getElementsByTagName('wc_type')[0].getAttribute('v'));

    var marker = new GMarker(point, markerOptions);

	if(typeof(toiletInfoHtml) == 'function')
	{
		GEvent.addListener(marker, "click", function()
		{
			marker.openInfoWindowHtml('<div style="width: 196px;">' + toiletInfoHtml(record) + '</div>');
		});
	}

	return marker;
}

function getFlag(type)
{
	if(liteFlags)
    {
        if(type == 2)
            var markerOptions = {icon:femaleFlag, clickable:false};
        else if(type == 3)
            var markerOptions = {icon:maleFlag, clickable:false};
        else
            var markerOptions = {icon:unisexFlag, clickable:false};
    }
    else
    {
        if(type == 2)
		    var markerOptions = {icon:femaleFlag};
	    else if(type == 3)
		    var markerOptions = {icon:maleFlag};
	    else
		    var markerOptions = {icon:unisexFlag};
    }

	return markerOptions;
}

function getFlagLite(type)
{
    if(type == 2)
        var markerOptions = {icon:femaleFlagLite, clickable:false};
    else if(type == 3)
        var markerOptions = {icon:maleFlagLite, clickable:false};
    else
        var markerOptions = {icon:unisexFlagLite, clickable:false};

    return markerOptions;
}

function searchMap(address)
{
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address,
	function(point)
	{
		if(point)
		{
			setMap.setCenter(point);
			setMap.clearOverlays();
			posMarker.setLatLng(point);

            setMap.addOverlay(posMarker);
			saveCoords(id, point.lat(), point.lng());

            ignoreIds = toiletID;
            drawToilets(setMap);
		}
		else
			alert("Adresse nicht gefunden!");
	});

	return false;
}

function MoreControl(){};
MoreControl.prototype = new GControl();
MoreControl.prototype.initialize = function(aroundMap)
{
    var div = document.createElement('div');
    div.style.right = '15.3em';
    div.style.cursor = 'pointer';
    div.style.width = '5em';
    div.style.textAlign = 'center';
    div.style.backgroundColor = '#FFF';
    div.style.border = '1px solid #000';
    div.id = 'amtc_option_custom';
    div.title = 'Listenansicht';

    childDiv = document.createElement('div');
    childDiv.style.fontSize = '12px';
    childDiv.style.borderWidth = '1px';
    childDiv.style.borderColor = '#FFF #B0B0B0 #B0B0B0 #FFF';
    childDiv.style.borderStyle = 'solid';

    childDiv.appendChild(document.createTextNode('Liste'));
    div.appendChild(childDiv);

    aroundMap.getContainer().appendChild(div);
    return div;
}

MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(190, 7));
}

function webField(coords, count)
{
    this.coords_ = coords;
    this.count_ = count;
}

webField.prototype = new GOverlay();

webField.prototype.initialize = function(map)
{
    if (parseInt(this.count_) > 0)
    {
        var polygon = new GPolygon(this.coords_, '#72BE16', 1, 1, '#DBEFC2', 0.3, {clickable:false});

        map.addOverlay(polygon);

        var pixel = map.fromLatLngToDivPixel(this.coords_[1]);
        var div = document.createElement("div");
        div.style.position = 'absolute';
        div.style.top = (pixel.y + 30) + 'px';
        div.style.left = (pixel.x + 50) +  'px';
        div.style.width = '100px';
        div.style.padding = '4px';
        div.style.background = '#FFF';
        div.style.opacity = '0.85';
        div.style.border = '1px solid #72BE16';
        div.style.zIndex = '999';
        div.style.textAlign = "center";
        div.onclick = function() {
            map.disableInfoWindow();
            map.setCenter(polygon.getBounds().getCenter(), map.getBoundsZoomLevel(polygon.getBounds()));
            map.enableInfoWindow();
            return false;
        };
        //div.innerHTML = toilets_label + this.count_;

        var link = document.createElement("a");
        var stlyeLink = document.createAttribute("class");
        stlyeLink.nodeValue = "iconLink";
        var linkHref = document.createAttribute("href");
        linkHref.nodeValue = "#";
        link.setAttributeNode(stlyeLink);
        link.setAttributeNode(linkHref);

        var imgBracketOpen = document.createElement("img");
        var stlyeImage1 = document.createAttribute("class");
        stlyeImage1.nodeValue = "leftParenthesis";
        var imageBorder1 = document.createAttribute("border");
        imageBorder1.nodeValue = "0";
        var imageSource1 = document.createAttribute("src");
        imageSource1.nodeValue = "/images/blank.gif";
        imgBracketOpen.setAttributeNode(imageBorder1);
        imgBracketOpen.setAttributeNode(stlyeImage1);
        imgBracketOpen.setAttributeNode(imageSource1);

        var imgBracketClose = document.createElement("img");
        var stlyeImage2 = document.createAttribute("class");
        stlyeImage2.nodeValue = "infoToilets";
        var imageBorder2 = document.createAttribute("border");
        imageBorder2.nodeValue = "0";
        var imageSource2 = document.createAttribute("src");
        imageSource2.nodeValue = "/images/blank.gif";
        imgBracketClose.setAttributeNode(imageBorder2);
        imgBracketClose.setAttributeNode(stlyeImage2);
        imgBracketClose.setAttributeNode(imageSource2);

        link.appendChild(imgBracketOpen);
        txtToiletCounter = document.createTextNode(this.count_);
        link.appendChild(txtToiletCounter);
        link.appendChild(imgBracketClose);
        div.appendChild(link);
        map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).appendChild(div);

        this.map_ = map;
        this.polygon_ = polygon;
        this.div_ = div;
    }
}

webField.prototype.remove = function()
{
    this.div_.parentNode.removeChild(this.div_);
}

webField.prototype.copy = function()
{
    return new webField(this.coords_);
}

webField.prototype.redraw = function(force)
{

}
