$(document).ready(function(){
  /*
   * rel=external
   */
  $("a[rel='external']").each(function(){
    $(this).attr('target', '_blank');
	});

	/*
	 * rollover
	 */
	var suffix = '_on';
	$('img.rlov', 'a').each(function() {
		var img = $(this);
		var src = img.attr('src');
		var src_on = src.substr(0, src.lastIndexOf('.')) + suffix + src.substring(src.lastIndexOf('.'));
		// preload
		$('<img>').attr('src', src_on);
		// hover event
		img.hover(
			function() {
				img.attr('src', src_on);
			},
			function() {
				img.attr('src', src);
			}
		);
	});
});

/*
 * 文字サイズ変更
 */
var sizeArry = ['13px', '14px', '15px', '16px', '17px', '18px', '19px'];
var curSize = 0;

var fsize = $.cookie('fsize');
if (fsize != null && fsize >= 0 && fsize <= 6){
	curSize = parseInt(fsize);
}
$(function(){
	$('body').css('font-size', sizeArry[curSize]);
});

function fontSizeInit(){
	curSize = 0;
  $('body').css('font-size', sizeArry[curSize]);
	$.cookie('fsize', null);
}
function fontSizeInc(){
	if (curSize == 6) return false;
	curSize = curSize + 1;
  $('body').css('font-size', sizeArry[curSize]);
	$.cookie('fsize', curSize, { expires: 30 });
  return false;
}

/*
 * jquery ui tabs
 */
function mkTabs(disabled_tabs,tl,keyword,cl,pl)
{
	$.ajaxSetup({cache: false, async: false});
  $('#tabcontainer-1').tabs({
		cache:true,
		spinner:'',
		load: function(event, ui) {
			// load後は強制select
	  	$('#tabcontainer-1').tabs('select', '#' + ui.panel.id);
	  }
	});
  $('#tabcontainer-2').tabs({cache:true, spinner:''});

	/*
	 * データがないタブの無効化
	 */
  if (disabled_tabs.length > 0){
		$('#tabcontainer-2').tabs('option', 'disabled', disabled_tabs);
	}
	/*
	 * 引数に応じてタブの切り替え
	 */
  if (tl != ""){
		restoreTidChecked(tl);
  }else if(keyword != ""){
    $('#tabcontainer-1').tabs('load', 1);
    $('body').data('keyword', keyword);
  }else if(cl != ""){
    $('#tabcontainer-1').tabs('load', 2);
		restoreCidChecked(cl);
  }else if(pl != ""){
    $('#tabcontainer-1').tabs('load', 3);
  }
}

/*
 * 選択肢の復元
 */
function restoreTidChecked(tids)
{
  var tid_arry = tids.split(',');
  for(i=0;i<tid_arry.length;i++){
		if (!tid_arry[i].match(/^[0-9]+$/)) continue;
		// チェック状態をレストア
		$('#tid_' + tid_arry[i]).attr("checked", "checked");
  }
}

function restoreCTidChecked(ctids)
{
  var ctid_arry = ctids.split(',');
  for(i=0;i<ctid_arry.length;i++){
		if (!ctid_arry[i].match(/^[0-9]+_[0-9]+$/)) continue;
		// チェック状態をレストア
		$('#ctid_' + ctid_arry[i]).attr("checked", "checked");
  }
}

function restorePTidChecked(ptids)
{
  var ptid_arry = ptids.split(',');
  for(i=0;i<ptid_arry.length;i++){
		if (!ptid_arry[i].match(/^[0-9]+_[0-9]+$/)) continue;
		// チェック状態をレストア
		$('#ptid_' + ptid_arry[i]).attr("checked", "checked");
  }
}

function restoreCidChecked(cids)
{
	if (cids == "" || cids == undefined) return true;
  var cid_arry = cids.split(',');
  for(i=0;i<cid_arry.length;i++){
		if (!cid_arry[i].match(/^[1-5]+$/)) continue;
		// チェック状態をレストア
		$('#cid_' + cid_arry[i]).attr("checked", "checked");
  }
}

