var search_flag = false;
var geocoder;
var map;
var geoXmlcafes_clicked;
var geoXmlbeer_gardens_clicked;
var geoXmlrestaurants_clicked;
var geoXmlsupermarkets_clicked;
var geoXmlpubs_clicked;
var geoXmltheatres_clicked;
var geoXmlcinemas_clicked;
var geoXmlsightseeing_clicked;
var geoXmlgyms_clicked;
var geoXmlpharmacists_clicked;
var geoXmlclinics_clicked;
var geoXmlswimming_pools_clicked;
var geoXmlhairdressers_clicked;
var geoXmlchurches_clicked;
var geoXmlbutchers_clicked;
var geoXmlopticians_clicked;
var geoXmllibraries_clicked;
var geoXmlclothes_shops_clicked;
var geoXmlmuseums_clicked;
var geoXmlgalleries_clicked;
var geoXmldoctors_clicked;


var restaurant = "The Old Mohawk Restaurant";
var address = "Innere Wiener Str, Munich";
var nlocation;
var placemark_title = "";
// ====== Array for decoding the failure codes ======
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";


// Create the marker and corresponding information window
function createInfoMarker(point, content) 
{
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click",
						function() 
						{
							marker.openInfoWindowHtml(content);
						}
						);
	return marker;
}

function load() 
{
	if (GBrowserIsCompatible()) 
	{
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(48.13759,11.58042), 13);
		//map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
                var extLargeMapControl = new ExtLargeMapControl();
                map.addControl(extLargeMapControl);
		svOverlay = new GStreetviewOverlay();
		map.addOverlay(svOverlay);
                //map.addMapType(G_PHYSICAL_MAP) ;
                // Add selectable terrain map
                map.addMapType(G_PHYSICAL_MAP);
                map.addMapType(G_HYBRID_MAP);
                var hControl = new GHierarchicalMapTypeControl();
                hControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
                map.addControl(hControl);

                // Add the self created control
                map.addControl(new MoreControl());
			
		/* add marker desc here */
		/*
		var point = new GLatLng(48.140150, 11.564080);
		var marker = new GMarker(point);
		var bubble_content = "Test Point";
		var marker = createInfoMarker(point, bubble_content);
		map.addOverlay(marker);
		
		// Create new geocoding object
		geocoder = new GClientGeocoder();

		// Retrieve location information, pass it to addToMap()
		geocoder.getLocations(address, addToMap);
		*/

		var myPano = new GStreetviewPanorama(document.getElementById("street_view"));
		GEvent.addListener(myPano, "error", handleNoFlash);  
		GEvent.addListener(map,"click", function(overlay,latlng) {
							myPano.setLocationAndPOV(latlng);});
	}
	
	$new_location = getQueryVariable("location");
	if ($new_location)
	{
		map.clearOverlays();
		next_location($new_location);
	}
}

function handleNoFlash(errorCode)
{
	if (errorCode == 603) 
	{
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	}
}

function find_location()
{		
	if (document.getElementById("munich_search").checked)
	{
		var new_address = document.getElementById("search_address").value + ",munich";
			new_address = new_address.replace(/,munich,munich/,",munich");
		document.getElementById("search_address").value = new_address;
		address = new_address;
	}
	else
        {
		address = document.getElementById("search_address").value;
        }
		
	// Create new geocoding object
	geocoder = new GClientGeocoder();

	// Retrieve location information, pass it to addToMap()
	geocoder.getLocations(address, addToMap);
}

function find_location_from_history()
{		
        var select_address = document.getElementById("search_address");
	address = select_address.value;

        //alert ("address = " + address + "; placemark title = " + placemark_title);
		
	// Create new geocoding object
geocoder = new GClientGeocoder();

// Retrieve location information, pass it to addToMap()
geocoder.getLocations(address, addToMap);
}

function next_location(new_street)
{
	if (new_street.indexOf("Select previous search") != false)
	{
		document.getElementById("search_address").value = new_street;
		find_location();
	}
}

function next_location_from_history(new_street)
{
	if (new_street.indexOf("Select previous search") != false)
	{
		document.getElementById("search_address").value = new_street;
		find_location_from_history();
	}
}

