﻿var map;
var formMaker = null;
var mode = 0;
var mode1HTML = '<p><form method="post" action="php/new_report.php" enctype="multipart/form-data" name="report_form" id="report_form" onsubmit="return send.reportFormCheck()"><input type="hidden" name="lat" id="lat" /><input type="hidden" name="lng" id="lng" /><input type="hidden" name="zoom" id="zoom" />投稿者名<br /><input type="text" maxlength="24" name="name" id="name" /><br />ラベル（魚種名・風景名）<br /><input type="text" maxlength="24" name="label" id="label" /><br />コメント (800文字以内)<br /><textarea wrap="physical" name="coment" id="coment"></textarea><br />画像<select name="photo_num_select" id="photo_num_select" onchange="photoNumChange(this.value);"><option value="1">1枚</option><option value="2">2枚</option><option value="3">3枚</option><option value="4">4枚</option><option value="5">5枚</option></select>（各200kB以内）<br /><input type="hidden" name="MAX_FILE_SIZE" value="1024000" /><div id="photo_selects"><input type="file" name="photo_select[]" class="photo_select" /></div><br />撮影日時（24h表記）<br /><input type="text" maxlength="4" name="photo_year" id="photo_year" />年<input type="text" maxlength="2" name="photo_month" id="photo_month" />月<input type="text" maxlength="2" name="photo_day" id="photo_day" />日<input type="text" maxlength="2" name="photo_hour" id="photo_hour" />時<br />全長（風景の場合は0cm）<br /><input type="text" maxlength="3" name="fish_length" id="fish_length" />cm<input type="submit" value="書き込む" name="submit" id="submit" /></form></p>';
var mode2HTML = '<p><form method="post" action="php/new_link.php" name="link_form" id="link_form" onsubmit="return send.linkFormCheck()"><input type="hidden" name="lat" id="lat" /><input type="hidden" name="lng" id="lng" /><input type="hidden" name="zoom" id="zoom" />URL<br /><input type="text" maxlength="64" name="site_url" id="site_url" /><br />タイトル<br /><input type="text" maxlength="24" name="site_name" id="site_name" /><br /><input type="submit" value="書き込む" name="submit" id="submit" /></form></p>';
var mode3HTML = '<p><form method="post" action="php/new_point.php" name="point_form" id="point_form" onsubmit="return send.pointFormCheck()"><input type="hidden" name="lat" id="lat" /><input type="hidden" name="lng" id="lng" /><input type="hidden" name="zoom" id="zoom" />魚種名<br /><input type="text" maxlength="64" name="fish_name" id="fish_name" /><br /><input type="submit" value="書き込む" name="submit" id="submit" /></form></p>';

