// Form fields with this class and a rel attribute with the default value

/**
 * Class: meMarker Implementation of the sidebarMarker/tgMapMarker Class for
 * displaying mediaEntries
 */
var meMarker = Class.create(tgMapMarker, {

	initialize: function($super, id, position, opts) {
		if($("telegate")){
			var iconPath ="/11880/img/maps/icons/icon_me.png";			
		} else if($("klicktel")){
			var iconPath ="/global/img/maps/icons/icon_me.png";
		}else {
			var iconPath ="/11880/img/maps/icons/icon_me.png";
		}	

		$super(id, position, {
					icon: {
						iconImg: iconPath,
						hoverImg: null,
						shadowUrl: "/global/img/maps/icons/iconshadow.png",
						width: 34,
						height: 47,
						shadowwidth: 34,
						shadowheight: 47,
						tipX: 10,
						tipY: 44,
						activeArea: "5,5,28,5,28,28,20,28,11,45,9,45,9,28,5,28",
						priority: 10
					},

					title: opts.title
				});

		this.type = "me";
		

	},
	
	_click: function ($super, e) {
		$super(e);
		Event.stop(e);
	}
});

/**
 * Class: meMultiMarker Implementation of the tgMapMarker Class for displaying
 * multi media entries but not multimedia entries
 */
var meMultiMarker = Class.create(tgMapMarker, {

	initialize: function($super, id, position, opts) {
		if($("telegate")){
			var iconPath ="/11880/img/maps/icons/icon_me_multi.png";			
		} else if ($("klicktel")){
			var iconPath ="/global/img/maps/icons/icon_me_multi.png";
		} else {
			var iconPath ="/11880/img/maps/icons/icon_me.png";
		}

		$super(id, position, {
					icon: {
						iconImg: iconPath,
						hoverImg: null,
						shadowUrl: "/global/img/maps/icons/iconshadow.png",
						width: 34,
						height: 47,
						shadowwidth: 34,
						shadowheight: 47,
						tipX: 10,
						tipY: 44,
						activeArea: "5,5,28,5,28,28,20,28,11,45,9,45,9,28,5,28",
						priority: 10
					},

					title: opts.title
				});

		this.type = "meMulti";

	},
	
	_click: function ($super, e) {
		$super(e);
		Event.stop(e);
	}
});

/**
 * Class: stMultiMarker Implementation of the tgMapMarker Class for displaying
 * mutli standard entries
 */
var stMultiMarker = Class.create(tgMapMarker, {

	initialize: function($super, id, position, opts) {

		$super(id, position, {
					icon: {
						iconImg: "/global/img/maps/icons/icon_st_multi.png",
						hoverImg: null,
						shadowUrl: "/global/img/maps/icons/iconshadow.png",
						width: 34,
						height: 47,
						shadowwidth: 34,
						shadowheight: 47,
						tipX: 10,
						tipY: 44,
						activeArea: "5,5,28,5,28,28,20,28,11,45,9,45,9,28,5,28",
						priority: 10
					},

					title: opts.title
				});

		this.type = "stMulti";

	},
	
	_click: function ($super, e) {
		$super(e);
		Event.stop(e);
	}
});

var tgManager = Class.create ({
	_mapUtils: null,

	initialize: function (mapUtils) {
		this._mapUtils = mapUtils;
	},

	_getMap: function () {
		return this._mapUtils.map;
	}
});


