var map;
var select_damkmlall;
var select_damkmllim;
var selarea = null;  // 地域選択のSELECT
var sellayer = null; // レイヤ選択

var layer_damkmlall = null;
var layer_damkmllim = null;

var lock_layerchange = false;


Rococo.init.push(init);


function init_page() {
  var e;
  e = document.getElementById('legend');
  if( e ) {
    e.innerHTML = '<img src="c16x16w.gif" alt="[白玉]" width="16" height="16" />:欠測等 <img src="c16x16r.gif" alt="[赤玉]" width="16" height="16" />:-50 <img src="c16x16y.gif" alt="[黄玉]" width="16" height="16" />:-80  <img src="c16x16b.gif" alt="[青玉]" width="16" height="16" />:80-';
  }
  e = document.getElementById('map');
  if( e ) {
    e.style.width='100%';
    e.style.height='30em';
    e.style.borderStyle='solid';
    e.style.borderColor='rgb(153,153,153)'; // # 999
    e.style.borderWidth='1px';
    e.style.backgroundColor='rgb(221,238,255)'; // #def;
  }
}

function init() {
  init_page();

//	  maxExtent: new OpenLayers.Bounds(-180,-90,180,90),
//	  maxExtent: new OpenLayers.Bounds(122.0,22.0,149.0,46.0),
  var options = {
	  maxResolution:1.40625/2,
	  controls: [
		  new Rococo.ola.Control.PanZoomBar(), //OpenLayers -> Rococo.ola
		  new OpenLayers.Control.LayerSwitcher(),
		  new OpenLayers.Control.Navigation(),
		  new OpenLayers.Control.Permalink(),
		  new OpenLayers.Control.Attribution({displayClass: 'prmtcd'})
		],
	  numZoomLevels: 17
    }

  map = new OpenLayers.Map('map',options);

  map.div.style.backgroundColor = 'rgb(221,238,255)';

  var kibanwms = new OpenLayers.Layer.WMS(
	  "KIBAN 25000 WMS",
	  "http://www.finds.jp/ws/kiban25000gwc.cgi?",
	  {
	    layers: "kiban25000:AllT",
	    format: "image/png"
	  },
	  {
	    attribution: '<a target=\"_blank\" href="http://www.finds.jp/wsdocs/kibanwms/index.html">基盤地図情報(平20業使、第449号)</a>',
	    isBaseLayer: true
	  }
	);

//  var kibanwms = new OpenLayers.Layer.WMS(
//	  "KIBAN 25000 WMS",
//	  "http://www.finds.jp/ws/kiban25000wms.cgi?",
//	  {
//	    layers: "AdmArea,PrefSmpl,JpSmpl,BldA,Cntr10,Cntr100,WL,RdEdg,RailCL",
//	    format: "image/png"
//	  },
//	  {
//	    attribution: '<a target=\"_blank\" href="http://www.finds.jp/wsdocs/kibanwms/index.html">基盤地図情報(平20業使、第449号)</a>',
//	    isBaseLayer: true
//	  }
//	);


  layer_damkmlall = new OpenLayers.Layer.Vector("ダム貯水",
	{
	  projection: map.displayProjection,
	  visibility: false,
	  strategies: [new OpenLayers.Strategy.Fixed()],
	  protocol: new OpenLayers.Protocol.HTTP({
		  url: "http://"+document.location.hostname+"/kml/damimp.kml",
		  format: new OpenLayers.Format.KML({
			  extractStyles: true,
			  extractAttributes: true
			})
		})
	});

  layer_damkmllim = new OpenLayers.Layer.Vector("ダム貯水(欠測等非表示)",
	{
	  projection: map.displayProjection,
	  visibility: true,
	  strategies: [new OpenLayers.Strategy.Fixed()],
	  protocol: new OpenLayers.Protocol.HTTP({
		  url: "http://"+document.location.hostname+"/kml/damimplim.kml",
		  format: new OpenLayers.Format.KML({
			  extractStyles: true,
			  extractAttributes: true
			})
		})
	});

  var pnwms = new OpenLayers.Layer.TMS(
	  "地名",
	  "http://www.finds.jp/ws/tmc/",
	  {
		  layername: 'pntms-4326',
		  type: 'png',
		  isBaseLayer: false
	  },
	  {
	    isBaseLayer: false
	  }
	);
/*
  var pnwms = new OpenLayers.Layer.WMS.Untiled(
	  "都道府県・市区町村名",
	  "http://www.finds.jp/ws/pnwms.cgi?",
	  {
	    layers: "PrefName,MncplName,AzaName",
	    styles: "largeborder,mediumborder,smallborder",
	    format: "image/png"
	  },
	  {
	    attribution: '<a target="_blank" href="http://www.finds.jp/wsdocs/mnwms/index.html">自治体名WMS配信サービス</a>',
	    ratio: 1,
	    isBaseLayer: false
	  }
	);
*/
  map.addLayers([kibanwms,pnwms,layer_damkmlall,layer_damkmllim]);
  if(!map.getCenter()) {
    map.setCenter(new OpenLayers.LonLat(139, 37), 4);
//    map.setCenter(new OpenLayers.LonLat(133.39, 34.5), 7);
  }

  map.events.on({"changelayer": function(){ onChangeLayer();}});

  select_damkmlall = new OpenLayers.Control.SelectFeature(layer_damkmlall);
  layer_damkmlall.events.on({
	  "featureselected": onFeatureSelect,
	  "featureunselected": onFeatureUnselect
	});
  map.addControl(select_damkmlall);
  select_damkmlall.activate();   

  select_damkmllim = new OpenLayers.Control.SelectFeature(layer_damkmllim);
  layer_damkmllim.events.on({
	  "featureselected": onFeatureSelect,
	  "featureunselected": onFeatureUnselect
	});
  map.addControl(select_damkmllim);
  select_damkmllim.activate();   

  // -------- #submenu の作成
  var div_sc = document.getElementById('shortcut');
  if( div_sc != null ) {
    var frm_sc = document.createElement('form');
    var div = Rococo.tk.em.createElement('div');
    // レイヤ選択: 本体
    sellayer = div.createChild('sellayer','select',null, { list: [
	  Rococo.tk.preset.emptyline_string, // ''
	  {'text': '表示しない'       , 'value':  'FF'},
	  {'text': '欠測等非表示' , 'value':  'FT'},
	  {'text': 'すべて表示'   , 'value':  'TF'}
	] } );
    sellayer.addEventHandler('change',function(){onSelectLayer();});
    div.setChild('sellayer',sellayer);

    // 地域選択: 標題
    var span = document.createElement('span');
    span.className = 'leftpadding';
    span.appendChild(document.createTextNode('地域選択 '));
    div.appendChild(span);
    // 地域選択: 本体
    selarea = div.createChild('selarea','select',null, { list: [
	  Rococo.tk.preset.emptyline_integer,
	  {'text': '北海道'        , 'value':  '1'},
	  {'text': '東北北部'      , 'value':  '2'},
	  {'text': '東北南部・新潟', 'value':  '3'},
	  {'text': '関東'          , 'value':  '4'},
	  {'text': '北陸・長野'    , 'value':  '5'},
	  {'text': '東海'          , 'value':  '6'},
	  {'text': '近畿'          , 'value':  '7'},
	  {'text': '中国四国'      , 'value':  '8'},
	  {'text': '九州'          , 'value':  '9'},
	  {'text': '沖縄'          , 'value': '10'},
	  Rococo.tk.preset.emptyline_integer,
	  {'text': '全国'          , 'value': '11'}
	] } );
    selarea.addEventHandler('change',function(){onSelectArea();});
    div.setChild('selarea',selarea);

    frm_sc.appendChild(div);
    div_sc.appendChild(frm_sc);
  }

  // 初期状態を反映させる
  onChangeLayer();

}

