var map;
var latl = 37.5;
var lngl = 137.8233;
var zml = 5;
var latr;
var lngr;
var zmr;
var pointData = '';
var pointData2 = '';
var parray = new Array();
var pagekind = 'both';

function zoomMapControl() {}
zoomMapControl.prototype = new GControl();
zoomMapControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var zoomMap = document.createElement("img");
    zoomMap.setAttribute("src", "./skin/default/img/mapext.gif");
    zoomMap.setAttribute("id", "zmbtn");
    this.setButtonStyle_(zoomMap);
    container.appendChild(zoomMap);
    GEvent.addDomListener(
        zoomMap,
        "click",
        function() {
            extmap();
        }
    );
    map.getContainer().appendChild(container);
    return container;
}
zoomMapControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 265));
}
zoomMapControl.prototype.setButtonStyle_ = function(button) {
    button.style.cursor = "pointer";
    button.style.height = "69px";
}

function areaSearchControl() {}
areaSearchControl.prototype = new GControl();
areaSearchControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var areaSearch = document.createElement("div");
    this.setButtonStyle_(areaSearch);
    container.appendChild(areaSearch);
    areaSearch.appendChild(document.createTextNode("現在の範囲で絞り込む"));
    GEvent.addDomListener(
        areaSearch,
        "click",
        function() {
            searcharea();
        }
    );
    map.getContainer().appendChild(container);
    return container;
}
areaSearchControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(215, 7));
}
areaSearchControl.prototype.setButtonStyle_ = function(button) {
    button.style.backgroundColor = "white";
    button.style.borderTop = "1px solid";
    button.style.borderLeft = "1px solid";
    button.style.borderRight = "2px ridge";
    button.style.borderBottom = "2px ridge";
    button.style.textAlign = "center";
    button.style.width = "150px";
    button.style.cursor = "pointer";
}

function loadMap() {
	map = new GMap2(document.getElementById("map"));
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new areaSearchControl());
	map.addControl(new zoomMapControl());
	icon = new GIcon();
	icon.image = "./skin/default/img/markerg.png";
	icon.shadow = "./skin/default/img/shadow50.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(10, 34);
	icon.infoWindowAnchor = new GPoint(10, 0);
	GEvent.addListener(
	    map,
	    'zoomend',
	    function(oldZoomLevel,newZoomLevel) {
	        zml = newZoomLevel;
	    }
	);
	GEvent.addListener(
	    map,
	    'moveend',
	    function() {
	        xy = map.getCenter();
	        latl = xy.lat();
	        lngl = xy.lng();
	    }
	);

	map.setCenter(new GLatLng(latl,lngl),zml,G_NORMAL_MAP);
	addllz();
}

function initMarker() {
	var i;
	for (i=0;i<pointData.length;i++) {
	    if(!isNaN(pointData[i].zoom) && !isNaN(pointData[i].lon) && !isNaN(pointData[i].lat)) {
	        plotById(i);
	    }
	}
	var j;
	for (j=0;j<pointData2.length;j++) {
	    if(!isNaN(pointData2[j].zoom) && !isNaN(pointData2[j].lon) && !isNaN(pointData2[j].lat)) {
	        plotById2(j);
	    }
	}
}

function plotById(id) {
    pointData[id].marker = new GMarker(new GPoint(pointData[id].lon, pointData[id].lat),icon);
    map.addOverlay(pointData[id].marker);
    GEvent.addListener(pointData[id].marker, "click", function() {
        this.openInfoWindowHtml(makeInfom(pointData[id].info, pointData[id].note, pointData[id].img, pointData[id].date, pointData[id].url, pointData[id].inid, id), {"maxWidth":280});});
}

function plotById2(id) {
    pointData2[id].marker = new GMarker(new GPoint(pointData2[id].lon, pointData2[id].lat));
    map.addOverlay(pointData2[id].marker);
    GEvent.addListener( pointData2[id].marker, "click", function() {
        this.openInfoWindowHtml(makeInfo2m(pointData2[id].info, pointData2[id].note, pointData2[id].img, pointData2[id].date, pointData2[id].url, pointData2[id].inid, id), {"maxWidth":280});});
}

