/*
*Based on ExtMapTypeControl Class v1.3 
*  Copyright (c) 2007, Google 
*  Author: Pamela Fox, others
*/


function ExtMapTypeControl(opt_opts) {
  this.options = opt_opts || {};
};


ExtMapTypeControl.prototype = new GControl();

/**
 * Is called by GMap2's addOverlay method. Creates the button 
 *  and appends to the map div.
 * @param {GMap2} map The map that has had this ExtMapTypeControl added to it.
 * @return {DOM Object} Div that holds the control
 */ 
ExtMapTypeControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  var me = this;

  var mapTypes = map.getMapTypes();
  var mapTypeDivs = me.addMapTypeButtons_(map);

  GEvent.addListener(map, "addmaptype", function() {
    var newMapTypes = map.getMapTypes();
    var newMapType = newMapTypes.pop();
    var newMapTypeDiv = me.createButton_(newMapType.getName());
    newMapTypeDiv.setAttribute('title', newMapType.getAlt());
    mapTypes.push(newMapType);
    mapTypeDivs.push(newMapTypeDiv);
    me.resetButtonEvents_(map, mapTypeDivs);
    container.appendChild(newMapTypeDiv);
  });
  GEvent.addListener(map, "removemaptype", function() {
    for (var i = 0; i < mapTypeDivs.length; i++) {
      GEvent.clearListeners(mapTypeDivs[i], "click");
      container.removeChild(mapTypeDivs[i]);
    }
    mapTypeDivs = me.addMapTypeButtons_(map);
    me.resetButtonEvents_(map, mapTypeDivs);
    for (var i = 0; i < mapTypeDivs.length; i++ ) {
      container.appendChild(mapTypeDivs[i]);
    }
  });

  if (me.options.showStreetView) {
	var StreetViewDiv = me.createButton_("ｽﾄﾘｰﾄﾋﾞｭｰ");
	StreetViewDiv.setAttribute('title', 'ストリートビューを見る');
	StreetViewDiv.style.marginRight = "8px";
	StreetViewDiv.style.visibility = 'hidden';
	StreetViewDiv.firstChild.style.cssFloat = "left";
	StreetViewDiv.firstChild.style.styleFloat = "left";

	StreetViewDiv.style.visibility = 'visible';

	GEvent.addDomListener(StreetViewDiv.firstChild, "click", function() {
		if (!overlayInstance) {
			overlayInstance = new GStreetviewOverlay();
			map.addOverlay(overlayInstance);
			if ( lastMarkerLocation == null ) {
				lastMarkerLocation = map.getCenter();
			}
			guyMarker = new GMarker(lastMarkerLocation, {icon: guyIcon, draggable: true});
			GEvent.addListener(guyMarker, "dragend", onDragEnd);
			GEvent.addListener(guyMarker, "click", openPanoramaBubble);
			map.addOverlay(guyMarker);
			var panoNode = getPanoramaViewNode();
			guyMarker.openInfoWindow(panoNode,{});
			setTimeout("openPanoramaBubble();",1000);
			if ( lastPov!= null ) {
				onYawChange(lastPov.yaw);
			} else {
				
			}
		} else {
			map.removeOverlay(overlayInstance);
			overlayInstance = null;
			map.removeOverlay(guyMarker);
			guyMarker = null;
		}
		me.toggleButton_(StreetViewDiv.firstChild, overlayInstance);
	});

	me.toggleButton_(StreetViewDiv.firstChild, false);
	container.appendChild(StreetViewDiv);
  }

  if (me.options.showNews) {
	var NewsDiv = me.createButton_("地域ﾆｭｰｽ");
	NewsDiv.setAttribute('title', '地域ニュースを見る');
	NewsDiv.style.marginRight = "8px";
	NewsDiv.style.visibility = 'hidden';
	NewsDiv.firstChild.style.cssFloat = "left";
	NewsDiv.firstChild.style.styleFloat = "left";
	NewsDiv.style.visibility = 'visible';

	GEvent.addDomListener(NewsDiv.firstChild, "click", function() {
		if (!newsOverlays) {
			getLocalNews();
			
		} else {
			if ( newsOverlays != null ) {
				for (var i=0;i<newsOverlays.length;i++) {
					map.removeOverlay(newsOverlays[i]);
				}
				newsOverlays = null;
			}
		}
		me.toggleButton_(NewsDiv.firstChild, newsOverlays);
	});

	me.toggleButton_(NewsDiv.firstChild, true);
	container.appendChild(NewsDiv);
	getLocalNews();
  }

  if (me.options.showNearPlaces) {
	var NearPlacesDiv = me.createButton_("近くの物件");
	NearPlacesDiv.setAttribute('title', '近くの物件を見る');
	NearPlacesDiv.style.marginRight = "8px";
	NearPlacesDiv.style.visibility = 'hidden';
	NearPlacesDiv.firstChild.style.cssFloat = "left";
	NearPlacesDiv.firstChild.style.styleFloat = "left";
	NearPlacesDiv.style.visibility = 'visible';

	GEvent.addDomListener(NearPlacesDiv.firstChild, "click", function() {
		if (!isShowingNearPlaces) {
			//表示
			if (( nearPlacesOverlays != null )&&(nearPlacesOverlays.length>0)) {
				for (var i=0;i<nearPlacesOverlays.length;i++) {
					map.addOverlay(nearPlacesOverlays[i]);
				}
				
			} else {
				alert("近くに他の物件がありません。");
				return;
			}
		} else {
			if (( nearPlacesOverlays != null )&&(nearPlacesOverlays.length>0)) {
				for (var i=0;i<nearPlacesOverlays.length;i++) {
					map.removeOverlay(nearPlacesOverlays[i]);
				}
			}
		}
		isShowingNearPlaces = !isShowingNearPlaces;
		me.toggleButton_(NearPlacesDiv.firstChild, isShowingNearPlaces);
  	});
	isShowingNearPlaces = true;
	me.toggleButton_(NearPlacesDiv.firstChild, true);
	container.appendChild(NearPlacesDiv);

	if (( nearPlacesOverlays != null )&&(nearPlacesOverlays.length>0)) {
		for (var i=0;i<nearPlacesOverlays.length;i++) {
			map.addOverlay(nearPlacesOverlays[i]);
		}
	}
  }

  for (var i = 0; i < mapTypeDivs.length; i++ ) {
    container.appendChild(mapTypeDivs[i]);
  }

  map.getContainer().appendChild(container);
  return container;
};

