var home = '.';

var XMLHTTP_LOAD_COMPLETE = 4;
var XMLHTTP_HTTP_STATUS = 200;
var MSXMLHTTP = false;

var xmlhttp = createXmlHttp();
var list = createXmlHttp();
var aws = createXmlHttp();
var gc = createXmlHttp();
var html = new Array();
var map;
var detail = 'show';
var admin = 0;
var progName="";
var songName="";
var selectN=0;
var modeList=['books-jp','music-jp','dvd-jp'];
var status = 0;
var box;
var initflag;
var idflag;
var minx;
var miny;
var maxx;
var maxy;
var mapmode = "dual";
var printm = 0;
var iconw = 20;
var iconh = 10;
var baseIcon = new GIcon();
var urlid;
baseIcon.shadow = "";
baseIcon.iconSize = new GSize(iconw, iconh);
baseIcon.shadowSize = new GSize(0, 0);
baseIcon.iconAnchor = new GPoint(0, iconh);
baseIcon.infoWindowAnchor = new GPoint(0, iconh);
baseIcon.infoShadowAnchor = new GPoint(0, iconh);
var tile = new Array();

function createXmlHttp() {
    var xmlhttp;
    try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	MSXMLHTTP = true;
    } catch (e) {
	try {
	    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    MSXMLHTTP = true;
	} catch (E) {
	    xmlhttp = false;
	}
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function locaRequest(key) {
    var requrl = home + '/contents.cgi?url=' + encodeURI(key);
    var urlary = key.split('/');
    urlary.reverse();
    urlary = urlary[0].split('.');
    urlid = urlary[0];

    var progress  = document.getElementById('progress');
    try {
	xmlhttp.open("GET", requrl, true);
	xmlhttp.onreadystatechange = function () {
	    progress.innerHTML = '<img src="/x/image/progress.gif" />';
	    progress.style.display = 'block';
	    if (xmlhttp.readyState == XMLHTTP_LOAD_COMPLETE) {
		initflag = 1;
		idflag = 1;
		var root = xmlhttp.responseXML.documentElement;
		var count = locaOutput(root);
		if (count > 0) {
		    progress.innerHTML = '<br />'+count;
		    progress.style.color = '#000000';
		} else {
		    progress.innerHTML = '<br />0';
		    progress.style.color = '#ff9090';
		}
		awsRequest();
	    }
	}
	xmlhttp.send(null);
    } catch (e) {
	progress.innerHTML = e;
	progress.style.display = 'block';
    }
}

function tagRequest() {
    if(mapmode == 'sat'){
	map.setMapType(G_SATELLITE_MAP); 
    }else if(mapmode == 'map'){
	map.setMapType(G_NORMAL_MAP); 
    }else if(mapmode == 'dual'){
	map.setMapType(G_HYBRID_MAP); 
    }

    var requrl = home + '/menu.cgi';
    try {
	list.open("GET", requrl, true);
	list.onreadystatechange = function () {
	    if (list.readyState == XMLHTTP_LOAD_COMPLETE) {
		var root = list.responseXML.documentElement;
		tagOutput(root,'menu');
	    }
	}
	list.send(null);
    } catch (e) {
    }
}

function tagRequest2(name, cast, song, waku) {
    var requrl = home + '/lsearch.cgi?name='+encodeURI(name)+'&cast='+encodeURI(cast)+'&song='+encodeURI(song)+'&waku='+encodeURI(waku);
    try {
	list.open("GET", requrl, true);
	list.onreadystatechange = function () {
	    if (list.readyState == XMLHTTP_LOAD_COMPLETE) {
		var root = list.responseXML.documentElement;
		tagOutput(root, 'menu2');
	    }
	}
	list.send(null);
    } catch (e) {
    }
}

function mapchange(maptype) {
    var omapmode = mapmode;
    mapmode = maptype;
    if(mapmode == 'sat'){
	map.setMapType(G_SATELLITE_MAP); 
    }else if(mapmode == 'map'){
	map.setMapType(G_NORMAL_MAP); 
    }else if(mapmode == 'dual'){
	map.setMapType(G_HYBRID_MAP); 
    }
    locaOutput(xmlhttp.responseXML.documentElement);
    var center = map.getCenter();
}

function awsRequest() {
    if(progName && status == 0){
	var mode="blended";
	var key=progName;
	status = 1;
	var requrl = '/x/aws.cgi?mode='+mode+'&keyword='+encodeURI(key);
	try {
	    aws.open("GET", requrl, true);
	    aws.onreadystatechange = function () {
		if (aws.readyState == XMLHTTP_LOAD_COMPLETE) {
		    if(aws.responseXML){
			var root = aws.responseXML.documentElement;
			awsOutput(root);
		    }
		}
	    }
	    aws.send(null);
	} catch (e) {
	}
    }
}

function gcRequest(addr,mode,n,id) {
    var requrl = '/x/geocode2.cgi?addr='+encodeURI(addr)+'geosys='+mode;
    try {
	gc.open("GET", requrl, true);
	gc.onreadystatechange = function () {
	    if (gc.readyState == XMLHTTP_LOAD_COMPLETE) {
		var root = gc.responseXML.documentElement;
		gcOutput(root,n,id);
	    }
	}
	gc.send(null);
    } catch (e) {
    }
}

function mapinit() {
    var mapBox = document.getElementById("map");
    map = new GMap2(mapBox);
    map.setCenter(new GLatLng(36.87476,137.55228), 5, G_SATELLITE_MAP); 
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    //map.addControl(new GOverviewMapControl());
    new GKeyboardHandler(map); 
}

function locaOutput(root) {
    var output = '';

    map.clearOverlays();

    if(initflag == 1){
	minx = 0;
	maxx = 0;
	miny = 0;
	maxy = 0;
    }

    admin = eval(getValue( root, 'admin'));

    var prog = root.getElementsByTagName('prog');
    var http = getValue( root, 'url');
    var progOutput = '直接リンク：<a href="/x/lmap.cgi?id='+urlid+'">http://saya.s145.xrea.com/x/lmap.cgi?id='+urlid+'</a><br />';
    progOutput += 'Google Earth KML：<a href="/x/locakml.cgi?id='+urlid+'">http://saya.s145.xrea.com/x/locakml.cgi?id='+urlid+'</a><br />';
    progOutput += 'オリジナルURL：<a href="'+http+'" target="_blank">'+http+'</a><br />';;

    progName = '';
    songName = '';
    selectN = 0;
    if(prog[0]){
	var name = getValue( prog[0], 'name');
	var year = getValue( prog[0], 'year');
	var cast = getValue( prog[0], 'cast');
	var song = getValue( prog[0], 'song');
	var url = getValue( prog[0], 'url');
	var subjects = getValue( prog[0], 'subjects');
	progOutput += "作品名："+name+'<br />';
	progOutput += "制作年："+year+'<br />';
	progOutput += "主題歌："+song+'<br />';
	progOutput += "公式URL："+url+'<br />';
	progOutput += "キャスト："+cast+'<br />';
	progOutput += "タイトル：<br />"+subjects+'<br />';
	progName = name;
	songName = song;
    }
    var target = 'desc';
    var resultBox = document.getElementById(target);
    resultBox.innerHTML = progOutput;
    resultBox.style.display = 'block';

    var title;
    var x;
    var y;
    var addr;
    var desc;
    var items = root.getElementsByTagName('item');
    var color = ["#FFFFFF","#EEFFFF"];
    var id;
    var idicon;
    var minor;
    var j=0;

    for (var i = 0; i < items.length ; i++) {
     minor = eval(getValue( items[i], 'minor' ));
     if((detail=='show' && minor==0)||detail=='info'){
	title = getValue( items[i], 'title' )+"<br />";
	x = eval(getValue( items[i], 'x' ));
	y = eval(getValue( items[i], 'y' ));
	if( x == 0 && y == 0 ){
	    x = eval(getValue( items[i], 'xt' ));
	    y = eval(getValue( items[i], 'yt' ));
	}
	addr = getValue( items[i], 'addr' );
	id = getValue( items[i], 'id' );
	desc = getValue( items[i], 'desc' )+"<br />";
	idicon = '<img src="/cimg/'+id+'.gif">';
	if( x == 0 && y == 0 ){
	    var sokuchi = "world";
	    html[j] = idicon+title+addr+"<br />"+desc+"(位置は住所を変換して表示しています。)";
	    output = '<div id="items" onclick="gcRequest(\''+addr+'\',\''+sokuchi+'\','+j+',\''+id+'\');" style="background-color: #DDDDDD;"><a href="#" onclick="return false;">'+idicon+title+'</a></div>'+output;
	}else{
	    addr += "<br />";
	    html[j] = idicon+title+addr+desc;
	    output = '<div id="items" onclick="seeAt('+x+','+y+',html['+j+'],\''+id+'\');" style="background-color: '+color[j % color.length]+';"><a href="#" onclick="return false;">'+idicon+title+'</a></div>'+output;
	    addMarker(x, y, html[j], id);
	    if( minx == 0 || minx > x ){
		minx = x;
	    }
	    if( maxx == 0 || maxx < x ){
		maxx = x;
	    }
	    if( miny == 0 || miny > y ){
		miny = y;
	    }
	    if( maxy == 0 || maxy < y ){
		maxy = y;
	    }
	}
	j++;
     }
    }
    if( initflag == 1){
	allview();
    }


    if( admin == 0 ){
	output += '*ロケ地を探して彷徨ってもらうという趣旨と個人情報保護のため、位置情報は約300mのブロック(赤色の四角のエリア)に分けて表示しています。<br />';
    }
    //    output += '*背景がグレーの項目は、位置情報がないため住所の代表地点を表示しています。(表示には時間がかかります)<br />';
    //    output += '*地図と衛星写真の切り替えは右上のマップ、サテライトで切り替えることができます。';

    var target = 'list';
    var resultBox = document.getElementById(target);
    resultBox.innerHTML = output;
    resultBox.style.display = 'block';

    return(items.length);
}

function locaOutputforPrint(root) {
    var output = '';

    map.clearOverlays();

    admin = eval(getValue( root, 'admin'));

    var title;
    var x;
    var y;
    var addr;
    var desc;
    var items = root.getElementsByTagName('item');
    var color = ["#FFFFFF","#EEFFFF"];
    var id;
    var idicon;

    var bounds = map.getBounds();
    var span = bounds.toSpan(); 
    var size = map.getSize();
    var dx = ( span.lng() / size.width );
    var dy = ( span.lat() / size.height );
    var mx = Math.floor(size.width/iconw);
    var my = Math.floor(size.height/iconh);
    var ix;
    var iy;

    for (var i = 0; i < mx*my; i++) {
	tile[i] = 0;
    }
    for (var i = items.length - 1; i >= 0 ; i--) {
     minor = eval(getValue( items[i], 'minor' ));
     if((detail=='show' && minor==0)||detail=='info'){
	x = eval(getValue( items[i], 'x' ));
	y = eval(getValue( items[i], 'y' ));
	if( x == 0 && y == 0 ){
	    x = eval(getValue( items[i], 'xt' ));
	    y = eval(getValue( items[i], 'yt' ));
	}
	var iconbounds = new GLatLngBounds(new GLatLng(y,x), new GLatLng(y+iconh*dy,x+iconw*dx) );
	if( bounds.containsBounds(iconbounds) ){
	    title = getValue( items[i], 'title' )+"<br />";
	    addr = getValue( items[i], 'addr' );
	    id = getValue( items[i], 'id' );
	    desc = getValue( items[i], 'desc' )+"<br />";
	    idicon = '<img src="/cimg/'+id+'.gif">';
	    addr += "<br />";
	    html[i] = idicon+title+addr+desc;
	    ix = Math.floor((x-bounds.getSouthWest().lng())/dx/iconw);
	    iy = Math.floor((y-bounds.getSouthWest().lat())/dy/iconh);
	    var flag = 0;
	    area(x,y);
	    var xx = x;
	    var yy = y;
	    if( tile[ix+iy*mx] || tile[ix+1+iy*mx] || tile[ix+(iy+1)*mx] || tile[ix+1+(iy+1)*mx] ){
		var lx;
		var ly;
		for(var l=2;l<mx;l++){
		    for(lx=1; lx< l; lx++){
			ly = l-lx;
			if( !tile[ix+lx+(iy+ly)*mx] && !tile[ix+lx+1+(iy+ly)*mx] && !tile[ix+lx+(iy+ly+1)*mx] && !tile[ix+lx+1+(iy+ly+1)*mx]  && ix+lx<mx && iy+ly<my){
			    x += lx*iconw*dx;
			    y += ly*iconh*dy;
			    tile[ix+lx+(iy+ly)*mx] = 1;
			    tile[ix+lx+1+(iy+ly)*mx] = 1;
			    tile[ix+lx+(iy+ly+1)*mx] = 1;
			    tile[ix+lx+1+(iy+ly+1)*mx] = 1;
			    flag = 1;
			    break;
			}
			if( !tile[ix-lx+(iy+ly)*mx] && !tile[ix-lx+1+(iy+ly)*mx] && !tile[ix-lx+(iy+ly+1)*mx] && !tile[ix-lx+1+(iy+ly+1)*mx]  && ix-lx>=0 && iy+ly<my){
			    x -= lx*iconw*dx;
			    y += ly*iconh*dy;
			    tile[ix-lx+(iy+ly)*mx] = 1;
			    tile[ix-lx+1+(iy+ly)*mx] = 1;
			    tile[ix-lx+(iy+ly+1)*mx] = 1;
			    tile[ix-lx+1+(iy+ly+1)*mx] = 1;
			    flag = 1;
			    break;
			}
			if( !tile[ix+lx+(iy-ly)*mx] && !tile[ix+lx+1+(iy-ly)*mx] && !tile[ix+lx+(iy-ly+1)*mx] && !tile[ix+lx+1+(iy-ly+1)*mx]  && ix+lx<mx && iy-ly>=0){
			    x += lx*iconw*dx;
			    y -= ly*iconh*dy;
			    tile[ix+lx+(iy-ly)*mx] = 1;
			    tile[ix+lx+1+(iy-ly)*mx] = 1;
			    tile[ix+lx+(iy-ly+1)*mx] = 1;
			    tile[ix+lx+1+(iy-ly+1)*mx] = 1;
			    flag = 1;
			    break;
			}
			if( !tile[ix-lx+(iy-ly)*mx] && !tile[ix-lx+1+(iy-ly)*mx] && !tile[ix-lx+(iy-ly+1)*mx] && !tile[ix-lx+1+(iy-ly+1)*mx]  && ix-lx>=0 && iy-ly>=0){
			    x -= lx*iconw*dx;
			    y -= ly*iconh*dy;
			    tile[ix-lx+(iy-ly)*mx] = 1;
			    tile[ix-lx+1+(iy-ly)*mx] = 1;
			    tile[ix-lx+(iy-ly+1)*mx] = 1;
			    tile[ix-lx+1+(iy-ly+1)*mx] = 1;
			    flag = 1;
			    break;
			}
		    }
		    if( flag ){
			break;
		    }
		}
	    }else{
		tile[ix+iy*mx] = 1;
		tile[ix+1+iy*mx] = 1;
		tile[ix+(iy+1)*mx] = 1;
		tile[ix+1+(iy+1)*mx] = 1;
	    }
	    printm = 1;
	    addMarker(x, y, html[i], id);
	    line(xx,yy,x,y);
	    printm = 0;
	    var desca = desc.split("<br />");
	    output += '<div id="items" onclick="seeAt('+x+','+y+',html['+i+'],\''+id+'\');" style="background-color: '+color[i % color.length]+';"><a href="#" onclick="return false;">'+idicon+title+addr+desca[0]+'</a></div>';
	}
     }

    }

    var target = 'desc';
    var resultBox = document.getElementById(target);
    resultBox.innerHTML = output;
    resultBox.style.display = 'block';
    var target = 'list';
    var resultBox = document.getElementById(target);
    resultBox.style.display = 'none';
    var target = 'progress';
    var resultBox = document.getElementById(target);
    resultBox.style.display = 'none';
    var target = 'aws';
    var resultBox = document.getElementById(target);
    resultBox.style.display = 'none';

    return(items.length);
}

function allview() {
    var bounds = new GLatLngBounds(new GLatLng(miny,minx),new GLatLng(maxy,maxx));
    var zoom = map.getBoundsZoomLevel(bounds);
    var x = (minx+maxx)/2;
    var y = (miny+maxy)/2;
    map.setCenter(new GLatLng(y,x), zoom);

    initflag = 0;
}


function tagOutput(root, target) {
    var output = "";

    var groups = root.getElementsByTagName('group');
    for (var j = 0; j < groups.length; j++ ){
	name = getValue( groups[j], 'name' );
	if(target == 'menu'){
	    output += '<form name="select"><select name="sel'+j+'" onchange="locaRequest(document.select.sel'+j+'.value); return false;"><option>'+name+'</option>';
	}else{
	    output += '<form name="select2"><select name="sel'+j+'" onchange="locaRequest(document.select2.sel'+j+'.value); return false;"><option>'+name+'</option>';	}
	var items = groups[j].getElementsByTagName('item');
	for (var i = 0; i < items.length ; i++) {
	    var index = getValue( items[i], 'index' );
	    var link = getValue( items[i], 'link' );
	    output += '<option value="'+link+'">'+index+'</option>';
	}
	output += '</select><br />';
    }
    
    var resultBox = document.getElementById(target);
    resultBox.innerHTML = output;
    resultBox.style.display = 'block';
}

function gcOutput(root,n,id) {
    var x = eval(getValue( root, 'longitude' ));
    var y = eval(getValue( root, 'latitude' ));
    if(x){
	var point = new GLatLng(y,x);
	map.panTo(point);
	var icon = new GIcon(baseIcon);
	icon.image = "/cimg/"+id+".gif";
	var marker = new GMarker(point, icon);
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml('<div id="popup">'+html[n]+'</div>');
        });
	marker.openInfoWindowHtml('<div id="popup">'+html[n]+'</div>');
    }
}

