// globals
var PM_VE_MAP;
var PM_GE_MAP;

// overwrite hide/show functions to avoid markermanager refresh problem
GMarker.prototype.hide = function ()
{
  if (this.getPoint().lat() < 90)
    try {
      this.savePoint = this.getPoint();
      this.setPoint(new GLatLng(90, 0));
    } catch(e) {}
}
GMarker.prototype.show = function ()
{
  if (this.getPoint().lat() == 90)
  if (this.savePoint)
    try {
      this.setPoint(this.savePoint);
      this.savePoint = null;
    } catch(e) {}
}

// general functions
function resizeContent (e)
{
	var height, width;
	if (self.innerHeight) // all except Explorer
	{
		height = self.innerHeight;
		width = self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		height = document.documentElement.clientHeight;
		width = document.documentElement.clientWidth;
	}
	else if (document.body) // other Explorers
	{
		height = document.body.clientHeight;
		width = document.body.clientWidth;
	}
	
	var wrapper = $('wrapper');
	var sidebars = $$('.sidebar');
	var mapdiv = $('map');
	var mapOverlayLeft = $$('.mapoverlayleft');
	var tabs = $('tabs');
	var sidebarWidth = 274;
	var topHeight = 125;
	var mapLeft = parseInt(mapdiv.getStyle('left')); // needed for overlays
	
	wrapper.style.height = (height - topHeight) + 'px';
	if (sidebars.length > 0)	// no sidebar supported as well
	{
		sidebars.each(function(sidebar){sidebar.style.height = (height - topHeight - 8) + 'px';});
	}
	else
	{
		// span map across the whole page
		mapdiv.style.left = 4 + 'px'; 
		sidebarWidth = 4;
	}
	mapdiv.style.height = (height - topHeight - 8) + 'px';
	mapdiv.style.width = (width - sidebarWidth - 4) + 'px';
	mapOverlayLeft.each(function(mol){
		var dif = parseInt(mol.getStyle('left')) - mapLeft;
		mol.style.left = (parseInt(mapdiv.getStyle('left')) + dif) + 'px';
		mol.setStyle({opacity: 0.8});
	});
	if (tabs) tabs.style.width = (width - 30) + 'px';	// correct width for padding
	
	// top link
	if ($('streetindex_toplink'))
	{
		var toplink = $('streetindex_toplink');
		var streetindex = $(toplink.parentNode);
		toplink.style.top = (streetindex.getHeight() - 25) + 'px';
	}
}

function showModule(num)
{
	var tabs = $$('#tabs a');
	
	tabs.each(function(tab)
	{
		if (tab.id == 'tab_' + num)
			tab.className = 'active';
		else
			tab.className = 'default';
	});
	
	var sidebars = $$('.sidebar');
	
	sidebars.each(function(sidebar)
	{
		if (sidebar.id == 'sidebar_' + num)
			sidebar.show();
		else
			sidebar.hide();
	});	
}

function toggleSection(id, root, hook)
{
	$('img_' + id).src = ($(id).visible()) ? root + '/files/default/arrow.gif' : root + '/files/default/arrow_down.gif';
	
	if (hook)
	{
		hook(!$(id).visible());
	}
	Effect.toggle(id, 'blind', { duration: 0.15 });
}

function addCustomIcon(id, img, imgShadow,
	imgSize, imgShadowSize,
	anchorPoint, winAnchorPoint, imageMap)
{
	var newIcon = new GIcon(G_DEFAULT_ICON);
	newIcon.image = img + '.png';
	newIcon.iconSize = imgSize;
	newIcon.shadow = imgShadow + '.png';
	newIcon.shadowSize = imgShadowSize;
	newIcon.iconAnchor = anchorPoint;
	newIcon.infoWindowAnchor = winAnchorPoint;
	newIcon.printImage = img + '.gif';
	newIcon.mozPrintImage = img + '.gif';
	newIcon.printShadow = imgShadow + '.gif';
	newIcon.transparent = 'files/default/transparent.png';
	newIcon.imageMap = imageMap; 
    
    customIcons[id] = newIcon;	
}

function createMarker(id, location, iconId, info, category)
{
	var marker = new GMarker(location, { icon: customIcons[iconId] });
	marker.customId = id;
	marker.category = category;
	markersArray.push(marker);
	markersObject[id] = marker;
	if (info)
	{
		var addressId = id.match(/[0-9]+$/);
		if(addressId && media != 'print')
		{
			info += '<div><a onclick="return openPrintWindow(\''+idRoot+'/print/'+addressId+'\');" href="'+idRoot+'/print/'+addressId+'">Druckansicht</a></div>';
		}
		GEvent.addListener(marker, "click", function() {
  		marker.openInfoWindowHtml(info);
		});
		GEvent.addListener(marker, "infowindowclose", function() {
  		showAllSearchMarkers();
		});
	}
  	
  	return marker;
}

