/**
 * map functions
 *
 * @copyright  2007 Wirtschaftskammer Baselland
 * @version    0.1
 * @link       http://www.kmu.org
*/

String.prototype.normalize = function() {
	var lower = this.toLowerCase();
	return lower.replace(/[^a-z0-9]/g,' ').replace(/ +/g, '_').replace(/^_/,'').replace(/_$/,'');
}

google.load('maps','2.x');
var map = {
    direction:null,
    contextMenu:null,
    markers:null,
    fromAddress:null,
    wheelzooming:true,
    construct:function() {
		//InfoWindow.prototype = Object.extend(new GOverlay(),InfoWindow.prototype);

        map.gmap = new GMap2(document.getElementById('map'),{logoPassive:true});
        map.gmap.addControl(new GLargeMapControl());
        map.gmap.enableContinuousZoom();
        map.gmap.enableScrollWheelZoom();

        var lat = 47.533838;
        var lng = 7.721673;
        var zoom = 13;
        
		var query = location.search.substring(1);
		var anchorPos = query.indexOf('#');
		if(anchorPos > -1) {
			query = query.substring(0,anchorPos);
		}
		var pairs = query.split("&");
		for (var i=0; i<pairs.length; i++) {
			var pos = pairs[i].indexOf("=");
			var argname = pairs[i].substring(0,pos).toLowerCase();
			var value = pairs[i].substring(pos+1).toLowerCase();
			switch(argname) {
				case 'lat': lat = parseFloat(value);break;
				case 'lng': lng = parseFloat(value);break;
				case 'toom': zoom = parseFloat(value);break;
			}
		}
        map.gmap.setCenter(new GLatLng(lat,lng), zoom);
        map.direction = new direction({locale:'de_CH',getPolyline:true});
        map.contextMenu = new contextMenu();
        if(typeof pois != 'undefined') {
			map.pois = new placeSet();
			map.pois.addPlaces(pois);
			map.pois.showInMap();
        	var poinode = document.getElementById('pois');
        	if(poinode) {
				var div = document.createElement('div');
				div.innerHTML = '<br/>POINTS OF INTERESTS';
				poinode.appendChild(div);
				var ul = document.createElement('ul');
				for(var i=0;i<map.pois.allPlaces.length;i++) {
					var li = document.createElement('li');
					var div = document.createElement('div');
					div.className = 'link_bt';
					div.onclick = function() {
						var point = new GLatLng(this.getLatitude(),this.getLongitude());
						map.getMap().setCenter(point);
						this.showInfoWindow();
					}.bind(map.pois.allPlaces[i]);
					div.innerHTML = map.pois.allPlaces[i].getName();
					li.appendChild(div);
					ul.appendChild(li);
				}
				poinode.appendChild(ul);
			}
        } else {
        	map.pois = new placeSet();
        }
        if(typeof addressList != 'undefined') {
        	map.addresses = new placeSet();
            map.addresses.addPlaces(addressList);
        	map.addresses.showInMap();
        } else {
			map.addressList = new placeSet();
		}
        
        if(/from=(.*)/g.exec(query)) {
            var fromAddress = decodeURIComponent(RegExp.$1);
            map.getDirection().setStartAddress(true);
            var from = new place(fromAddress,function() {
            	map.getDirection().setStartAddress(this);
            });
        }
        if(/poi[=|\/]([^&|\.]*)/g.exec(query)) {
        	var found = false;
        	if(map.pois && map.pois.allPlaces.length) {
        		var norm = RegExp.$1;
        		for(var i=0; i<map.pois.allPlaces.length; i++) {
        			var normPlace = map.pois.allPlaces[i].name.normalize();
        			if(norm == normPlace) {
						 map.pois.allPlaces[i].panTo();
						 map.pois.allPlaces[i].showInfoWindow();
					}
        		}
        	}
            var immo = new place(decodeURIComponent(RegExp.$1),function() {
                map.getDirection().setStartAddress(immo.getName());
                immo.showInMap();
                immo.setCenter();
                immo.showInfoWindow();
            });
        } else if(typeof startAddress != 'undefined') {
        	var immo = new place(startAddress,function() {
				this.showInMap();
				this.setCenter();
				if(map.getDirection().hasStartAddress()) {
					map.getDirection().setEndAddress(this);
					window.setTimeout(function() {
						map.getDirection().calcDirection();
					},500);
				} else {
					map.getDirection().setStartAddress(this);
				}
				this.showInfoWindow();
        	});
        }
		searchControl.prototype = Object.extend(new GControl(false,true),searchControl.prototype);
		map.gmap.addControl(new searchControl());
    },
    showAddress:function(lat,lng) {
    	if(map.pois) {
			var l = map.pois.allPlaces.length;
			for(var i=0;i<l;i++) {
				var currPlace = map.pois.allPlaces[i];
				if(currPlace.getLatitude() == lat && currPlace.getLongitude() == lng) {
					currPlace.panTo();
					currPlace.showInfoWindow();
// 					window.setTimeout(
// 						function() {
// 							this.setCenter();
// 						}.bind(currPlace)
// 					,500);
				}
			}
		}
    },
    getMarkers:function() {
    	return map.markers;
    },
    getMap:function() {
    	return map.gmap;
    },
    getDirection:function() {
        return map.direction;
    },
    getContextMenu:function() {
        return map.contextMenu;
    },
    back:function() {
        GUnload();
        document.location.href = map.fromAddress;
    }	
};