function next_location_from_placemark(new_street)
{
	if (new_street.indexOf("Select placemark") != false)
	{
                
		document.getElementById("search_address").value = new_street;
                address_selected_index = document.getElementById("placemark_history").selectedIndex;
                placemark_title = document.getElementById("placemark_history").options[address_selected_index].text;
		find_location_from_history();
	}
}

function addToMap(result)
{
	if (result.Status.code == G_GEO_SUCCESS)
	{
		document.getElementById("street_view").innerHTML = "";
                search_flag = true;
		// How many resuts were found
		if (result.Placemark.length == 1)
			document.getElementById("result").innerHTML = "Found " +result.Placemark.length +" result";
		else
			document.getElementById("result").innerHTML = "Found " +result.Placemark.length +" results";
		
		for (var i=0; i<result.Placemark.length; i++)  // Loop through the results, placing markers
		{
			var p = result.Placemark[i].Point.coordinates;
			var marker = new GMarker(new GLatLng(p[1],p[0]));
			nlocation = result.Placemark[i].address;
			document.getElementById("result").innerHTML += "<br><a href=\"javascript:next_location_from_history('" + nlocation + "')\">" + (i+1)+ ": " + result.Placemark[i].address + " " + marker.getPoint() + "</a>";
			map.addOverlay(marker);
		}
		
		// centre the map on the first result
		var p = result.Placemark[0].Point.coordinates;
		map.setCenter(new GLatLng(p[1],p[0]),16);
		
		if (document.getElementById("munich_search_history_save").checked)
			save_history();
		
		// Retrieve the object
		//var place = response.Placemark[0];
					var place = result.Placemark[0];

		// Retrieve the latitude and longitude
		var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

		// Center the map on this point
		var address = result.Placemark[0].address;
		map.setCenter(point, 16);
		var marker = createInfoMarker(point, address);	

		// Create a marker
		//var marker = new GMarker(point);

		// Add the marker to map
		map.addOverlay(marker);

		// Add address information to marker
		//marker.openInfoWindowHtml(place.address);
                search_flag = true;
	}
	else 
	{
		var reason="Code "+result.Status.code;
		if (reasons[result.Status.code]) 
		{
			reason = reasons[result.Status.code]
		} 
		alert('Could not find "'+address+ '" ' + reason);
	}

}	

function getQueryVariable(variable) 
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) 
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable) 
		{
			var query_str = unescape(pair[1]);
			return query_str;
		}
	} 
	//alert('Query Variable ' + variable + ' not found');
}


// Create the marker and corresponding information window
function createInfoMarker(point, address) 
{
    var marker = new GMarker(point);

    if (placemark_title != "")
    {
        var address_form = "<input id=\"placemark_title_id\" onClick=\"this.value='';\" name=\"title of placemark\" value=\"Enter Placemark Title\" /><br /><br />" + placemark_title + "<br /><span id=\"placemark_address_id\">" + address + "</span><br /><input onClick=\"save_user_placemark()\" style=\"float: right;\" class=\"button\" type=\"submit\" value=\"Save Placemark\" /><br /><br /><br />";
    }
    else
    {
        var address_form = "<input id=\"placemark_title_id\" onClick=\"this.value='';\" name=\"title of placemark\" value=\"Enter Placemark Title\" /><br /><br /><span id=\"placemark_address_id\">" + address + "</span><br /><input onClick=\"save_user_placemark()\" style=\"float: right;\" class=\"button\" type=\"submit\" value=\"Save Placemark\" /><br /><br /><br />";
    }

    GEvent.addListener(marker, "click",
        function() {
            marker.openInfoWindowHtml(address_form);
        }
    );

    return marker;
}
	
    
/*
getLocations() returns an object to a callback which looks like this:

<kml>
 <Response>
    <name>821 Mohawk St, Columbus, OH</name>
    <Status>
       <code>200</code>
       <request>geocode</request>
    </Status>
    <Placemark>
       <address>821 Mohawk St, Columbus, OH 43206, USA</address>
       <AddressDetails>
          <Country>
             <CountryNameCode>US</CountryNameCode>
             <AdministrativeArea>
                <AdministrativeAreaName>OH</AdministrativeAreaName>
                <SubAdministrativeArea>
                   <SubAdministrativeAreaName>Franklin</SubAdministrativeAreaName>
                   <Locality>
                      <LocalityName>Columbus</LocalityName>
                      <Thoroughfare>
                         <ThoroughfareName>821 Mohawk St</ThoroughfareName>
                      </Thoroughfare>
                      <PostalCode>
                         <PostalCodeNumber>43206</PostalCodeNumber>
                      </PostalCode>
                   </Locality>
                </SubAdministrativeArea>
             </AdministrativeArea>
          </Country>
       </AddressDetails>
       <Point>
          <coordinates>-82.992942,39.945728,0</coordinates>
       </Point>
    </Placemark>
 </Response>
</kml>

var streetAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
var zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;

// Add address information to marker
marker.openInfoWindowHtml(restaurant + '<br />' + 
   streetAddress + '<br />' + 
   city + ', ' + state + ' ' + zip);
    
*/

