var gm_header = null;
var gm_marker = null;
var map_filters = null;
var map_startup_params = null;
var divs = null;
var icon = new Array();
var allPois = new Array();
var poiMarkers = new Object();
var lastKey = "";
var lastIcon = "";
var geoXml = null;
var clusterMarkers = new Array();
var map_condition_data = null;
var map_cond = null;

function move(x, y) {
	map.panDirection(x,y);
}

function changeType(id) {
	divs = $("gmaps").getElementsByTagName("div");
	if (id == 1) {
		alp.gmap.api.setMapType(map, 'Karte');
		$('typelink_one').addClassName("active");
		$('typelink_two').removeClassName("active");
		$('typelink_three').removeClassName("active");
		try {
			divs[21].setStyle({ right: '198px' });
		} catch (e) {}
	}
	if (id == 2) {
		alp.gmap.api.setMapType(map, 'Hybrid');
		$('typelink_one').removeClassName("active");
		$('typelink_two').addClassName("active");
		$('typelink_three').removeClassName("active");
		try {
			divs[15].setStyle({ right: '198px' });
		} catch (e) {}
	}
	if (id == 3) {
		alp.gmap.api.setMapType(map, G_PHYSICAL_MAP);
		$('typelink_one').removeClassName("active");
		$('typelink_two').removeClassName("active");
		$('typelink_three').addClassName("active");
		try {
			divs[15].setStyle({ right: '198px' });
		} catch (e) {}
	}
}

function loadMaps () {
	google.load("maps", "2", {"callback" : loadAlpstein});
}

function loadAlpstein () {
	LazyLoad.load('http://www.alpserver.de/alp.gmap.api/stable/dojo/dojo.xd.js?key=8cdbef65cfffc9746b877c92f7d41a3e', loadTrimpath);
}
function loadTrimpath () {
	LazyLoad.load('/static/source/js/at/steiermark/gmaps/trimpath-template.js', loadClusterer);
}
function loadClusterer () {
	LazyLoad.load('/static/source/js/at/steiermark/gmaps/markerclusterer.js', mapsLoaded);
}

function mapsLoaded () {	
	$('gm_loading').setStyle({ display: 'none' });
	$('gmaps').setStyle({ display: 'block' });
	
	map = new google.maps.Map2($("gmaps"));
	var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,30));
	
	// alpstein map
	alp.gmap.api.add(map, {mapControls:false});
	
	icons = new Array(
		'null','2hotel','3hotel','4hotel','5hotel','adventmarkt','appartment','badesee','bauernhof','burg_schloss','buschenschanke','campingplatz','familie',
		'ferienhaus','ferienstrasse','flughafen','gasthof','golfclub','hallenbad','haubenlokal','historisch_traditionell','hochseilgarten_klettersteig','hotel','huetten','jugendunterkunft',
		'kulinarium','kulinarium_steiermark','modern','moderne_architektur','museum','natur_abenteuer','naturpark','nordic_fitness','ort','outdoor_anbieter','panoramastrasse','pension',
		'privatzimmer','radtour','reitstall','skigebiet','skihuetten','sommer_seilbahn','stift_kirche_kloster','therme_spazentrum','touristik','wandertour','webcam','wetterfest'
	);
	
	amapping = new Array();
	amapping[3002] = 3516;
	amapping[3003] = 3515;
	amapping[3004] = 3514;
	amapping[3005] = 3509;
	amapping[3008] = 3520;
	amapping[3010] = 3522;
	amapping[3013] = 3525;
	amapping[3009] = 3521;
	amapping[3006] = 3518;
	amapping[3001] = 3517;
	amapping[3012] = 3524;
	amapping[3007] = 3519;
	amapping[3011] = 3523;
	amapping[3014] = 29369;
	
	for (t=0; t<icons.length; t++) {
		v = icons[t];
		
		icon[v] = new GIcon();
		icon[v].iconSize = new GSize(60, 68);
		icon[v].iconAnchor = new GPoint(30, 55);
		icon[v].image = "/static/source/img/gmaps/icons/" + v + ".png";
	}
	
	// steiermark tiles	
	var tilelayer = new GTileLayer();
	tilelayer.getTileUrl = SteiermarkTileUrl
	tilelayer.getOpacity = function () { return 0.40; };
	tilelayer.isPng = function() { return true; };
	
	var myTileLayer = new GTileLayerOverlay(tilelayer);
	map.addOverlay(myTileLayer);

	map_center = new GLatLng(47.21,15.15);
	map.setCenter(map_center, 8);
	
	try {
		divs = $("gmaps").getElementsByTagName("div");
		for (v=0; v<divs.length; v++) {
			if (divs[v].className.indexOf("gmnoprint") >= 0) {
				var copydiv = v+1;
			}
		}
		divs[copydiv].setStyle({ right: '198px' });
	} catch (e) {}
	
	$('gmcontrols').setStyle({ display: 'block' });
	$('gmclose').setStyle({ display: 'block' });
	$('gmsize').setStyle({ display: 'block' });
	$('gminfo').setStyle({ display: 'block' });
	
	// create pois on load
	if (map_condition_data != null) {
		gm_header.toogleCustomPoi(map_condition_data);	
	}
	else {
		if (map_startup_params.cat_id != '') {
			try {
				if (amapping[map_startup_params.cat_id] != '') {
					if ($('cat_' + amapping[map_startup_params.cat_id]) != '') {
						$('cat_' + amapping[map_startup_params.cat_id]).checked = true;
					}
				}
				else {
					if ($('cat_' + map_startup_params.cat_id) != '') {
						$('cat_' + map_startup_params.cat_id).checked = true;
					}
				}
			} catch (e) {}
			gm_header.tooglePoi(map_startup_params.cat_id, true, map_startup_params.cat_icon);
		}
	}
	if (map_startup_params.poi_id != '') {
		new Ajax.Request('/' + lang + '/poi/json/detail/' + map_startup_params.poi_id + '/',{ method: 'get', parameters: '', onComplete: gm_header.createPoi.bind(gm_header) });
	}

}