var $A = Array.from = function(iterable) {
	if(!iterable) return [];
  	if(iterable.toArray) {
    	return iterable.toArray();
  	} else {
    	var results = [];
    	for( var i = 0, length = iterable.length; i < length; i++ ) results.push( iterable[ i ] );
    	return results;
	}
}

Function.prototype.bind = function() {
	var __method = this, args = $A(arguments), object = args.shift();
  	return function() {
    		return __method.apply( object, args.concat( $A( arguments ) ) );
  		}
}

Object.extend = function(dest,source) {
  for(var property in source) {
    dest[property] = source[property];
  }
  return dest;
}

var setclass = {
  	create: function() {
    	return function() {
    		if(typeof this.construct == 'function') {
				this.construct.apply(this, arguments);
			}
    	}
  	}
}
var searchControl = setclass.create();
searchControl.prototype = {
	searchInput:null,
	okInput:null,
	searchResult:null,
	defaultSearchValue:'ihre Adresse',
	initialize:function(map) {
		var container = document.createElement('div');
		this.searchInput = document.createElement('input');
		this.searchInput.type = 'text';
		this.searchInput.value = this.defaultSearchValue;
		this.searchInput.onkeyup = this.keyup.bind(this);
		this.searchInput.onfocus = function(event) {
			if(this.searchInput.value == this.defaultSearchValue) {
				this.searchInput.value = '';
			}
		}.bind(this);
		this.searchInput.onblur = function(event) {
			if(!this.searchInput.value) {
				this.searchInput.value = this.defaultSearchValue;
			}
		}.bind(this);
		this.okInput = document.createElement('input');
		this.okInput.type = 'button';
		this.okInput.value = 'suchen';
		this.okInput.onclick = this.search.bind(this);
		this.searchResult = document.createElement('div');
		this.searchResult.style.position = 'absolute';
		this.searchResult.style.overflow = 'auto';
		this.searchResult.style.backgroundColor = '#fff';
		this.searchResult.style.border = '1px solid #000';
		container.appendChild(this.searchInput);
		container.appendChild(this.okInput);
		container.appendChild(this.searchResult);
		map.getContainer().appendChild(container);
		this.searchResult.style.width = '190px';
		this.hideSearchResult();
		return container;
	},
	hideSearchResult:function() {
		this.searchResult.style.display = 'none';
	},
	showSearchResult:function() {
		this.searchResult.style.display = '';
		
	},
	keyup:function(event) {
		switch(event.keyCode) {
			case 13: this.search(event); break;
		}
	},
	search:function(event) {
		if(this.searchInput.value && this.searchInput.value != this.defaultSearchValue) {
			this.searchInput.disabled = 'disabled';
			var geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode('.ch');
			geocoder.getLocations(this.searchInput.value,this.geocoderResponse.bind(this));
		}
	},
	geocoderResponse:function(response) {
		this.searchInput.disabled = false;
		while(this.searchResult.hasChildNodes()) {
			this.searchResult.removeChild(this.searchResult.firstChild);
		}
		if(response && response.Status.code == G_GEO_SUCCESS) {
			if(response.Placemark.length > 1) {
				for(var i=0;i<response.Placemark.length;i++) {
					this.createSearchResultEntry(response.Placemark[i]);
				}
				this.showSearchResult();
			} else {
				if(typeof this.placeAddress == 'object') {
					this.placeAddress.remove();
				}
				this.placeAddress = new place({
					name:response.Placemark[0].address,
					latitude:response.Placemark[0].Point.coordinates[1],
					longitude:response.Placemark[0].Point.coordinates[0]});
				this.placeAddress.setCenter();
				this.placeAddress.showInMap();
				this.placeAddress.showInfoWindow();
			}
		}
	},
	createSearchResultEntry:function(placemark) {
		var row = document.createElement('div');
		row.innerHTML = placemark.address;
		row.className = 'link_bt';
		row.onclick = function(control) {
			control.hideSearchResult();
			if(typeof control.placeAddress == 'object') {
				control.placeAddress.remove();
			}
			control.placeAddress = new place({
				name:this.address,
				latitude:this.Point.coordinates[1],
				longitude:this.Point.coordinates[0]});
			control.placeAddress.setCenter();
			control.placeAddress.showInMap();
			control.placeAddress.showInfoWindow();
		}.bind(placemark,this);
		this.searchResult.appendChild(row);
	},	
	getDefaultPosition:function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
	}
}
var contextMenu = setclass.create();
contextMenu.prototype = {
	element:null,
	mapContainer:null,
    construct:function() {
    	this.mapContainer = map.getMap().getContainer();
    	GEvent.bind(map.getMap(),'singlerightclick',this,this.openContextMenu);
    },
    createContextMenu:function() {
    	this.element = document.createElement('div');
    	this.element.style.background = '#fff';
    	this.element.style.border = '1px solid #8888FF';
    	this.mapContainer.appendChild(this.element);
	},    	
    openContextMenu:function(pixel,tile) {
    	var x = pixel.x;
    	var y = pixel.y;
    	if (x > map.getMap().getSize().width - 120) { x = map.getMap().getSize().width - 120 }
    	if (y > map.getMap().getSize().height - 100) { y = map.getMap().getSize().height - 100 }	
    	this.closeContextMenu();
    	map.getMap().closeInfoWindow();
    	this.createContextMenu();
    	this.addCenterQuestion(pixel);
    	this.addAddressQuestion(pixel);
    	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
    	pos.apply(this.element);
    	GEvent.bind(map.getMap(),'click',this,this.closeContextMenu);
	},
	addItem:function(innerHTML) {
		var div = document.createElement('div');
		div.innerHTML = '&nbsp;&nbsp;'+innerHTML+'&nbsp;&nbsp;';
		div.style.cursor = 'pointer';
		div.style.color = '#4444ff';
		div.style.fontSize = 'small';
		div.style.textDecoration = 'none';
		div.onmouseover = function(event) {
			event = event ? event : window.event;
			var target = event.target ? event.target : event.srcElement;
			target.style.background = '#eee';
		};
		div.onmouseout = function(event) {
			event = event ? event : window.event;
			var target = event.target ? event.target : event.srcElement;
			target.style.background = '#fff';
		};
		return div;
	},
	addCenterQuestion:function(pixel) {
		var div = this.addItem('hierher zentrieren');
		div.onclick = function(pixel) {
			this.closeContextMenu();
			var point = map.getMap().fromContainerPixelToLatLng(pixel);
			map.getMap().setCenter(point);
		}.bind(this,pixel);
		this.element.appendChild(div);
	},
	addAddressQuestion:function(pixel) {
		var direction = map.getDirection();
		if(direction.getStartAddress()) {
			var div = this.addItem('Route hierher berechnen');
			div.onclick = function(pixel) {
				this.closeContextMenu();
				var point = map.getMap().fromContainerPixelToLatLng(pixel);
				var direction = map.getDirection();
				direction.setOption('hideMarker',false);
				direction.setEndAddress(point.lat() + ',' + point.lng());
				direction.calcDirection(function(direction) {
					var marker = direction.getMarker(1);
					marker.openInfoWindowHtml(direction.getGeocode(1).address);
				}.bind(this));
			}.bind(this,pixel);
			this.element.appendChild(div);
		} else {
			var div = this.addItem('als Startaddresse festlegen');
			div.onclick = function(pixel) {
				this.closeContextMenu();
				var point = map.getMap().fromContainerPixelToLatLng(pixel);
				var direction = map.getDirection();
				direction.setStartAddress(point.lat() + ',' + point.lng());
			}.bind(this,pixel);
			this.element.appendChild(div);
		}			
	},
	closeContextMenu:function() {
		if(this.element && this.element.parentNode) {
			this.element.parentNode.removeChild(this.element);
		}
	}
}