function makeInfo(info, note, img, date, url ,inid ,id) {
	var html = "<div style='width:280px;line-height:150%;font-size:9pt;font-family:sans-serif;text-align:left;'><div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#60E060;'>■日記</span>&nbsp;<a href='javascript:indiv(\"d_page\","+inid+");'>この日記で絞り込む</a></div>";
	if (img != '') {
		html += "<div><div style='width:150px;float:left;'><div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div></div><div style='width:130px;float:right;'><img src='./img.php?filename="+ img +"&w=120&h=120' style='padding:5px;'></div></div>";
	} else
		html += "<div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div>";
	html += "<div style='text-align:right;clear:both;'><a href='javascript:rv("+id+");'>前に戻る</a>&nbsp;&nbsp;<a href='" + url + "' target='_blank'>続きを読む</a></div>";
	return html + "</div>";
}

function makeInfo2(info, note, img, date, url ,inid ,id) {
    if(url.indexOf("event") != -1) {
        cname = "<div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#FD766A;'>■イベント</span>&nbsp;<a href='javascript:indiv(\"c_page\","+inid+");'>このイベントで絞り込む</a></div>";
    } else {
        cname = "<div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#FD766A;'>■トピック</span>&nbsp;<a href='javascript:indiv(\"c_page\","+inid+");'>このトピックで絞り込む</a></div>";
    }
	var html = "<div style='width:280px;line-height:150%;font-size:9pt;font-family:sans-serif;text-align:left;'>"+cname;
	if (img != '') {
		html += "<div><div style='width:150px;float:left;'><div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div></div><div style='width:130px;float:right;'><img src='./img.php?filename="+ img +"&w=120&h=120' style='padding:5px;'></div></div>";
	} else
		html += "<div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div>";
	html += "<div style='text-align:right;clear:both;'><a href='javascript:rv2("+id+");'>前に戻る</a>&nbsp;&nbsp;<a href='" + url + "' target='_blank'>続きを読む</a></div>";
	return html + "</div>";
}

function makeInfom(info, note, img, date, url ,inid ,id) {
    var npoint = '';
	if(!(pointData[id].lat == latl && pointData[id].lon == lngl && pointData[id].zoom == zml)){
	    npoint = '<a href=\'javascript:listSelected('+id+');\'>作成時の位置・倍率で表示</a>&nbsp;&nbsp;';
	}
	var html = "<div style='width:280px;line-height:150%;font-size:9pt;font-family:sans-serif;text-align:left;'><div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#60E060;'>■日記</span>&nbsp;<a href='javascript:indiv(\"d_page\","+inid+");'>この日記で絞り込む</a></div>";
	if (img != '') {
		html += "<div><div style='width:150px;float:left;'><div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div></div><div style='width:130px;float:right;'><img src='./img.php?filename="+ img +"&w=120&h=120' style='padding:5px;'></div></div>";
	} else
		html += "<div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div>";
	html += "<div style='text-align:right;clear:both;'>"+npoint+"<a href='" + url + "' target='_blank'>続きを読む</a></div>";
	return html + "</div>";
}

function makeInfo2m(info, note, img, date, url ,inid ,id) {
    var npoint = '';
	if(!(pointData2[id].lat == latl && pointData2[id].lon == lngl && pointData2[id].zoom == zml)){
	    npoint = '<a href=\'javascript:listSelected2('+id+');\'>作成時の位置・倍率で表示</a>&nbsp;&nbsp;';
	}
    if(url.indexOf("event") != -1) {
        cname = "<div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#FD766A;'>■イベント</span>&nbsp;<a href='javascript:indiv(\"c_page\","+inid+");'>このイベントで絞り込む</a></div>";
    } else {
        cname = "<div style='border-bottom:#cccccc 1px solid;'><span style='font-weight:bold;color:#FD766A;'>■トピック</span>&nbsp;<a href='javascript:indiv(\"c_page\","+inid+");'>このトピックで絞り込む</a></div>";
    }
	var html = "<div style='width:280px;line-height:150%;font-size:9pt;font-family:sans-serif;text-align:left;'>"+cname;
	if (img != '') {
		html += "<div><div style='width:150px;float:left;'><div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div></div><div style='width:130px;float:right;'><img src='./img.php?filename="+ img +"&w=120&h=120' style='padding:5px;'></div></div>";
	} else
		html += "<div>" + date + "</div><div style='font-weight:bold;'><a href='" + url + "' target='_blank'>" + info + "</a></div><div>" + note + "</div>";
	html += "<div style='text-align:right;clear:both;'>"+npoint+"<a href='" + url + "' target='_blank'>続きを読む</a></div>";
	return html + "</div>";
}