function clearAllChecked(id)
{
	$("input[name!=ao]:checked", id).attr("checked", "");
}

function setTabPanelForm(tabid, frmclass, flg){
  $(frmclass).ajaxForm({
    target:tabid,
    success:function(responseText, statusText){
    	$('a.tabcontent', tabid).click(function() {
      	$(tabid).load(this.href);
      	return false;
    	});
    }
  });
};

function isChecked1(id){
  var n = $("input[name^=tids]:checked", id).length;
 
  if (n == 0){
    alert('対象となる先進医療技術をひとつ以上選択してください');
    return false;
  }
	return true;
}

function isChecked2(id){
  var n = $("input[name^=cids]:checked", id).length;
 
  if (n == 0){
    alert('対象となるカテゴリをひとつ以上選択してください');
    return false;
  }
	return true;
}

function isChecked3(id){
  var n = $("input[name^=ptid]:checked", id).length;
 
  if (n == 0){
    alert('対象となる先進医療技術をひとつ以上選択してください');
    return false;
  }
	return true;
}

function isChecked4(id){
  var n = $("input[name^=ctids]:checked", id).length;
 
  if (n == 0){
    alert('対象となる先進医療技術をひとつ以上選択してください');
    return false;
  }
	return true;
}

function isNotEmpty(id){
  if ($(id).val() == ""){
    alert('検索キーワードを指定してください');
    return false;
  }
	return true;
}

function openInfo(tid){
  subwin = window.open("?mode=info&tid=" + tid, tid, "width=700,height=500,scrollbars=1");
  subwin.focus();
}

function tglCheck(cls, id){
  $('input.'+cls, id).each(function(){
    this.checked = !this.checked;
  });
}

/*
 * show google map
 */
function sGmap(base_no){
  jQuery(function() {
    window.open('?mode=detail&id=' + base_no, '_blank');
  });
}

/*
 * paging
 */
function loadPage(obj){
  jQuery(function() {
    /* ページ切り替え用リンクの書き換え */
    var rel = obj.getAttribute('rel');
    if (rel == 'first'){
      if (cur == 1) return false;
      rel = 1;
    }else if(rel == 'prev'){
      if (cur == 1) return false;
      rel = cur - 1;
    }else if(rel == 'next'){
      if (cur == maxPage) return false;
      rel = cur + 1;
    }else if(rel == 'last'){
      if (cur == maxPage) return false;
      rel = maxPage;
    }

    /* 表示中の内容を退避 */
    var old = $(".page").html();

    /* loading...表示 */
    $(".page").html('<p id="loading"><img src="img/loading2.gif" /></p>');

		/* firefoxだけキャッシュしない... */
    $.ajax({
      url: obj.href + '&ajax=Y',
      type: 'get',
      dataType: 'html',
      cache: true,
      error: function(){
        $(".page").html(old);
        alert('Error loading XML document');
      },
      success: function(data){
				/* リスト書き換え */
        $(".page").html(data);

				/* ページ一覧書き換え */
        cur = Number(rel);
        var prev;
        var next;
        var start;
        var end;

        prev = cur - 1;
        if (prev < 1) prev = 1;

        next = cur + 1;
        if (next > maxPage) next = maxPage;

        start = cur - 5;
        if(maxPage <= pageNum){
          start = 0;
        }else if (start < 0){
          start = 0;
        }else if(start > maxPage - pageNum){
          start = maxPage - pageNum;
        }

        end = start + pageNum;
        if (end > maxPage) end = maxPage;
        
        var sNum;
        sNum = (cur - 1) * dataPerPage;
        if (sNum < 0) sNum = 0;
        var eNum;
        eNum = sNum + dataPerPage; 
        if (eNum > datanum) eNum = datanum;
        
        /* 0から開始なので1足す */
        sNum +=1;
        
        var tmp = '?mode=list'+qstr+'&amp;sort='+sort+'&amp;desc='+desc;
        var str = '<p id="total">[ ' + datanum + '件中 ' + sNum + '-' + eNum +'件を表示 ]</p>';
        str += '<div id="nav" class="nav">'; 
        str += '<a href="'+tmp+'&amp;page=1" onclick="loadPage(this);return false;" rel="first">';
        str += '<img src="img/first.png" alt="first" title="first" /></a>';
        str += '<a href="'+tmp+'&amp;page='+prev+'" onclick="loadPage(this);return false;" rel="prev">';
        str += '<img src="img/prev.png" alt="prev" title="prev" /></a>';
        for(var i = start; i < end; i++) {
          var j = i+1; 
          //str += '<a href="#" rel="' + j + '" class="naviitem">' + j + '</a>';
          str += '<span class="item">';
          if (cur != j){
            str += '<a href="'+tmp+'&amp;page='+j+'" onclick="loadPage(this);return false;" rel="'+j+'">'+j+'</a>';
          }else{
            str += j;
          }
          str += '</span>';
        }
        str += '<a href="'+tmp+'&amp;page='+next+'" onclick="loadPage(this);return false;" rel="next">';
        str += '<img src="img/next.png" alt="next" title="next" /></a>';
        str += '<a href="'+tmp+'&amp;page='+maxPage+'" onclick="loadPage(this);return false;" rel="last">';
        str += '<img src="img/last.png" alt="last" title="last" /></a>';
        str += '</div>';
        $("#pagenavi").html(str);
      }
    });
  });
}

