var map = null;
var geocoder = null;
var stores = null;
var areas = null;
var markers = null;

var read_ids =[];
var no_refresh = false;

var byZip=false;
var byZip2=false;

function initialize(is_test) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("Contact_Map"),{size:new GSize(639,380)});

		var centerLatLng = new GLatLng(35.694003, 139.753595);
		//var centerLatLng = new GLatLng(35.6575141821702, 139.74730610847473);
	
		map.setCenter(centerLatLng,15);
		//map.setUIToDefault();
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
		
		//event
		GEvent.addListener(map, 'moveend', onMove)
		
	}
	geocoder = new GClientGeocoder();
	/*
	console.log("N"+ (45+(33/60)+(28/3600)));
  console.log("S"+ (20+25/60+31/3600));
  console.log("W"+ (153+59/60+11/3600));
  console.log("E"+ (122+56/60+01/3600));
  */
}

var need_resize=true;
var selected_city_id = 0;

function showMap(){
	byZip=false;
	need_resize=true;
	
	var address;
	//zip
/*
	if($('form_zip1') && $('form_zip2') && $('form_zip1').value.length >0 && $('form_zip2').value.length >0){
	  address = $('form_zip1').value+'-'+$('form_zip2').value;

  	$('beforemap').style.display = 'none';
  	$('aftermap').style.display = 'block';

	}else{
*/
  	//validation
  	if( $('form_pref_id').value.length < 1 ){
  		alert('都道府県は必須です');
  		return false;
  	}
  	if( $('form_city_id').value == 0 ){
  			alert('市町村区は必須です');
  			return false;
  	}
  	/*
  	if( $('form_address').value == 0 ){
  			alert('住所は必須です');
  			return false;
  	}
  	*/
  	$('beforemap').style.display = 'none';
  	$('aftermap').style.display = 'block';

  	address = ($('form_pref_id').value ? $('form_pref_id').options[$('form_pref_id').selectedIndex].text : '');
    /*
    	if (typeof window.console != 'object'){
    		window.console = {log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},assert:function(){},dir:function(){},dirxml:function(){},trace:function(){},group:function(){},groupEnd:function(){},time:function(){},timeEnd:function(){},profile:function(){},profileEnd:function(){},count:function(){}};
    	}
    */
    	if($('form_city_id').value){
    		var city =$('form_city_id').options[$('form_city_id').selectedIndex].text;
    		if(city == '糸島市') city = '糸島';
    		else if(city=='名古屋市中区') city+=' ';
    		else if(city=='那須塩原市') city='那須塩原 ';		
    		address += city;	
    	}
    	address += $('form_address').value;

    	//console.log(address);
    	if(address == '愛媛県宇和島市三間町') address += '務田';
    	else if(address == '愛媛県西予市城川町') address += '下相';
    	else if(address == '愛媛県西予市野村町') address += '野村';
    	else if(address == '山梨県南巨摩郡富士川町') address = '山梨県南巨摩郡 富士川町';
	//}
	//console.log(address);
	
	
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address +
              " \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002");
        } else {
          //console.log(point);
        	map.setCenter(point, 14);
					//onMove();
        }
      }
    );
  }
	
	/* obj = document.getElementById("aftermap2");
	y = obj.offsetTop;
	scrollTo(0,y);
	*/
	
	a_pos = $('aftermap2').positionedOffset();
	scrollTo(0,a_pos[1]);
	return false;
	
}

function showMapByZip(){
	byZip=true;
	byZip2=true;
	
	need_resize=true;
	var address;

	//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;
	}
	
	  address = $('form_zip1').value+'-'+$('form_zip2').value;
  	$('beforemap').style.display = 'none';
  	$('aftermap').style.display = 'block';
  	
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point || (point.x<122.9336 || point.x>153.9864 || point.y<20.4252 || point.y>45.5578)) {
          //alert(address +" \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002");
          alert('該当するエリアが見つかりません。');
        } else {
          //console.log(point +":"+point.x);
        	map.setCenter(point, 14);
					//onMove();
        }
      }
    );
  }
	
	/* obj = document.getElementById("aftermap2");
	y = obj.offsetTop;
	scrollTo(0,y);
	*/
	
	a_pos = $('aftermap2').positionedOffset();
	scrollTo(0,a_pos[1]);
	return false;
	
}

