var map = null;
var geocoder = null;

var read_ids= [];
var draw_layers= [];
var map_directions = [];
var repeater_image_url="http://wavemap.digisuppo.jp/images/direction/repeater.gif";

var is_oneshot=true;

function initialize(is_test) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("Contact_Map"),{size:new GSize(639,500)});

		var centerLatLng = new GLatLng(35.694003, 139.753595);
		//var centerLatLng = new GLatLng(35.6575141821702, 139.74730610847473);
	
		map.setCenter(centerLatLng,15);
		map.setUIToDefault();

		//event
		if(is_test== 1)GEvent.addListener(map, 'moveend', addLayerTest)
		else GEvent.addListener(map, 'moveend', addLayerTest)
		
		$('Contact_Map').insert($('direction'));
		
		repeaterIcon = new GIcon(G_DEFAULT_ICON);
    repeaterIcon.image = repeater_image_url;
		repeaterIcon.iconSize = new GSize(45,98);
		markerOptions = { icon:repeaterIcon };
		
	}
	geocoder = new GClientGeocoder();
	
	
	$('zip_ok').hide();
  $('zip_ng').hide();
  
}

function addLayer(){
	var centerLatLng = map.getCenter();
	//if(window.console) console.log('moveend X:'+ escape(centerLatLng.x) + ' Y: ' + escape(centerLatLng.y) );

	var url_cid = '/cityid2map/' + $('form_city_id').value + '/';
	var url_latlon = '/latlon2map/' + (''+centerLatLng.x).replace('.','_') + '/' + (''+centerLatLng.y).replace('.','_') + '/';

	var url;
	if(is_oneshot) url = url_cid;
	else url = url_latlon;

	//if(window.console) console.log('URL:' + url);
	var ch = $F('form_station_id');
	//if(window.console) console.log('ch:' + ch);
	if(ch) url +=ch +  '/';
	//alert(url);
	is_oneshot=false;
	
	var ajax = new Ajax.Request(
				url, 
				{
					method: 'get', 
					onComplete: showMap
				});
}

function addLayerTest(){
	var centerLatLng = map.getCenter();
	//if(window.console) console.log('moveend X:'+ escape(centerLatLng.x) + ' Y: ' + escape(centerLatLng.y) );

	var url_cid = '/index.php/cityid2map/' + $('form_city_id').value + '/';
	var url_latlon = '/index.php/latlon2map/' + (''+centerLatLng.x).replace('.','_') + '/' + (''+centerLatLng.y).replace('.','_') + '/';

	var url;
	if(is_oneshot) url = url_cid;
	else url = url_latlon;

	//if(window.console) console.log('URL:' + url);
	var ch = $F('form_station_id');
	//if(window.console) console.log('ch:' + ch);
	if(ch) url +=ch +  '/';
	//alert(url);
	is_oneshot=false;
	
	var ajax = new Ajax.Request(
				url, 
				{
					method: 'get', 
					onComplete: showMap
				});
}
function showMap(ajax_response){
	
	var json = ajax_response.responseText;

	var layer = eval('(' + json + ')');
	if(!layer.id){
		$('mapstatus').innerHTML= '<strong> この地域のデータはありません</strong>';
		
	}else if(! read_ids.contains(layer.id)){
		var pointSW = new GLatLng(layer.north,layer.east);
		var pointNE = new GLatLng(layer.south,layer.west);

		var groundOverlay = new GGroundOverlay(
			layer.url, 
			new GLatLngBounds(pointSW, pointNE));

		map.addOverlay(groundOverlay);

		read_ids.push(layer.id);
		draw_layers.push(groundOverlay);
		$('mapstatus').innerHTML='';
		
		$('repeater_description').innerHTML = "中継局: "+layer.repeater_name;
		
		/*
		console.log('MAP URL:' + layer.url);
		console.log('N:' + layer.north);
		console.log('S:' + layer.south);
		console.log('E:' + layer.east);
		console.log('E:' + layer.west);
		*/
	}else{
		$('mapstatus').innerHTML='';
	}
	
	if(layer.id && layer.repeater_latitude && layer.repeater_longitude){
    map.addOverlay(new GMarker(new GLatLng(layer.repeater_latitude,layer.repeater_longitude) , markerOptions));		
	}else	if(layer.id && $('direction_img')){
		//console.log("DD"+layer.direction);
		$('direction_img').src= 'http://wavemap.digisuppo.jp/images/direction/'+layer.direction+'.gif';
	}
}