var tgActionLinkManager = Class.create(tgManager,{
	activeInfoWindow: null,
	handleClick: null,
	tgmFreeCallDialog: null,

	initialize: function($super, mapUtils) {
		if (mapUtils.actionLinkManager != null) {
			return mapUtils.actionLinkManager;
		};

		$super(mapUtils);

		this.handleClick = this._handleClick.bindAsEventListener(this);
	},

	_handleClick: function(e) {
		var eo = Event.element(e);
				
		
		if (Element.hasClassName(eo.parentNode, "linksection")) {
			//Default behaviour for regular links
			return;
		}
		
		if (eo.className == "crossclose_multi") {
			this._getMap().closeInfoWindow();
			Event.stop(e);
			return;

		} else if (eo.className == "crossclose") {
			this._getMap().closeInfoWindow();
			Event.stop(e);
			return;

		} else if (eo.className == "route") {
			this._startRouting(eo);
			Event.stop(e);
			return;
			
		} else if (eo.className == "infoWindowDBLink") {
			return;

		} else if (eo.className == "action freecall javascript") {
			this._startFreeCall(eo.id);
			
			return;

		} else if (eo.className == "addressbook") {
			
			this.startSaveAddress(eo.id);
			eo.removeClassName("addressbook");
			eo.addClassName("savedIW");
			Event.stop(e);
			return;
			
		} else if (eo.hasClassName('mailto')) {
			if (tgmEmailDialog == null || tgmEmailDialog == 'undefined') {
				tgmEmailDialog = new tgmContactEmailDialogClass();
				
			}
			tgmEmailDialog.entryId = eo.getAttribute("rel");
			tgmEmailDialog.show();
			Event.stop(e);
			return; 

		} else if (eo.className == "call" || eo.className == "callTxt"
				|| eo.className == "callIMG") {
			
			if (eo.className == "callIMG") {
				var entryIdString = eo.parentNode.id;
			} else {
				var entryIdString = eo.id;
			}
			this._startFreeCall(entryIdString);
			Event.stop(e);
			return;

		} else if (eo.className == "infoWindowStMultiPagingBack"
				|| eo.className == "infoWindowStMultiPagingForward"
				|| eo.className == "infoWindowMeMultiPagingBack"
				|| eo.className == "infoWindowMeMultiPagingForward") {
			this._startInfowindowPaging(eo);
			Event.stop(e);
			return;

		} else if (eo.className == "moreTrades") {
			this._showMoreTrades();
			Event.stop(e);
			return;

		} else if (eo.className == "freecall") {
			var entryId = eo.rel;
			tgmMain.fireEvent('onClickDialogFreecall', { entryId:entryId });
			Event.stop(e);
			return;
		} else if (eo.className == "freefax") {
			var entryId = eo.rel;
			tgmMain.fireEvent('onClickDialogFax', { entryId:entryId });
			Event.stop(e);
			return;
		}		
		document.location.href = "/homepage/detail?id="+mapUtils.iconManager.openEntry;
		Event.stop(e);
	},

	_showMoreTrades: function() {

	},

	_startRouting: function(eo) {
		var locId        = eo.id.split("_");
		var locationInfo = $("routing_" + locId[1]).value.split("|");
		var formName     = locationInfo[0] + " " + locationInfo[1] + " " + locationInfo[2] + " " + locationInfo[3];
		if (formName.strip() == "") {
			var title = eo.up(".tgInfoWindowContent").down(".title");
			if (typeof title != undefined && title != null) {
				formName = title.firstChild.data;
			}
		}
		
		url = "http://"+location.hostname+"/routenplaner/?s0=&s4="+formName;
		
		var w = window.open (url, "", "");		
	},

	_startFreeCall: function(eId) {
		var idArray = eId.split("_");
		var entryId = idArray[1];
		
		var kostenlostelefonieren = window.open('http://' + pandoraData.apiDuoDomain + '/kostenlosanrufen/initiateCall.php?id=' + entryId + '&website=' + pandoraData.website, 'kostenlostelefonieren', 'status=no,scrollbars=yes,resizable=no,width=530,height=520');
		if (kostenlostelefonieren) {
			kostenlostelefonieren.focus();
		} else {
			alert('Das Fenster zum kostenlosen telefonieren kann nicht geöffnet werden.\nBitte deaktivieren Sie vorübergehend den PopUp-Blocker für diese Seite!');
		}
	},

	startSaveAddress: function(entryId) {

		var data = {
			entryId: entryId
		};

		new Ajax.Request("/ajax/addressbook/add", {
			method: 'get',
			parameters: data,
			evalJSON: true,
			onComplete: function(response) {
				if (response.responseJSON != null) {
					if (response.responseJSON.success == 1) {
						// Fire event so that the UI can change the display of
						// the link "add to addressbook"
						tgmMain.fireEvent('onAddressbookAdd', data);
					} else {
						tgmMain.showError('Der Eintrag konnte nicht als Favorit gespeichert werden.');
						if (callback != null) {
							callback(false);
						}
					}
				} else {
					// Must be an error - server did not reply with JSON
					tgmMain.showError('Der Server hat fehlerhafte Daten geliefert.');
					if (callback != null) {
						callback(false);
					}
				}
			}.bind(this)
		});

	},

	_startInfowindowPaging: function(eo) {
		var parentId      = eo.parentNode.id;
		var idParts       = parentId.split("_");
		var entryIdString = idParts[0];
		var displayNoPrev = idParts[1];
		this._mapUtils.reloadInfowindowContent(entryIdString, displayNoPrev);
	}

});

