//document.onselectstart=function(){return false;};
google.load('gdata', '2', {packages: ['maps']});
var geocoder;
var map;
var myPOIs=[];
var myPOIMarkers=[];
var myPolygons=[];
var myPrintedAreas=[];
var myPolylines=[];
var myMapList=[];
var mapFeed;
var featureFeedUrl;
var route;
var overlay;
var weatherLat;
var weatherLng;
var directionsService;
var directionsDisplay;
var printmap_container=null;
var currentSection;
var staticMapLoadingCheck;

textOverlay.prototype = new google.maps.OverlayView();
 
function onGoogleDataLoad() {
	service = new google.gdata.maps.MapsService('print-friendly');
	$("#loading").hide();
	$("#map_loading").hide();

	if(checkLogin()=="")
	{
		$("#login").show();
		$("#logout").hide();
		$("#maps_toolbar").show();
		$("#mymaps_toolbar").hide();
		$("#mymap_toolbar").hide();
		currentSection=1;
		gotoSection(currentSection);
	}
	else
	{
		$("#login").hide();
		$("#logout").show(); 
		$("#maps_toolbar").hide();
		$("#mymaps_toolbar").show();        
		//console.log(checkLogin());
		listMaps();
		currentSection=2;
		gotoSection(currentSection);
	}  
}

function doLogin() {
	var token = google.accounts.user.login('http://maps.google.com/maps/feeds');
}

// Check whether the user is authenticated.
function checkLogin() {
	return google.accounts.user.checkLogin('http://maps.google.com/maps/feeds');
}

// Log the user out.
function doLogout() {
	google.accounts.user.logout();
}

// Optionally, include a callback parameter that
// gets called once the user is logged out.
function doLogoutAndRefresh() {
	google.accounts.user.logout(function() {
		window.location.reload();
	});
}

function handleInfo(data) {
	var response = eval(data.currentTarget.responseText);

	alert('Target: ' + response.Target + "\n" + 
	      'Scope: ' + response.Scope + "\n" +
	      'Secure: ' + response.Secure);
}

function doGetInfo() {
	scope = "http://maps.google.com/maps/feeds/maps/";
	if (google.accounts.user.checkLogin(scope)) {
		google.accounts.user.getInfo(handleInfo);
	}
}
function jumpTo(location) {
	$("#loading").show();
	$("#map_loading").show();
	$("#map_loaded").hide();
	geocoder.geocode({ address: location }, function(results, status) {
		if(status=="OK")
		{
			$("#error").hide();
			map.fitBounds(results[0].geometry.viewport);
			getStaticMap();
		}
		else
		{
			alert("沒有找到資料。");
		}
	});
}

function listMaps() {
	console.log("listMaps()");
	$("#loading").show();
	$("#map_loading").show();
	$("#map_loaded").hide();
	$("#error").hide();
	$("#my_maps > option").remove();
	$("#my_maps").append('<option value="" >載入中...</option>');
	$("#mymap_toolbar").hide();	
	myMapList=[];
	$("#my_maps")[0].disabled=true;
	 mapFeedUrl = 'http://maps.google.com/maps/feeds/maps/default/owned';
	
	fr="";
	service.getMapFeed(mapFeedUrl, function(feedRoot) {
		console.log(feedRoot);
		fr=feedRoot;
		$("#my_maps").append('<option value="'+i+'" >'+mapTitle+'</option>');
		$("#my_maps > option").remove();
		$("#my_maps").append('<option value="" >請選擇一個地圖</option>');
		$("#loading").hide();
		$("#map_loaded").show();
		$("#map_loading").hide();
		$("#my_maps")[0].disabled=false;
		var  feed = feedRoot.feed;      
		var entries = feed.getEntries();

		for (var i = 0; i < entries.length; i++) {
			var entry = entries[i];
			var mapTitle = entry.getTitle().getText();      
			// console.log(U2A(mapTitle)); 
			var mapId = entry.getId().getValue();
			var mapUrl = entry.getLinks()[2].href;
			console.log("mapUrl="+mapUrl);
			var featureFeedUrl = entry.getContent().getUri();

			var mapEntrie={
				"mapTitle": mapTitle,
				"mapId": mapId,
				"mapUrl": mapUrl,
				"featureFeedUrl": featureFeedUrl
			};
	
			myMapList.push(mapEntrie);
			console.log("featureFeedUrl="+featureFeedUrl);
			$("#my_maps").append('<option value="'+i+'" >'+mapTitle+'</option>');
		}
	}, errorHandler);
	
	
}
  
function errorHandler(e) {
	var errorDiv = document.createElement('div');
	document.body.appendChild(errorDiv);
	if (e instanceof Error) {
		errorDiv.innerHTML = 'Error on line ' + e.lineNumber + ' in ' + e.fileName
		                   + '\nMessage: ' + e.message;
	if (e.cause) {
		  errorDiv.innerHTML = errorDiv.innerHTML + '<br />Root cause: HTTP error '
		                     + e.cause.status + ': ' + e.cause.statusText;
	}
	} else {
		alert(e.toString());
	}
}
  