function onMove(){

	if(no_refresh ){
		no_refresh = false;
		return;
	}
	
	var z = map.getZoom();
	if(z<13) return;

	var centerLatLng = map.getCenter();

  var bounds=map.getBounds();
  var sw=bounds.getSouthWest();
  var ne=bounds.getNorthEast();

	var url = '/estore/shops/search/'+(byZip||byZip2?'zip/':'')+(sw.lat()+'').replace('.','_')+'/'+(sw.lng()+'').replace('.','_')+'/'+(ne.lat()+'').replace('.','_')+'/'+(ne.lng()+'').replace('.','_')+'/';
	if(need_resize) url += $('form_city_id').value+'/';

	//zip
	if(!byZip) byZip2=false;
	byZip = false;
	
	var ajax = new Ajax.Request(
				url, 
				{
					method: 'get', 
					onComplete: showStores
				});
}

function showStores(ajax_response){
	
	map.clearOverlays();
	
	var json = ajax_response.responseText;
	markers　=new Array();

	var data = eval('(' + json + ')');
	stores = data['stores'];
	
	var tablesource='';
	if(stores){
		$('nodata').style.display = 'none';

		tablesource = '<table border="0" cellspacing="0" cellpadding="0" class="shop-result-table" id="estoretable">';
		tablesource +='<thead style="display:none;">		<tr>	<th>1</th><th>2</th><th>3</th><th>4</th></tr>	</thead>';
	
		for(var i=0;i<stores.length;i++){
					
			markers[ stores[i].id ] = createMarker(stores[i]);
			map.addOverlay(markers[ stores[i].id ]);
			
			//table
			tablesource +='<tr class="'+( i%2==0 ? 'odd':'even' )+'">';
			tablesource +='<th scope="row" class="id-number"><a href="#" onclick="showStoreBaloon('+stores[i].id+');return false;">'+ stores[i].id +'</a></th>';
			tablesource +='<td class="shop-name"><a href="#" onclick="showStoreBaloon('+stores[i].id+');return false;">'+ stores[i].name +'</a></td>';
			tablesource +='<td class="shop-address">'+ stores[i].address +'</td>';
			tablesource +='<td class="shop-telnum">'+ stores[i].telnum +'</td>';
			tablesource +='</tr>';
			
		}
		
		tablesource +='</table>';
		
		tablesource +='<div id="estore_pager" class="estore_pager">';
		tablesource +='<form>';
		tablesource +='	<img src="/images/pager/first.png" class="first"/>';
		tablesource +='	<img src="/images/pager/prev.png" class="prev"/>';
		//	tablesource +='	<input type="text" class="pagedisplay"/>';
	
		tablesource +='	<span class="pagedisplay" id="pagedisplay">-&nbsp;-</span>';
		
		tablesource +='	<img src="/images/pager/next.png" class="next"/>';
		tablesource +='	<img src="/images/pager/last.png" class="last"/>';
		tablesource +='	<select class="pagesize" style="display:none;">';
		tablesource +='		<option selected="selected"  value="5">5</option>';
		tablesource +='		<option value="10">10</option>';
		tablesource +='	</select>';
		tablesource +='</form>';
		tablesource +='</div>';
		
	}else{
		$('nodata').style.display = 'block';	
	}
	
	$('tableview').innerHTML= tablesource;

	pagenate('estoretable');
	
	if(need_resize){
		if(data['zoom']){
			map.setZoom(data['zoom']);
			need_reseize = false;
		}
	}
	
	need_resize=false;
	
	//show area government
	areas = data['areas'];
		
		tablesource='';
    if(areas){
		  tablesource = '<table border="0" cellspacing="0" cellpadding="0" class="shop-result-table" id="estoretable2">';
		  tablesource += '<thead ><tr id="t2_global_title"><th colspan="2"><strong>ケーブルテレビ、光回線テレビの連絡先</strong></th></tr>';
		  //tablesource += '<tr id="t2_column_title">	<th>対応エリア</th><th>事業者名</th><th>電話番号</th><th>&nbsp;</th></tr>	</thead>';
	    
		  for(var i=0;i<areas.length;i++){
		   	//table
		  	tablesource +='<tr class="'+( i%2==0 ? 'odd':'even' )+'">';
		  	//tablesource +='<th scope="row" class="id-number">'+areas[i].area_description+'</th>';
			tablesource +='<td style="width:40%"><strong>'+ areas[i].name +'</strong><p>'+ areas[i].telnum +'</p><img src="/images/common/estore/'+areas[i].category+'.gif"></td>';
		  	//tablesource +='<td class="nowrap">'+ areas[i].telnum +'</td>';
		  	tablesource +='<td style="width:60%">'+ areas[i].description +'&nbsp;</td>';
		  	//tablesource +='<td><img src="/images/common/estore/'+ areas[i].category +'.gif"></td>';
		  	tablesource +='</tr>';
		  	
		  }
		  tablesource +='</table>';
	  }else{
	  }
		//if(is_test)	$('tableview2').innerHTML= tablesource;
		$('tableview2').innerHTML= tablesource;
		
	/*
	
	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);
		
		
	}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';
	}
	*/
}

