var LB = {
	
	latitude: 50.399985,
	longitude: 7.3493,
	ew: {},
	
	OnMonthChanged: function(daySelectId, monthSelectId) {
        var daySelect = document.getElementById(daySelectId);
        var monthSelect = document.getElementById(monthSelectId);
        var selectedDate = monthSelect.options[monthSelect.selectedIndex].value;

        var parts = selectedDate.split(':');
        
        var daysInMonth = 32 - new Date(parts[0], parts[1] - 1, 32).getDate();

        if(daySelect.options.count != daysInMonth)
        {
            LB.RemoveDays(daySelect, daysInMonth);
            LB.AddDays(daySelect, daysInMonth);
        }
    },

    AddDays: function(list, days) {
        while(list.length < days) 
        {
            var option = document.createElement('option');
        
            option.text = list.length + 1;
            option.value = list.length + 1;

            try {
                // standards compliant; doesn't work in IE
                list.add(option, null); 
            }
            catch(ex) {
                // IE only
                list.add(option); 
            }
        }
    },

    RemoveDays: function(list, days) {
        while(list.length > days)
        {
            list.remove(list.length - 1);
        }
    },

	startpage_map: function(html) {
		
		// create container
		var startmapcontainer = document.createElement("div");
		startmapcontainer.setAttribute("id", "LB-startmapcontainer");
		var startmap = document.createElement("div");
		startmap.setAttribute("id", "LB-startmap");
		startmapcontainer.appendChild(startmap)
	
		// create great looking frame
		var span = [];
		for(var i=1; i<5; i++) {
			span[i] = document.createElement("span");
			span[i].className = "LB-goverlay"+i;
			startmapcontainer.appendChild(span[i]);
		}
		$("LB-container").appendChild(startmapcontainer);
	},

	createMarker: function(point, bublehtml, map, icon) {
		var marker = new GMarker(point, icon);
			    
	    GEvent.addListener(marker, "click", function() {

		    var dayoptions = null;
		    var cloned_dayoptions = null;

 		    var selects = bublehtml.getElementsByTagName("select");
		    if(selects != null && selects.length > 1)
		    {
			    dayoptions = selects[1].getElementsByTagName("option");			
		    }

            bublehtml = bublehtml.cloneNode(true);

		    var cloned_selects = bublehtml.getElementsByTagName("select");
		    if(cloned_selects != null && cloned_selects.length > 1)
		    {
			    dayoptions_cloned = cloned_selects[1].getElementsByTagName("option");			
		    }

            Element.show(bublehtml);
            var buble = document.createElement("div");
            buble.className = "LB-buble";
            buble.appendChild(bublehtml);

		    if(dayoptions != null && dayoptions_cloned != null)
		    {
	                for(var i; i<dayoptions.length; i++) {
      	              if(dayoptions[i].selected) 
            	            dayoptions_cloned[i].selected = true;
            	    }
		    }
	
			if(map.__style == E_STYLE_1) {

				var multiplier = 0;

				switch (map.getZoom()) {
					case 1:
						multiplier = 2560;
						break
					case 2:
						multiplier = 1280;
						break
					case 3:
						multiplier = 640;
						break
					case 4:
						multiplier = 320;
						break
					case 5:
						multiplier = 160;
						break
					case 6:
						multiplier = 80;
						break
					case 7:
						multiplier = 40;
						break
					case 8:
						multiplier = 20;
						break;
					case 9:
						multiplier = 10;
						break;
					case 10:
						multiplier = 5;
						break;
					case 11:
						multiplier = 2.5;
						break;
					case 12:
						multiplier = 1.5;
						break;
				}
				var close = document.createElement("img");
				close.className = "LB-close";
				close.src = "./graphics/eclose.gif";
				close.style.position = "absolute";
				close.style.top = "5px";
				close.style.right = "4px";
				buble.appendChild(close);
				map.__ew.openOnMarker(marker, buble.innerHTML);
				map.savePosition();
				
				map.panTo( 
				    new GLatLng( 
				        (point.lat() + 0.010 * multiplier), 
				        (point.lng() + 0.015 * multiplier) 
					) 
				);
			}
			else {
				marker.openInfoWindow(
					buble, 
					{ maxWidth: 215, maxHeight: 240 });

/*				map.openInfoWindow(
					new GLatLng( 
					    (point.lat() + 2.50), 
					    (point.lng() - 1) ), 
					buble, 
					{ maxWidth: 215, maxHeight: 240 });
*/
			}
		});
		
		return marker;
	},

	// create map
	map: function(args) {
		
		var address;
		
		if(args["latitude"] && args["longitude"]) {
		    LB.latitude = args["latitude"];
		    LB.longitude = args["longitude"];
		} else {
		    address = LB.getElementsByClassName(args["html"], "*", "vcard")[0];

		    LB.latitude = parseFloat(LB.getElementsByClassName(address, "span", "latitude")[0].innerHTML);
		    LB.longitude = parseFloat(LB.getElementsByClassName(address, "span", "longitude")[0].innerHTML);
    	}
		
		var map = new GMap2(args["mapDiv"]);
		
		map.__zoom = args["zoom"] ? args["zoom"] : 12;
		map.__style = args["style"]
		
		var point = new GLatLng(LB.latitude, LB.longitude);
		
		map.setCenter(point, map.__zoom);
		
		if(!args["nobuble"]) {
			map.__ew = new EWindow(map, args["style"])
			map.__centerpoint = point;
			map.__center = function() {
				map.panTo(point);
			}

			map.addOverlay(map.__ew);
	
            if(!args["dontCreateFirstMarker"]) {
				var icon = new GIcon(G_DEFAULT_ICON);
				if(map.__style == E_STYLE_1) {
					icon.infoWindowAnchor = new GPoint(10, 33);									
				}
				map.actual_location_marker = LB.createMarker(point, address, map, icon);
		        map.addOverlay(map.actual_location_marker);
			}
			
			GEvent.addListener(map, "click", function(marker,point) {
				if (point) {
					map.__ew.hide();
					map.returnToSavedPosition();
				}
			});			
		}
		
		//map.addOverlay(LB.createMarker(point, address, map));

		return map;
	},

	/* Taken from http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ */
	getElementsByClassName: function(oElm, strTagName, oClassNames){
	    if(oElm == null) 
	        return null;
	
		var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		var arrRegExpClassNames = new Array();
		if(typeof oClassNames == "object"){
			for(var i=0; i<oClassNames.length; i++){
				arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames[i].replace(/-/g, "\-") + "(\s|$)"));
			}
		}
		else{
			arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames.replace(/-/g, "\-") + "(\s|$)"));
		}
		var oElement;
		var bMatchesAll;
		for(var j=0; j<arrElements.length; j++){
			oElement = arrElements[j];
			bMatchesAll = true;
			for(var k=0; k<arrRegExpClassNames.length; k++){
				if(!arrRegExpClassNames[k].test(oElement.className)){
					bMatchesAll = false;
					break;
				}
			}
			if(bMatchesAll){
				arrReturnElements.push(oElement);
			}
		}
		return (arrReturnElements)
	},
	
	erlangeMap: function(html) {
		if(!document.getElementById("LB-erlangedMapOverlay")) {    		
			var body = document.getElementsByTagName("body")[0];
		
			var erlangedMapOverlay = document.createElement("div");
			erlangedMapOverlay.setAttribute("id", "LB-erlangedMapOverlay");
			erlangedMapOverlay.style.display = "none";
			erlangedMapOverlay.onclick = LB.closeZoom;
			body.appendChild(erlangedMapOverlay);

			var erlangedMapContainer = document.createElement("div");
			erlangedMapContainer.setAttribute("id", "LB-erlangedMapContainer");
			erlangedMapContainer.style.display = "none";
			body.appendChild(erlangedMapContainer);
		
			var erlangedMap = document.createElement("div");
			erlangedMap.setAttribute("id", "LB-erlangedmap");
			erlangedMapContainer.appendChild(erlangedMap);

			var zoomClose = document.createElement("p");
			zoomClose.className = "LB-zoom-close";
			erlangedMapContainer.appendChild(zoomClose);
			
			var close = document.createElement("a");
			var closeImage = document.createElement("img");
			closeImage.setAttribute("src", "./graphics/zoom.png");
			close.appendChild(closeImage);
			close.href = "javascript:LB.closeZoom()";
			close.appendChild(document.createTextNode("Close map"))
			zoomClose.appendChild(close);
		
			var map = LB.map({
				"html": html,
				"style": E_STYLE_1,
				"mapDiv": erlangedMap
			});
		}
		
		new Effect.Appear('LB-erlangedMapOverlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });
		Element.show('LB-erlangedMapContainer');
		
		if(!document.getElementById("LB-erlangedMapOverlay").map) {
			document.getElementById("LB-erlangedMapOverlay").map = map;
		}
		else {
			var map = document.getElementById("LB-erlangedMapOverlay").map;
		}
		
		map.checkResize();
		map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
		var point = new GLatLng(LB.latitude, LB.longitude);
		map.setCenter(point, 12);
		
		hideSelectBoxes();
	    hideFlash();
		
		return map;
	},
	
	addMarkers: function(args) {
	
		var addresses = LB.getElementsByClassName(args["html"], "*", "vcard");
		var icon = new GIcon(G_DEFAULT_ICON);
		
		if(args["colour"]) {
			icon.image = "./graphics/boat_blue.png";
			icon.shadow = "./graphics/boat_shadow.png";
			icon.iconSize = new GSize(12, 20);
			icon.shadowSize = new GSize(22, 20);
			icon.iconAnchor = new GPoint(6, 20);
			icon.infoWindowAnchor = new GPoint(5, 15);
		}
		
		if(addresses != null)
		{
		    for(var i=0; i<addresses.length; i++) {
			    (function() {
				    var map = args["map"];
				    var html = addresses[i];
				    var latitude = parseFloat(LB.getElementsByClassName(html, "span", "latitude")[0].innerHTML);
				    var longitude = parseFloat(LB.getElementsByClassName(html, "span", "longitude")[0].innerHTML);
				    var point = new GLatLng(latitude, longitude);
    				
				    if(html.tagName != "DIV") {
					    var h = document.createElement("div");
					    h.className = html.className;
					    h.innerHTML = html.innerHTML;
					    html = h;
				    }
				    var marker = LB.createMarker(point, html, map, icon);
				    map.addOverlay(marker);

				    var a = LB.getElementsByClassName(addresses[i], "a", "fn org");
				    if(a[0]) {
					    a[0].onclick = function() { GEvent.trigger(marker, "click"); }
				    }
    				
			    })()
		    }
		 }
	},
	
	zoomOut: function() {
		document.getElementById("LB-erlangedMapOverlay").map.zoomOut();
	},
	
	closeZoom: function() {
		Element.hide('LB-erlangedMapContainer');
		new Effect.Fade('LB-erlangedMapOverlay', { duration: overlayDuration});
		showSelectBoxes();
		showFlash();
	},
	
	showOnMap: function(html) {
		var sidebar = LB.map({
			html: html,
			style: E_STYLE_1,
			mapDiv: $("LB-map")
		});

		var tbodies = $('LB-restaurants').getElementsByTagName("tbody");
		for(var i=0; i<tbodies.length; i++) {
			if(tbodies[i] === html) {
				$("LB-restaurants").actual = i;
				break;
			}
		}
		
		var other_html = $('LB-restaurants').cloneNode(true);
		other_html.removeChild(other_html.getElementsByTagName("tbody")[$('LB-restaurants').actual]);
		LB.addMarkers({ map: sidebar, html: other_html, colour: "blue" });
		GEvent.trigger(sidebar.actual_location_marker, "click");
		
	},
	
	printPopup: function(title, width, height) {
		
		var html = $('LB-book');
		
		var printWindow = window.open("", "printpopup", "" );
		printWindow.document.open("text/html");
		printWindow.document.writeln("<html>");
		printWindow.document.writeln("<head>");
		printWindow.document.writeln(" <title>" + title + "</title>");
		printWindow.document.writeln(" <style type='text/css'>");
		printWindow.document.writeln("  body { margin: 10px; padding: 0; background: white; color: black; font-family: Georgia, Times, serif; }");
		printWindow.document.writeln("  #LB-printmap { width: " + width + "px; height: " + height + "px; }");
		printWindow.document.writeln("  .geo { display: none; }");
		printWindow.document.writeln(" ul, li { list-style-type: none; margin-left: 0; padding-left: 0; }");
		printWindow.document.writeln(" </style>");
		printWindow.document.writeln("<body>");
		printWindow.document.writeln(" <div>" + LB.getElementsByClassName(html, "*", "vcard")[0].innerHTML + "</div>");
		printWindow.document.writeln("</body>");
		printWindow.document.writeln("</html>");
	    printWindow.document.close();

		var erlangedMap = printWindow.document.createElement("div");
		erlangedMap.setAttribute("id", "LB-printmap");
		printWindow.document.getElementsByTagName("body")[0].appendChild(erlangedMap);
		
		var map = LB.map({
			"html": html,
			"style": E_STYLE_1,
			"mapDiv": erlangedMap,
			"nobuble": true,
			"zoom": 16
		});
		
		printWindow.focus();
		printWindow.print();
	},
	
	checkScroll: function(top) {
		var bodytop = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
		var hasClass = ($("LB-mainsidebar").className.search('(^|\\s)LB-fixed(\\s|$)') != -1);
		if(bodytop > top) {
			if(!hasClass) {
				$("LB-mainsidebar").className = " LB-fixed";
			}
		}
		else {
			if(hasClass) {
				$("LB-mainsidebar").className = $("LB-mainsidebar").className.replace(new RegExp('(^|\\s)LB-fixed(\\s|$)'), RegExp.$1+RegExp.$2);
			}
		}
	}
}


