var zoomValue;
var latlng;
var myOptions;
var geocoder;
var map;
var path = null;
var markerN = 2; // マーカーが何種類あるか
var markerColor16 = []; // マーカーの色の配列（16進数）
var formValues = [];  // フォームに書かれた地名を格納する配列（カンマ区切りで分割される前）
var markerPlaceList = []; // マーカーを立てたい地名文字列を格納する配列
var markerList = []; // マーカーオブジェクトそのものが格納される配列
var formFilled = false; // フォームに値が一つでもあるかどうか
var mapExists = false; // マップが作られているかどうか
var noAlert = false; // trueの時はアラートを出さない
  
  function invisibleAllMarker() {
	for (var i = 0; i < markerList.length; i ++) {
	  markerList[i].setVisible(false);
	}
	markerList.length = 0;
	markerList = [];
  }

  function initMarker() {
	invisibleAllMarker();
	markerPlaceList.length = 0;
	markerPlaceList = [];
    for (var i = 0; i < markerN; i ++) {
	  markerPlaceList[i] = [];
	}
	markerColor16[0] = "FF776D";
	markerColor16[1] = "00CCFF";
  }
  
  function initPath() {
	if (path != null) {
	  path.setOptions({strokeOpacity: 0});
	  path.setMap(null);
	}
	path = new google.maps.Polyline({
	  strokeColor: "#0000FF",
	  strokeOpacity: 0.5,
	  strokeWeight: 5
	});
  }
  
  function init() {
    initMarker();
	initPath();
  }
  
  function initialize() {
    init();
	
	var zoomValueText = $("#zoomDefaultValHidden").val();
	if (zoomValueText=="") {
	  zoomValue = 5;
	} else {
	  zoomValue = parseInt(zoomValueText);
	}
	latlng = new google.maps.LatLng(51.5, 0.0);
    myOptions = {
      zoom: zoomValue,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false // added on SEP/07/2011 nta
    }
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	mapExists = true;
	changeZoom(zoomValue);
  }
  
  // マーカーオブジェクトを作って返す（msgは吹き出しのメッセージ、countは番号）
  function myMarker(msg, markerColor, count) {
    var marker = createPintypeMarkerIcon({map:map, position:latlng, title:msg},{fillColor:markerColor, letter:String(count)});
	google.maps.event.addListener(marker, 'click', function() {
		var infoWindow = new google.maps.InfoWindow();
		infoWindow.setContent(msg);
		infoWindow.open(map, marker);
	});
	return marker;
  }
  
  // 受け取った地名をジオコーディングして得た座標にマーカーを立てる
  function addPlaceAddress(placeAddress, msg, color, count) {
	var time = 100;
	time += 200 * count;
	time += 5000 * (count / 10);
	
	// Geocordingの間隔を空けないと、OVER_QUERY_LIMITエラーが発生する
	setTimeout(function(){
		geocoder.geocode({ 'address': placeAddress }, function (results, status) {
		  if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			latlng = results[0].geometry.location;
			markerList[count-1] = myMarker(msg, color, count);
		  } else if (!noAlert) {
			if (status == "ZERO_RESULTS") {
			  alert("Geocode was not successful for the following reason: " + status + "（" + placeAddress + "は存在しない住所である可能性があります）");
			} else {
			  alert("Geocode was not successful for the following reason: " + status);
			}
		  }
		});
	}, time);
  }

  // フィールドの地名（カンマ区切りされててもOK）を配列に格納
  function makePlaceArray(i, place) {
	var placeArray = place.split(",");
	for (var j = 0; j < placeArray.length; j ++) {
	  if (placeArray[j] != "") {
		markerPlaceList[i].push(placeArray[j]);
	  }
	}
  }

  function makeMarker() {
	var msg;
	var count;
	// マーカー作成開始
	for (var i = 0; i < markerN; i ++) {
	  for (var j = 0; j < markerPlaceList[i].length; j ++) {
		msg = markerPlaceList[i][j];
		count = j+1;
		addPlaceAddress(markerPlaceList[i][j], msg, markerColor16[i], count);
	  }
	}
  }
  
  function drawPolyline() {
	var signal = true;
	var markerPositions = [];
	for (var i = 0; i < markerList.length; i ++) {
	  if (markerList[i]) {
		markerPositions[i] = markerList[i].getPosition();
	  } else {
		if (i != 0 && markerList[i-1]) {markerPositions[i] = markerPositions[i-1];}
		else if (markerList[i+1]) {markerPositions[i] = markerList[i+1].getPosition();}
		else {markerPositions[i] = map.getCenter(); signal = false;}
	  }
	}
	path.setPath(markerPositions);
	path.setMap(map);
	return signal;
  }
  
  function changeZoom(zoomVal) {
	zoomValue = zoomVal;
	$("#zoomDefaultVal").text("現在のズームデフォルト値："+zoomValue);
	$("#zoomDefaultValHidden").val(zoomValue);
	map.setZoom(zoomVal);
  }
  
  function refreshMarkerListText() {
	var comment = [];
	for (var i = 0; i < markerN; i ++) {
	  comment[i] = "マーカー#"+markerColor16[i]+"：";
	}
	var comment_join = "";
	for (var i = 0; i < markerN; i ++) {
	  for (var j = 0; j < markerPlaceList[i].length; j ++) {
		comment[i] += ""+(j+1)+"-"+markerPlaceList[i][j]+", ";
	  }
	}
	for (var i = 0; i < markerN; i ++) {
	  comment_join += comment[i];
	}
	$("#markerPlaceList").text(comment_join);
  }
  
  function getFormValue() {
	for (var i = 0; i < markerN; i ++) {
	  formValues[i] = [];
	}
	// フォームの値を読み込む（赤マーカー）
	for (var i = 1; i < 21; i++) {
	  if ($("#products_schedule_map_"+i).val()) {
		formValues[0][i-1] = $("#products_schedule_map_"+i).val();
		noAlert = false;
	  } else if ($("input[name='products_schedule_map_"+i+"']").val()) {
		formValues[0][i-1] = $("input[name='products_schedule_map_"+i+"']").val();
		noAlert = true;
	  }
	  if (formValues[0][i-1] && formFilled == false) {formFilled = true;}
	}
	// フォームの値を読み込む（青マーカー）
//	for (var i = 0; i < 4; i++) {
//	  formValues[1][i] = $('#placeSetTextBlue'+i).val();
//	  if (formValues[0][i-1] != "" && formFilled == false) {formFilled = true;}
//	}
  }

  function hideMap() {
	var divMapCanvas = document.getElementById("map_canvas");
	if (divMapCanvas.style.display != "none") {
		divMapCanvas.style.display = "none";
	}
  }
  function showMap() {
	var divMapCanvas = document.getElementById("map_canvas");
	if (divMapCanvas.style.display != "") {
		divMapCanvas.style.display = "";
	}
  }

  // ボタンクリック時の処理
  $(function () {
	// ズーム率の変更
	$('#changeZoomButton').click(function () {
	  var zoomVal = $('#changeZoomValue').val();
	  if (mapExists) {
		changeZoom(parseInt(zoomVal));
	  } else {
		$("#zoomDefaultVal").text("Googleマップが作成されていません。");
	  }
	});
	
	// マーカー作成ボタン
	$('#placeSetButton').click(function () {
	  init();
	  var timer = new Cost();
	  
	  getFormValue();
	  if (formFilled && !mapExists) {
		initialize();
		showMap();
	  }
	  
	  if (mapExists) {
		for (var i = 0; i < markerN; i ++) {
		  for (var j = 0; j < formValues[i].length; j ++) {
			if (formValues[i][j]) {
			  // フィールドから地名を読み込み
			  makePlaceArray(i, formValues[i][j]);
			}
		  }
		}
		// マーカーを作成
		makeMarker();
		// ポリラインを作成
		var tempLength = 0;
		var noChangeCount = 0;
		var interval = setInterval(function () {
			var signal = drawPolyline();
			if (tempLength != markerList.length) {
				noChangeCount = 0;
				tempLength = markerList.length;
			} else {
				noChangeCount += 1;
			}
			$("#timeCount").text("起動時間："+timer.getCurrent());
			if (noChangeCount > 10 && tempLength != 0) {
				timer._End();
				$("#timeCount").text("起動時間："+timer.Total+"（終了）");
				clearInterval(interval);
			}
			if (!signal) {
				timer._End();
				$("#timeCount").text("起動時間："+timer.Total+"（異常終了）");
				clearInterval(interval);
			}
		}, 200);
		
		// 表示マーカー一覧を更新
		refreshMarkerListText();
	  } else {
		$("#markerPlaceList").text("Googleマップ用地名を入力してください。");
	  }
	});
  });

  $(function () {
	// 最初にフォームの値があるかどうかを確認
	getFormValue();
	if (formFilled) {
	  initialize();
	  $("#placeSetButton").click();
	} else {
	  hideMap();
	}
  });