function initList() {
        if(d_total_num == 'トータル数[0]件') {
            document.getElementById("d_page").innerHTML = "";
        } else {
	        var str = "";
	        var i;
	        var pre = "<li style='padding:3px 0;border-bottom:1px solid #cccccc;'><img src='./skin/dummy.gif' style='width:14px;height:14px;' class='icon icon_1'>";
	        var mid ="<br><a href='javascript:listSelectedm(";
	        var mid2 =")'>";
	        var tail = "</a></li>";
	        for (i=0;i<pointData.length;i++) {
		        if (pointData[i].info == undefined) break;
	        	if(!isNaN(pointData[i].zoom) && !isNaN(pointData[i].lon) && !isNaN(pointData[i].lat)) {
		            str += pre + pointData[i].date + mid + i + mid2 + pointData[i].info + tail;
		        }
	        }
	        str = "<div style='text-align:left;padding:5px;'><ol>" + str + "</ol></div>";
	        document.getElementById("d_page").innerHTML = str;
	    }
	
        if(c_total_num == 'トータル数[0]件') {
            document.getElementById("c_page").innerHTML = "";
        } else {
	        var str = "";
	        var j;
	        var pre = "<li style='padding:3px 0;border-bottom:1px solid #cccccc;'><img src='./skin/dummy.gif' style='width: 14px; height: 14px;' class='icon icon_2'>";
	        var mid ="<br><a href='javascript:listSelected2m(";
	        var mid2 =")'>";
	        var tail = "</a></li>";
	        for (j=0;j<pointData2.length;j++) {
		        if (pointData2[j].info == undefined) break;
	        	if(!isNaN(pointData2[j].zoom) && !isNaN(pointData2[j].lon) && !isNaN(pointData2[j].lat)) {
		            str += pre + pointData2[j].date + mid + j + mid2 + pointData2[j].info + tail;
		        }
	        }
	        str = "<div style='text-align:left;padding:5px;'><ol>" + str + "</ol></div>";
	        document.getElementById("c_page").innerHTML = str;
	    }
}

function initPager() {
	    document.getElementById("num1").innerHTML = d_total_num;
	    document.getElementById("pager1").innerHTML = d_page_link;
        document.getElementById("num2").innerHTML = c_total_num;
        document.getElementById("pager2").innerHTML = c_page_link;
}

function listSelected(id) {
	if(!(pointData[id].lat == latl && pointData[id].lon == lngl && pointData[id].zoom == zml)){
		addllz();
		map.setCenter(new GLatLng(pointData[id].lat, pointData[id].lon), parseInt(pointData[id].zoom), G_NORMAL_MAP);
		pointData[id].marker.openInfoWindowHtml(makeInfo( pointData[id].info, pointData[id].note, pointData[id].img, pointData[id].date, pointData[id].url ,pointData[id].inid, id), {"maxWidth":280});
		}
}

function listSelected2(id) {
	if(!(pointData2[id].lat == latl && pointData2[id].lon == lngl && pointData2[id].zoom == zml)){
		addllz();
		map.setCenter(new GLatLng(pointData2[id].lat, pointData2[id].lon), parseInt(pointData2[id].zoom), G_NORMAL_MAP);
		pointData2[id].marker.openInfoWindowHtml(makeInfo2( pointData2[id].info, pointData2[id].note, pointData2[id].img, pointData2[id].date, pointData2[id].url ,pointData2[id].inid, id), {"maxWidth":280});
		}
}

function listSelectedm(id) {
		map.panTo(new GLatLng(pointData[id].lat, pointData[id].lon));
		pointData[id].marker.openInfoWindowHtml(makeInfom( pointData[id].info, pointData[id].note, pointData[id].img, pointData[id].date, pointData[id].url ,pointData[id].inid, id), {"maxWidth":280});
}