var direction = setclass.create();
direction.prototype = {
    startAddress:null,
    endAddress:null,
    gdir:null,
    options:{},
    wayPointIcon:{},
    construct:function(options) {
    	if(options) {
    		this.options = options;
    	}
    	this.setWayPointIcon();
        this.gdir = new GDirections(map.getMap());
    },
    setOption:function(name,value) {
    	this.options[name] = value;
    },
    getOption:function(name) {
    	var result = null;
    	if(typeof this.options[name] != 'undefined') {
    		result = this.options[name];
    	}
    	return result;
    },
    getOptions:function() {
    	return this.options;
    },
    setStartAddress:function(address) {
        this.startAddress = address;
    },
    getStartAddress:function() {
        return this.startAddress;
    },
    hasStartAddress:function() {
    	var result = null;
    	if(this.startAddress) {
    		result = true;
    	}
    	return result;
    },
    setEndAddress:function(address) {
        this.endAddress = address;
    },
    getEndAddress:function() {
        return this.endAddress;
    },
    calcDirection:function(callback) {
    	if(this.getOption('addStepMarker')) {
    		GEvent.bind(this.gdir,'addoverlay',this,this.addStepMarker);
    	}
    	if(callback) {
    		GEvent.bind(this.gdir,'addoverlay',this,callback);
    	}
    	if(this.getOption('hideMarker')) {
    		GEvent.bind(this.gdir,'addoverlay',this,this.hideMarker);
    	}
    		
    	if(typeof this.startAddress == 'object') {
    		var startAddress = this.startAddress.getLatitude() + ',' + this.startAddress.getLongitude();
    	} else {
    		var startAddress = this.startAddress;
    	}

    	if(typeof this.endAddress == 'object') {
    		var endAddress = this.endAddress.getLatitude() + ',' + this.endAddress.getLongitude();
    	} else {
    		var endAddress = this.endAddress;
    	}
    	
        this.gdir.load('from:'+startAddress+' to:' + endAddress,this.getOptions());
    },
    hideMarker:function(direction) {
    	if(direction) {
    		var numRoute = direction.getNumRoutes();
    		for(var i=0;i<numRoute+1;i++) {
    			direction.getMarker(i).hide();
    		}
    	}
    },
    addStepMarker:function(direction) {
    	if(direction) {
    		var numRoute = direction.getNumRoutes();
    		for(var i=0;i<numRoute;i++) {
    			var currRoute = direction.getRoute(i);
    			var numSteps = currRoute.getNumSteps();
    			for(var s=0;s<numSteps;s++) {
    				var currStep = currRoute.getStep(s);
    				currStep.waypoint = new GMarker(currStep.getLatLng(),{icon:map.getDirection().getWayPointIcon()});
    				currStep.showWayPoint = function() {
						map.getMap().addOverlay(this.waypoint);
    				}.bind(currStep);
    				currStep.hideWayPoint = function() {
						map.getMap().removeOverlay(this.waypoint);
    				}.bind(currStep);
    			}
    		}
    	}
    },
    setWayPointIcon:function() {
		this.icon = new GIcon();
		this.icon.image = iconBaseUrl + 'waypoint.gif';
		this.icon.iconSize = new GSize(16,16);
		this.icon.iconAnchor = new GPoint(8,16);
		this.icon.infoWindowAnchor = new GPoint(9,2);
	},    
    getWayPointIcon:function() {
    	return this.icon;
    },
    getMarker:function(i) {
    	return this.gdir.getMarker(i);
    },
    getDuration:function() {
        return this.gdir.getDuration();
    },
    getGeocode:function(i) {
    	return this.gdir.getGeocode(i);
    },
    getDistance:function() {
        return this.gdir.getDistance();
    }
}

