﻿//declaring the class

var Flexmap = Class.create();

Flexmap.prototype = {
	debugMode : false,
	iconMode : 'big',
	bigMarkerArray : [],
	smallMarkerArray : [],
	smallIconArray :[],
	bigIconArray : [],
	pointArray : [],
	ignoreChange : false,
	
	defaultConfig : {
		bigIconSize : new GSize(32,32),
		iconShadowSize : new GSize(59,32),
		smallIconSize : new GSize(16,16),
		defaultIcon : "typo3conf/ext/flexmap/res/icon.png",
		defaultIconShadow : "typo3conf/ext/flexmap/res/icons.png",
		defaultSmallIcon : "typo3conf/ext/flexmap/res/smallIcon.png",
		iconFolder : "uploads/media",
		width : 700,
		height : 400,
		lat : 50,
		lon : 8,
		defaultZoom : 10,
		singlePointZoom : 13,
		type : G_NORMAL_MAP,
		iconModeSwitch : 11,
		showMapTypeButtons : 1,
		showCategorySelector : 1,
		showNavControls : 2,
		showOverviewMap : 1,
		resizeView : true //resize map, so that all points are in the viewport
	},
	
	initialize: function(mapElement,varName) {
		
		if(this.initialize.arguments.length >2){
			this.loadConfig(this.initialize.arguments[2]);
		}
		else this.loadConfig();
		this.map = new GMap2($("mapcontainer"));
		this.map.setCenter(new GLatLng(this.conf['lat'],this.conf['lon']),this.conf['defaultZoom']);
		this.map.setMapType(this.conf['type']);
		if(this.conf['showNavControls']){
			if(this.conf['showNavControls'] == 1)this.map.addControl(new GSmallMapControl());	//add small map controls
			else this.map.addControl(new GLargeMapControl());	//add large map controls
		}
		if(this.conf['showMapTypeButtons'])this.map.addControl(new GMapTypeControl());	//add map/satellite buttons
		this.map.addControl(new GScaleControl());
		if(this.conf['showCategorySelector'])this.map.addControl(new CategorySelector());
		this.mapsize = this.map.getSize();
		if(this.conf['showOverviewMap'])this.map.addControl(new GOverviewMapControl(new GSize((this.mapsize.width/5),(this.mapsize.height/4))));
		GEvent.bind(this.map,  "zoomend",  this,  this.zoomChanged);
		GEvent.bind(this.map,  "click",  this,  this.clickProcess);
		this.mgrOptions = { borderPadding: 150, maxZoom: 15, trackMarkers: true };
		this.mgr = new GMarkerManager(this.map, this.mgrOptions);
		this.showInfoTextComplete.bind(this);
	},
	
	loadConfig : function(){
		this.conf = new Array();
		for(key in this.defaultConfig)this.conf[key] = this.defaultConfig[key];
		if(this.loadConfig.arguments.length >0){
			var conf = this.loadConfig.arguments[0];
			for(key in conf)this.conf[key] = conf[key];
		}
	},
		
	// argument:array with key value pairs 
	zoomChanged : function(){
		if(this.ignoreChange)return;
		z = this.map.getZoom();
		//$('zoomlevel').innerHTML = z;
		changed = false;
		if(z >= this.conf['iconModeSwitch'] && this.iconMode == 'small'){
			this.iconMode = 'big';
			changed = true;
		}
		else if(z < this.conf['iconModeSwitch'] && this.iconMode == 'big'){
			this.iconMode = 'small';
			changed = true;
		}
		if(changed){
			this.map.clearOverlays();
			for(i=0;i<this.markerArray[this.iconMode].length;i++){
				this.map.addOverlay(this.markerArray[this.iconMode][i]);
			}
		}
	},

	
	clickProcess : function(overlay) {
		if(this.clickProcess.arguments[0]){
			if(typeof overlay.uid !='undefined'){
				this.showInfoText(overlay.uid);
				//this.map.openInfoWindowHtml(overlay.getPoint(),'Marker: ' + overlay.uid); 
			}
		}
	},
		

	showInfoText : function(uid){
			vars = {
				'ajax' : 'showInfoText',
				'uid' : uid
			}
			this.sendVars(vars);
	},
	
	showInfoTextComplete : function(request){
			if(this.debugMode)GLog.write('showInfoTextComplete responseText' + request.responseText);
			//alert(request.responseText);
			eval(request.responseText);
			
			this.map.openInfoWindowTabsHtml(new GLatLng(lat,lon),infoTabs); 
	},
	
	
	

	
	// ############### manage points #############################

	
	displayPoint : function(lat,lon,uid,iconIndex,iconMode){
		this.ignoreChange = true;
		p = new GLatLng(lat,lon);
		m = this.createMarker(p,uid,iconIndex,iconMode);
		this.map.addOverlay(m);
		this.map.setCenter(p,this.conf['singlePointZoom']);
	},
	
	showPoint : function(uid){
		this.ignoreChange = true;
			vars = {
				'ajax' : 'showPoint',
				'uid' : uid
			}
			this.sendVars(vars);
	},
	
	showPointComplete : function(request){
		this.ignoreChange = true;
		if(this.debugMode)GLog.write('showPointComplete.responseText: ' + request.responseText);
		eval(request.responseText);
		
		p = new GLatLng(lat,lon);
		m = new GMarker(p);
		m.uid = uid;
		this.map.addOverlay(m);
	},
	
	showPoints : function (){
		if(this.showPoints.arguments.length >0)points = this.showPoints.arguments[0];
		else points = this.points;
		
		if(this.points.length > 0){
			if(this.debugMode)GLog.write('Geladene Punkte: ' + points.length);
			bounds = new GLatLngBounds();
			//this.map.setCenter(bounds.getCenter(),this.map.getBoundsZoomLevel(bounds));
			this.markerArray = new Array();
			this.markerArray['big'] = new Array();
			this.markerArray['small'] = new Array();
			for(i=0;i<points.length;i++){
				point = points[i];
				p = new GLatLng(point[0],point[1]);
				cat = point[3];
				if(typeof categories[cat[0]] !='undefined'){
					iconIndex = categories[cat[0]][2];
					smallIconIndex = categories[cat[0]][3];
				}
				else {
					iconIndex = 'default';
					smallIconIndex ='default';
				}
				if(!bounds.contains(p)){
					bounds.extend(p);
				}
				this.markerArray['small'].push(this.createMarker(p,point[2],smallIconIndex,'small'));
				
				//this.map.addOverlay(this.createMarker(p,point[2],smallIconIndex,'small'));
				this.markerArray['big'].push(this.createMarker(p,point[2],iconIndex,'big'));
				if(this.debugMode)GLog.write('Punkt: ' + point[2] + 'Kat.:' + categories[cat[0]]);
				// for debugging only
				this.pointArray.push([p,point[2],iconIndex,cat]);
			}
	
			//this.mgr.addMarkers(this.smallMarkerArray,3,this.conf['iconModeSwitch']);
			//this.mgr.addMarkers(this.bigMarkerArray,this.conf['iconModeSwitch']+1);
			if(this.conf['resizeView']){
				this.ignoreChange = true;
				z = this.map.getBoundsZoomLevel(bounds);
				if(z > this.conf['singlePointZoom'])z = this.conf['singlePointZoom'];
				this.map.setCenter(bounds.getCenter(),z);
				this.ignoreChange = false;
			}
			if(this.map.getZoom() < this.conf['iconModeSwitch']){
				this.iconMode = 'small';
			}
			else {
				this.iconMode = 'big';
			}

			for(i=0;i<this.markerArray[this.iconMode].length;i++){
				this.map.addOverlay(this.markerArray[this.iconMode][i]);
			}
			
		}
		//else alert('no points');
	},
		
	
	showCategories : function (selectedCats){
		selectedPoints = new Array();
		this.points.each(
			function(point){
				cats = point[3];
				cats.each(
					function(cat){
						if(sel = selectedCats.detect(function(sel){if(cat == sel)return true;})){
							if(this.debugMode)GLog.write('point: ' + point[0] + ':' + point[1] + 'cat:' + cat );
							point[3] = [sel];
							selectedPoints.push(point);
							
						}
					}
				);
			}	
		);
		
		this.map.clearOverlays();
		if(selectedPoints.length == 0)return;
		this.showPoints(selectedPoints);
	},
	
	createMarker : function(point,uid,iconIndex,iconMode){
		markerOptions = {};
		if(this.getPointIcon(iconIndex,iconMode))markerOptions.icon = this.getPointIcon(iconIndex,iconMode);
		m = new GMarker(point,this.getPointIcon(iconIndex,iconMode));
		m.uid = uid;
  		return m;
	},
		
	getPointIcon : function(iconIndex,iconMode){
		iconArray = eval('this.' + iconMode + 'IconArray');
		if(typeof iconArray[iconIndex] !='undefined')return iconArray[iconIndex];
		iconShadow = 'noShadow';
		if(iconMode == 'big'){
			if(icons[iconIndex] == 'default' || iconIndex == 'default'){
				iconImage = this.conf['defaultIcon'];
				iconShadow = this.conf['defaultIconShadow'];
			}
			else iconImage = iconFolder + icons[iconIndex];
			if(iconShadows[iconIndex]!='noShadow'){
				iconShadow = iconFolder + iconShadows[iconIndex];
			}
			iconSize = this.conf['bigIconSize'];
		}
		else {
			if(smallIcons[iconIndex] == 'default' || iconIndex == 'default')iconImage = this.conf['defaultSmallIcon'];
			else iconImage = iconFolder + smallIcons[iconIndex];
			
			iconSize = this.conf['smallIconSize'];
		}
		icon = this.createIcon(iconImage,iconSize,iconShadow);
		iconArray[iconIndex] = icon;
		return icon;
	},
	
	createIcon : function(iconImage,iconSize,iconShadow){
		//alert(iconImage + '-' + iconSize + '-' + iconShadow);
		var icon = new GIcon();
		icon.image = iconImage;
		if(iconShadow!='noShadow'){
			icon.shadow = iconShadow;
			icon.shadowSize = this.conf['iconShadowSize'];
		}
		icon.iconSize = iconSize;
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		return icon;
	},
	
	loadPointsFromServer : function(id){
		this.status('Hole Daten');
		var v = new Array();
		v['action'] = 'loadPoints';
		v['tour_id'] = id;
		this.resetPoints();
		this.sendVars(v);
	},
	
	loadPointsComplete : function(request){
		if(this.debugMode)GLog.write('loadPoints responseText' + request.responseText);
		if(xmlDoc = request.responseXML){	
			var pointsArr = xmlDoc.documentElement.getElementsByTagName("point");		
		}

	},

	getCurrentMapType : function (){
		t = this.map.getCurrentMapType();
		var maptypes = this.map.getMapTypes();
		for(i=0;i<maptypes.length;i++){
			if(t == maptypes[i])return i;
		}
	},
	
	
	sendVars : function (vars){
		if(this.debugMode)GLog.write('sendVars');
		//var _this = this; // don't overload the meaning of 'this'
		var url = window.location.href;
		varstring = '';
		for (var key in vars){
			if(typeof vars[key] !='function'){
				varstring += 'tx_flexmap_pi1[' + key + ']=' + escape(vars[key]) + '&';
				if(this.debugMode)GLog.write('sendVars ' + key +': ' + vars[key]);
			}
		}
		
		myAjax = new Ajax.Request( url, { method: 'post', parameters: varstring, onComplete:eval('this.' + vars['ajax'] + 'Complete.bind(this)') });

		
	},
	
	
	debug : function (){

		f = window.open("","Fenster1","width=910,height=600,left=0,top=0,resizable=yes,scrollbars=yes");
		
		f.document.write('Points:<br /><table border="1" cellpadding="5" style="border-collapse:collapse;font-family:Arial;font-size:10pt">');

		for(i=0;i< this.pointArray.length;i++){

				f.document.write('<tr><td>Punkt ' + i + '</td><td> uid: ' + this.pointArray[i][1] + '</td><td> x : ' +  this.pointArray[i][0].x + '</td><td> y : ' +  this.pointArray[i][0].y + '</td><td>  bigIconIndex : ' +  this.pointArray[i][2] + '</td><td> Cat : ' +  this.pointArray[i][3] + '</td></tr>');
		}
		f.document.write('</table>');
		f.document.close();	
		
	}
	
}