function listSelected2m(id) {
		map.panTo(new GLatLng(pointData2[id].lat, pointData2[id].lon));
		pointData2[id].marker.openInfoWindowHtml(makeInfo2m( pointData2[id].info, pointData2[id].note, pointData2[id].img, pointData2[id].date, pointData2[id].url ,pointData2[id].inid, id), {"maxWidth":280});
}

function reSize(relat,relng,rezoom) {
    map.setCenter(new GLatLng(relat,relng),rezoom,G_NORMAL_MAP);
}

function addPoint() {
    pointname = document.getElementById('pname').value;
    if(pointname == '') {
        alert('ブックマーク名を入力してください');
    } else {
        if(parray.length > 9){
            alert('ブックマークは10か所までです');
        } else {
            id = (new Date()).getTime();
            document.getElementById('mapnavi').innerHTML += '<span id="c'+id+'">&nbsp;|&nbsp;<input type="checkbox" class="no_bg" value="c'+id+'" id="'+id+'">&nbsp;<a href="javaScript:void(0)" onClick="reSize('+latl+','+lngl+','+zml+')">'+pointname+'</a></span>';
            encpname = encodeURI(pointname);
            parray.push({"id":id,"lat":latl,"lng":lngl,"zm":zml,"pname":encpname});
            recPoint();
        }
    }
}

function deletePoint() {
    var flg = false;
    var parray2 = new Array();
    for(i=0; i<parray.length; i++) {
        var chkObj = document.getElementById(parray[i].id);
        if (chkObj.checked) {
            document.getElementById(chkObj.value).style.display = "none";
            flg = true;
        } else {
            parray2.push(parray[i]);
        }
    }
    if(flg) {
        parray = parray2;
        recPoint();
    } else {
        alert('削除するブックマークをチェックしてください');
    }
    delete parray2;
}

function recPoint() {
    if(parray.length != 0) {
        var cookiestr = 'parray=['
        for (i=0; i<parray.length; i++) {
            cookiestr += '{"id":"'+parray[i].id+'","lat":"'+parray[i].lat+'","lng":"'+parray[i].lng+'","zm":"'+parray[i].zm+'","pname":"'+parray[i].pname+'"},';
        }
        cookiestr = cookiestr.slice(0,-1);
        cookiestr += '];';
        document.cookie = cookiestr + "; expires=Thu, 1-Jan-2030 00:00:00 GMT";
    } else {
        document.cookie = "parray=; expires=Thu, 1-Jan-1970 00:00:00 GMT";
    }
}

function openPoint() {
    ckary = document.cookie.split("; ");
    ckstr = "";
    i = 0;
    for(i=0; i<ckary.length; i++) {
        if (ckary[i].substr(0,7) == "parray=") {
            eval(ckary[i]);
        }
    }
    buildpoint = "";
    if(parray) {
        for (i=0; i<parray.length; i++) {
            buildpoint += '<span id="c'+parray[i].id+'">&nbsp;|&nbsp;<input type="checkbox" class="no_bg" value="c'+parray[i].id+'" id="'+parray[i].id+'">&nbsp;<a href="javaScript:void(0)" onClick="reSize('+parray[i].lat+','+parray[i].lng+','+parray[i].zm+')">'+decodeURI(parray[i].pname)+'</a></span>';
        }
        document.getElementById('mapnavi').innerHTML += buildpoint;
    }
}

function extmap() {
    if(document.getElementById('zmbtn').src.indexOf('minus',0) == -1) {
        document.getElementById('zmbtn').src = './skin/default/img/mapext_minus.gif';
        document.getElementById('mainflm').style.width = screen.width-20 + 'px';
        document.getElementById('mapflm').style.width = screen.width-200 + 'px';
        document.getElementById('map').style.width = screen.width-205 + 'px';
        document.getElementById('mapnavi').style.width = screen.width-233 + 'px';
        map.checkResize();
        map.setCenter(new GLatLng(latl,lngl),zml,G_NORMAL_MAP);
    } else {
        document.getElementById('zmbtn').src = './skin/default/img/mapext.gif';
        document.getElementById('mainflm').style.width = '713px';
        document.getElementById('mapflm').style.width = '533px';
        document.getElementById('map').style.width = '528px';
        document.getElementById('mapnavi').style.width = '500px';
        map.checkResize();
        map.setCenter(new GLatLng(latl,lngl),zml,G_NORMAL_MAP);
    }
}