var param = {
	init: function() {
		var randam = [
			{x: 140.462651, y: 35.536871, z: 15, t: 'm', place: '片貝漁港'},
			{x: 140.430272, y: 35.498771, z: 17, t: 'k', place: '真亀川河口'},
			{x: 140.420165, y: 35.476049, z: 16, t: 'h', place: '堀川河口'},
			{x: 140.533075, y: 35.609476, z: 16, t: 'h', place: '屋形漁港'},
			{x: 140.737953, y: 35.690938, z: 15, t: 'h', place: '飯岡漁港'},
			{x: 140.839620, y: 35.703973, z: 16, t: 'h', place: '銚子マリーナ'},
			{x: 140.868813, y: 35.707519, z: 17, t: 'h', place: '犬吠崎'},
			{x: 140.859811, y: 35.746251, z: 16, t: 'h', place: '銚子漁港'},
			{x: 140.405102, y: 35.450375, z: 16, t: 'h', place: '南白亀川河口'},
			{x: 140.391927, y: 35.391989, z: 15, t: 'm', place: '一宮川河口'},
			{x: 140.401958, y: 35.329945, z: 17, t: 'm', place: '太東岬漁港'},
			{x: 140.406218, y: 35.254241, z: 15, t: 'm', place: '大原漁港'},
			{x: 140.307684, y: 35.144336, z: 14, t: 'm', place: '勝浦'},
			{x: 140.311203, y: 35.146442, z: 16, t: 'm', place: '勝浦漁港'},
			{x: 140.252860, y: 35.132141, z: 16, t: 'm', place: '興津'},
			{x: 140.190139, y: 35.121839, z: 15, t: 'h', place: '内浦湾'},
			{x: 140.151944, y: 35.120962, z: 15, t: 'h', place: '安房天津'},
			{x: 140.123234, y: 35.115486, z: 15, t: 'h', place: '鴨川'},
			{x: 140.100617, y: 35.076264, z: 16, t: 'm', place: '仁右衛門島'},
			{x: 140.015259, y: 35.034775, z: 16, t: 'h', place: '岩和田漁港'},
			{x: 139.965842, y: 34.956096, z: 16, t: 'h', place: '千倉港'},
			{x: 139.928205, y: 34.910376, z: 16, t: 'h', place: '乙浜漁港'},
			{x: 139.824307, y: 34.920194, z: 17, t: 'm', place: '布良'},
			{x: 139.848168, y: 34.988291, z: 16, t: 'm', place: '館山ポートマリーン'},
			{x: 139.847717, y: 35.024005, z: 16, t: 'm', place: '館山湾'},
			{x: 139.822150, y: 35.039932, z: 17, t: 'm', place: '富浦港'},
			{x: 139.826249, y: 35.110702, z: 17, t: 'h', place: '勝山漁港'},
			{x: 139.828202, y: 35.118759, z: 17, t: 'h', place: '勝山堤防'},
			{x: 139.836463, y: 35.131255, z: 17, t: 'h', place: '保田漁港'},
			{x: 139.820745, y: 35.164810, z: 17, t: 'h', place: '金谷漁港'},
			{x: 139.816743, y: 35.170406, z: 17, t: 'h', place: '金谷フェリー'},
			{x: 139.823020, y: 35.301257, z: 16, t: 'h', place: '新富津漁港'},
			{x: 139.828405, y: 35.330707, z: 15, t: 'h', place: '富津新港'},
			{x: 139.839478, y: 35.353076, z: 14, t: 'm', place: '小糸川'},
			{x: 139.881277, y: 35.376664, z: 15, t: 'k', place: '木更津沖提'},
			{x: 139.896169, y: 35.370365, z: 15, t: 'h', place: '木更津港'},
			{x: 139.963374, y: 35.449938, z: 15, t: 'h', place: '千葉港'},
			{x: 140.060771, y: 35.543253, z: 17, t: 'h', place: '養老川臨海公園'},
			{x: 140.069418, y: 35.550489, z: 16, t: 'h', place: '五井火力発電所北堤防'},
			{x: 140.104823, y: 35.596286, z: 15, t: 'h', place: 'ポートタワー周辺'},
			{x: 140.073709, y: 35.606440, z: 15, t: 'h', place: '稲毛海浜公園'},
			{x: 140.048883, y: 35.624826, z: 16, t: 'h', place: '検見川の浜'},
			{x: 140.035472, y: 35.639825, z: 15, t: 'h', place: '幕張の浜'},
			{x: 139.982986, y: 35.668872, z: 14, t: 'm', place: '船橋周辺'},
			{x: 139.944577, y: 35.684699, z: 15, t: 'h', place: '江戸川河口'},
			{x: 139.911060, y: 35.632117, z: 14, t: 'm', place: '浦安周辺'},
			{x: 139.864883, y: 35.631140, z: 14, t: 'm', place: '葛西臨海公園周辺'},
			{x: 139.833899, y: 35.624024, z: 14, t: 'h', place: '若洲海浜公園周辺'},
			{x: 139.783216, y: 35.662945, z: 15, t: 'm', place: '月島周辺'},
			{x: 139.799609, y: 35.654890, z: 14, t: 'm', place: '豊洲周辺'},
			{x: 139.780855, y: 35.661027, z: 15, t: 'm', place: '月島周辺'},
			{x: 139.783773, y: 35.626396, z: 14, t: 'm', place: 'お台場周辺'},
			{x: 139.800425, y: 35.594367, z: 14, t: 'm', place: 'ごみ処理センター周辺'},
			{x: 139.763775, y: 35.573077, z: 14, t: 'm', place: '昭和島周辺'},
			{x: 139.761543, y: 35.507496, z: 14, t: 'm', place: '川崎港周辺'},
			{x: 139.688158, y: 35.460670, z: 14, t: 'h', place: '大黒埠頭周辺'},
			{x: 139.687235, y: 35.428872, z: 17, t: 'h', place: '本牧海釣り施設'},
			{x: 139.646015, y: 35.337114, z: 15, t: 'h', place: '八景島シーパラダイス周辺'},
			{x: 139.699059, y: 35.279609, z: 15, t: 'h', place: '猿島周辺'},
			{x: 139.726181, y: 35.241974, z: 13, t: 'm', place: '久里浜周辺'}
		];
		param.get();
		if(!param.x || !param.y || !param.z) {
			var r = Math.floor(Math.random() * randam.length);
			param.x = randam[r].x;
			param.y = randam[r].y;
			param.z = randam[r].z;
			param.t = randam[r].t;
		} else {
			param.z = parseInt(param.z);
		}
		if(!param.id) param.id = null;
		if(param.t == 'k')
			param.t = G_SATELLITE_MAP;
		else if(param.t == 'h')
			param.t = G_HYBRID_MAP;
		else
			param.t = G_NORMAL_MAP;
	},
	get: function() {
		var lh = window.location.hash.substring(1).split('&');
		for(i = 0, t = Array; i < lh.length; i++) {
			t = lh[i].split('=');
			param[t[0]] = t[1];
		}
	},
	set: function(id) {
		param.t = map.getCurrentMapType().getUrlArg();
		param.x = map.getCenter().lng().toFixed(6);
		param.y = map.getCenter().lat().toFixed(6);
		param.z = map.getZoom();
		if(!id)
			param.id = null;
		else
			param.id = id
		var name = ['t', 'x', 'y', 'z', 'id'];
		var lh = '#';
		for(var i = 0; i < name.length; i++) {
			if(param[name[i]])
				lh += name[i] + '=' + param[name[i]] + '&';
		}
		if(lh.substr(lh.length - 1) == '&')
			lh = lh.substr(0, lh.length - 1);
		window.location.hash = lh;
	}
};