var tgIconManager = Class.create(tgManager, {
	_mapUtils: null,
	openEntry: null,
	
	initialize: function($super, mapUtils) {
		if (mapUtils.iconManager != null) {
			return mapUtils.iconManager;
		};

		$super(mapUtils);	
	},
	
	_getMap: function () {
		return this._mapUtils.map;
	},
	
	handleClick: function(marker, markerId, type) {
		var lnglat = marker.getLngLat().getTg();
		if (lnglat.longitude == 0 && lnglat.latitude == 0) {
			//Marker is in Nirvana
			return;
		}
		
		if (this._mapUtils.actionLinkManager.activeInfoWindow != null) {
			Event.stopObserving(this._mapUtils.actionLinkManager.activeInfoWindow, "click",	this._mapUtils.actionLinkManager.handleClick);
			this._getMap().stopObserving("infowindowload",
			this._loadobserver);
		}
		
		var displtype = marker.type;
		if (typeof(type) != "undefined" && type != null) {
			if (type == "media" && marker.type == "stMulti") {
				displtype = "meMulti";
			} else if (type == "std" && marker.type == "meMulti") {
				displtype = "stMulti";
			}
		}

		if (displtype == "me") {
			// MediaEntry, show customized infowindow
			var url        = "/ajax/maps/infowindowMediaEntry";
			var parameters = "entry_id=" + marker.id;
			var method     = "get";
			if($("11880")){
				var iconShadowPath ="/11880/maps/img/infowindow_single_me_shadow.png";			
			} else if($("klicktel)")){
				var iconShadowPath ="/klicktel/maps/img/infowindow_single_me_shadow.png";
			}
			this._getMap().openInfoWindowAjax(marker.getLngLat(), url,
					parameters, method, {
						marker: marker,
						classes: ['tgInfoWindowMeSingle'],
						shadowUrl: iconShadowPath,
						shadowOffsetY: 160,
						shadowwidth:578,
						shadowheight:39,
						tipX: 5,
						tipY: 195
					});
			var infowindowClassName = "div.tgInfoWindowMeSingle";
			this.openEntry          = marker.id;
		} else if (displtype == "meMulti") {
			// Multi MediaEntry, show customized infowindow
			var url = "/ajax/maps/infowindowMediaEntryMulti";
			if (markerId != null && typeof(markerId) != "undefined") {
				var m          = marker.id.split(",");
				var displayNo  = m.indexOf(markerId);
				var parameters = "entry_id=" + marker.id + "&displayNo="+ displayNo;
			} else {
				var parameters = "entry_id=" + marker.id;
			}
			var method = "get";
			if($("11880")){
				var iconShadowPath ="/11880/maps/img/infowindow_multi_me_shadow.png";			
			} else if($("klicktel")){
				var iconShadowPath ="/klicktel/maps/img/infowindow_multi_me_shadow.png";
			}
			this._getMap().openInfoWindowAjax(marker.getLngLat(), url,
					parameters, method, {
						marker: marker,
						classes: ['tgInfoWindowMeMulti'],
						shadowUrl: iconShadowPath,
						shadowOffsetY: 190,
						shadowwidth:591,
						shadowheight:41,
						tipX: 5,
						tipY: 229
					});
			var infowindowClassName = "div.tgInfoWindowMeMulti";
			var entryIds            = marker.id.split(",");
			this.openEntry          = entryIds[0];	
		}

		this._loadobserver = function(e) {
			
			this._mapUtils.actionLinkManager.activeInfoWindow = $$(infowindowClassName)[0];
			Event.observe(this._mapUtils.actionLinkManager.activeInfoWindow, "click", this._mapUtils.actionLinkManager.handleClick);
			
		}.bindAsEventListener(this);

		// Webtrends Tracking Infowindow ->Map Actions
		if (typeof(_tag)!= "undefined") {
			_tag.DCSext = {};
		}
		dcsMultiTrack('DCSext.mapSType', '8', 'DCSext.displayIWType', displtype, 'DCSext.iwEntryID', marker.id);
		this._mapUtils.ivwBoxManager.track();
		this._getMap().observe("infowindowload", this._loadobserver);
	}
});