function addMarker(data){
	var latlng = new google.maps.LatLng(data.IDO,data.KEIDO);
	var marker= new google.maps.Marker({
		position: latlng,
		map: map,
		title: data.SHORT_NAME
	});

	markers[data.BASE_NO] = marker;

	google.maps.event.addListener(marker, 'click', function() {
		clickFlg = 1;
		/* この中でinfowindowの作成を行う必要有り */
		if (infowindow) infowindow.close();
		var html = '<div style="width: 200px;height: 70px;"><b>';
		if (data.URL != "")
			html += '<a href="'+data.URL+'" target="_blank">'+data.SHORT_NAME+'</a>';
		else
			html += data.SHORT_NAME;
		html += '</b><br>〒'+data.NEW_ADDR_NO+'<br>住所'+data.ADDR+'</div>';
		infowindow = new google.maps.InfoWindow({content: html});
	  infowindow.open(map,marker);
	});
}

var oldCenter;
var oldZoom;
var tidArry=[];
function updateMapList(forceFlg){
	var newCenter = map.getCenter();
	var newZoom = map.getZoom();
	$(function(){
		/* 前回検索地点からの中心地点の移動距離が一定以上ない場合、再検索しない */
		if (oldCenter && forceFlg != true){
			var latDiff = Math.round(Math.abs((oldCenter.lat() - newCenter.lat())*100000));
			var lngDiff = Math.round(Math.abs((oldCenter.lng() - newCenter.lng())*100000));
			/* 縮尺によって閾値を変える(21より大きいzoom値ができた場合正しく動かないので注意) */
			var threshold = (21 - newZoom) * (21 - newZoom) * 6;
			if (Math.sqrt(latDiff*latDiff+lngDiff*lngDiff) < threshold && oldZoom <= newZoom) return true;
		}

    /* loading...表示 */
		var target1 = $("div#maplist");
		target1.empty();
    target1.html('<p id="loading">Loading...</p>');

		var target2 = $("div#tid_selecter");
		target2.empty();
    target2.html('<p id="loading">Loading...</p>');

  	$.getJSON(
			location.protocol+'//'+location.hostname+location.pathname,
			{mode:"map_search", bnds:map.getBounds().toUrlValue()},
			function(json, status){
  	  	var cnt = 1;
  	  	var i;
				target1.empty();
				for (i in json.list) {
					/* 一覧に出力 */
  	  	  target1.append('<div id="name_'+i+'"><a href="javascript:void(0)" onclick="clickSidebar('+i+')">'+json.list[i].SHORT_NAME+'</a></div>');
					/* マーカー設置 */
					if (markers[json.list[i].BASE_NO] == undefined) addMarker(json.list[i]);
					/* この施設が対応可能な先進医療コードを保管 */
					tidArry[i] = json.list[i].tids;
  	  	}
				target2.empty();
				for (i in json.techlist) {
					/* 選択肢出力 */
  	  	  target2.append('<input type="checkbox" name="tid[]" checked="checked" id="tid_'+i+'" value="'+i+'" onclick="tidSelect('+i+', true)" /><label for="tid_'+i+'">'+json.techlist[i].name+'</label><br />');
				}
				oldCenter = newCenter;
				oldZoom = newZoom;
  		}
		)
	});
}