function openPrintWindow (url) {
	var vr = new Array();
	for (var i = 0; i < routesArray.length; i++)
	{
		if (routesArray[i].visible) vr.push(routesArray[i].id);
	}
	url += '?vr=' + vr.join(',');
	detailinfo = window.open(url, "detailinfo", "width=550,height=430,left=100,top=200,scrollbars=yes,status=no,toolbar=no,location=no,menubar=no");
	detailinfo.focus();
	return false;
}


function highlightMarker(id, keepOthers)
{
	if (markersObject[id])
	{
		var marker = markersObject[id];
		marker.show();
		GEvent.trigger(marker, "click");
		if (!keepOthers) hideAllSearchMarkers(id);
	}
}

function hideAllSearchMarkers(exception)
{
	for (var id in markersObject)
	{
		if (id == exception || (id.substr(0, 1) != 's' && id.substr(0, 1) != 'c'))
		{
			continue;
		}
		markersObject[id].hide();
	}
}

function showAllSearchMarkers()
{
	for (var id in markersObject)
	{
		var prefix = id.substr(0, 1);
		if (prefix == 's' || prefix == 'c')
		{
			if (prefix == 'c' && !($('catcb_' + markersObject[id].category).checked)) continue;
			markersObject[id].show();
		}
	}
}

function resetSearch()
{
	$($('search_result').parentNode).remove();
	$('searchreset').remove();
	for (var id in markersObject)
	{
		if (id.substr(0, 1) == 's')
		{
			markerManager.removeMarker(markersObject[id]);
			delete markersObject[id];
		}
	}
}

function refreshViewport(markers) {
	var bounds = new GLatLngBounds();
	var m;
	markers.each(function(m)
	{
		if (m.getLatLng().lat() != 90)
		{
			bounds.extend(m.getLatLng());
		}
	});
	
	if (!bounds.isEmpty())
	{
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
	}
}

function toggleStreetindex(streetname, index)
{
	var streetId = 's' + index;
	var checkbox = $('schk'+index); 
	if (!(checkbox.checked))
	{
		// remove markers
		$('street'+index).style.fontWeight = 'normal';
		if (categoryMarkers[streetId])
		{
			categoryMarkers[streetId].each(function(mid){
				if(markersObject[mid])
				{
					markersObject[mid].closeInfoWindow();
					markersObject[mid].hide();
				}
			});
		}
	}
	else
	{
		// load/show markers
		hideAllStreets(checkbox.id);
		if (!categoryMarkers[streetId])
		{
//			$('categoryload').show();
			var url = encodeURI(idRoot + '/ajax/streetindex/get/' + streetname);
			new Ajax.Request(url, {
				method: 'get',
			  	onSuccess: function(transport){
					$('street'+index).style.fontWeight = 'bold';
					checkbox.checked = true;
			      	var markers = transport.responseText.evalJSON();
			      	markersArray = [];
			      	categoryMarkers[streetId] = [];
			      	for (i = 0; i < markers.length; i++)
			      	{
			      		categoryMarkers[streetId].push('s' + markers[i][0]);
			      		var marker = createMarker('s' + markers[i][0],
			      			new GLatLng(markers[i][1], markers[i][2]),
			      			'default', markers[i][3]);
			      	}
			      	markerManager.addMarkers(markersArray, 0);
        			markerManager.refresh();
//        			$('categoryload').hide();
        			
        			refreshViewport(markersArray);
			    }
			});
		}
		else
		{
			$('street'+index).style.fontWeight = 'bold';
			if (categoryMarkers[streetId])
			{
				var markers = new Array();
				categoryMarkers[streetId].each(function(mid){
					if(markersObject[mid])
					{
						markersObject[mid].show();
						markers.push(markersObject[mid]);
					}
				});
				refreshViewport(markers);
			}
		}
	}
}

function hideAllStreets(exception)
{
	var checkboxes = $$('.streetindexList input');
	checkboxes.each(function(checkbox)
	{
		if(checkbox.checked && checkbox.id != exception)
		{
			checkbox.click();
		}
	});
}