var placeSet = setclass.create();
placeSet.prototype = {
	construct:function(places) {
		this.allPlaces = [];
		if(places) {
			this.addPlaces(places);
		}
	},
	addPlaces:function(places) {
		if(!places) return;
		for(var i=0;i<places.length;i++) {
			this.allPlaces.push(new place(places[i]));
		}
	},
	getPlaces:function() {
		return this.allPlaces;
	},
	addPlace:function(place) {
		this.allPlaces.push(place);
	},
	showInMap:function() {
		for(var i=0;i<this.allPlaces.length;i++) {
			this.allPlaces[i].showInMap.apply(this.allPlaces[i]);
		}
	}
}

var place = setclass.create();
place.prototype = Object.extend(
    {},
    {
        extraContent:[],
        marker:null,
        name:null,
        innerHTML:null,
        longitude:null,
        latitude:null,
        point:null,
        icon:null,
        callback:null,
        address:null,
        id:null,
        construct:function(place,callback) {
            this.extraContent=[];
            if(typeof place == 'object') {
            	if(typeof place.id != 'undefined') { this.setID(place.id); }
                if(typeof place.name != 'undefined') { this.setName(place.name);}
                if(typeof place.latitude != 'undefined') { this.setLatitude(place.latitude); }
                if(typeof place.longitude != 'undefined') { this.setLongitude(place.longitude); }
                if(typeof place.icon != 'undefined') { this.setIcon(place.icon); }
                if(typeof place.extra != 'undefined') { this.addExtraContent(place.extra); }
                if(typeof place.address != 'undefined') { this.setAddress(place.address); }
                this.createMarker();
                if(callback) {
                	callback.apply(this);
                }
            } else if(typeof place == 'string') {
                this.geocode(place,callback);
            }
        },
        geocode:function(address,callback) {
        	this.callback = callback
            var geocoder = new GClientGeocoder();
            geocoder.getLocations(address,function(response) {
				if(response && response.Status.code == 200) {
					this.setLatitude(response.Placemark[0].Point.coordinates[1]);
					this.setLongitude(response.Placemark[0].Point.coordinates[0]);
					this.setName(response.Placemark[0].address);
					this.createMarker();
					if(this.callback) {
						this.callback.apply(this);
						this.callback = null;
					}
				} else {
					alert(address + ' not found');
				}
			}.bind(this));
		},
		setID:function(id) {
			this.id = id;
		},
		getID:function() {
			return this.id;
		},
		setAddress:function(address) {
			this.address = address;
		},
		getAddress:function() {
			return this.address;
		},
        setInnerHTML:function(html) {
            this.innerHTML = html;
        },
        getInnerHTML:function() {
            return this.innerHTML;
        },
        setName:function(name) {
            this.name = name;
        },
        getName:function() {
            return this.name;
        },
        setLatitude:function(lat) {
            this.latitude = lat;
        },
        getLatitude:function() {
            return this.latitude;
        },
        setLongitude:function(lng) {
            this.longitude = lng;
        },
        getLongitude:function() {
            return this.longitude;
        },
        setIcon:function(iconImage) {
            this.icon = new GIcon();
            this.icon.image = iconBaseUrl + iconImage;
            this.icon.iconSize = new GSize(16,16);
            this.icon.iconAnchor = new GPoint(8,16);
            this.icon.infoWindowAnchor = new GPoint(9,2);
        },
        getIcon:function() {
            return this.icon;
        },
        getPoint:function() {
            return new GLatLng(this.getLatitude(),this.getLongitude());
        },
        getMarkerOptions:function() {
            var options = {};
            icon = this.getIcon();
            if(icon) {
                options.icon = icon;
            }
            return options;
        },
        createMarker:function() {
            var point = this.getPoint();
            if(point) {
            	//this.marker = new InfoWindow(point,this.getMarkerOptions())
                this.marker = new GMarker(point,this.getMarkerOptions());
            }
        },
        getMarker:function() {
        	return this.marker;
        },
        showInMap:function() {
            if(this.marker) {
                this.addMarkerListener('click');
                map.getMap().addOverlay(this.marker);
            }
        },
        remove:function() {
        	if(this.marker) {
        		map.getMap().removeOverlay(this.marker);
        	}
        },
        panTo:function() {
			map.getMap().panTo(this.getPoint());
		},
        setCenter:function() {
            map.getMap().setCenter(this.getPoint())
        },
        getRouteQuestion:function() {
        	var direction = map.getDirection();
        	if(direction.hasStartAddress()) {
        		var startAddress = direction.getStartAddress();
        		var endAddress = direction.getEndAddress();
        		if(startAddress == this) {
        			var span = document.createElement('span');
        			span.innerHTML = 'dies ist ihre Startaddresse';
        			return span;
        		} else if(endAddress == this) {
        			var span = document.createElement('span');
        			span.innerHTML = 'dies ist ihre Endadresse';
        			return span;
        		} else {
        			var cont = document.createElement('div');
					var div = document.createElement('div');
					if(typeof startAddress == 'object' && startAddress.getAddress()) {
						div.innerHTML = 'Route von ' + startAddress.getAddress() + ' berechnen';
					} else {
						div.innerHTML = 'Route hierher berechnen';
					}
					div.className = 'link_bt';
					div.onclick = function() {
						var direction = map.getDirection();
						direction.setOption('hideMarker',true);
						direction.setOption('getSteps',true);
						direction.setOption('addStepMarker',true);
						direction.setEndAddress(this);
						direction.calcDirection(function(direction) {
							var content = document.createElement('div');
							var dis = document.createElement('div');
								dis.innerHTML = 'Entfernung: ' + Math.round(direction.getDistance().meters / 1000) + ' Kilometer';
							var dur = document.createElement('div');
								dur.innerHTML = 'Zeit: ' + Math.round(direction.getDuration().seconds / 60) + ' Minuten';
							content.appendChild(dis);
							content.appendChild(dur);
							var currRoute = direction.getRoute(0);
							for(var i=0;i<currRoute.getNumSteps();i++) {
								var currStep = currRoute.getStep(i);
								var div = document.createElement('div');
								var meters = currStep.getDistance().meters;
								if(meters > 1000) {
									var meterDescription = ( Math.round(meters*100) / 100 / 1000) + ' km';
								} else if( meters > 10000) {
									var meterDescription = Math.round(meters / 1000) + ' km';
								} else {
									var meterDescription = meters + ' m';
								}
									
								div.innerHTML = (i + 1) + '. ' + currStep.getDescriptionHtml() + ' (' + meterDescription + ')';
								div.className = 'link_bt';
								div.onmouseover=function() {
									this.showWayPoint();
								}.bind(currStep);
								div.onmouseout=function() {
									this.hideWayPoint();
								}.bind(currStep);
								content.appendChild(div);
							}
								
							var currWindow = map.getMap().getInfoWindow();
							var currContent = currWindow.getContentContainers();
							currContent[1].style.overflow = 'auto';
							while(currContent[1].hasChildNodes()) {
								currContent[1].removeChild(currContent[1].firstChild);
							}
							currContent[1].appendChild(content);
							currWindow.show();
							//var currTab = currMarker.getSelectedTab();
							//var currTabs = currMarker.getTabs();
							//currTabs[currTab] = new GInfoWindowTab('Route',content);
							//currMarker.show();
							//this.marker.openInfoWindowTabs(currTabs,{selectedTab:currTab});
						}.bind(this));
					}.bind(this);
					cont.appendChild(div);
					cont.appendChild(this.setStartAddress());
					return cont;
				}
			} else {
				return this.setStartAddress();
			}
			return false;
		},
        setStartAddress:function() {
			var span = document.createElement('span');
			span.innerHTML = 'als Startadresse festlegen';
			span.className = 'link_bt';
			span.onclick = function(event) {
				event = event ? event : window.event;
				var target = event.target ? event.target : event.srcElement;
			
				var direction = map.getDirection();
				direction.setStartAddress(this);
				var span = document.createElement('span');
				span.innerHTML = 'als Startadress GESETZT';
				target.parentNode.replaceChild(span,target);
				this.marker
			}.bind(this);
			return span;
		},        
        getDescription:function() {
        	var div = document.createElement('div');
			var description = document.createElement('div');
				var text = this.getInnerHTML();
				if(!text) {
					text = this.getName();
				}
				var address = this.getAddress();
				if(address) {
					text = text + '<br />' + address;
				}
			description.innerHTML = '<b>' + text.replace(/,/g,'<br/>') + '</b>';
			div.appendChild(description);
			var id = this.getID();
			if(id) {
				var link = document.createElement('div');
				link.className = 'link_bt';
				link.innerHTML = 'zum Angebot';
				link.onclick = function(event) {
					event = event ? event : window.event;
					var target = event.target ? event.target : event.srcElement;
					document.location.href = baseUrl + '/offer/view/'+id;
					target.innerHTML = 'Angebot wird geladen ...';
				}.bind(this);
				div.appendChild(link);
			}
			return div;
		},        
        getContent:function() {
        	var content = document.createElement('div');
				if(this.extraContent.length) {
					var div = document.createElement('div');
					for(var i=0;i<this.extraContent.length;i++) {
						if(typeof this.extraContent[i] == 'function') {
							var ctn = this.extraContent[i].apply(this);
						} else if(typeof this.extraContent[i] == 'object') {
							var ctn = this.extraContent[i];
						} else if(typeof this.extraContent[i] == 'string') {
							var ctn = document.createElement('div');
							ctn.innerHTML = this.extraContent[i];
						}
						if(ctn) {
							content.appendChild(ctn);
							var br = document.createElement('br');
							content.appendChild(br);
						}
					}
				}
			return content;
        },
        showInfoWindow:function() {
        	var tabs = [];
        	//tabs.push({title:'Angebot',content:this.getDescription()});
        	tabs.push(new GInfoWindowTab('Adresse',this.getDescription()));
        	var route = this.getRouteQuestion();
        	if(route) {
				tabs.push(new GInfoWindowTab('Route',route));
        		//tabs.push({title:'Route',content:route});
        	}
        	var currMarker = this.getMarker();
        	if(currMarker) {
        		currMarker.openInfoWindowTabs(tabs);
        	}
//         	this.marker.openInfoWindowTabs(tabs);
        },
        addMarkerListener:function(event) {
            GEvent.bind(this.marker,event,this,function() {
                this.showInfoWindow();
            });
        }
    }
);