function getMap()
{
	console.log("getMap()");
	$("#loading").show();
	$("#map_loading").show();
	$("#map_loaded").hide();
	$("#error").hide();
	document.getElementById("mymap_title").innerHTML=myMapList[parseInt($("#my_maps").val())].mapTitle;
	mapFeed = myMapList[parseInt($("#my_maps").val())].mapFeedUrl;
	featureFeedUrl = myMapList[parseInt($("#my_maps").val())].featureFeedUrl;

	$("#mymap_toolbar").hide();
	
	ff="";
	service.getFeatureFeed(featureFeedUrl, function(featureFeedRoot) {
		ff=featureFeedRoot;
		$("#loading").hide();
		$("#map_loading").hide();
		$("#map_loaded").show();
		$("#mymap_toolbar").show();
		$("#mymaps_toolbar").hide();
	
		clearMap();
		for(i=0; i<$(featureFeedRoot.feed.entry).length;i++)
		{
			var feature=$(featureFeedRoot.feed.entry[i].content.getText());
			console.log("===ff.feed.entry["+i+"].content.getText()===");
      console.log($(feature).find('point').length);

			if($(feature).find('point').length==1){ //This is a point
				console.log("point");
				//feature=$(featureFeedRoot.feed.entry[i].content.$t)[0];
				var name=$(feature).find("name")[0].innerText;
				name=U2A(name); 
				// console.log("name: "+name);

				// start of description
				if($(feature).find("description").length>0){ 
					var description=$(feature).find("description")[0].innerHTML;
					description=description.replace('<div dir="ltr">',"");
					description=description.replace(']]&gt;',"");
					description=description.replace('</div>',"");
					description=description.replace('<br>',"");
					description=U2A(description);  
				}
				else{
					description="";
				}
				// console.log("description: "+description);
				// end of description
				
				if($(feature).find("coordinates").length>0){ 
					var coordinate=$(feature).find("coordinates")[0].outerText;
					console.log(coordinate);
					var lng=coordinate.split(",")[0];
					var lat=coordinate.split(",")[1];
				}
				 console.log("lat: "+lat);
				 console.log("lng: "+lng);
				var icon=$(feature).find("style")[0].innerText;
				icon=$(icon).find("href").html();

				if(!icon)
				{
					icon="http://maps.gstatic.com/intl/zh-TW_tw/mapfiles/ms/micons/blue-dot.png";
				}

				console.log(icon); 

			//	console.log(name +" "+description+" "+coordinates+" "+icon);

				POI=new Object();
				POI.name=name;
				POI.lat=lat;
				POI.lng=lng;
				POI.icon=icon;
				POI.description=description;
				myPOIs.push(POI);
			}
			else{ //This is a polygon or polyline
				console.log("polygon or polyline");
				var lineStyleString;
				var lineColor;
				var lineWidth;
				var lineOpacity;
		
				var polyStyleString;
				var polyColor;	
				var polyOpacity;
				var polyFill;
				var polyOutline;
			
				if($(feature).find('Style').length>0)
				{
					var styleString=$(feature).find('Style')[0].innerText;
					//lineStyle
					if(styleString.indexOf("<LineStyle>")>-1)
					{
						lineStyleString=styleString.match(/<LineStyle>(.*)<\/LineStyle>/,"$1")[0];

						lineColor=$(lineStyleString).find("color").text().substr(2,6);
						lineOpacity=$(lineStyleString).find("color").text().substr(0,2);
						var b=lineColor.substr(0,2);
						var g=lineColor.substr(2,2);
						var r=lineColor.substr(4,2);
						lineColor="#"+r+g+b;	
						lineOpacity=parseInt(lineOpacity,16)/255;
						lineWidth=parseInt($(lineStyleString).find("width").text());

						console.log("lineColor="+lineColor);
						console.log("lineOpacity="+lineOpacity);
						console.log("lineWidth="+lineWidth);
					}else{
						lineColor="#000000";
						lineOpacity=1;
						lineWidth=3;
					}

					//polyStyle
					if(styleString.indexOf("<PolyStyle>")>-1)
					{
						polyStyleString=styleString.match(/<PolyStyle>(.*)<\/PolyStyle>/,"$1")[0];
						polyColor=$(polyStyleString).find("color").text().substr(2,6);
						polyOpacity=$(polyStyleString).find("color").text().substr(0,2);
						var b=polyColor.substr(0,2);
						var g=polyColor.substr(2,2);
						var r=polyColor.substr(4,2);
						polyColor="#"+r+g+b;	
						polyOpacity=parseInt(polyOpacity,16)/255;
						polyFill=parseInt($(polyStyleString).find("fill").text());
						polyOutline=parseInt($(polyStyleString).find("outline").text());

						console.log("polyColor="+polyColor);
						console.log("polyOpacity="+polyOpacity);
						console.log("polyOutline="+polyOutline);
					}else
					{
						polyColor="#000000";	
						polyOpacity=1;
						polyFill="#000000";
						polyOutline=1;
					}
				}
				if($(feature).find('coordinates').length>0)
				{
			
					var coordinates=$(feature).find("coordinates")[0].innerText.split(" ");

					var polyCoordinates=[];

					$.each(coordinates,function(index,coordinate){
						var lng=coordinate.split(",")[0];
						var lat=coordinate.split(",")[1];
						polyCoordinates.push(new google.maps.LatLng(lat, lng));
					});

					var name=$(feature).find("name")[0].innerText;

					if($(feature).find('polygon').length==1) //Polygon
					{
						if($(feature).find("description").length>0){ 
							var description=$(feature).find("description")[0].innerHTML;
							polygon = new google.maps.Polygon({
							    paths: polyCoordinates,
							    strokeColor: lineColor,
							    strokeOpacity: lineOpacity,
							    strokeWeight: lineWidth,
							    fillColor: polyColor,
							    fillOpacity: polyOpacity
							});

							polygon.name=U2A(name);
							if(description.indexOf("PrintMyMap")>0)
							{
								console.log("列印範圍");
								polygon.name=polygon.name.substring(5,polygon.name.length);
								myPrintedAreas.push(polygon);
							}
							else
							{
								myPolygons.push(polygon);
							}
						}
					}
					else //Polyline
					{
						  console.log("Polyline");
						  var polyline = new google.maps.Polyline({
						    path: polyCoordinates,
						    strokeColor: lineColor,
						    strokeOpacity: lineOpacity,
						    strokeWeight: lineWidth
						  });

						polyline.name=U2A(name);
						myPolylines.push(polyline);
					}	
				}
			}  
		}
		drawMap();
		//fit list printed area
		if($("#my_printed_areas")[0].length>1)
		{
			$("#my_printed_areas")[0].selectedIndex=$("#my_printed_areas")[0].length-1;
			fitPrintedArea();
		}
		});
}