var currentCategory = null;
function toggleCategory(checkbox, category, img, imgShadow, root)
{
	var categoryResultDiv = $('categoryresult');
	
	if (!(checkbox.checked))
	{
		// remove markers
		if (categoryMarkers[category])
		{
			categoryMarkers[category].each(function(mid){
				if(markersObject[mid])
				{
					markersObject[mid].closeInfoWindow();
					markersObject[mid].hide();
				}
			});
			if (category == currentCategory)
			{
				categoryResultDiv.update('');
				currentCategory = null;
			}
		}
	}
	else
	{
		categoryResultDiv.update('');
		currentCategory = null;
		// load/show markers
		if (!customIcons[category])
		{
			$('categoryload').show();
			addCustomIcon(category, img, imgShadow,
			new GSize(32, 37), new GSize(32, 37), new GPoint(12, 36), new GPoint(15, 4),
			new Array(11,36, 0,15, 0,6, 7,0, 17,0, 24,7, 24,15));
			var url = root + '/ajax/category/get/' + category;
			new Ajax.Request(url, {
				method: 'get',
			  	onSuccess: function(transport){
			      	var markers = transport.responseText.evalJSON();
			      	markersArray = [];
			      	categoryMarkers[category] = [];
			      	var resultHtml = '<dl class="result_list">';
			      	for (i = 0; i < markers.length; i++)
			      	{
			      		categoryMarkers[category].push('c' + markers[i][0]);
			      		var marker = createMarker('c' + markers[i][0],
			      			new GLatLng(markers[i][1], markers[i][2]),
			      			category, markers[i][3], category);
			      		marker.resultHtml = '<dt><a href="javascript:highlightMarker(\'' + 'c' + markers[i][0] + '\')">' + markers[i][4] + '</a></dt><dd><span class="address">' + markers[i][5] + '</span></dd>';
			      		resultHtml = resultHtml + marker.resultHtml;
			      	}
			      	markerManager.addMarkers(markersArray, 0);
        			markerManager.refresh();
        			$('categoryload').hide();
        			
        			refreshViewport(markersArray);
        			resultHtml = resultHtml + '</dl>';
        			categoryResultDiv.update(resultHtml);
        			currentCategory = category;
			    }
			});
		}
		else
		{
			if (categoryMarkers[category])
			{
				var markers = new Array();
				var resultHtml = '<dl class="result_list">';
				categoryMarkers[category].each(function(mid){
					if(markersObject[mid])
					{
						markersObject[mid].show();
						markers.push(markersObject[mid]);
						resultHtml = resultHtml + markersObject[mid].resultHtml;
					}
				});
				refreshViewport(markers);
				resultHtml = resultHtml + '</dl>';
       			categoryResultDiv.update(resultHtml);
       			currentCategory = category;
			}
		}
	}
}

function toggleSubCategory(id)
{
	var subCategories = $('subcat' + id); 
	if (subCategories)
	{
		if (subCategories.visible())
		{
			Effect.BlindUp('subcat' + id, { duration: 0.15 });
		}
		else
		{
			Effect.BlindDown('subcat' + id, { duration: 0.15 });
		}
	}
}

function hideAllCategories()
{
	var checkboxes = $$('#categorytable input');
	checkboxes.each(function(checkbox)
	{
		if(checkbox.checked)
		{
			checkbox.click();
		}
	});
}

function advSearchHook(visible)
{
	// disblae all input fields within the advanced search section
	var inputs = $$('#address_search input');
	inputs.each(function(input)
	{
		if (visible) input.enable();
		else input.disable();
	});
}

// global routes object
var routesArray = [];