/*
 * 選択に応じてマーカーの増減
 */
function tidSelect(id, refreshFlg) {
	var flg1 = $('#tid_'+id).attr("checked");
	var flg2=false;
	for(var i in markers){
		if (flg1){
			if (tidArry[i][id] == 0) tidArry[i][id] = 1;
		}else{
			if (tidArry[i][id] == 1) tidArry[i][id] = 0;
		}
	}
	if (refreshFlg) tidSelectRefresh();
}

function tidSelectAll() {
	for(var i in markers){
		for(var j in tidArry[i]){
			if (tidArry[i][j] == 0) tidArry[i][j] = 1;
		}
	}
	tidSelectRefresh();
}

/*
 * 選択肢にしたがってマーカーの表示/非表示を更新
 */
function tidSelectRefresh() {
	/* どのmarkerのwindowかわからないので問答無用で消す */
	if (infowindow) infowindow.close();
	for(var i in markers){
		var sum = 0;
		for(var j in tidArry[i]){
			sum += tidArry[i][j];
		}
		/* 選択が一つもなければ非表示にする */
		if (sum == 0){
			markers[i].setVisible(false);
			$('div#name_'+i, 'div#maplist').hide();
		}else{
			markers[i].setVisible(true);
			$('div#name_'+i, 'div#maplist').show();
		}
	}
	/* PDF出力等のためにチェックされた選択肢を取得(実際の送信時に取得すればいいか...) */
	//var tmp=[];
	//$('input[name="tid[]"]:checked', '#tid_selecter').each(function(i,el){tmp.push($(el).val())});
	//$('body').data('tidSelected', tmp);
}

/*
 * 選択肢を全選択
 */
function tidCheckAll() {
	$('input[name="tid[]"]', '#tid_selecter').attr("checked", "checked");
	tidSelectAll();
}

/*
 * 選択肢を反転
 */
function tidCheckToggle() {
	$('input[name="tid[]"]', '#tid_selecter').each(function(){
		this.checked = !this.checked;
		tidSelect($(this).val(), false);
	});
	tidSelectRefresh();
}

/*
 * 画面外のマーカーをクリア
 */
function clearMarker() {
	/* どのmarkerのwindowかわからないので問答無用で消す */
	if (infowindow) infowindow.close();
	/* 一旦全て削除 */
	for(var i in markers){
    markers[i].setMap(null);
    markers[i] = null;
  }
  markers.length = 0; 
	/* 表示範囲だけ作り直す */
	updateMapList(true);
}

/*
 * 全てのマーカーが画面に収まるようにする
 */
function adjustMap() {
	clickFlg = 1;
  var bounds;
  var first = 1;
  for(var i in markers){
    if(first){
			bounds = new google.maps.LatLngBounds(markers[i].getPosition(),markers[i].getPosition());
      first = 0;
    }else{
      bounds.extend(markers[i].getPosition());
    }
  }
  map.fitBounds(bounds);
 	/* ※マーカーと施設一覧が一致しないので再検索。施設が増えるかも。 */
	updateMapList();
}

function clickSidebar(id) {
	google.maps.event.trigger(markers[id], 'click', null);
}