function showLabelDiv(thumbUrl,title,point) {
	var coords = map.fromLatLngToContainerPixel(point);
	coords.x=coords.x-80;coords.y=coords.y-174;
	var shortTitle = title.substring(0,13);
	labelDiv.style.width = '160px';
	labelDiv.innerHTML='<img height=120 src="' + thumbUrl + '" style="padding-bottom:2px"><br>' + shortTitle;
	if ( title.length > 13 ) {
		labelDiv.innerHTML+='<br>' + title.substring(13,26);
		labelDiv.style.height = '156px';
		coords.y=coords.y-15;
		if (coords.y<-10) {coords.y=coords.y+195;}
	} else {
		labelDiv.style.height = '142px';
		if (coords.y<-10) {coords.y=coords.y+185;}
	}
	labelDiv.style.visibility = 'visible';
	labelDiv.style.left=coords.x + 'px';
	labelDiv.style.top=coords.y + 'px';
}

function showThisPropertyLabelDiv(point) {
	var coords = map.fromLatLngToContainerPixel(point);
	coords.x=coords.x-28;coords.y=coords.y-65;
	labelDiv.style.width = '49px';
	labelDiv.style.height = '18px';
	labelDiv.innerHTML='<img src="../images/thisproperty.gif">';

	labelDiv.style.visibility = 'visible';
	labelDiv.style.left=coords.x + 'px';
	labelDiv.style.top=coords.y + 'px';
}

function addNewsMarkers(items) {
	for (var i = 0; i < items.length; ++i) {
		var latitude = items[i]['latitude'];
		var longitude = items[i]['longitude'];
		var thumbUrl = items[i]['thumbUrl'];
		var title = items[i]['title'];
		var description = items[i]['description'];
		var link = items[i]['link'];

		newsOverlays[i] = new GMarker(new GPoint(longitude,latitude),newsIcon);
		newsOverlays[i].windowHTML = getNewsBalloonHtml(title, description, link, thumbUrl);
		newsOverlays[i].title = title;
		newsOverlays[i].thumbUrl = thumbUrl;
		
		GEvent.addListener(newsOverlays[i], 'mouseover', function(point) {
			showLabelDiv(this.thumbUrl,this.title,point)
		});
		GEvent.addListener(newsOverlays[i], 'mouseout', function(point) {
			labelDiv.style.visibility = 'hidden';
		});

		map.addOverlay(newsOverlays[i]);
	}
}