// custom polyline object
function Route(id, name, weight) {
	this.id = id;
	this.name = name;
	this.markers = new Array();
	this.polyline = null;
	this.selected = false;
	this.addedToMap = false;
	this.visible = false;
	this.weight = weight;
}
Route.prototype.highlight = function(show)
{
	if (this.polyline)
	{
		var opacity = 0.7;
		if (show)
		{
			opacity = 1;
		}
		this.polyline.setStrokeStyle({opacity: opacity});
	}
}
Route.prototype.select = function(select)
{
	if (select && !(this.visible)) this.show();
	this.highlight(select);
	
	if (select && !(this.selected))
	{
		var bounds = this.polyline.getBounds();
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
		this.showMarkers(true);
	}
	else if (!select && this.selected)
	{
		this.hideMarkers();
	}
	
	this.selected = select;
}
Route.prototype.setPolyline = function(polyline)
{
	this.polyline = polyline;
	var route = this;
	if (media == 'screen')
	{
		GEvent.addListener(this.polyline, "click", function() {
	  		selectRoute(route.id);
		});
		GEvent.addListener(this.polyline, "mouseover", function() {
			map.getDragObject().setDraggableCursor("pointer"); 
	  		if (!(route.selected)) route.highlight(true);
		});
		GEvent.addListener(this.polyline, "mouseout", function() {
	  		if (!(route.selected)) route.highlight(false);
	  		map.getDragObject().setDraggableCursor("url(http://maps.google.com/intl/en_us/mapfiles/openhand.cur),default"); 
		});
	}
}
Route.prototype.addToMap = function()
{
	map.addOverlay(this.polyline);
	this.addedToMap = true;
}
Route.prototype.show = function()
{
	if (!this.addedToMap) this.addToMap();
	this.polyline.show();
	this.visible = true;
	routesVisible = true;
}
Route.prototype.hide = function()
{
	if (this.addedToMap)
	{
		this.select(false);
		this.polyline.hide();
		this.visible = false;
	}
}
Route.prototype.showMarkers = function(showInfo)
{
	if (this.markers.length == 0)
	{
		this.loadMarkers(showInfo);
		return;	// load markers will  be called by loadMarkers again
	}
	else
	{
		for (var i = 0; i < this.markers.length; i++)
		{
			this.markers[i].show();
		}
		//if (showInfo) highlightMarker(this.markers[0].customId, true);
		if (media == 'screen' && $('routeelements_' + this.id).visible() == false) Effect.BlindDown('routeelements_' + this.id, { duration: 0.2 });
	}
}
Route.prototype.hideMarkers = function()
{
	for (var i = 0; i < this.markers.length; i++)
	{
		this.markers[i].closeInfoWindow();
		this.markers[i].hide();
	}
	if (media == 'screen') Effect.BlindUp('routeelements_' + this.id, { duration: 0.2 });
}
Route.prototype.loadMarkers = function(showInfo)
{
	var url = idRoot + '/ajax/route/get/' + this.id;
	var route = this;
	new Ajax.Request(url, {
		method: 'get',
	  	onSuccess: function(transport){
	  		var marker;
			var html = '';
	      	var markers = transport.responseText.evalJSON();
	      	markersArray = [];
	      	if (markers.length > 0)
	      	{
		      	for (i = 0; i < markers.length; i++)
		      	{
		      		marker = createMarker(markers[i][0],
		      			new GLatLng(markers[i][1], markers[i][2]),
		      			'default', markers[i][3]);
		      		route.markers.push(marker);
		      		html += '<a href="javascript:highlightMarker(' + markers[i][0] + ', true)">' + markers[i][4] + '</a><br />';
		      	}
		      	if (media == 'screen') $('routeelements_' + route.id).update(html);
		      	markerManager.addMarkers(markersArray, 0);
	      		markerManager.refresh();
	      		route.showMarkers(showInfo);
	      	}
	    }
	});
}
function selectRoute(id)
{
	for (var i = 0; i < routesArray.length; i++)
	{
		var route = routesArray[i];
		if (id == route.id)
		{
			route.select(true);
		}
		else if (route.visible)
		{
			route.select(false);
		}
	}
}

function toggleRoute(checkbox, id)
{
	for (var i = 0; i < routesArray.length; i++)
	{
		var route = routesArray[i];
		if (id == route.id)
		{
			if (checkbox.checked)
			{
				route.select(true);
			}
			else
			{
				route.hide();
			}
		}
		else if (route.visible)
		{
			route.select(false);
		}
	}
}

function deselectAllRoutes()
{
	for (var i = 0; i < routesArray.length; i++)
	{
		routesArray[i].select(false);
	}
}

function addRoutesToMap()
{
	for (var i = 0; i < routesArray.length; i++)
	{
		routesArray[i].show();
	}
}

var routesVisible = false;
function toggleRoutes()
{
	var hide = routesVisible;
	for (var i = 0; i < routesArray.length; i++)
	{
		var route = routesArray[i];
		if(hide)
		{
			route.hide();
		}
		else
		{
			route.show();
		}
	}
	routesVisible = !hide;
}

function setupTopLink()
{
	// top link in street index
	if ($('streetindex_toplink'))
	{
		var toplink = $('streetindex_toplink');
		var streetindex = $(toplink.parentNode);
		toplink.style.top = (streetindex.getHeight() - 25) + 'px';
		var savedEffect = null;
		Event.observe(streetindex, 'scroll', function(event)
		{
			var newtop = (this.getHeight() + this.scrollTop - 25);
			if (savedEffect)
			{
				savedEffect.cancel();
			}
			savedEffect = new Effect.Move('streetindex_toplink', {
				x: 0,
				y: newtop,
				mode: 'absolute',
				duration: 1.0,
				transition: Effect.Transitions.sinoidal
			});
		});
	}
}