/* Taken from http://www.econym.demon.co.uk/googlemaps/ewindows.htm */

// Version 0.0  Initial version

function EStyle(stemImage, stemSize, boxClass, boxOffset) {
  this.stemImage = stemImage;
  this.stemSize = stemSize;
  this.boxClass = boxClass;
  this.boxOffset = boxOffset;
  //this.border = border;
  
  // Known fudge factors are:
  // Firefox (1.0.6 and 1.5)    5, -1
  // IE 6.0                     0, -1
  // Opera 8.54                 3, -1
  // Opera 9 prev               4, -1
  // Netscape (7.2, 8.0)        5, -1
  // Safari                     5, -1        
  
  var agent = navigator.userAgent.toLowerCase();
  
  var fudge = 5;  // assume Netscape if no match found
 
  if (agent.indexOf("opera") > -1) {
    fudge = 3;
  }   
  if (agent.indexOf("firefox") > -1) {
    fudge = 5;
  }   
  if (agent.indexOf("safari") > -1) {
    fudge = 5;
  }   
  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){
    fudge = 0;
  }
  this.fudge = fudge;
}

var E_STYLE_1 = new EStyle("./graphics/stem1.png", new GSize(82,61), "LB-boublecontainer", new GPoint(-33,58));
var E_STYLE_2 = new EStyle("./graphics/stem1.png", new GSize(0,0), "LB-boublecontainer2 LB-buble", new GPoint(0,0))