function getNewsBalloonHtml(title, description, link, thumbUrl) {
	var htmlCode = '<div style="font-size:12px;position:relative;width:270px;text-align:left;line-height:140%;">';
	htmlCode += '<a href="' + link + '" target="_blank">';
	htmlCode += '<img width="76" border=0 style="float:left;margin:2px 8px 0 0;display:block;" src="' + thumbUrl + '"></a>';
	htmlCode += '<p style="width: 174px; margin-left: 76px;"><strong><a href="' + link + '" target="_blank">';
	htmlCode += title + '</a></strong><br>' + description;
	htmlCode += '</p></div>';
	return htmlCode;
}

function getLocalNews() {
	newsOverlays = new Array();
	var request = GetXmlHttpObject();
	var requestUrl = 'getLocalNews.aspx?latitude=' + latitude + '&longitude=' + longitude;
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200) {
			var parser = new SimpleXmlParser(request.responseXML);
			
			items = parser.getItems('item');

			if ( (items ==null) || (items.length == 0) ) {
				//alert("この範囲に地域ニュースがありません。");
			} else {
				addNewsMarkers(items);
			}
		}
	};
	request.open("GET", requestUrl, true);
	request.setRequestHeader("Content-Type", "text/xml");
  	request.send(null);
}

function GetXmlHttpObject()
{
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
}

function onDragEnd() {
	var latlng = guyMarker.getLatLng();
	if (panorama) {
		client.getNearestPanorama(latlng, onResponse);
	}
}

function openPanoramaBubble() {
	if ( scope != null ) return; //a location is opened

	var panoNode = document.getElementById('pano');
	guyMarker.openInfoWindow(panoNode,{});
	panorama = new GStreetviewPanorama(panoNode,{latlng:guyMarker.getLatLng(), pov:lastPov});

	if ( panorama!= null ) {
		GEvent.addListener(panorama, "newpano", onNewLocation);
		GEvent.addListener(panorama, "yawchanged", onYawChange);
		GEvent.addListener(panorama, "initialized", onPathMove);
		GEvent.addListener(panorama, "error", onPanoError);
	}
}

function getPanoramaViewNode() {
	var smallNode = document.getElementById('pano');
	if (smallNode == null) {
		smallNode = document.createElement('div');
		smallNode.style.width = '312px';
		smallNode.style.height = '234px';
		smallNode.id = 'pano';
		guyMarker.bindInfoWindow(smallNode, {});
	} else {
		
	}
	return smallNode;
}

function onPanoError(errorCode) {
	panorama = null;
	if (errorCode==GStreetviewPanorama.ErrorValues.FLASH_UNAVAILABLE)
	{
		guyMarker.openInfoWindow("<font size=-1>Flash(TM) プラグインがインストールされてません。</font>");
	}
	else
	{
		guyMarker.openInfoWindow("<font size=-1>近くにストリートビューがありません。アイコンを青いラインの上に移動してください。"+errorCode);
	}
}

function onNewLocation(lat, lng) {
	var latlng = new GLatLng(lat, lng);
	guyMarker.setLatLng(latlng);
}

function onYawChange(newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
  if (newYaw < 0) {
    newYaw += 360;
  }
  lastPov = panorama.getPOV();
  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.gstatic.com/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  guyMarker.setImage(guyImageUrl);
}

function onResponse(response) {
  if (response.code != 200) {
    guyMarker.setLatLng(lastMarkerLocation);
  } else {
    var latlng = new GLatLng(response.Location.lat, response.Location.lng);
    guyMarker.setLatLng(latlng);
    lastMarkerLocation = latlng;
    openPanoramaBubble();
  }
}

function onPathMove(streetViewLocation) {
	onNewLocation(streetViewLocation.latlng.lat(), streetViewLocation.latlng.lng());
}