function SteiermarkTileUrl(a,b) {
	if ( b == 7 && a.x >= 66 && a.x <= 71 && a.y >= 43 && a.y <= 46 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 8 && a.x >= 133 && a.x <= 143 && a.y >= 86 && a.y <= 92 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 9 && a.x >= 266 && a.x <= 286 && a.y >= 173 && a.y <= 185 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 10 && a.x >= 532 && a.x <= 573 && a.y >= 346 && a.y <= 370 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 11 && a.x >= 1064 && a.x <= 1146 && a.y >= 692 && a.y <= 740 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 12 && a.x >= 2128 && a.x <= 2292 && a.y >= 1385 && a.y <= 1481 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 13 && a.x >= 4256 && a.x <= 4585 && a.y >= 2770 && a.y <= 2963 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 14 && a.x >= 8512 && a.x <= 9170 && a.y >= 5540 && a.y <= 5927 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 15 && a.x >= 17024 && a.x <= 18340 && a.y >= 11081 && a.y <= 11855 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	else if ( b == 16 && a.x >= 34048 && a.x <= 36681 && a.y >= 22162 && a.y <= 23711 ) {
		return "/static/stt_gm_layer/Z" + b + "/" + a.y + "/" + a.x + ".png";
	}
	return G_PHYSICAL_MAP.getTileLayers()[0].getTileUrl(a,b);
}

function closeDetailWindow() {
	$('poi_detail_window').setStyle({ display: 'none' });
}

function closeMap() {	
	this.head_height = $$('#head.hd_overwrite, #head.hd_overwrite .hd_out, #head.hd_overwrite .hd_out .background');
	ex0 = new Animator({ 
		transition: Animator.makeEaseOut(4),
		duration: 1600,
		onComplete: removeMapClasses()
	});
	ex0.addSubject(new NumericalStyleSubject(this.head_height, 'height', 505, 95));
	//ex0.addSubject(new NumericalStyleSubject($('site'), 'padding-top', 225, 0));
	ex0.play();
}

function removeMapClasses () {
	$$('#head .hd_out .background')[0].setStyle({ display: 'block' });
	$('gmaps').setStyle({ display: 'none' });
	$('gmcontrols').setStyle({ display: 'none' });
	$('gmclose').setStyle({ display: 'none' });
	$('gmsize').setStyle({ display: 'none' });
	$('gminfo').setStyle({ display: 'none' });
	$('head').removeClassName('mapopen');
	if ($('search_book') != null) {
		$('search_book').removeClassName('seb_overwrite');
	}
	$('gm_header').setStyle({ display: 'none' });
	$('head').removeClassName('mapopen');
}						


new Namespace("at.steiermark.gmaps.gmapsheader");
at.steiermark.gmaps.gmapsheader = Class.create({
	initialize: function() {
		this.poiMarkers = new Object();
		this.lastKey = "";
		this.lastIcon = "";
	},
	
	initLoader : function (cat_id, cat_icon, poi_id, map_condition) {
        //console.log(map_condition);



		$$('#head .hd_out .background')[0].setStyle({ display: 'none' });
		$('head').addClassName('mapopen');
		try {
			if ($('search_book') != null) {
				$('search_book').addClassName('seb_overwrite');
			}
		} catch (e) {}
		$('gm_header').setStyle({ display: 'block' });
		
		try {
			if (map_condition != "") {
				map_condition_data = map_condition;
			}
		} catch (e) {}
		
		map_startup_params = {cat_id : cat_id, cat_icon : cat_icon, poi_id : poi_id};
			
		this.head_height = $$('#head.hd_overwrite, #head.hd_overwrite .hd_out, #head.hd_overwrite .hd_out .background');
		if (parseInt($('head').getStyle('height')) < 120) {
			ex0 = new Animator({ 
				transition: Animator.makeEaseOut(4),
				duration: 1600,
				onComplete: this.loadMap
			});
			ex0.addSubject(new NumericalStyleSubject(this.head_height, 'height', 97, 505));
			ex0.addSubject(new NumericalStyleSubject($('site'), 'padding-top', 225, 0));
			ex0.play();
		}
	},
	
	loadMap : function () {
		LazyLoad.load('http://www.google.com/jsapi?key=' + googleMapsApiKey, loadMaps);
	},
	
	enableDisableCheckboxes : function () {
		/*var checks = $('gminfo_content').getElementsByTagName("input");
		for (e=0;e<checks.length;e++) {
			if(checks[e].disabled == true) {
				checks[e].disabled = false;
			}
			else {
				checks[e].disabled = true;
			}
		}*/
	},
	
	toogleCustomPoi : function (condition) {

		this.enableDisableCheckboxes();
		map_cond = {
			data : condition,
			filters : map_filters
		};
        //console.log("Map Condition inside toogleCustomPoi");
        //console.log(map_cond);
		new Ajax.Request('/' + lang + '/poi/json/custom/',{ method: 'get', parameters: map_cond, onComplete: this.createPois.bind(this) });
	},
	
	tooglePoi : function (category, checked, icon) {

		this.lastKey = category;
		this.lastIcon = icon;

		if(checked == true) {
			this.enableDisableCheckboxes();
			map_cond = {
				filters : map_filters
			};
            //console.log("Map Condition inside tooglePoi");
            //console.log(map_cond);
			new Ajax.Request('/' + lang + '/poi/json/' + category + '/',{ method: 'get', parameters: map_cond, onComplete: this.createPois.bind(this) });
		}
		else {
			this.rewritePois(true);
		}
	},
	
	createPois : function (transport) {
       // console.log('createPois - start');

		this.enableDisableCheckboxes();
		var pois = transport.responseText.evalJSON();

		this.poiMarkers[this.lastIcon] = new Array();
       // console.log('pois ' + pois.length);
		for (i = 0; i < pois.length; i++) {
          //  console.log(pois[i]);
			if (pois[i]) {
    try{

				this.poiMarkers[this.lastIcon][i] = new GMarker(new GLatLng(pois[i].lat,pois[i].lng),{icon: icon[pois[i].icon]});
				this.poiMarkers[this.lastIcon][i].myID = 'win_' + pois[i].id;
				this.poiMarkers[this.lastIcon][i].myMap = map;

				if (!pois[i].wah) { pois[i].wah = "f"; }
				if (!pois[i].nwh) { pois[i].nwh = "f"; }
				if (!pois[i].llh) { pois[i].llh = "f"; }
				if (!pois[i].skh) { pois[i].skh = "f"; }
				if (!pois[i].mbh) { pois[i].mbh = "f"; }
				if (!pois[i].fwf) { pois[i].fwf = "f"; }
				if (!pois[i].weh) { pois[i].weh = "f"; }
				if (!pois[i].awh) { pois[i].awh = "f"; }
				if (!pois[i].ghh) { pois[i].ghh = "f"; }
				if (!pois[i].thh) { pois[i].thh = "f"; }
				if (!pois[i].wsb) { pois[i].wsb = "f"; }
				if (!pois[i].fah) { pois[i].fah = "f"; }
				if (!pois[i].goh) { pois[i].goh = "f"; }
				if (!pois[i].rah) { pois[i].rah = "f"; }
				if (!pois[i].reg) { pois[i].reg = "f"; }
				if (!pois[i].nap) { pois[i].nap = "f"; }
				if (!pois[i].bio) { pois[i].bio = "f"; }

				//this.poiMarkers[this.lastIcon][i].data = poi_detail_data.process(pois[i]);
				this.poiMarkers[this.lastIcon][i].data = pois[i];
                //TrimPath.processDOMTemplate("poi_detail_data", pois[i]);

				GEvent.addListener(this.poiMarkers[this.lastIcon][i], "click", function () {
					$('poi_detail_window').setStyle({ display: 'block' });
					$('poi_detail_window').innerHTML = TrimPath.processDOMTemplate("poi_detail_data",this.data);
					toolTips($$('.inhalt .icn'));
				});
    }catch(e){
       // console.log(e);
    }


			}

		}

		this.rewritePois();
	},
	
	createPoi : function (transport) {

		var poi_data = transport.responseText.evalJSON();
		poi = new GMarker(new GLatLng(poi_data.lat,poi_data.lng),{icon: icon[poi_data.icon]});
		
		if (!poi_data.wah) { poi_data.wah = "f"; }
		if (!poi_data.nwh) { poi_data.nwh = "f"; }
		if (!poi_data.llh) { poi_data.llh = "f"; }
		if (!poi_data.skh) { poi_data.skh = "f"; }
		if (!poi_data.mbh) { poi_data.mbh = "f"; }
		if (!poi_data.fwf) { poi_data.fwf = "f"; }
		if (!poi_data.weh) { poi_data.weh = "f"; }
		if (!poi_data.awh) { poi_data.awh = "f"; }
		if (!poi_data.ghh) { poi_data.ghh = "f"; }
		if (!poi_data.thh) { poi_data.thh = "f"; }
		if (!poi_data.wsb) { poi_data.wsb = "f"; }
		if (!poi_data.fah) { poi_data.fah = "f"; }
		if (!poi_data.goh) { poi_data.goh = "f"; }
		if (!poi_data.rah) { poi_data.rah = "f"; }
		if (!poi_data.reg) { poi_data.reg = "f"; }
		if (!poi_data.nap) { poi_data.nap = "f"; }
		if (!poi_data.bio) { poi_data.bio = "f"; }

		//poi.data = poi_detail_data.process(poi_data);
		poi.data = poi_data;


		//TrimPath.processDOMTemplate("poi_detail_data", poi_data);
		
		GEvent.addListener(poi, "click", function () {
			$('poi_detail_window').setStyle({ display: 'block' });
			$('poi_detail_window').innerHTML = TrimPath.processDOMTemplate("poi_detail_data",this.data);
			toolTips($$('.inhalt .icn'));
		});
		
		map.addOverlay(poi);
		
		if (poi_data.kml != null) {
			if (geoXml) map.removeOverlay(geoXml);			
			geoXml = new GGeoXml("http://www.steiermark.com" + poi_data.kml);
			map.addOverlay(geoXml);
			
			geoXml.gotoDefaultViewport(map);
  			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			
		}

	},
	
	rewritePois : function  (deleteItem) {
		if (this.markerClusterer != null) {
			this.markerClusterer.clearMarkers();
		}

		if(deleteItem == true) {
			delete this.poiMarkers[this.lastIcon];	
		}
		
		this.markers = new Array();
		var keys = Object.keys(this.poiMarkers);
		if (keys.length > 0) {
			for (var i = 0; i < keys.length; i++) {
				for (var m = 0; m < this.poiMarkers[keys[i]].length; m++) {
					this.markers.push(this.poiMarkers[keys[i]][m]);
				}
			}
		}
		
		this.markerClusterer = new MarkerClusterer(map, this.markers);
	}

		
});