var InfoWindowTab = setclass.create();
InfoWindowTab.prototype = Object.extend(
{
	header:{},
	body:{}
},
{
	construct:function(header,body) {
		this.header = document.createElement('span');
		this.header.innerHTML = header;
		this.header.style.cursor = 'pointer';
		this.body = body;
	},
	getHeader:function() {
		return this.header;
	},
	getBody:function() {
		return this.body;
	},
	show:function() {
		this.header.className = 'selected';
		this.body.style.display = '';
	},
	hide:function() {
		this.header.className = '';
		this.body.style.display = 'none';
	}
});

var InfoWindowTabs = setclass.create();
InfoWindowTabs.prototype = Object.extend(
{
	tabs:[],
	selectedTabIndex:null,
	infoWindow:null
},
{
	construct:function(tabs,infoWindow) {
		this.tabs = [];
		this.infoWindow = infoWindow;
		for(var i=0;i<tabs.length;i++) {
			var tab = new InfoWindowTab(tabs[i].name,tabs[i].contentElem);
			this.tabs.push(tab);
		}
	},
	create:function() {
		for(var i=0;i<this.tabs.length;i++) {
			this.tabs[i].getHeader().onclick = function(tabs) {
				tabs.selectTab(this);
			}.bind(this.tabs[i],this);
			this.infoWindow.getHeader().appendChild(this.tabs[i].getHeader());
			this.infoWindow.getBody().appendChild(this.tabs[i].getBody());
		}
	},	
	getSelectedTab:function() {
		return this.tabs[this.selectedTabIndex];
	},
	getSelectedTabIndex:function() {
		return this.selectedTabIndex;
	},
	selectTab:function(tab) {
		if(typeof tab == 'object') {
			for(var i=0;i<this.tabs.length;i++) {
				if(this.tabs[i] == tab) {
					this.selectedTabIndex = i;
					this.tabs[i].show();
				} else {
					this.tabs[i].hide();
				}
			}
		} else if(typeof tab == 'number') {
			for(var i=0;i<this.tabs.length;i++) {
				if(tab == i) {
					this.selectedTabIndex = i;
					this.tabs[i].show();
				} else {
					this.tabs[i].hide();
				}
			}
		}
	}
});
		
	