var point = {
  json: null,
  array: Array,
  lNum: 0,
  rNum: 0,
  pNum: 0,
  sum: 0,
  dl: function(){
    $('loading').style.display = 'block';
    json = null;
    point.remove();
    GDownloadUrl('php/points.php?keyword=' + encodeURIComponent($('keyword').value) + '&year=' + $('year').value + '&terms=' + $('terms').value + '&hour=' + $('hour').value + '&time=' + new Date().getTime(), function(data) {
      json = eval('(' + data + ')');
      if(json == null) {
        alert('読み込み失敗');
        $('total').innerHTML = 0;
      } else {
        $('total').innerHTML = json.points.length + json.links.length + json.reports.length;
        point.show();
      }
      $('loading').style.display = 'none';
    });
  },
  show: function() {
    if(json.points != null) {
      var jp = json.points;
      for(var i = 0; i < jp.length && this.pNum < 100; i++) {
        var gLatLng = new GLatLng(jp[i].y, jp[i].x);
        if(map.getBounds().contains(gLatLng)) {
          this.array[this.sum++] = new Label(gLatLng, jp[i].id, jp[i].fn, null, 'point');
          this.pNum++;
        }
      }
    }
    if(json.links != null) {
      var jl = json.links;
      for(var i = 0; i < jl.length; i++) {
        var gLatLng = new GLatLng(jl[i].y, jl[i].x);
        if(map.getBounds().contains(gLatLng)) {
          this.array[this.sum++] = new Label(gLatLng, null, jl[i].title, jl[i].url, 'link');
          this.lNum++;
	      $('info').innerHTML = '<p><a href="javascript:map.setCenter(new GLatLng(' + jl[i].y + ',' + jl[i].x + '), 16)">' + jl[i].title + '</a></p>' + $('info').innerHTML;
        }
      }
	  $('info').innerHTML = '<h3>リンク</h3>' + $('info').innerHTML;
    }
    if(json.reports != null) {
      var jr = json.reports;
      for(var i = 0; i < jr.length; i++) {
        var gLatLng = new GLatLng(jr[i].y, jr[i].x);
        if(map.getBounds().contains(gLatLng)) {
          var str = (jr[i].fl == 0) ? jr[i].label : jr[i].label + ' ' + jr[i].fl + 'cm';
          var type = (jr[i].fl == 0) ? 'scenery' : 'report';
          this.array[this.sum++] = new Label(gLatLng, jr[i].id, str, null, type);
          this.rNum++;
	      $('info').innerHTML = '<p><a href="javascript:javascript:windowOpen(' + jr[i].id + ')">' + str + '</a></p>' + $('info').innerHTML;
        }
      }
	  $('info').innerHTML = '<h3>釣果・風景</h3>' + $('info').innerHTML;
    }
    for(var i = 0; i < this.sum; i++)
      map.addOverlay(this.array[i]);
    $('visible').innerHTML = this.pNum + this.lNum + this.rNum;
  },
  remove: function() {
    for(var i = 0; i < this.sum; i++)
      map.removeOverlay(this.array[i]);
    this.array = new Array;
    this.lNum = this.rNum = this.pNum = this.sum = 0;
	$('info').innerHTML = '';
  }
}


