var refreshIntervalSeconds = 3600;
var timeoutUpdate;
var map = null;
var markerCluster = null;
var positionList = null;
var xmlHttp;
var IE = false;

var pinList;

      var styles = [[{
        url: '/_imgworldmap/people35.png',
        height: 35,
        width: 35,
        anchor: [17, 17],
        opt_anchor: [16, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '/_imgworldmap/people45.png',
        height: 45,
        width: 45,
        anchor: [22, 22],
        opt_anchor: [24, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '/_imgworldmap/people55.png',
        height: 55,
        width: 55,
        anchor: [27, 27],
        opt_anchor: [32, 0]
      }],
      [{
        url: '/_imgworldmap/conv30.png',
        height: 27,
        width: 30,
        anchor: [27, 27],
        opt_anchor: [3, 0],
        textColor: '#FF00FF'
      },
      {
        url: '/_imgworldmap/conv40.png',
        height: 36,
        width: 40,
        anchor: [37, 36],
        opt_anchor: [6, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '/_imgworldmap/conv50.png',
        width: 50,
        height: 45,
        anchor: [47, 45],
        opt_anchor: [8, 0]
      }],
      [{
        url: '/_imgworldmap/heart30.png',
        height: 26,
        width: 30,
        anchor: [15, 26],
        opt_anchor: [4, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '/_imgworldmap/heart40.png',
        height: 35,
        width: 40,
        anchor: [20, 35],
        opt_anchor: [8, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '/_imgworldmap/heart50.png',
        width: 50,
        height: 44,
        anchor: [25, 44],
        opt_anchor: [12, 0]
      }],

      [{
        url: '/_imgworldmap/bubble_green30.png',
        height: 27,
        width: 30,
        anchor: [27, 27],
        opt_anchor: [3, 0]
      },
      {
        url: '/_imgworldmap/bubble_green40.png',
        height: 36,
        width: 40,
        anchor: [37, 36],
        opt_anchor: [6, 0]
      },
      {
        url: '/_imgworldmap/bubble_green50.png',
        width: 50,
        height: 45,
        anchor: [47, 45],
        opt_anchor: [8, 0]
      }],

      [{
        url: '/_imgworldmap/bubble_yellow30.png',
        height: 27,
        width: 30,
        anchor: [27, 27],
        opt_anchor: [3, 0]
      },
      {
        url: '/_imgworldmap/bubble_yellow40.png',
        height: 36,
        width: 40,
        anchor: [37, 36],
        opt_anchor: [6, 0]
      },
      {
        url: '/_imgworldmap/bubble_yellow50.png',
        width: 50,
        height: 45,
        anchor: [47, 45],
        opt_anchor: [8, 0]
      }],

      [{
        url: '/_imgworldmap/bubble_red30.png',
        height: 27,
        width: 30,
        anchor: [27, 27],
        opt_anchor: [3, 0]
      },
      {
        url: '/_imgworldmap/bubble_red40.png',
        height: 36,
        width: 40,
        anchor: [37, 36],
        opt_anchor: [6, 0]
      },
      {
        url: '/_imgworldmap/bubble_red50.png',
        width: 50,
        height: 45,
        anchor: [47, 45],
        opt_anchor: [8, 0]
      }]
      ];


function Pin( latlng ) {
	this.latlng   = latlng;

	this.marker   = null;
	this.count    = 0;
	this.group    = -1;
	this.zindex   = -1;
} // Pin


function handleError( err ) {
	alert( "The page throws the error '"+err.message+"'.\n\nYou may have to reload the page" );
	throw( err );
} // handleError

function onPageLoad() {
	initializeMap();
	ajaxFunction( "allpos", "" );

	window.resizeTo( screen.availWidth, screen.availHeight );
	window.moveTo( 0, 0 );
	map.checkResize();
} // init

function update() {
	ajaxFunction( "allpos", "" );
	return false;
}


function fullscreen() {
	fullscreenstate = ! fullscreenstate;

	var mapElement = document.getElementById("gmap");
	var serverErrorElement = document.getElementById("serverError");

	if (fullscreenstate) {
		window.resizeTo( screen.availWidth, screen.availHeight );
		window.moveTo( 0, 0 );

		mapElement.style.position = "fixed";
		mapElement.style.top = "0";
		mapElement.style.left = "0";
		mapElement.style.height = "100%";
		mapElement.style.width = "100%";

		map.checkResize();

		toolbarElement.style.position = "fixed";
		toolbarElement.style.top = "10px";
		toolbarElement.style.left = "90px";

		serverErrorElement.style.position = "fixed";
		serverErrorElement.style.top = "10px";
		serverErrorElement.style.left = "170px";

	} else {
		mapElement.style.position = "relative";
		mapElement.style.top = "0px";
		mapElement.style.left = "0px";
		mapElement.style.height = "380px";
		mapElement.style.width = "600px";

		map.checkResize();

		toolbarElement.style.position = "relative";
		toolbarElement.style.top = "-510px";
		toolbarElement.style.left = "535px";

		serverErrorElement.style.position = "relative";
		serverErrorElement.style.top = "-860px";
		serverErrorElement.style.left = "0";

	}
}


function ajaxFunction( operation, param ) {
	var params, url;
	params = param.split( '\t' );

	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert( "Your browser does not support AJAX!" );
				return false;
			}
		}

		IE = true;
	}

	xmlHttp.onreadystatechange = serverResponse;

	if (operation == "allpos") {
		var from = document.getElementById("from").value;
		var to = document.getElementById("to").value;
		if (from == "") from = 24;
		accessServer( server+"hanashimap/Ajax?comm=allpos&from="+from+"&to="+to );
	}
} // ajaxFunction


function accessServer( url ) {
	log( "accessing "+url );
	xmlHttp.open( "GET", url, true );
	xmlHttp.send( null );
} // accessServer


function serverResponse() {
	try {

		if (xmlHttp.readyState != 4) {
			return;
		}

		var r = xmlHttp.responseText.indexOf("HTTP Status");
		if (xmlHttp.status != 200) {
			log( "error "+xmlHttp.status );
			document.getElementById("serverError").innerHTML = "Unexpected error from server "+xmlHttp.status + ". Retrying.";
			setRefresh();
			return;
		}

		positionList = xmlHttp.responseText.replace(/\015/g,"").replace(/\012/g,"");
		putContactsOnMap( true );

		document.getElementById("refreshTime").innerHTML = now();
		setRefresh();

	} catch (err) {
		handleError( err );
	}
} // serverResponse


function setRefresh() {
	removeRefresh();
	if (refreshIntervalSeconds > 0) {
		timeoutUpdate = setTimeout( "update()", refreshIntervalSeconds*1000 );
	}
}

function removeRefresh() {
	if (timeoutUpdate != undefined && timeoutUpdate != null) {
		clearTimeout( timeoutUpdate );
	}
	timeoutUpdate = null;
}


// ------------------------------
//	 Functions for GoogleMap
// ------------------------------

function removeAllPins() {
	if (markerCluster != null)
		markerCluster.clearMarkers();
	map.clearOverlays();
}


function putContactsOnMap( zoom ) {
	removeAllPins();

	if (positionList == null) return;

	var contactIcon = new GIcon(G_DEFAULT_ICON);
    contactIcon.image = "http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png";
// 	contactIcon.image = "pin.png";
// 	contactIcon.iconSize = new GSize( 32, 32 );

	var lines = positionList.split( "\t" );
	var bounds = new GLatLngBounds();
	var markers = [];
	var totals = 0;
	for (var i = 0; i < lines.length; i++) {
		var line = lines[i].split( ";" );
		if (line.length >= 2) {
			var latlng = new GLatLng( line[0], line[1], true );
			bounds.extend( latlng );
		    var marker = new GMarker( latlng, {icon:contactIcon, clickable:false} );
		    markers.push(marker);
		    totals++;
		}
	}

	if (markerCluster == null) {
		var mcOptions = { gridSize: 50, styles: styles[1] };
		markerCluster = new MarkerClusterer( map, markers, mcOptions );
	} else {
		markerCluster.addMarkers( markers );
	}

	document.getElementById("totals").innerHTML = totals;

	if (zoom)
		map.setCenter( bounds.getCenter(), map.getBoundsZoomLevel(bounds) );

	document.getElementById("waitBox").style.display = "none";

} // putContactsOnMap


function mapIsZoomed( oldLevel, newLevel ) {
// 	putContactsOnMap( false );
}


function initializeMap() {
  if (GBrowserIsCompatible()) {
	map = new GMap2( document.getElementById("gmap") );

	map.setCenter( new GLatLng(13.29495, 39.71485), 2 );
	map.setMapType( G_SATELLITE_MAP ); // G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP
	map.addControl( new GLargeMapControl() );
	map.addControl( new GScaleControl() );
	map.addControl( new GMapTypeControl() );

	GEvent.addListener(map, "zoomend", mapIsZoomed);
  }
}


function getQueryString( name ) {
	var paramExpressions, param, parts;
	paramExpressions = window.location.search.substr(1).split("&");
	for (var param in paramExpressions) {
		parts = paramExpressions[param].split("=");
		if (parts.length >= 2) {
			if (parts[0] == name)
				return unescape( parts[1] );
		}
	}
	return "";
}


function now()
{
	var today = new Date();
	var h = today.getHours();
	var m = today.getMinutes();
	var s = today.getSeconds();

	return (h<10?"0"+h:h)+"."+(m<10?"0"+m:m)+"."+(s<10?"0"+s:s);
}

function log( text ) {
	try {
		console.log( text );
// 	if (! IE && getQueryString("debug") != "") {
// 		var logelement = document.getElementById("debug");
// 		if (logelement != undefined) {
// 			logelement.innerHTML = document.getElementById("debug").innerHTML + text + "<br>";
// 		}
// 	}
	} catch (e) {
	}
} // log