if( ! Array.prototype.contains ){
	Array.prototype.contains = function( value ){
		for(var i in this){
			if( this.hasOwnProperty(i) && this[i] === value){
				return true;
			}
		}
		return false;
	}
}

function resetLayer(){
	//if(window.console)	console.log('reset'+ draw_layers.length);
	for(var i in draw_layers){
		map.removeOverlay(draw_layers[i]);
	}
	draw_layers=[];
	read_ids=[];
}

function showAddress() {
	
	//validation
	if( $('form_pref_id').value.length < 1 ){
		alert('都道府県は必須です');
		return false;
	}
	if( $('form_city_id').value == 0 ){
			alert('市町村区は必須です');
			return false;
	}
	if( $('form_station_id').value == 0 ){
			alert('放送局名は必須です');
			return false;
	}
	
	is_oneshot=true;
	resetLayer();
	address = ($('form_pref_id').value.length>0 ? $('form_pref_id').options[$('form_pref_id').selectedIndex].text : '')
	 			+ ($('form_pref_id').value.length>0 ? $('form_city_id').options[$('form_city_id').selectedIndex].text : '')
				+ $F('form_address');
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address +
              " \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002");
        } else {
        	map.setCenter(point, 15);
//        var marker = new GMarker(point);
//        map.addOverlay(marker);
//        marker.openInfoWindowHtml(address + "(" + point.lat() + "," + point.lng() + ")");
        }
      }
    );
  }

//  obj = document.getElementById('resultmap');
//  y = obj.offsetTop;
//  scrollTo(0,y);
	window.location.hash  ='resultmap';
	return false;
}




function showAddressByZip() {
	
	
	$('zip_ok').hide();
	$('zip_ng').hide();
	
	//zip
	if( $('form_zip1').value.length < 1  ||  $('form_zip2').value.length < 1){
		alert('郵便番号を入力してください。');
		return false;
	}

	if( $('form_zip1').value.length != 3 ||  $('form_zip2').value.length != 4 ){
		alert('郵便番号は３桁-４桁で正しく入力してください。');
		return false;
	}
	
	if( !Number($('form_zip1').value)  || !Number($('form_zip2').value)){
		alert('郵便番号が間違っています。');
		return false;
	}

	var zip = ''+$('form_zip1').value+$('form_zip2').value;

  var data;
  var ajax = new Ajax.Request('/test.php/zip2pref/'+zip+'/',
    {
      "method":"get",
      onSuccess: function(request){
        eval("data="+request.responseText);
        
        if(!data){
          //alert('郵便番号が間違っています。');
          $('zip_ng').show();
          return false;
        }
        
        $('form_pref_id').value=data['pid'];
        
        if(data['pid']<0){
          //alert('郵便番号が間違っています。');
          $('zip_ng').show();
          return false;
        }
        
        new Ajax.Request( '/test.php/city_combo/', {method: 'get', asynchronous:false, evalScripts:true, parameters:'pid=' + $F('form_pref_id'),

          onSuccess: function(request){
            Element.update('city_combobox',request.responseText);
            $('form_city_id').value=data['cid'];
            
            new Ajax.Updater('station_combobox', '/test.php/station_combo/', {method: 'get',asynchronous:false, evalScripts:true, parameters:'cid=' + $F('form_city_id')});
            
            new Ajax.Updater('repeater_description', '/test.php/repeaterdescript/'+$F('form_city_id')+'/'+$F('form_station_id')+'/', {asynchronous:true, evalScripts:true});
            
          }
        });
        $('zip_ok').show();
      }
    
    });


	return false;
}