var Label = function(point, id, str, url, type) {
  this.point = point;
  this.id = id;
  this.str = str;
  this.url = url;
  this._class = type; //識別子「class」はIEとSafaliで予約語の為、使用不可
}
Label.prototype = new GControl();
Label.prototype.initialize = function(map) {
  this.map = map;
  this.element = document.createElement('a');
  if(this._class == 'link') {
    this.element.href = this.url;
	this.element.title = 'このサイトへ行く';
	this.element.target = '_blank';
  } else if(this._class == 'point') {
    this.element.href = 'javascript:map.setCenter(new GLatLng(' + this.point.y + ',' + this.point.x + '), 16)';
	this.element.title = 'ここへズーム';
  } else {
    this.element.href = 'javascript:windowOpen(' + this.id + ')';
	this.element.title = '詳細を見る';
  }
  this.element.className = 'label ' + this._class;
  this.element.innerHTML = this.str;
  this.map.getPane(G_MAP_MAP_PANE).appendChild(this.element);
}
Label.prototype.redraw = function(force) {
  if(!force) return;
  var pixel = this.map.fromLatLngToDivPixel(this.point);
  this.element.style.left = pixel.x + 'px';
  this.element.style.top = pixel.y + 'px';
}
Label.prototype.remove = function() {
  this.element.parentNode.removeChild(this.element);
}


var cr = function() {}
cr.prototype = new GControl();
cr.prototype.initialize = function(map) {
  var span = document.createElement('span');
  span.id = 'copyright';
  span.innerHTML = '&copy 2008 fishing-map.net';
  map.getContainer().appendChild(span);
  return span;
}
cr.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(180, 4));
}