function addllz() {
	latr=map.getCenter().lat();
	lngr=map.getCenter().lng();
	zmr=map.getZoom();
	}
	
function rv(id) {
	map.setCenter(new GLatLng(latr,lngr),zmr,G_NORMAL_MAP);
    pointData[id].marker.openInfoWindowHtml(makeInfom( pointData[id].info, pointData[id].note, pointData[id].img, pointData[id].date, pointData[id].url ,pointData[id].inid, id), {"maxWidth":280});
	}
	
function rv2(id) {
	map.setCenter(new GLatLng(latr,lngr),zmr,G_NORMAL_MAP);
	pointData2[id].marker.openInfoWindowHtml(makeInfo2m( pointData2[id].info, pointData2[id].note, pointData2[id].img, pointData2[id].date, pointData2[id].url ,pointData2[id].inid, id), {"maxWidth":280});
	}
	
function search(keyword) {
    url = './?m=pc&a=page_h_gmaps_list_data&keyword=' + encodeURI(keyword);
    map.clearOverlays();
    pagekind = 'both';
    loadData(url);
}

function pagenetion(keytype,pagetype,page) {
    if(pagetype) {
        pageq = '&' + pagetype + '=' + page;
    } else {
        pageq = '';
    }
    if(document.getElementById(keytype) && document.getElementById(keytype).value) {
        keyq = '&' + document.getElementById(keytype).value;
    } else {
        keyq = '';
    }
    url = './?m=pc&a=page_h_gmaps_list_data'+pageq+keyq;
    map.clearOverlays();
    pagekind = pagetype;
    loadData(url);
}

function searcharea() {
    var area = map.getBounds();
    var n = area.getNorthEast().lat();
    var s = area.getSouthWest().lat();
    var e = area.getNorthEast().lng();
    var w = area.getSouthWest().lng();
    url = './?m=pc&a=page_h_gmaps_list_data&area='+n+"_"+s+"_"+e+"_"+w;
    map.clearOverlays();
    pagekind = 'both';
    loadData(url);
}

function indiv(pagetype,id) {
    page = 1;
    pageq = '&' + pagetype + '=' + page;
    idq = '&' + pagetype + '_id=' + id;
    url = './?m=pc&a=page_h_gmaps_list_data'+pageq+idq;
    map.clearOverlays();
    pagekind = pagetype;
    loadData(url);
}

function reset() {
    map.clearOverlays();
    latl = 37.5;
    lngl = 137.8233;
    zml = 5;
	map.setCenter(new GLatLng(latl,lngl),zml,G_NORMAL_MAP);
	pagekind = 'both';
    loadData('./?m=pc&a=page_h_gmaps_list_data&','both');
}

function loadData(urls) {
    var url = urls;
    var options = {
        method : 'get',
        parameters : '',
        onFailure: function() { alert("通信に失敗しました"); },
        onComplete: function(res) {
            eval(res.responseText);
            if(d_total_num == 'トータル数[0]件') {
                pointData = '';
            }
            if(c_total_num == 'トータル数[0]件') {
                pointData2 = '';
            }
            if(urls == './?m=pc&a=page_h_gmaps_list_data') {
                loadMap();
                openPoint();
            }
            initMarker();
            initList();
            initPager();
        }
    }
    new Ajax.Request(url, options);
}

Ajax.Responders.register({
    onCreate: function() {
        if(pagekind) {
            if(pagekind == 'both') {
                document.getElementById('d_page').innerHTML = '<div style="padding:5px;text-align:center"><img src="./skin/default/img/loading.gif"></div>';
                document.getElementById('c_page').innerHTML = '<div style="padding:5px;text-align:center"><img src="./skin/default/img/loading.gif"></div>';
            } else {
                document.getElementById(pagekind).innerHTML = '<div style="padding:5px;text-align:center"><img src="./skin/default/img/loading.gif"></div>';
            }
        }
    }
});