function awsOutput(root) {
    var item = root.getElementsByTagName('item');
    if( item ){
	if( item.length > 0 ){
        var output = "";
        for(var i=0; i<item.length; i++){
	    var image = getValue( item[i], 'imagem' );
	    var url = getValue( item[i], 'url' );
	    var name = getValue( item[i], 'name' );
	    if(image != ""){
		output += '<a href="'+url+'" target="_blank"><img src="'+image+'" alt="'+name+'" title="'+name+'" onmouseover="awsItem('+i+');"></a>';
	    }
        }
	var target = 'aws';
	var resultBox = document.getElementById(target);
	resultBox.innerHTML = output;
	resultBox.style.display = 'block';
	}
    }
    status = 0;
}

function awsItem(no) {
    var root = aws.responseXML.documentElement;
    var item = root.getElementsByTagName('item');
    var output = "";
    var name = getValue( item[no], 'name' );
    var url = getValue( item[no], 'url' );
    var desc = getValue( item[no], 'desc' );
    var review = getValue( item[no], 'review' );
    output += '<a href="'+url+'" target="_blank">'+name+'</a><br />';
    output += desc+'<br />'+review;
    var target = 'ad';
    var resultBox = document.getElementById(target);
    resultBox.innerHTML = output;
    resultBox.style.display = 'block';
}