var InfoWindow = setclass.create();
InfoWindow.prototype = Object.extend(
{
	element:{},
	shadow:{},
	header:{},
	body:{},
	point:{},
	visible:null,
	marker:{},
	tabs:[]
},
{
	construct:function(point,markerOptions) {
		this.tabs = [];
		this.marker = new GMarker(point,markerOptions);
		this.point = point;
	},
	initialize:function(currMap) {
		this.marker.initialize(currMap);
		this.shadow = document.createElement('div');
		this.shadow.style.position = "absolute";
		this.shadow.style.backgroundColor = '#000';
		this.shadow.style.width = '300px';
		this.shadow.style.height = '100px';
		this.shadow.style.display = 'none';
		
		this.element = document.createElement('div');
		this.element.style.position = "absolute";
		this.element.style.backgroundColor = '#eee';
		this.element.style.width = '300px';
		this.element.style.height = '100px';
		this.element.style.display = 'none';
		
		this.header = document.createElement('div');
		this.header.style.backgroundColor = '#666699';
		this.header.style.color = '#fff';
		this.header.style.padding = '2px';
		this.header.style.fontWeight = 'bold';
		this.body = document.createElement("div");
		this.body.style.color = '#666699';
		this.body.style.padding = '2px';
		this.element.appendChild(this.header);
		this.element.appendChild(this.body);
		currMap.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(this.shadow);
		currMap.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(this.element);
	},
	getHeader:function() {
		return this.header;
	},
	getBody:function() {
		return this.body;
	},
	openInfoWindowTabs:function(tabs) {
		this.tabs = new InfoWindowTabs(tabs,this);
		this.tabs.create();
		this.show();
	},
	show:function() {
		this.element.style.display = '';
		this.shadow.style.display = '';
	},
	redraw:function() {
		this.marker.redraw();
		var p = map.getMap().fromLatLngToDivPixel(this.point);
		this.shadow.style.top = (p.y + 3)+ 'px';
		this.shadow.style.left = (p.x + 3) + 'px';
		this.element.style.top = p.y + 'px';
		this.element.style.left = p.x + 'px';
	},
	remove:function() {
		document.title += 'remove';
	},
	getMarker:function() {
		return this.marker;
	},
	getPoint:function() {
		return this.point;
	},
	getIcon:function() {
		return this.marker.getIcon();
	},
	getLatLng:function() {
		return this.marker.getLatLng();
	}
});
		
		
google.setOnLoadCallback(map.construct);