var windowOpen = function(id) {
  if(!id) return;
  $('loading').style.display = 'block';
  GDownloadUrl('php/report.php?id=' + id + '&time=' + new Date().getTime(), function(data) {
    var report = eval('(' + data + ')');
    if(report) {
      var tabs = new Array;
      tabs[0] = new GInfoWindowTab('詳細', '<div id="window"><a href="photo/' + report.id + '_0.jpg" class="highslide" onclick="return hs.expand(this)"><img src="photo/t_' + report.id + '_0.jpg" id="thumbnail"></a><div id="detail"><p id="date_time">' + report.dt + '</p><p>投稿者： <span id="from_name">' + report.name + '</span></p><p id="photo_date">' + report.photo_date + '時撮影</p><p><span id="from_title">' + report.label + '</span><span id="length"> ' + report.fish_length + '</span></p></div><div id="from_coment">' + report.coment + '</div></div>');
      if(report.photo_num > 1) {
        var photos = '';
        for(var i = 1; i < report.photo_num; i++) {
          photos += '<a href="photo/' + report.id + '_' + i + '.jpg" class="highslide" onclick="return hs.expand(this)"><img src="photo/t_' + report.id + '_' + i + '.jpg" id="thumbnail"></a>';
        }
        tabs[1] = new GInfoWindowTab('他の画像', photos);
      }
      map.openInfoWindowTabsHtml(new GLatLng(report.lat, report.lng), tabs, {maxWidth: 310});
      param.set(report.id);
    }
    $('loading').style.display = 'none';
  });
}


var send = {
  sending: false, //送信中true
  setValue: function(point) {
    $('lat').value = point.lat().toFixed(6);
    $('lng').value = point.lng().toFixed(6);
    $('zoom').value = map.getZoom();
  },
  check: function() {
    if(!this.sending) return true;
    alert('送信中です。しばらくお待ち下さい。\n\n(長時間送信中の場合は、ページを再読み込みして下さい。)');
    return false;
  },
  reportFormCheck: function() {
    this.check;

    var err = new String;

    if($('name').value.length < 2 || $('name').value.length > 8)
      err += '名前：2～8文字にして下さい。\n\n';

    if($('label').value.length < 2 || $('label').value.length > 8)
      err += 'ラベル：2～8文字にして下さい。\n\n';

    if($('fish_length').value.length == 0 || $('fish_length').value < 0 || $('fish_length').value > 255)
      err += '全長：半角で0～255にして下さい。\n\n';

    if($('photo_year').value < 1980 || $('photo_year').value > 2009)
      err += '年：半角で正しく入力して下さい。\n\n';

    if($('photo_month').value < 1 || $('photo_month').value > 12)
      err += '月：半角で正しく入力して下さい。\n\n';

    if($('photo_day').value < 1 || $('photo_day').value > 31)
      err += '日：半角で正しく入力して下さい。\n\n';

    if($('photo_hour').value.length == 0 || $('photo_hour').value < 0 || $('photo_hour').value > 23)
      err += '時刻：半角で0～23にして下さい。\n\n';

    if($('coment').value.length < 4 || $('coment').value.length > 800)
      err += 'コメント：4～800文字にして下さい。\n\n';

    return this.conf(err);
  },
  linkFormCheck: function() {
    this.check;

    var err = new String;

    if($('site_name').value.length < 2 || $('site_name').value.length > 8)
      err += 'サイト名：2～8文字にして下さい。\n\n';

    if(!$('site_url').value.match(/^http(s?):\/\/.+(\..+)+$/))
      err += 'URL：正しく入力して下さい。\n\n';

    return this.conf(err);
  },
  pointFormCheck: function() {
    this.check;

    var err = new String;

    if($('fish_name').value.length < 2 || $('fish_name').value.length > 8)
      err += '魚種名：2～8文字にして下さい。\n\n';

    return this.conf(err);
  },
  conf: function(err) {
    if(err != '') {
      alert(err);
      return false;
    }
    if(window.confirm('送信しますか？')) {
      this.sending = true;
      return true;
    } else {
      return false;
    }
  }
}