/**************************** Large map control ***************************************/

/**
 * @name ExtLargeMapControl
 * @version 1.0
 * @author Masashi, Bjorn Brala
 * @fileoverview Creates a control with buttons to pan in four directions,
 * and zoom in and zoom out, and a zoom slider. The UI is based on the 
 * LargeMapControl from Google Maps (circa December 2008), but it does not
 * have any integration with Street View.
 */


/*global GKeyboardHandler, GDraggableObject*/

/**
 * @desc Creates an ExtLargeMapControl. No configuration options are available.
 *
 * @constructor
 */    
function ExtLargeMapControl() {
  this.sliderStep = 9;
  this.imgSrc = "http://maps.google.com/intl/en_ALL/mapfiles/mapcontrols3d.png";
}


/**
 * @private
 */
ExtLargeMapControl.prototype = new GControl();


/**
 * @private
 * @type GMap2
 */
ExtLargeMapControl.prototype._map = null;


/**
 * @private
 * @type Element
 */
ExtLargeMapControl.prototype._container = null;


/**
 * @private
 * @type Element
 */
ExtLargeMapControl.prototype._slider = null;


/**
 * @private
 * @type GKeyboardHandler 
 */
ExtLargeMapControl.prototype._keyboardhandler = null;


/**
 * @desc Initialize the map control
 * @private
 */