/*
 * Creates buttons for map types.
 * @param {GMap2} Map object for which to create buttons.
 * @return {Array} Divs containing the buttons.
 */
ExtMapTypeControl.prototype.addMapTypeButtons_ = function(map) {
  var me = this;
  var mapTypes = map.getMapTypes();
  var mapTypeDivs = new Array();
  for (var i = 0; i < mapTypes.length; i++) {
    mapTypeDivs[i] = me.createButton_(mapTypes[i].getName());
    mapTypeDivs[i].setAttribute('title', mapTypes[i].getAlt());
  }
  me.resetButtonEvents_(map, mapTypeDivs);
  return mapTypeDivs;
};

/*
 * Ensures that map type button events are assigned correctly.
 * @param {GMap2} Map object for which to reset events.
 * @param {Array} mapTypeDivs Divs containing map type buttons.
 */
ExtMapTypeControl.prototype.resetButtonEvents_ = function(map, mapTypeDivs) {
  var me = this;
  var mapTypes = map.getMapTypes();
  for (var i = 0; i < mapTypeDivs.length; i++) {
    var otherDivs = new Array;
    for (var j = 0; j < mapTypes.length; j++ ) {
      if (j != i) {
        otherDivs.push(mapTypeDivs[j]);
      }
    }
    me.assignButtonEvent_(mapTypeDivs[i], map, mapTypes[i], otherDivs);
  }
  GEvent.addListener(map, "maptypechanged", function() {
    var divIndex = 0;
    var mapType = map.getCurrentMapType();
    for (var i = 0; i < mapTypes.length; i++) {
      if (mapTypes[i] == mapType) {
        divIndex = i;
      }
    }
    GEvent.trigger(mapTypeDivs[divIndex], "click");
  });
};

/*
 * Creates simple buttons with text nodes. 
 * @param {String} text Text to display in button
 * @return {DOM Object} The div for the button.
 */
ExtMapTypeControl.prototype.createButton_ = function(text) {
  var buttonDiv = document.createElement("div");
  this.setButtonStyle_(buttonDiv);
  buttonDiv.style.cssFloat = "left";
  buttonDiv.style.styleFloat = "left";
  var textDiv = document.createElement("div");
  textDiv.appendChild(document.createTextNode(text));
  textDiv.style.width = "6em";
  buttonDiv.appendChild(textDiv);
  return buttonDiv;
};

/*
 * Assigns events to MapType buttons to change maptype
 *  and toggle button styles correctly for all buttons
 *  when button is clicked.
 *  @param {DOM Object} div Button's div to assign click to
 *  @param {GMap2} Map object to change maptype of.
 *  @param {Object} mapType GMapType to change map to when clicked
 *  @param {Array} otherDivs Array of other button divs to toggle off
 */  
ExtMapTypeControl.prototype.assignButtonEvent_ = function(div, map, mapType, otherDivs) {
  var me = this;

  GEvent.addDomListener(div, "click", function() {
    for (var i = 0; i < otherDivs.length; i++) {
      me.toggleButton_(otherDivs[i].firstChild, false);
    }
    me.toggleButton_(div.firstChild, true);
    map.setMapType(mapType);
  });
};

/*
 * Changes style of button to appear on/off depending on boolean passed in.
 * @param {DOM Object} div  Button div to change style of
 * @param {Boolean} boolCheck Used to decide to use on style or off style
 */
ExtMapTypeControl.prototype.toggleButton_ = function(div, boolCheck) {
   div.style.fontWeight = boolCheck ? "bold" : "";
   div.style.border = "1px solid white";
   var shadows = boolCheck ? ["Top", "Left"] : ["Bottom", "Right"];
   for (var j = 0; j < shadows.length; j++) {
     div.style["border" + shadows[j]] = "1px solid #b0b0b0";
  } 
};

/*
 * Required by GMaps API for controls. 
 * @return {GControlPosition} Default location for control
 */
ExtMapTypeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
};

/*
 * Sets the proper CSS for the given button element.
 * @param {DOM Object} button Button div to set style for
 */
ExtMapTypeControl.prototype.setButtonStyle_ = function(button) {
  button.style.color = "#000000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "0px";
  button.style.margin= "0px";
  button.style.textAlign = "center";
  button.style.fontSize = "12px"; 
  button.style.cursor = "pointer";
};