function EWindow(map,estyle) {
  // parameters
  this.map=map;
  this.estyle=estyle;
  // internal variables
  this.visible = false;
  // browser - specific variables
  this.ie = false;
  var agent = navigator.userAgent.toLowerCase();
  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}
} 

EWindow.prototype = new GOverlay();

EWindow.prototype.initialize = function(map) {
  var div1 = document.createElement("div");
  div1.style.position = "absolute";
  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div1);
  var div2 = document.createElement("div");
  div2.style.position = "absolute";
  div2.style.width = this.estyle.stemSize.width+"px";
  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div2);
  this.div1 = div1;
  this.div2 = div2;
}

EWindow.prototype.openOnMap = function(point, html, offset) {
  this.offset = offset||new GPoint(0,0);
  this.point = point;
  this.div1.innerHTML = '<div class="' + this.estyle.boxClass + '"><nobr>' + html + '</nobr></div>';
  if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
    var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
    this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
  } else {
    this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
  }
  var z = GOverlay.getZIndex(this.point.lat());
  this.div1.style.zIndex = z;
  this.div2.style.zIndex = z+1;
  this.visible = true;
  this.show();
  this.redraw(true);
}

EWindow.prototype.openOnMarker = function(marker,html,adjustment) {
  adjustment = adjustment||0;
  var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
  var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y - adjustment;
  this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
}


EWindow.prototype.redraw = function(force) {
  if (!this.visible) {return;}
  var p = this.map.fromLatLngToDivPixel(this.point);
  this.div2.style.left   = (p.x + this.offset.x) + "px";
  this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
  this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
  this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
}

EWindow.prototype.remove = function() {
  this.div1.parentNode.removeChild(this.div1);
  this.div2.parentNode.removeChild(this.div2);
  this.visible = false;
}

EWindow.prototype.copy = function() {
  return new EWindow(this.map, this.estyle);
}

EWindow.prototype.show = function() {
  this.div1.style.display="";
  this.div2.style.display="";
  this.visible = true;
}

EWindow.prototype.hide = function() {
  this.div1.style.display="none";
  this.div2.style.display="none";
  this.visible = false;
}