var mapPrefNavi = function(v) {
  v = v.split(',');
  mapPan(v[0],v[1]);
}
var mapPan = function(lat,lng) {
  map.panTo(new GLatLng(lat,lng));
}
var modeChange = function(m) {
  mode = m;
}
var modeCheck = function() {
  mode = $('mode').value;
}
var photoNumChange = function(v) {
  $('photo_selects').innerHTML = '';
  for(var i = 1; i <= v; i++)
    $('photo_selects').innerHTML += '<input type="file" name="photo_select[]" class="photo_select" />';
}
var serchOnclick = function() {
  point.dl();
  return false;
}
var toggle = function(id) {
  if($(id).style.display == 'block')
    $(id).style.display = 'none';
  else
    $(id).style.display = 'block';
}
var getHW = function() {
    var r = {'h': 0, w: 0}
	var ua = navigator.userAgent;
	var nHit = ua.indexOf("MSIE");
	var bIE = (nHit >=  0);
	var bVer6 = (bIE && ua.substr(nHit+5, 1) == "6");
	var bVer7 = (bIE && ua.substr(nHit+5, 1) == "7");
	var bStd = (document.compatMode && document.compatMode=="CSS1Compat");
	if (bIE) {
		if ((bVer6 && bStd) || bVer7) {
			r.h = document.documentElement.clientHeight;
			r.w = document.documentElement.clientWidth;
		} else {
			r.h = document.body.clientHeight;
			r.w = document.body.clientWidth;
		}
	} else {
		r.h = window.innerHeight;
		r.w = window.innerWidth;
	}
	return r;
}
var $ = function(e) {return document.getElementById(e);}

var resize = function() {
  $('map').style.height = getHW().h - 68 + 'px';
  $('map').style.width = getHW().w - 204 + 'px';
  $('right').style.height = getHW().h - 86 + 'px';
  $('contents').style.height = getHW().h - 286 + 'px';
  if(map) map.checkResize();
}

var init = function() {
  param.init();

  map = new GMap2($('map'));
  map.setCenter(new GLatLng(param.y, param.x), param.z, param.t);
  map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(4, 4)));
  map.addControl(new GMenuMapTypeControl(true, false), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(4, 4)));
  map.addControl(new GScaleControl(100));
  map.addControl(new GOverviewMapControl(new GSize(120, 120)));
  map.addControl(new cr());
  map.enableContinuousZoom();
  map.disableDoubleClickZoom();
  new GKeyboardHandler(map);

  resize();
  point.dl();
  hs.preloadImages();
  windowOpen(param.id);
  modeCheck();
  //GDownloadUrl('', function(data) {}

  GEvent.addListener(map, 'maptypechanged', function() {
    param.set();
  });
  GEvent.addListener(map, 'moveend', function() {
    point.remove();
    point.show();
    param.set(param.id);
  });

  GEvent.addListener(map, 'click', function(m, p) {
	if(formMaker != m) map.removeOverlay(formMaker);
    if(mode == 0) {
	  if(m) map.removeOverlay(m);
	  $('form').innerHTML = '';
	} else if(m) {
	} else {
	  switch(mode) {
	    case '1': $('form').innerHTML = mode1HTML; break;
	    case '2': $('form').innerHTML = mode2HTML; break;
	    case '3': $('form').innerHTML = mode3HTML; break;
		default: alert("defa");break;
      }	  
      formMaker = new GMarker(p, {draggable: true});
	  GEvent.addListener(formMaker, 'dragend', function() {send.setValue(formMaker.getPoint());});
      map.addOverlay(formMaker);
      send.setValue(formMaker.getPoint());
	}
  });

  GEvent.addListener(map, 'infowindowclose', function() {
    param.set();
  });

  $('serch').onsubmit = serchOnclick;
}

if(GBrowserIsCompatible()) {
  window.onload = init;
  window.onunload = GUnload;
  window.onresize = resize;
}