ExtLargeMapControl.prototype.initialize = function (map) {
  ExtLargeMapControl.prototype._map = map;

  var _handleList = {};
  
  this._keyboardhandler = new GKeyboardHandler(map);
  var agt = navigator.userAgent.toLowerCase();
  
  this._is_ie    = ((agt.indexOf("msie") !== -1) && (agt.indexOf("opera") === -1));
  this._is_gecko = (agt.indexOf('gecko') !== -1);
  this._is_opera = (agt.indexOf("opera") !== -1);

  //common image
  var commonImg = new Image();
  commonImg.src = this.imgSrc;

  // calculation of controller size
  var currentMapType = map.getCurrentMapType();
  var minZoom = parseInt(currentMapType.getMinimumResolution(), 10);
  var maxZoom = 0;
  var maptypes = map.getMapTypes();  
  for (var i = 0; i < maptypes.length; i++) {
    if (maptypes[i].getMaximumResolution() > maxZoom) {
      maxZoom = maptypes[i].getMaximumResolution();
    }
  }
  ExtLargeMapControl.prototype._maxZoom = parseInt(maxZoom, 10);
  ExtLargeMapControl.prototype._step = this.sliderStep;
  var ctrlHeight = (86 + 5) + (maxZoom - minZoom + 1) * this.sliderStep + 5;

  // create container
  var container = document.createElement("div");
  container.style.width = "59px";
  container.style.height = (ctrlHeight + this.sliderStep + 2) + "px";
  container.style.overflow = "hidden";
  container.style.padding = "0";
  container.style.MozUserSelect = "none";
  container.style.textAlign = "left";
  _handleList.container = container;
  ExtLargeMapControl.prototype._container = container;

  //image load
  var imgContainer = document.createElement("div");
  imgContainer.style.width = "59px";
  imgContainer.style.height = "62px";
  imgContainer.style.overflow = "hidden";
  if (this._is_ie) {
    imgContainer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.imgSrc + "')";
  }
  container.appendChild(imgContainer); 

  if (!this._is_ie) {
    var baseImg = commonImg.cloneNode(false);
    baseImg.style.position = "absolute";
    baseImg.style.left = "0px";
    baseImg.style.top = "0px";
    baseImg.style.width = "59px";
    baseImg.style.height = "458px";
    imgContainer.appendChild(baseImg);
  }

  //top arrow button
  var topBtn = document.createElement("div");
  topBtn.style.position = "absolute";
  topBtn.style.left = "20px";
  topBtn.style.top = "0px";
  topBtn.style.width = "18px";
  topBtn.style.height = "18px";
  topBtn.style.cursor = "pointer";
  topBtn.style.overflow = "hidden";
  topBtn.title = "up";
  container.appendChild(topBtn); 

  //left arrow button
  var leftBtn = topBtn.cloneNode(true);
  leftBtn.style.left = "0px";
  leftBtn.style.top = "20px";
  leftBtn.title = "left";
  container.appendChild(leftBtn); 

  //right arrow button
  var rightBtn = topBtn.cloneNode(true);
  rightBtn.style.left = "40px";
  rightBtn.style.top = "20px";
  rightBtn.title = "right";
  container.appendChild(rightBtn); 

  //bottom arrow button
  var bottomBtn = topBtn.cloneNode(true);
  bottomBtn.style.left = "20px";
  bottomBtn.style.top = "40px";
  bottomBtn.title = "bottom";
  container.appendChild(bottomBtn); 

  //center button
  var homeBtn = topBtn.cloneNode(true);
  homeBtn.style.left = "20px";
  homeBtn.style.top = "20px";
  homeBtn.title = "home position";
  container.appendChild(homeBtn); 

  _handleList.topBtn = topBtn;
  _handleList.leftBtn = leftBtn;
  _handleList.rightBtn = rightBtn;
  _handleList.bottomBtn = bottomBtn;
  _handleList.homeBtn = homeBtn;

  // zoom slider Button
  var zoomSlideBarContainer = document.createElement("div");
  zoomSlideBarContainer.style.position  = "absolute";
  zoomSlideBarContainer.style.left = "19px";
  zoomSlideBarContainer.style.top = "86px";
  zoomSlideBarContainer.style.width = "22px";
  zoomSlideBarContainer.style.height = ((maxZoom - minZoom + 1) * this.sliderStep) + "px";
  zoomSlideBarContainer.style.overflow = "hidden";
  zoomSlideBarContainer.style.cursor = "pointer";
  container.appendChild(zoomSlideBarContainer); 
  _handleList.slideBar = zoomSlideBarContainer;

  var zoomLevel = map.getZoom();
  //zoomOut Btn load
  var zoomSliderContainer = document.createElement("div");
  zoomSliderContainer.style.position  = "absolute";
  zoomSliderContainer.style.left = 0;
  zoomSliderContainer.style.top = ((maxZoom - zoomLevel) * this.sliderStep + 1) + "px";
  zoomSliderContainer.style.width = "22px";
  zoomSliderContainer.style.height = "14px";
  zoomSliderContainer.style.overflow = "hidden";
  zoomSliderContainer.style.cursor = "url(http://maps.google.com/intl/en_ALL/mapfiles/openhand.cur), default";
  zoomSlideBarContainer.appendChild(zoomSliderContainer); 
  _handleList.slideBarContainer = zoomSliderContainer;

  if (this._is_ie) {
    var zoomSliderBtnImg = document.createElement("div");
    zoomSliderBtnImg.style.position = "relative";
    zoomSliderBtnImg.style.left = 0;
    zoomSliderBtnImg.style.top = "-384px";
    zoomSliderBtnImg.style.width = "22px";
    zoomSliderBtnImg.style.height = "14px";
    zoomSliderBtnImg.style.overflow = "hidden";
    zoomSliderBtnImg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src = '" + this.imgSrc + "')";
    zoomSliderContainer.appendChild(zoomSliderBtnImg);
    _handleList.zoomSlider = zoomSliderBtnImg;
  } else {
    var slideImg = commonImg.cloneNode(false);
    slideImg.style.position = "absolute";
    slideImg.style.left = "0px";
    slideImg.style.top = "-384px";
    slideImg.style.MozUserSelect = "none";
    slideImg.style.border = "0px none";
    slideImg.style.margin = "0px";
    slideImg.style.padding = "0px";
    slideImg.style.width = "59px";
    slideImg.style.height = "458px";
    zoomSliderContainer.appendChild(slideImg);
    _handleList.zoomSlider = slideImg;
  }

  //zoomOut Btn load
  var zoomOutBtnContainer = document.createElement("div");
  zoomOutBtnContainer.style.position = "absolute";
  zoomOutBtnContainer.style.left = 0;
  zoomOutBtnContainer.style.top = (86 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
  zoomOutBtnContainer.style.width = "59px";
  zoomOutBtnContainer.style.height = "23px";
  zoomOutBtnContainer.style.overflow = "hidden";
  container.appendChild(zoomOutBtnContainer); 


  if (this._is_ie) {
    var zoomOutBtnImg = document.createElement("div");
    zoomOutBtnImg.style.position = "relative";
    zoomOutBtnImg.style.left = 0;
    zoomOutBtnImg.style.top = "-360px";
    zoomOutBtnImg.style.width = "59px";
    zoomOutBtnImg.style.height = "23px";
    zoomOutBtnImg.style.overflow = "hidden";
    zoomOutBtnImg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.imgSrc + "')";
    zoomOutBtnContainer.appendChild(zoomOutBtnImg);
  } else {
    var btnImg = commonImg.cloneNode(false);
    btnImg.style.position = "absolute";
    btnImg.style.left = "0px";
    btnImg.style.top = "-360px";
    btnImg.style.width = "59px";
    btnImg.style.height = "458px";
    zoomOutBtnContainer.appendChild(btnImg);
  }

  //zoomOut button
  var zoomOutBtn = document.createElement("div");
  zoomOutBtn.style.position = "absolute";
  zoomOutBtn.style.left = "20px";
  zoomOutBtn.style.top = (91 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
  zoomOutBtn.style.width = "18px";
  zoomOutBtn.style.height = "23px";
  zoomOutBtn.style.cursor = "pointer";
  zoomOutBtn.style.overflow = "hidden";
  zoomOutBtn.title = "zoom out";
  container.appendChild(zoomOutBtn); 
  _handleList.zoomOutBtn = zoomOutBtn;

  //zoomIn button
  var zoomInBtn = document.createElement("div");
  zoomInBtn.style.position = "absolute";
  zoomInBtn.style.left = "20px";
  zoomInBtn.style.top = "65px";
  zoomInBtn.style.width = "18px";
  zoomInBtn.style.height = "23px";
  zoomInBtn.style.cursor = "pointer";
  zoomInBtn.style.overflow = "hidden";
  zoomInBtn.title = "zoom in";
  container.appendChild(zoomInBtn); 
  _handleList.zoomInBtn = zoomInBtn;

  // events
  GEvent.addDomListener(_handleList.topBtn, "click", 
      GEvent.callback(this, this._eventTop));
  GEvent.addDomListener(_handleList.leftBtn, "click", 
      GEvent.callback(this, this._eventLeft));
  GEvent.addDomListener(_handleList.rightBtn, "click", 
      GEvent.callback(this, this._eventRight));
  GEvent.addDomListener(_handleList.bottomBtn, "click", 
      GEvent.callback(this, this._eventBottom));
  GEvent.addDomListener(_handleList.homeBtn, "click", 
      GEvent.callback(this, this._eventHome));
  GEvent.addDomListener(_handleList.zoomOutBtn, "click", 
      GEvent.callback(this, this._eventZoomOut));
  GEvent.addDomListener(_handleList.zoomInBtn, "click", 
      GEvent.callback(this, this._eventZoomIn));
  GEvent.addDomListener(_handleList.slideBar, "click", 
      GEvent.callback(this, this._eventSlideBar));
  GEvent.addListener(map, "zoomend", 
      GEvent.callback(this, this._eventZoomEnd));

  var drgOpt = {
    container : _handleList.slideBar
  };
  var drgCtrl = new GDraggableObject(_handleList.slideBarContainer, drgOpt);
  GEvent.addDomListener(drgCtrl, "dragend", 
      GEvent.callback(this, this._eventSlideDragEnd));
  ExtLargeMapControl.prototype._slider =  drgCtrl;

  //set current slider position
  this._eventZoomEnd(map.getZoom(), map.getZoom());

  map.getContainer().appendChild(container);
  
  return container;
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventTop = function () {
  ExtLargeMapControl.prototype._map.panDirection(0, 1);
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventLeft = function () {
  ExtLargeMapControl.prototype._map.panDirection(1, 0);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventRight = function () {
  ExtLargeMapControl.prototype._map.panDirection(-1, 0);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventBottom = function () {
  ExtLargeMapControl.prototype._map.panDirection(0, -1);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomOut = function () {
  ExtLargeMapControl.prototype._map.zoomOut();
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomIn = function () {
  ExtLargeMapControl.prototype._map.zoomIn();
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventSlideBar = function (e) {
  var map = this._map;
  //calculate zoomlevel
  var mouseY = e.clientY;
  var slideStep = this._step;
  var maxZoom = this._maxZoom;
  var container = this._container;

  //set new zoomLevel
  var ctrlPos = this._getDomPosition(container);
  mouseY -= (ctrlPos.y + 91);
  var zoomLevel = Math.floor(maxZoom - (mouseY / slideStep));
  zoomLevel = zoomLevel < 0 ? 0 : zoomLevel;
  map.setZoom(zoomLevel);  
};

/**
  * @private
 */
ExtLargeMapControl.prototype._getDomPosition = function (that) {
  var targetEle = that;
  var pos = { x : 0, y : 0 };
  
  while (targetEle) {
    pos.x += targetEle.offsetLeft; 
    pos.y += targetEle.offsetTop; 
    targetEle = targetEle.offsetParent;

    if (targetEle && this._is_ie) {
      pos.x += (parseInt(ExtLargeMapControl.getElementStyle(targetEle, 
          "borderLeftWidth", "border-left-width"), 10) || 0);
      pos.y += (parseInt(ExtLargeMapControl.getElementStyle(targetEle, 
          "borderTopWidth", "border-top-width"), 10) || 0);
    }
  }

  if (this._is_gecko) {
    var bd = document.getElementsByTagName("BODY")[0];
    pos.x += 2 * (parseInt(ExtLargeMapControl.getElementStyle(bd, 
        "borderLeftWidth", "border-left-width"), 10) || 0);
    pos.y += 2 * (parseInt(ExtLargeMapControl.getElementStyle(bd, 
        "borderTopWidth", "border-top-width"), 10) || 0);
  }
  return pos;
};


/**
 * @private
 */
ExtLargeMapControl.getElementStyle = function(targetElm, IEStyleProp, CSSStyleProp) {
  var elem = targetElm;
  if (elem.currentStyle) {
    return elem.currentStyle[IEStyleProp];
  } else if (window.getComputedStyle) {
    var compStyle = window.getComputedStyle(elem, "");
    return compStyle.getPropertyValue(CSSStyleProp);
  }
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventSlideDragEnd = function (e) {
  //calculate zoomlevel
  var maxZoom = this._maxZoom;
  var mouseY = this._slider.top;
  var step = this._step;

  //set new zoomLevel
  var zoomLevel = Math.floor(maxZoom - (mouseY / step));
  zoomLevel = zoomLevel < 0 ? 0 : zoomLevel;
  this._map.setZoom(zoomLevel);
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventHome = function () {
  this._map.returnToSavedPosition();
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomEnd = function (oldZoom, newZoom) {
  var maxZoom = this._maxZoom;
  var step = this._step;
  this._slider.moveTo(new GPoint(0, (maxZoom - newZoom) * step));
};


/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.getDefaultPosition = function () {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
};


/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.selectable = function () {
  return false;
};

/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.printable = function () {
  return true;
};

/**************************************************************************************/

/************************************** more box **************************************/

var timer;
var chosen = [];
 
/* Array of GLayers
 * The 'name' label is not being used here
*/
var layers = [
 { name: "Pano", obj: new GLayer("lmc:panoramio") },
 { name: "Wiki", obj: new GLayer("lmc:wikipedia_en") }
];


function buildMap() {


 // Add selectable terrain map
 map.addMapType(G_PHYSICAL_MAP);
 var hControl = new GHierarchicalMapTypeControl();
 hControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
 map.addControl(hControl);

 // Add the self created control
 map.addControl(new MoreControl());
}


function hideAll() {

 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) {
   boxes[i].checked = false;
   switchLayer(false, layers[i].obj);
   chosen.push(i);
  }
 }
}


function checkChecked() {

 /* Returns true if a checkbox is still checked
 *  otherwise false
 */
 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) return true;
 }
 return false;
}


function switchLayer(checked, layer) {

 /* Function was originally borrowed from Esa:
 *  http://esa.ilmari.googlepages.com/dropdownmenu.htm
 */
 var layerbox = document.getElementById("box");
 var boxlink = document.getElementById("boxlink");
 var button = document.getElementById("more_inner");

 if(checked) {
   map.addOverlay(layer);
   // Reset chosen array
   chosen.length = 0;
   /* Highlight the link and
   *  make the button font bold.
   */
   boxlink.className ="highlight";
   layerbox.className ="highlight";
   button.className ="highlight";
 }
 else {
   map.removeOverlay(layer);
   /*  Reset the link and the button
    * if all checkboxes were unchecked.
   */
   if(!checkChecked()) {
    boxlink.blur();
    boxlink.className ="";
    layerbox.className ="";
    button.className ="";
   }
 }
}


function showLayerbox() {

if (search_flag == false)
{
 var layerbox = document.getElementById("box");
 // Left size of more control plus mapdiv.style.left
 var offsetX = 686;
 // Top size of more control plus mapdiv.style.top plus more button height
 var offsetY = -595;
}
else
{
    var layerbox = document.getElementById("box");
    // Left size of more control plus mapdiv.style.left
    var offsetX = 686;
    // Top size of more control plus mapdiv.style.top plus more button height
    var offsetY = -595;
}
 var lpos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offsetX, offsetY));
 lpos.apply(layerbox);
 if(window.timer) clearTimeout(timer);
 layerbox.style.display = "block";
 layerbox.style.position = "relative";
 layerbox.style.bgcolor = "#FFFFFF";
}


function setClose(e) {

 if(!e) e = window.event;
 var layerbox = document.getElementById("box");

 if(checkMouseLeave(layerbox, e))
  timer = setTimeout(function() {
   layerbox.style.display = "none"; }, 400);
}


function checkMouseLeave(element, evt) {

 /* Avoid firing a mouseout event
 *  when the mouse moves over a child element.
 *  Borrowed from:
 *  http://www.faqts.com/knowledge_base/view.phtml/aid/1606/fid/145
 */
 if(element.contains && evt.toElement) {
   return !element.contains(evt.toElement);
 }
 else if(evt.relatedTarget) {
   return !containsDOM(element, evt.relatedTarget);
 }
}


function containsDOM(container, containee) {

 var isParent = false;
 do {
  if((isParent = container == containee))
   break;
   containee = containee.parentNode;
 }
 while(containee != null);
 return isParent;
}


function toggleLayers() {

 if(chosen.length > 0 ) {
   /* Make an independent copy of chosen array since switchLayer()
   *  resets the chosen array, which may not be useful here.
   */
   var copy = chosen.slice();
   for(var i = 0; i < copy.length; i++) {
    var index = parseInt(copy[i]);
    switchLayer(true, layers[index].obj);
    document.getElementsByName("mark")[index].checked = true;
   }
 }
 else {
  hideAll();
 }
}


function MoreControl(){};
MoreControl.prototype = new GControl();
MoreControl.prototype.initialize = function(map) {

 var more = document.createElement("div");
 more.style.border = "1px solid black";
 more.title = "Show/Hide Layers";
 var inner = document.createElement("div");
 inner.id = "more_inner";
 inner.appendChild(document.createTextNode("More..."));
 more.appendChild(inner);
 more.onmouseover = showLayerbox;
 more.onmouseout = setClose;
 more.onclick = toggleLayers;
 map.getContainer().appendChild(more);
 return more;
}


MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(686, 7));
}


function showAddress(address) {

 var geocoder = new GClientGeocoder();
 geocoder.getLatLng(address, function(point) {

  if(!point) {
   alert(address + " not found.");
  }
  else {
   map.setCenter(point, 14);
  }
 });
}


/************************************* end of more box ********************************/

/*

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
  <name>New York City</name>
  <description>New York City</description>
  <Point>
    <coordinates>-74.006393,40.714172,0</coordinates>
  </Point>
</Placemark>
</kml>

*/