// Creates a marker whose info window displays the given number
function addMarker(lng, lat, html, id) {
    if( admin == 0 && printm == 0){
	area(lng,lat);
    }
    if( idflag == 1 ){
	var point = new GLatLng(lat, lng);
	var icon = new GIcon(baseIcon);
	icon.image = "/cimg/"+id+".gif";
	var marker = new GMarker(point, icon);
// Show this marker's index in the info window when it is clicked
	GEvent.addListener(marker, "click", function() {
			       marker.openInfoWindowHtml('<div id="popup">'+html+'</div>');
			   });
	map.addOverlay(marker);
    }
}

function seeAt(lng, lat, html, id)
{
    var point = new GLatLng(lat, lng);
    map.panTo(point);
    if( admin == 0 ){
	area(lng, lat);
    }
    var icon = new GIcon(baseIcon);
    icon.image = "/cimg/"+id+".gif";
    var marker = new GMarker(point, icon);
    map.addOverlay(marker);
// Show this marker's index in the info window when it is clicked
    GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml('<div id="popup">'+html+'</div>');
    });
    marker.openInfoWindowHtml('<div id="popup">'+html+'</div>');
    status = 0;
    //    awsRequest();
}

function area(lng, lat)
{
    var points = [];
    var w = 0.5/300;

    points.push(new GLatLng(lat-w,lng-w));
    points.push(new GLatLng(lat+w,lng-w));
    points.push(new GLatLng(lat+w,lng+w));
    points.push(new GLatLng(lat-w,lng+w));
    points.push(new GLatLng(lat-w,lng-w));
    box = new GPolyline(points,"#FF0000",1);
    map.addOverlay(box);
}

function line(x1,y1,x2,y2)
{
    var points = [];

    points.push(new GLatLng(y1,x1));
    points.push(new GLatLng(y2,x2));
    var line = new GPolyline(points,"#FF0000",1);
    map.addOverlay(line);
}

function getValue( node, key ){
    if(node.getElementsByTagName(key)[0].firstChild){
	return node.getElementsByTagName(key)[0].firstChild.nodeValue;
    }else{
	return "";
    }
}