var tgIVWBoxManagerFilliale = Class.create({

	className:'tgIVWBoxManager',
	detailMap:null,
	pixel: null,
	baseUrl: null,
	path: "/cgi-bin/ivw/CP/",
	context: null,
	timestamp: 0,

	initialize: function (detailMap) {

		this.pixel                  = document.createElement("img");
		this.pixel.style.width      = "1px";
		this.pixel.style.height     = "1px";
		this.pixel.style.visibility = "hidden";
		
		if (($("klicktel") != null && typeof($("klicktel")) != "undefined") || ($("telegate") != null && typeof($("telegate")) != "undefined")) {
			$("pandoraMap").appendChild(this.pixel);
		}
		
		this.baseUrl = "http://klicktel.ivwbox.de";
	},

	track: function () {
		var zeit = new Date();
		if (zeit.getTime() - this.timestamp > 1500) {
			this.timestamp = zeit.getTime();
			if (($("klicktel") != null && typeof($("klicktel")) != "undefined") ||
			($("telegate") != null && typeof($("telegate")) != "undefined")) {
				this.pixel.src = this.baseUrl + this.path + this.context + ";/?r=" + document.referrer + "&d=" + (Math.random() * 100000);
			}
		}
	}
});



var tgSubsidiaryMapClass = Class.create({

	className:'tgSubsidiaryMapClass',
	map: null,		
	groupDistance: Array(60, 120, 250, 500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, 256000, 512000, 1024000),
		
	
	subsidiaries: [],

	initialize:function()
	{
		
	},

	init:function(mapMarker, parentNode)
	{
		if (tgBrowserIsCompatible()) {
			map = new tgMap($(parentNode));
		
			mapUtils         = this;
			this.map         = map;
			this.iconManager = new tgIconManager(this);
			

			map.observe("markerclick", function(e) {
				var marker = e.memo.marker;
				mapUtils.iconManager.handleClick(marker);			
				Event.stop(e);
				return false;
			});
			
			//Calculate really good groupDistance Array
			var upp            = 0;
			this.groupDistance = [];
			
			var singleMarkerWidth = 34;
			var overlap_factor    = 0.75;
			
			for (var i = 0; i<_METER_PER_PIXEL.length; i++) {
				upp = _METER_PER_PIXEL[i]*10;
				this.groupDistance.push(Math.floor(upp*singleMarkerWidth*overlap_factor));
			}
			
			this.ivwBoxManager     = new tgIVWBoxManagerFilliale(this);
			this.actionLinkManager = new tgActionLinkManager(this);
		
			// add button for switching to subsidiary list 
			// (what does 'subsidiaryListeButton' do here? check again...)
			var buttonControl = new tgMapButton(TG_ANCHOR_TOP_RIGHT);
			this.map.addControl(buttonControl);
			var listViewButton = new Element( 'div').update( 'Liste' );
			listViewButton.addClassName('mapTypeButton');
			buttonControl.outerdiv.appendChild(listViewButton);

			Event.observe (listViewButton, "click", tgmEntryDetail.displayList.bindAsEventListener(tgmEntryDetail));
		
		
			this.map.addControl(new tgMapScale(TG_ANCHOR_BOTTOM_RIGHT));
			this.map.addControl(new tgMapSmallNavigation(TG_ANCHOR_TOP_LEFT));
			
			this.map.fitViewToMarkerlist(mapMarker, false);			
						
			this.subsidiaries = mapMarker;			
						
			this.displayMarker();
						
			this.ivwBoxManager.context = "MEDIA+Eintrag";

			/*
			 * Webtrends Tracking Calls (additional IVW pixel requests)
			 */

			if (pandoraData.premiumDomain != 1) {			 
				this.map.observe("zoomin", function() {
					if (typeof(_tag)!= "undefined") {
						_tag.DCSext = {};
					}
					dcsMultiTrack('DCSext.maps_action', 'Zoom-In');
					this.ivwBoxManager.track();
				}.bindAsEventListener(this));
				
				this.map.observe("zoomout", function() {
					if (typeof(_tag)!= "undefined") {
						_tag.DCSext = {};
					}
					dcsMultiTrack('DCSext.maps_action', 'Zoom-Out');
					this.ivwBoxManager.track();
				}.bindAsEventListener(this));
				
				this.map.observe("stopdrag", function() {
					if (typeof(_tag)!="undefined") {
						_tag.DCSext = {};
					}
					dcsMultiTrack('DCSext.maps_action', 'Pan');
					this.ivwBoxManager.track();
				}.bindAsEventListener(this));
				
				if (typeof(_tag) != "undefined") {
					_tag.DCSext = {};
				}
				dcsMultiTrack('DCSext.maps_action', 'map initialized');
				this.ivwBoxManager.track();

			}
			
			var grouper = function () {
				this.displayMarker();
				
			}.bindAsEventListener(this);
			
			this.map.observe("zoom", grouper);
			this.map.observe("stopdrag", grouper);
			
			
		}
	},
	
	reloadInfowindowContent: function(p_entryIdString, p_displayNo) {
		if (typeof(_tag)!="undefined"){
			_tag.DCSext = {};
		}

		dcsMultiTrack('DCSext.maps_action', 'paging InfoWindow Filial Finder');
		this.ivwBoxManager.track();

		var params = {
			entry_id: p_entryIdString,
			displayNo: p_displayNo
		};

		var aj = new Ajax.Request('/ajax/maps/infowindowReload', {
			method: 'get',
			parameters: params,
			onComplete: function(r) {
				var json = r.responseJSON;
				if (json.error == null) {
					var contentElement = $$('.tgInfoWindowContent')[0];
					var infoWindow     = contentElement.parentNode;
					if (json['markerType'] == "media"
							&& !infoWindow.hasClassName("tgInfoWindowMeMulti")) {
						// update Style and Position...
						Element.removeClassName(infoWindow,
								"tgInfoWindowStMulti");
						var topCorner = infoWindow.style.top.split("p");
						var top       = {
							top: (parseInt(topCorner[0]) - 64) + "px"
						};
						infoWindow.setStyle(top);
						Element.addClassName(infoWindow, "tgInfoWindowMeMulti");
						if($("11880")){
							var iconShadowPath ="/11880/maps/img/infowindow_multi_me_shadow.png";			
						} else if($("klicktel")){
							var iconShadowPath ="/klicktel/maps/img/infowindow_multi_me_shadow.png";
						}
						this.map.panes.floaterShadow.firstChild.src = iconShadwoPath;
					} else if (json['markerType'] == "std" && !infoWindow.hasClassName("tgInfoWindowStMulti")) {
						Element.removeClassName(infoWindow,	"tgInfoWindowMeMulti");
						var topCorner = infoWindow.style.top.split("p");
						var top       = {
							top: (parseInt(topCorner[0]) + 64) + "px"
						};
						infoWindow.setStyle(top);
						Element.addClassName(infoWindow, "tgInfoWindowStMulti");
						this.map.panes.floaterShadow.firstChild.src = "/klicktel/maps/img/infowindow_multi_shadow.png";
					}
					contentElement.update(json['infoWindowContent']);
					var entryIds               = p_entryIdString.split(",");
					this.iconManager.openEntry = entryIds[p_displayNo];
					tgmMain.fireEvent('onLoadAjaxContent');
				}
			}.bind(this)
		})
	},
	
	groupMarkerlist: function(p_markerlist) {
		var newMarkerlist = [];
		var zoomLevel     = this.map.getZoom();
		var range         = this.groupDistance[zoomLevel - 1];
		
		// Initialize variables outside of loop
		// to improve performance 
		var found         = 1;
		var marker        = null;
		var entryIdString = '';
		
		
				
		while (p_markerlist.length > 0) {
			found  = 1;
			marker = p_markerlist.shift();

			entryIdString = marker.entryId;

			
			var minLat = marker.latitude - range;
			var maxLat = marker.latitude + range;
			var minLng = marker.longitude - range;
			var maxLng = marker.longitude + range;
			

			p_markerlist.each(function(l_marker, l_key) {
				if (maxLat > l_marker.latitude && minLat < l_marker.latitude && maxLng > l_marker.longitude	&& minLng < l_marker.longitude) {					
					found++;
					entryIdString       = entryIdString + ","	+ l_marker.entryId;
					p_markerlist[l_key] = 0;
				}							
			});
		
					
			if (found > 1) {
				type = 'meMulti';
				
				var newMarker = {
					'entryId': entryIdString,
					'icon': 'multipin_me.png',
					'shadowIcon': 'iconshadow.png',
					'latitude': marker.latitude,
					'longitude': marker.longitude,
					'tooltip': found + ' Einträge',
					'type': type
				};

				newMarkerlist.push(newMarker);
			} else {
				newMarkerlist.push(marker);
			}
			
			p_markerlist = p_markerlist.reject(function(l_value) {
				return l_value == 0;
			});
			
			
			
		}
		return newMarkerlist;
	},
	
	displayMarker: function() {	
		var t       = new Date();
		var t_start = t.getTime();
			
		this.map._irqManager._frequency = 1024;

		var bounds = this.map.getBounds();
		
				
		var p_markerlist = this.subsidiaries.reject (function (marker) {
			return (marker.longitude < bounds.west 
			|| marker.longitude > bounds.east
			|| marker.latitude < bounds.south
			|| marker.latitude > bounds.north);
		}.bind(this));
				
		this.map.clearOverlays();		
						
		var groupMarker = this.groupMarkerlist(p_markerlist);
								
		for (var i = 0; i < groupMarker.length; ++i) {			
				if (groupMarker[i].title != null) {
					var opts = {
						'title': groupMarker[i].title,
						'type': groupMarker[i].type
					};
				} else {
					var opts = {
						'title': groupMarker[i].tooltip,
						'type': groupMarker[i].type
					};
				}
			
				var home = new tgLngLat(groupMarker[i].longitude, groupMarker[i].latitude);
				
				if (groupMarker[i].type == 'me') {
					this.map.addOverlay(new meMarker(groupMarker[i].entryId, home, opts));
				}
				
				if (groupMarker[i].type == 'meMulti') {
					this.map.addOverlay(new meMultiMarker(groupMarker[i].entryId, home, opts));
				}
				
		}
		
		var t        = new Date();
		var t_finish = t.getTime();		
	}
});