//
arr_area = [
	{zoom:7, lat:43.38306, lon:142.15445 },
	{zoom:8, lat:40.19702, lon:140.9075  },
	{zoom:8, lat:37.70862, lon:139.61661 },
	{zoom:8, lat:36.06068, lon:139.61661 },
	{zoom:8, lat:36.32984, lon:136.87003 },
	{zoom:8, lat:35.46192, lon:137.36441 },
	{zoom:8, lat:34.71485, lon:135.96914 },
	{zoom:8, lat:34.26441, lon:132.79272 },
	{zoom:7, lat:32.3418 , lon:130.69159 },
	{zoom:9, lat:26.51081, lon:128.02328 },
	{zoom:5, lat:37      ,      lon:139}
];

function onChangeLayer() {
  if( lock_layerchange ) {
    return;
  }

  // sellayerのセット
  var s =
 	  (layer_damkmlall.getVisibility() ? 'T' : 'F') +
	  (layer_damkmllim.getVisibility() ? 'T' : 'F');
  if( sellayer && sellayer.getValue() != s ) {
    sellayer.setValue(s);
  }
}

function onSelectLayer() {
  var ll = sellayer.getValue();
  if( ll == null || ll == '' ) {
    return;
  }
  // 現状
  var bNAll = layer_damkmlall.getVisibility();
  var bNLim = layer_damkmllim.getVisibility();
  // 比較
  var bCAll = ( (ll.charAt(0) == 'T') ^ bNAll );
  var bCLim = ( (ll.charAt(1) == 'T') ^ bNLim );

  lock_layerchange = true;
  if( bCAll ) {
    layer_damkmlall.setVisibility(!bNAll);
  }
  if( bCLim ) {
    layer_damkmllim.setVisibility(!bNLim);
  }
  lock_layerchange = false;
}