/*
****時間計測関数(完全版)の使い方****

var foo = new Cost();
でオブジェクトを生成し、この瞬間から時間計測が開始されます。
・全体の時間計測の終了は foo._End(); で終わります。この処理を実行すると、開始時からの時間がTotalに代入されます。
・再スタートしたい場合、foo._ReStart(); で計測を再開、Total時間はそのままです。
・foo._Refresh(); でTotal時間を0に戻し、計測もこの瞬間から0秒で開始されます。ラップタイムは操作しません。
・foo.isStopはfoo._End();が最後に実行されている場合、trueを返します。

・オブジェクト生成の瞬間に、ラップタイム計測もスタートします。
・foo._Lap_s(); でラップタイムの計測を開始します。
・foo._Lap_e(); でラップタイムの計測を終了します。

・Totalタイムはfoo.Totalで取り出し、ラップタイムはfoo.lap_timeで取り出せます。

・foo.isCostでtrueを返します。
・foo.typeで"cost"を返します。

*/

function Cost()
{
	var new_Times = new Date;
	this.isCost = true;
	this.isStop = false;
	this.type = "cost";
	this.Start = new_Times.getTime();
	this.End = this.Start;
	this.Total = 0;
	
	this.lap_sta = this.Start;
	this.lap_end = 0;
	this.lap_time = 0;
}


// 高際拡張
Cost.prototype.getCurrent = function() {
	var new_Times = new Date;
	var current = new_Times.getTime();
	return current - this.Start;
}

Cost.prototype._End = function()
{
	var new_Times = new Date;
	this.End = new_Times.getTime();
	this.Total += this.End-this.Start;
	this.isStop = true;
}

Cost.prototype._ReStart = function()
{
	var new_Times = new Date;
	this.Start = new_Times.getTime();
	this.End = this.Start;
	this.isStop = false;
}
Cost.prototype._Refresh = function()
{
	var new_Times = new Date;
	this.isStop = false;
	this.Start = new_Times.getTime();
	this.End = this.Start;
	this.Total = 0;
}


Cost.prototype._Lap_s = function()
{
	var new_Times = new Date;
	this.lap_sta = new_Times.getTime();
	this.lap_end = 0;
	this.lap_time = 0;
}


Cost.prototype._Lap_e = function()
{
	var new_Times = new Date;
	this.lap_end = new_Times.getTime();
	this.lap_time = this.lap_end-this.lap_sta;
}