function backToMymapList()
{
	$("#mymaps_toolbar").show();
	$("#mymap_toolbar").hide();
}

function makeMapAPIVisible(mapUrl) { 
	service.getMapEntry(mapUrl, function(entryRoot) {
	var entry = entryRoot.entry;
	//entry.gd$customProperty[0].$t=1;
	entry.addCustomProperty({name:'api_visible', value:'1'});
	entry.updateEntry(
	function(ent){alert('Updated!');},
	function(e){alert('Upadte err...' + e);});},
	function(e){alert("Err..." + e);}
	);
}
  
  //http://www.chinaue.com/tool/uni.htm
  // Unicode converter
function U2A(ustring) {
//	console.log("U2A("+ustring+")");
	if(ustring)
	{
		var regex =/(&#\d+;)/g;
		var code;
	//	console.log(ustring);
		code=ustring.split(regex);
		var result="";
		for (var i=0; i<code.length; i++)
		{
			if(code[i].search(/&#(\d+);/g)==0)
			{
				result+=String.fromCharCode(code[i].replace(/[&#;]/g, ''));
			}
			else
			{
				result+=code[i];
			}
		}  
		return result;   
	}else
	{
		return;
	}
}


/*
function reverseGeocodingMapCenter() {
    if (geocoder) {
      geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
		rt=results;
		console.log(results);
			console.log(map.getZoom());
          if (results[1]) {
			return results[1].formatted_address;
          }
        } else {
          	return null;
        }
      });
    }
 }
*/

function savePrintArea()
{
	console.log("savePrintArea()");
	var printAreaName;
	if (geocoder) {
      geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
		rt=results;
		console.log(results);
			console.log(map.getZoom());
          if (results[1]) {
			printAreaName=results[1].formatted_address;
          }
        } else {
          	printAreaName="";
        }
		var printedBound=[];
		printedBound.push(map.getBounds().getNorthEast());
		printedBound.push(new google.maps.LatLng(map.getBounds().getNorthEast().lat(),map.getBounds().getSouthWest().lng()));
		printedBound.push(map.getBounds().getSouthWest());
		printedBound.push(new google.maps.LatLng(map.getBounds().getSouthWest().lat(),map.getBounds().getNorthEast().lng()));

		/*
		printedbounds = new google.maps.Polygon({
		    paths: printedBound,
		    strokeColor: "#FF0000",
		    strokeOpacity: 1,
		    strokeWeight: 2,
		    fillColor: "#FF0000",
		    fillOpacity: 0.2
		  });

		  printedbounds.setMap(map);
		*/

		  service.getFeatureFeed(featureFeedUrl, function(feedRoot) {
		    var newFeature = new google.gdata.maps.FeatureEntry();

		    // Set the name for this feature.
		    var title = new google.gdata.atom.Text();
		//	var summary = new google.gdata.atom.Text();
		    title.setText('列印範圍：'+printAreaName);
		//	summary.setText('列印於'+ new Date().toString());
		    newFeature.setTitle(title);
		//    newFeature.setSummary(summary);

		    // Define the content.
		    var kmlContent = new google.gdata.maps.KmlContent();
			var coordinatesString="";
			$.each(printedBound,function(i,e){coordinatesString+=e.lng()+","+e.lat()+",30\n"})

			var kmlString ='<Placemark>'
						 + '<description><![CDATA[使用<a href="http://www.lis186.com/works/printmymap">PrintMyMaps</a>列印]]></description>'
						 +'<Style id="printedarea">'
						 +   '<PolyStyle>'
					     +      '<color>000000cc</color>'
						 +   '</PolyStyle>'
						 +   '<LineStyle>'
						 +  	'<color>ff0000cc</color>'
						 +	    '<width>2</width>'
						 +  '</LineStyle>'
						 +'</Style>'
					 	 +   '<Polygon>'
						 + '<name>Print Area</name>'  //will be ignored
						 + '<styleUrl>#printedarea</styleUrl>'
						 +    '<extrude>1</extrude>'
						 +     '<altitudeMode>clampToGround</altitudeMode>'
						 +     '<outerBoundaryIs>'
						 +       '<LinearRing>'
						 +        '<coordinates>'
					     +			coordinatesString
						 +         '</coordinates>'
						 +       '</LinearRing>'
						 +     '</outerBoundaryIs>'
						 +    '<innerBoundaryIs>'
						 +       '<LinearRing>'
						 +         '<coordinates>'
						 +           coordinatesString
						 +         '</coordinates>'
						 +       '</LinearRing>'
						 +     '</innerBoundaryIs>'
						 +   '</Polygon>'
						 +'</Placemark>';

			console.log(kmlString);

		    kmlContent.setText(kmlString);
		    kmlContent.setType(google.gdata.maps.KmlContent.TYPE_APPLICATION_VND_GOOGLE_EARTH_KML_XML);

		    newFeature.setContent(kmlContent);

		    feedRoot.feed.insertEntry(newFeature, function () {
			alert("儲存完成");
			getMap();
			}, errorHandler);
		  }, errorHandler);
      });
    }


}
 
function initialize() {

	if(!$.browser.webkit) //非webkit
	{
		$("div").remove();
		document.write('很抱歉！因為PrintMyMap使用了許多webkit限定的功能，這些功能在你的瀏覽器無法使用，請改用<a href="http://www.google.com.tw/chrome">Google瀏覽器</a>或<a href="http://www.apple.com/tw/safari/download/">Safari</a>。');
		return;
	}

	console.log("initialize()");

	geocoder = new google.maps.Geocoder();

	var myLatLng = new google.maps.LatLng(25.043723,121.550906);
	
	
	var myOptions = {
		zoom: 11,
		center: myLatLng,
	//	mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, "grayscale"],
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: true,
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		mapTypeControl: true,
		scaleControl: true,
		streetViewControl: true,
		disableDoubleClickZoom: false
	};
	
	myPOIMarkers=[];
	myPrintedAreas=[];
	myPolygons=[];
	myPolylines=[];
	
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	getStaticMap();
	/*
	var GreyscaleStyle= [
	    {              
	        featureType: 'all',
	        rules: [
	            {saturation: -100},
	            {gamma: 0.50}
	        ]
	    }
	];
	
	var styledMapType = new google.maps.StyledMapType(GreyscaleStyle, { name: 'grayscale' });
	map.mapTypes.set('grayscale', styledMapType);
	*/

	google.maps.event.addListener(map, 'idle', function() {
		updatePrintMap();
		getStaticMap();
	//	fixUIZoom(); 
	});

	google.maps.event.addListener(map, 'zoom_changed', function() {
		updatePrintMap();
	//	fixUIZoom(); 
	});


	google.maps.event.addListener(map, 'tilesloaded', function() {
		updatePrintMap();
	//	fixUIZoom();
	});
/*	
	google.maps.event.addListener(map, 'mousemove', function() { 
		fixUIZoom();
	});
	
	google.maps.event.addListener(map, 'dragend', function() { 
		fixUIZoom();
	});
	
	google.maps.event.addListener(map, 'tilesloaded', function() { 
		fixUIZoom();
	});
	*/
}
 
/*
function fixUIZoom()
{
	$("#map_canvas").css("height",1220);
	$("#map_canvas").css("width",1220);
	$("#map_canvas").css("zoom",0.5);
	$($("#map_canvas")[0].childNodes[0].childNodes[1]).css("zoom",2);
	$($("#map_canvas")[0].childNodes[0].childNodes[2]).css("zoom",2);
	$($("#map_canvas")[0].childNodes[0].childNodes[3]).css("zoom",2);
	$($("#map_canvas")[0].childNodes[0].childNodes[4]).css("zoom",2);
	$($("#map_canvas")[0].childNodes[0].childNodes[5]).css("zoom",2);
	google.maps.event.trigger(map, 'resize');
}
*/

function getCurrentPosition()
{
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(getPosition, fallbackToIPGeoLocation, {enableHighAccuracy: true});
	}
}

function fallbackToIPGeoLocation() {
	if (google.loader.ClientLocation) {
		var lat=google.loader.ClientLocation.latitude;
		var lng=google.loader.ClientLocation.longitude;
		var myLatLng = new google.maps.LatLng(lat,lng);
		map.setCenter(myLatLng);
	} else { 
		// 投降了，真的無法定位 
		alert("目前無法取得你的位置");
	}
}

function getPosition()
{
	console.log('定位了...');
	getStaticMap();
}

function getGroundResolution()
{
   // return range=20088000/Math.pow(2,map.getZoom())/305;
   return Math.cos(map.getCenter().lat() * Math.PI/180) * 2 * Math.PI * 6378137 / (256 * Math.pow(2,map.getZoom()));
}

function getStaticMap()
{
	console.log("getStaticMap()");
	var center=map.getCenter().lat()+","+map.getCenter().lng();
	var zoom=map.getZoom();
//	var size=$("#map_canvas").width()/2+"x"+$("#map_canvas").height()/2;
//	var size="305x305";
  var size="610x610";
	var marker="";
	var point="";
	var api_key="ABQIAAAAB8Xq-0ofVdh_kwUigRfN1xTjmpTRD5iUkw3HZEbk_xuMBrkCjBStFF8McNVwSYKP_vbOx6f-ib6_8Q";
//	var random=Math.floor(Math.random()*1000000);
	var static_map_url="http://maps.google.com/staticmap?center="+center+"&zoom="+zoom+"&size="+size+"&sensor=false&key="+api_key+"&"; //random="+random+"&";
	var max_length=1600;
	var latLngBounds=map.getBounds();
	
	//route

	if(route)
	{
		static_map_url+="path=rgba:0xff0000ff,weight:3|";
    route_path=GDouglasPeucker(route.overview_path,getGroundResolution());
		$.each(route_path,function(i,e){
			var point=parseInt(e.lat()*1000000)/1000000+","+parseInt(e.lng()*1000000)/1000000+"|";
			if(static_map_url.length+point.length<max_length)
			{
				static_map_url+=point;
			}
			else
			{
				return false;
			}
		});
		static_map_url+="&";
	}
	
	//polyline
	
	if(myPolylines.length>0)
	{	
		
		for(i=0;i<myPolylines.length;i++)
		{
			var polyline=myPolylines[i];
			
			static_map_url+="path=rgba:0x"+polyline.strokeColor.substr(1,6)+d2h(polyline.strokeOpacity*255)+",weight:"+polyline.strokeWeight+"|";	
			$.each(polyline.getPath(),function(j,e){
				var point=parseInt(polyline.getPath().getAt(j).lat()*1000000)/1000000+","+parseInt(polyline.getPath().getAt(j).lng()*1000000)/1000000+"|";
				if(static_map_url.length+point.length<max_length)
				{
					static_map_url+=point;
				}
				else
				{
					return false;
				}
			});	
			static_map_url+="&";	
		}
		static_map_url+="&";
	}

	//polygon
	
	if(myPolygons.length>0)
	{	
		
		for(i=0;i<myPolygons.length;i++)
		{
			var polygon=myPolygons[i];
			
			static_map_url+="path=rgba:0x"+polygon.strokeColor.substr(1,6)+d2h(polygon.strokeOpacity*255)+",weight:"+polygon.strokeWeight+"|";	
			$.each(polygon.getPath(),function(j,e){
				var point=parseInt(polygon.getPath().getAt(j).lat()*1000000)/1000000+","+parseInt(polygon.getPath().getAt(j).lng()*1000000)/1000000+"|";
				if(static_map_url.length+point.length<max_length)
				{
					static_map_url+=point;
				}
				else
				{
					return false;
				}
			});	
			static_map_url+="&";	
		}
		static_map_url+="&";
	}

	if(myPOIMarkers.length>0)
	{
		static_map_url+="markers=";
		$.each(myPOIMarkers,function(index,element){
			if(latLngBounds.contains(element.position))
			{
				var color="";
				var static_map_marker_color=["black", "brown", "green", "purple", "yellow", "blue", "gray", "orange", "red", "white", "ylw" /* yellow*/];
				$.each(static_map_marker_color,function(i,c){
				if(element.icon)
				{
					if(element.icon.indexOf(c)>0)
					{
						color=c;
						return false;
					}
				}
				});

				if(color=="ylw")
				{
					color="yellow";
				}
				if(color=="")
				{
					color="white";
				}

				marker=element.position.lat()+","+element.position.lng()+","+"small"+color+"|";

				if(static_map_url.length+point.length<max_length)
				{
					static_map_url+=marker;
				}
				else
				{
					return false;
				}
			}
		});
	}

	console.log(static_map_url);
	if($("#static_map_preview")[0].src!=static_map_url)
	{
		$("#loading").show();
		$("#map_loading").show();
		$("#map_loaded").hide();
		$("#error").hide();

		clearInterval(staticMapLoadingCheck);	
		var loadtime=0;
		staticMapLoadingCheck=setInterval(function(){
			console.log("loading time: "+loadtime+" sec");
			loadtime++;
			if(loadtime>15)
			{
				console.log("載入失敗!");
				clearInterval(staticMapLoadingCheck);
				$("#loading").hide();
				$("#map_loaded").show();
				$("#map_loading").hide();
				$("#error").show();
			}
		},1000);
		
		$("#static_map")[0].onload=function()
		{
			clearInterval(staticMapLoadingCheck);
			console.log("Static Map loaded.");
			$("#loading").hide();
			$("#map_loaded").show();
			$("#map_loading").hide();
			
		}
		$("#static_map_preview")[0].src=static_map_url;
		$("#static_map")[0].src=static_map_url;
	}

}
function clearMap()
{
	console.log("clearMap()");
	if(overlay){
	overlay.setMap(null);
		$.each(myPOIMarkers,function(index, element){element.setMap(null);});
		myPOIMarkers=[];
		myPOIs=[];
		$.each(myPrintedAreas,function(index, element){element.setMap(null);});
		$.each(myPolygons,function(index, element){element.setMap(null);});
		$.each(myPolylines,function(index, element){element.setMap(null);});
		myPrintedAreas=[];
		myPolygons=[];
		myPolylines=[];
		$("#start").empty();
		$("#end").empty();
	}
}

function showPrintedAreas()
{
	$.each(myPrintedAreas,function(index, element){element.setMap(map);});
}

function hidePrintedAreas()
{
	$.each(myPrintedAreas,function(index, element){element.setMap(null);});
}

function showPolygons()
{
	$.each(myPolygons,function(index, element){element.setMap(map);});
}

function hidePolygons()
{
	$.each(myPolygons,function(index, element){element.setMap(null);});
}

function showPolylines()
{
	$.each(myPolylines,function(index, element){element.setMap(map);});
}

function hidePolylines()
{
	$.each(myPolylines,function(index, element){element.setMap(null);});
}

function drawMap()
{
	console.log("drawMap()");
	overlay = new textOverlay(map);

	//Directions
	directionsService = new google.maps.DirectionsService();
	var strokeColor = {strokeColor: "#ff0000"};
	var visible = false;
	var DirectionsRendererOptions = {
		polylineOptions: strokeColor,
		markerOptions: visible
	};
	directionsDisplay = new google.maps.DirectionsRenderer(DirectionsRendererOptions);

	directionsDisplay.setMap(map);

	// console.log(myPOIs); 
	for(i=0;i<myPOIs.length;i++)
	{
		 $("#start").append('<option value="'+myPOIs[i].lat+','+myPOIs[i].lng+'">'+myPOIs[i].name+'</option>');
		 $("#end").append('<option value="'+myPOIs[i].lat+','+myPOIs[i].lng+'">'+myPOIs[i].name+'</option>');
	}
	
	$("#my_printed_areas > option").remove();
	
	if(myPrintedAreas.length>0)
	{
		for(i=0;i<myPrintedAreas.length;i++)
		{
			 $("#my_printed_areas").append('<option value="'+i+'">'+myPrintedAreas[i].name+'</option>');
		}
	}else
	{
		$("#my_printed_areas").append('<option value="" >沒有紀錄</option>');
	}
	
	//Markers

	for(i=0;i<myPOIs.length;i++)
	{
		var LatLng= new google.maps.LatLng(myPOIs[i].lat ,myPOIs[i].lng);
		var myPOIMarker = new google.maps.Marker({
			id: i,
			position: LatLng,
			description: myPOIs[i].description,
			map: map,
			icon: myPOIs[i].icon, //"blank.png",
			title: myPOIs[i].name 
		});
		myPOIMarkers.push(myPOIMarker);
	}

	$.each(myPOIMarkers,function(i,e){e.setVisible(false);});

	//Polygons
	showPolygons();
	
	showPolylines();
	
	fitMap();

	google.maps.event.addListener(map, 'tilesloaded', function() { 
		$("#loading").hide();
		$("#map_loaded").show();
		$("#map_loading").hide();
	});

	google.maps.event.addListener(map, 'idle', function() {
	//reset routing combobox
	/*
	$("#start").empty();
	$("#end").empty(); 
	var latlngbounds=map.getBounds();
	$.each(myPOIMarkers,function(index,value){
	var myPOIMarker=myPOIMarkers[index];
	if(latlngbounds.contains(myPOIMarker.position))
	{
		$("#start").append('<option value="'+myPOIMarker.position.lat()+','+myPOIMarker.position.lng()+'">'+myPOIMarker.title+'</option>');
		$("#end").append('<option value="'+myPOIMarker.position.lat()+','+myPOIMarker.position.lng()+'">'+myPOIMarker.title+'</option>');
	}
	
	});
	*/
	//Weather
	/*
	if(weatherLat!=(map.getCenter().lat()*1000000+"").split(".")[0])
	{
		weatherLat=(map.getCenter().lat()*1000000+"").split(".")[0];
		weatherLng=(map.getCenter().lng()*1000000+"").split(".")[0];
		var weather_uri="proxy.php?proxy_url="+encodeURIComponent("http://www.google.com/ig/api?hl=zh-tw&weather=,,,"+weatherLat+","+weatherLng);
		
		$.ajax({
		  url: weather_uri,
		  success: function(data) {
			console.log("weather");
		    console.log(data);
			w=data;
		    console.log($(data).find("current_conditions condition").attr("data"));
			console.log($(data).find("current_conditions temp_c").attr("data"));
			console.log($(data).find("current_conditions humidity").attr("data"));
			console.log("http://img0.gmodules.com"+$(data).find("current_conditions icon").attr("data"));
		  }
		});
	}  
	*/
	//static map
	getStaticMap();	
	});
}

function toggleLine()
{
	if($("#line").css("display")=="none")
	{
		$("#line").show();;
	}
	else
	{
		$("#line"	).hide();;
	}
	
}
 
function fitMap()
{
	var latlngbounds = new google.maps.LatLngBounds();
	$.each(myPOIMarkers,function(index,value){
		latlngbounds.extend(myPOIMarkers[index].position);
	});
	map.fitBounds(latlngbounds);
}

function fitPrintedArea()
{
	console.log("fitPrintedArea()");
	var latlngbounds = new google.maps.LatLngBounds();
	var latLngs=myPrintedAreas[parseInt($("#my_printed_areas").val())].latLngs.getAt(0);
	$.each(latLngs,function(index,element){
		latlngbounds.extend(latLngs.getAt(index));
	});
	map.fitBounds(latlngbounds);
	map.setZoom(map.getZoom()+1);
}

function textOverlay(map) {

	// Now initialize all properties.
	// this.bounds_ = bounds;

	//this.image_ = image;
	this.map_ = map;
	this.bounds_=map.getBounds();
	// We define a property to hold the image's
	// div. We'll actually create this div
	// upon receipt of the add() method so we'll
	// leave it null for now.
	this.div_ = null;

	// Explicitly call setMap on this overlay
	this.setMap(map);
}
 
textOverlay.prototype.onAdd = function() {

// Note: an overlay's receipt of add() indicates that
// the map's panes are now available for attaching
// the overlay to the map via the DOM.

// Create the DIV and set some basic attributes.


	var div = document.createElement('DIV');
	div.style.border = "none";
	div.style.borderWidth = "0px";
	div.style.position = "absolute";


	// Create an IMG element and attach it to the DIV.

	 /*
	var img = document.createElement("img");
	img.src = this.image_;
	img.style.width = "100%";
	img.style.height = "100%";
	div.appendChild(img);
	  */
 
	 /*  custom text
	var txt = document.createElement("div");
	txt.innerHTML = "Hotel"
	txt.style.width = "100%";
	txt.style.height = "100%";
	div.appendChild(txt);
	 */
 
	// Set the overlay's div_ property to this DIV
	this.div_ = div;

	// We add an overlay to a map via one of the map's panes.
	// We'll add this overlay to the overlayImage pane.
	var panes = this.getPanes();
	panes.overlayImage.appendChild(this.div_);
}

textOverlay.prototype.draw = function() {
	$(".nameLabel").remove();
	$(".printableMarker").remove();
	// Size and position the overlay. We use a southwest and northeast
	// position of the overlay to peg it to the correct position and size.
	// We need to retrieve the projection from this overlay to do this.
	var overlayProjection = this.getProjection();

	// Retrieve the southwest and northeast coordinates of this overlay
	// in latlngs and convert them to pixels coordinates.
	// We'll use these coordinates to resize the DIV.
	var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

	// Resize the image's DIV to fit the indicated dimensions.
	var div = this.div_;
	div.style.left = sw.x + 'px';
	div.style.top = ne.y + 'px';
	div.style.width = (ne.x - sw.x) + 'px';
	div.style.height = (sw.y - ne.y) + 'px';
	//  div.style.backgroundColor="red";
  
	for(i=0;i<myPOIs.length;i++)
	{
		var loc= overlayProjection.fromLatLngToDivPixel(new google.maps.LatLng( myPOIs[i].lat , myPOIs[i].lng));
		if(document.getElementById('myPOI'+i)!=null)
		{
			document.getElementById('myPOI'+i).parentNode.removeChild(document.getElementById('myPOI'+i));
		}
		var markerDiv = document.createElement("div");
		markerDiv.id='myMarker'+i;
		markerDiv.className="printableMarker";
		div.appendChild(markerDiv);
		markerDiv.innerHTML = "<img src='"+myPOIs[i].icon+"'>";
		markerDiv.style.padding = "0px";
		markerDiv.style.opacity = 1;
		markerDiv.style.position="absolute";
		markerDiv.style.left = loc.x-sw.x-16 + "px";
		markerDiv.style.top = loc.y-ne.y-34 + "px";
		
		/*
		var placenameDiv = document.createElement("div");
		placenameDiv.id='myPOIname'+i;
		placenameDiv.className="nameLabel";
		div.appendChild(placenameDiv);
		
		placenameDiv.innerHTML = myPOIs[i].name;
		placenameDiv.style.webkitBorderRadius = "5px";
		//placenameDiv.style.padding = "3px";
		placenameDiv.style.fontSize = "16px";
		placenameDiv.style.fontWeight = "bold";
		placenameDiv.style.fontSize = "16px";
		placenameDiv.style.webkitTextStroke = "1px #FFFFFF";
		placenameDiv.style.color = "#000";
		//placenameDiv.style.border = "2px solid orange";
		placenameDiv.style.opacity = 0.8;
	//	placenameDiv.style.backgroundColor = "white";
		// placenameDiv.style.textShadow= "1px 1px 1px #000";
		placenameDiv.style.position="absolute";
		placenameDiv.style.margin = "10px";
		console.log('$(".nameLabel:eq('+i+')").width(): '+$(placenameDiv).width());
		placenameDiv.style.left = loc.x-sw.x +10+ "px";
		placenameDiv.style.top = loc.y-ne.y -30 + "px";
		*/
		
		var markerDiv = document.createElement("div");
		markerDiv.id='myMarker'+i;
		markerDiv.className="printableMarker";
		div.appendChild(markerDiv);
		
		var labelCanvas=document.createElement("canvas");
		labelCanvas.setAttribute("width",myPOIs[i].name.length*13+"px");
		labelCanvas.setAttribute("height","13px");
	//	labelCanvas.style.width="200px";
	//	labelCanvas.style.height="20px";
		labelCanvas.id='myPOIname'+i;
		labelCanvas.className="nameLabel";
		div.appendChild(labelCanvas);
		
		var context=document.getElementById('myPOIname'+i).getContext("2d");
		context.textBaseline="top";
		context.textAlign = "left";
		context.fillStyle="#000000";
	//	context.fillRect(0,0,20,20);
		context.strokeStyle="#F3F781";
		context.lineWidth=5;
		context.font = "13px sans-serif";
		context.strokeText(myPOIs[i].name,0,0);
		
		context.strokeStyle="#FFFFFF";
		context.lineWidth=2;
		context.font = "13px sans-serif";
		context.strokeText(myPOIs[i].name,0,0);
		
		context.fillText(myPOIs[i].name,0,0);
		labelCanvas.style.position="absolute";
		labelCanvas.style.left = loc.x-sw.x+16+ "px";
		labelCanvas.style.top = loc.y-ne.y-34 + "px";
	}
	/*
	$(".nameLabel").mousedown(function(event){this.setAttribute("px")=event.pageX;this.setAttribute("py")=event.pageY});
	$(".nameLabel").mousemove(function(event){
		this.style.left=parseInt(this.style.left.split("px"[0]))+event.pageX-this.getAttribute("px");
		this.style.top=parseInt(this.style.top.split("px"[0]))+event.pageY-this.getAttribute("py");
		});
		*/
	
	//	console.log($("nameLabel:eq("+i+")").collidesWith(".nameLabel").length>0);
	/*
	$(".nameLabel").each(function(i,e){
		var pos=0;
		while($(e).collidesWith(".nameLabel").length>0)
		{
			pos++;
		
			switch (pos){
				case 1:
					$(e).animate({top:"+=17"},1);
					break;	
				case 2:
					$(e).animate({top:"-=17"},1);
					$(e).animate({left:"-="+(32+$(e).width()-24)},1);
					break;
				case 3:
					$(e).animate({top:"+=17"},1);
					break;
				case 4:
					$(e).animate({top:"-=51"},1);
					$(e).animate({left:"+="+$(e).width()/2},1);
					break;
				case 5:
					$(e).animate({top:"+=51"},1);
					break;
				default:
					break;
			}
		}
	});
	*/
}
   
textOverlay.prototype.onRemove = function() {
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;

	// $(".printableMarker").remove();
/*
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;
	this.setMap(null);*/
}
  
 
// Note that the visibility property must be a string enclosed in quotes
textOverlay.prototype.hide = function() {
	if (this.div_) {
		this.div_.style.visibility = "hidden";
	}
}

textOverlay.prototype.show = function() {
	if (this.div_) {
		this.div_.style.visibility = "visible";
	}
}

textOverlay.prototype.toggle = function() {
	if (this.div_) {
		if (this.div_.style.visibility == "hidden") {
			this.show();
		} else {
			this.hide();
		}
	}
}

textOverlay.prototype.toggleDOM = function() {
	if (this.getMap()) {
		this.setMap(null);
	} else {
		this.setMap(this.map_);
	}
}
  
function calcRoute() {
	console.log("calcRoute()");
	directionsDisplay.setMap(null);
	var start=new google.maps.LatLng(document.getElementById("start").value.split(",")[0],document.getElementById("start").value.split(",")[1]);
	var end=new google.maps.LatLng(document.getElementById("end").value.split(",")[0],document.getElementById("end").value.split(",")[1]);
	var mode=eval("google.maps.DirectionsTravelMode."+document.getElementById("travel_mode").value);
	console.log(start+","+end);
	var request = {
		origin: start, 
		destination: end,
		unitSystem: google.maps.DirectionsUnitSystem.METRIC,
		travelMode: mode
	};
	directionsService.route(request, function(response, status) {
		directionsDisplay.setMap(map);
		switch(status){
			case google.maps.DirectionsStatus.OK:
				directionsDisplay.setDirections(response);
				route = response.routes[0];
				//console.log(response.routes);
				document.getElementById("route").innerHTML=route.legs[0].distance.text+" "+route.legs[0].duration.text;
				break;
			
			case google.maps.DirectionsStatus.NOT_FOUND:
				alert("找不到資料");
				break;
				
			case google.maps.DirectionsStatus.ZERO_RESULTS:
				alert("沒有路徑");
				break;
				
			default:
				
		}
		
		/*
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			route = response.routes[0];
			//console.log(response.routes);
			document.getElementById("route").innerHTML=route.legs[0].distance.text+" "+route.legs[0].duration.text;
		}*/
		
	});
}

function codeAddress() {
	var address = document.getElementById("address").value;
	if (geocoder) {
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				var marker = new google.maps.Marker({
					map: map, 
					position: results[0].geometry.location
				});
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
}

function checkKeycode() {
	if (event.keyCode == 13)
	{
		jumpTo($('#jump_location').val());
	}
}

function setMapSize(width,height)
{
	var latLng=map.getCenter();
	$("#map_canvas").css("width",width+"px");
	$("#map_canvas").css("height",height+"px");
	$("#fold").css("width",width/2+"px");
	$("#fold").css("height",height/2+"px");
	google.maps.event.trigger(map, 'resize');
	map.setCenter(latLng);
	$("#paper_canvas").css("width",width+"px");
	$("#line").css("width",width+"px");
	$("#line").css("margin-top", width*-1.5+"px");
	getStaticMap();
}

function setMapSizeToDefault()
{
	$("#map_canvas")[0].style.width="100%";
	$("#map_canvas")[0].style.height="92%";
}

function updatePrintMap()
{
	console.log("updatePrintMap()");
  $("#line").hide();
	hidePrintedAreas();
	if(printmap_container)
	{
		printmap_container.remove();
	}
	//getStaticMap();
	var myOptions ={
		navigationControl: false,
		mapTypeControl: false,
		scaleControl: false,
		streetViewControl: false,
		disableDoubleClickZoom: true
	}
	map.setOptions(myOptions);	

	//var timeout=setTimeout(function(){
	printmap_container=$('#map_canvas').clone().appendTo('#print_map_canvas');
	
	
	$("#print_map_canvas .nameLabel").each(function(i,e){
		
		var context=$(e)[0].getContext("2d");
		context.textBaseline="top";
		context.textAlign = "left";
		context.fillStyle="#000000";
	//	context.fillRect(0,0,20,20);
		context.strokeStyle="#F3F781";
		context.lineWidth=5;
		context.font = "13px sans-serif";
		context.strokeText(myPOIs[i].name,0,0);

		context.strokeStyle="#FFFFFF";
		context.lineWidth=2;
		context.font = "13px sans-serif";
		context.strokeText(myPOIs[i].name,0,0);

		context.fillText(myPOIs[i].name,0,0);
		
		//$(e).css("cursor","");
		
	});
	
	$("#print_map_canvas .nameLabel").easydrag();
	$("#print_map_canvas .nameLabel").ondrop(function(e, element){
		 console.log(element.getAttribute("id")); 
		console.log("left: "+$(element).css("left")); 
		console.log("to: "+$(element).css("top")); 
	});
	
	var myOptions ={
		navigationControl: true,
		mapTypeControl: true,
		scaleControl: true,
		streetViewControl: true,
	    disableDoubleClickZoom: true
	}
	map.setOptions(myOptions);
//	showPrintedAreas();
	//},500);
	//clearTimeout(timeout);
}

function gotoSection(index)
{
	index=parseInt(index);
	$("#section"+currentSection).hide();
	$("#section"+currentSection+"_button").removeClass("active_section");
	$("#section"+index).show();
	$("#section"+index+"_button").addClass("active_section");
	$("#error").hide();

	switch(index)
	{
		case 1: // Intro
		break;
		
		case 2: //Select Maps and zone
		google.maps.event.trigger(map, 'resize');

		break;
		
		case 3: // Prnt
	//	google.maps.event.trigger(map, 'resize');
	
		break;
		
		case 4: // Cut and Fold
		break;
	}
	
	currentSection=index;
}
//	
function d2h(d) {
	return d.toString(16);
}
	
function h2d(h) {
	return parseInt(h,16);
}

// Call function once the client has loaded
google.setOnLoadCallback(onGoogleDataLoad);