function onSelectArea() {
  var ac = selarea.getValue();
  if( ac >= 1 && ac <= arr_area.length) {
    var zll = arr_area[ac-1];
    if( zll != null ) {
      map.setCenter(new OpenLayers.LonLat(zll['lon'],zll['lat']),zll['zoom'],false,false);
    }
  }
}

function onPopupClose(evt) {
  select_damkmlall.unselectAll();
  select_damkmllim.unselectAll();
}

function onFeatureSelect(event) {
  var feature = event.feature;

  var content = "<h2>"+feature.attributes.name + "</h2>" + feature.attributes.description;
  if (content.search("<script") != -1) {
    content = "Content contained Javascript! Escaped content below.<br />" + content.replace(/</g, "&lt;");
  }
  popup = new OpenLayers.Popup.FramedCloud(
	  "damimpcloud", 
	  feature.geometry.getBounds().getCenterLonLat(),
	  new OpenLayers.Size(260,300),
	  content,
	  null,
	  true,
	  onPopupClose
	);
  popup.autoSize = false;
  feature.popup = popup;
  map.addPopup(popup);
}

function onFeatureUnselect(event) {
  var feature = event.feature;
  if(feature.popup) {
    map.removePopup(feature.popup);
    feature.popup.destroy();
    delete feature.popup;
  }
}

// -------- Android
function init_android() {
  if( Rococo.and.isAndroid() ) {
    var div = map.div;
    div.style.position = 'absolute';
    div.style.left = "0";
    div.style.right = "0";
    div.style.top = "0";
    div.style.bottom = "0";
    div.style.height = "auto";
    div.style.margin = "0";
    div.style.padding = "0";

    var legend = document.getElementById("legend");
    legend.style.position = 'absolute';
    legend.style.left = "0";
    legend.style.bottom = '36px';
    legend.style.width = '100%';
    legend.style.height = '36px';
    legend.style.background = '#ffffff';
    legend.style.fontSize = '18px';
    legend.style.zIndex = '0';

    var shortcut = document.getElementById("shortcut");
    shortcut.style.position = 'absolute';
    shortcut.style.left = "0";
    shortcut.style.bottom = '0';
    shortcut.style.width = '100%';
    legend.style.height = '36px';
    shortcut.style.background = '#ffffff';
    shortcut.style.fontSize = '18px';
    shortcut.style.zIndex = '0';

    var arr_hitokoto = document.getElementsByClassName('hitokoto');
    var len_hitokoto = arr_hitokoto == null ? 0 : arr_hitokoto.length;
    for( var n = 0; n < len_hitokoto; n++ ) {
      if( arr_hitokoto[n] != null ) {
        arr_hitokoto[n].style.visibility = 'hidden';
      }
    }

    map.updateSize();
    var e = map.layerContainerDiv;
    if( e != null && e.addEventListener != null ) {
      Rococo.ola.recreateElement(e);
    }
  }
}

Rococo.init.push(init_android);