function pagenate(elementid){
	$j("#estoretable") 
		.tablesorter({widthFixed: true, widgets: ['zebra']}) 
		.tablesorterPager({container: $j("#estore_pager")});
	
}

function createMarker(store){
	var marker = new GMarker( new GLatLng(store.latitude, store.longitude),{title: store.name } );
	var sid = store.id;
	
	marker.id = sid;
	GEvent.addListener(marker,"click", function(){
		no_refresh = true;
		showStoreBaloon(sid);
	});
	return marker;
}

function showStoreBaloon(id){
	//alert("showStoreBaloon "+id);
	
	var store=null;
	
	if(stores)
		for(var i=0;i<stores.length;i++){
			if(markers)
				markers[stores[i].id].closeInfoWindow();

			if(stores[i].id == id){
				store = stores[i];
				break;
			}
		}
	if(!store)	return;
	no_refresh= true;
	
	if(!store.photo) store.photo = 'b.gif';
	
	var str = '<div class="baloon_title"><b>'+ store.name +'<!-- 電器店名が入ります --></b></div>'+
	'<div class="baloon_outer"><div class="clearfix"><div class="baloon_img"><img src="/uploads/shop/'+store.photo+'"><!-- 店舗画像が入ります。 --></div>'+
		'<div class="baloon_left">'+
			'<div class="baloon_inner">〒'+ store.zip +'<!-- 郵便番号が入ります。 --><br/>'+
				store.address +'<!-- 住所が入ります --><br/>'+
				store.telnum  +'<!-- 電話番号が入ります。 --><br/>'+
				'<!-- <a href="mailto:'+ store.email+'" >' + store.email +'</a> --> <!-- メールアドレスが入ります。 --> <!-- <br/> -->'+
				'<a href="'+ store.url+'" target="_blank">' + store.url +'</a><!-- URLが入ります。 -->';
	if(store.baloon_description) str +='<p>' + store.baloon_description + '</p>'
	str+=			
			'</div>' +
		'</div>' +
		'</div>' +
		'<br style="clear:both;">'+
	'</div>' +
	'<img src="/images/common/estore/'+store.category+'.gif" /><!-- 店舗区分画像 --> ';
	if(store.sell) str += '<img src="/images/common/estore/sell.gif" /> ';
	if(store.construction) str += '<img src="/images/common/estore/construction.gif" /><!-- 販売・工事画像 -->';
	if(store.service) str += '<img src="/images/common/estore/service.gif" /><!-- 販売・工事画像 -->';

	markers[stores[i].id].openInfoWindowHtml( str );
	
	/* obj = document.getElementById("aftermap2");
	y = obj.offsetTop;
	scrollTo(0,y);
	*/
	
	a_pos = $('aftermap2').positionedOffset();
	scrollTo(0,a_pos[1]);
	return false;
}

function submitStop(e){
    if (!e) var e = window.event;
 
    if(e.keyCode == 13){
			showMap();
			return false;
		}
}


