/*
var startZoom = 13;
var centerLatitude = -95.0446;
var centerLongitude = 40.6897;*/
var centerLatitude = 42.062293;
var centerLongitude = 59.513778;
var startZoom = 3;
var map;
/* var phpurl = 'gEarth/geoMethods.php?method=photosBetween';*/
var phpurl = 'gEarth/geoMethods.php?';
var log = 0;
var sDate = '1.7.2007';
var eDate = '1.1.2107';

// TODO: 
// 1. zoomaus valittaessa valikosta tietyn kuun kuvat: pitää välittää min max?
// 2. alakulmaan pannaus 
// 3. 

////////////////////////////////////////////////////////////////////////////
// 
function createMarkerClickHandler(marker, description) {
  return function() {
    var HTML = description;
    // marker.openInfoWindowHtml(HTML);
    //var picInfo = document.createElement('p');
    //picInfo.innerHTML = HTML;
    document.getElementById('pic-info').innerHTML = HTML;
  
    if (log) {GLog.write('click handle: '+ HTML);}
    // return false;
  };
}



////////////////////////////////////////////////////////////////////////////
// MESSAGES
//

var messagewidth = 180;
var t = setTimeout("messageAnim()",20);

function messageAnim () {
  messagewidth++;
  document.getElementById('message').style.width = messagewidth + 'px';
  t=setTimeout("messageAnim()",20);
}

function showMessage(message) {
  document.getElementById('message').innerHTML = message;
  document.getElementById('message').style.display = 'inline';
  messageAnim();

}

function hideMessage() {  
  document.getElementById('message').style.display = 'none';
  clearTimeout(t);
  messagewidth=180;
}


////////////////////////////////////////////////////////////////////////////
// 
function createMarker(pointData) {
  var latlng = new GLatLng(pointData.latitude, pointData.longitude);
  var icon = new GIcon();
  if (pointData.type == 'c') { // it's a cluster...
    icon.image = 'http://immu.org/geo/gEarth/Cluster4.png';
    icon.shadow = 'http://immu.org/geo/gEarth/Cluster4_shadow.png';
    icon.iconSize = new GSize(43, 35);
    icon.shadowSize = new GSize(43, 35);
    icon.iconAnchor = new GPoint(17, 17);
    icon.infoWindowAnchor = new GPoint(25, 7);
    icon.infoShadowAnchor = new GPoint(17, 17);
    opts = {
      "icon": icon,
      "clickable": true,
      "labelText": pointData.amount,
      "labelOffset": new GSize(-17, -14)
    };
    infoHTML =  '<div id=\'infotitle\'><br />'+ pointData.amount + ' photos around there <br /> Zoom to see them!</div>';
  } else { // it's a single photo
    icon.image = 'http://immu.org/geo/gEarth/single2.png';
    icon.shadow = 'http://immu.org/geo/gEarth/single_shadow.png';
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 15);
    icon.infoWindowAnchor = new GPoint(6, 1);
    icon.infoShadowAnchor = new GPoint(6, 60);
    opts = {
      "icon": icon,
      "clickable": true,
      "labelText": '',
      "labelOffset": new GSize(-6, -10)
    };
    infoHTML = '<div id=\'infotitle\'>'+ pointData.title + '</div><div id=\'infoimg\'><a href=\'http://www.flickr.com/photos/immmu/' + pointData.id + '\' target=\'photo' + pointData.id +'\'><img class=\'flickr\' src=\'' + pointData.url + '\'></a></div></div><div id=\'infodesc\'>' + pointData.date + '</div>';
  }
  
  if (log>1) {GLog.write('marker: ' + pointData.type + ', ' + pointData.latitude + ', ' + pointData.longitude);}
  
  var marker = new LabeledMarker(latlng, opts);
  var handler = createMarkerClickHandler(marker, infoHTML);
  
  GEvent.addListener(marker, "click", handler);
  
  map.addOverlay(marker);
  // return marker;
}



////////////////////////////////////////////////////////////////////////////
// 
function addMarker(pointData) {
  var marker = new GMarker(new GLatLng(pointData.latitude, pointData.longitude)); 
  GEvent.addListener(marker, 'click',
		     function() {
		       var HTML = pointData.description;
		       marker.openInfoWindowHtml(HTML);
		      });
  map.addOverlay(marker);
}



////////////////////////////////////////////////////////////////////////////
// 
function updateMarkers() {
  //remove the existing points
  map.clearOverlays();
  // debugging..
  if (log) {GLog.write('sdate:'+sDate+', edate:'+eDate);}
  // method & datevars for php:
  var getVars = 'method=photosBetween';//METODI
  if (sDate) {
    getVars +='&sdate='+sDate;
  }
  if (eDate) {
    getVars +='&edate='+eDate;
  } 
  // boundary fars from map to php
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var swlng = southWest.lng();
  var nelng = northEast.lng();

  if (nelng <= swlng) { //kartalle zoomi pituusrajan yli
    nelng = 180;
    swlng = -180;
  } 

  getVars += '&nelat=' + northEast.lat() + '&swlat=' + southWest.lat() + '&nelng=' + nelng + '&swlng=' + swlng;
  if (log) {GLog.write(phpurl+getVars);}

  //get the the points
  var request = GXmlHttp.create();
  request.open('GET', phpurl+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var jscript = request.responseText;
      // var markers;
      if (log>1) {GLog.write(jscript);}
      eval(jscript);
      if (log>0) {GLog.write('pics eval ok? ' + markers[0].amount + ' photos in 1st cluster');}
      //create each point from the list
      for (id in markers) {
	createMarker(markers[id]);
	if (log>1) {GLog.write('asdasd');}; 
      }
            hideMessage();
    }
  }
  request.send(null);
  //showMessage('Loading');
}



////////////////////////////////////////////////////////////////////////////
// 
function markersByDate(sdat,edat) {
  sDate = sdat;
  eDate = edat;
  if (log) {GLog.write(sDate+' '+eDate);}
  updateMarkers(sDate,eDate);
}



function markersByMonth(yearmo) { // input in "yyyy-mm"
  var yearmonth =  '.' + yearmo.substring(5,7) + '.' + yearmo.substring(0,4);
  sDate = '1' + yearmonth; 
  eDate = '31' + yearmonth;
  if (log) {alert(sDate + ' ' + eDate); GLog.write('getting photos between: ' + sDate + ' ' + eDate);}
  updateMarkers(sDate,eDate);
}



////////////////////////////////////////////////////////////////////////////
// 
function DBinfo() {
  var getVars = 'method=DBinfo';
  if (log) {GLog.write(phpurl+getVars);}
  //get the the points
  var request = GXmlHttp.create();
  request.open('GET', phpurl+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var jscript = request.responseText;
      if (log>1) {GLog.write(jscript);}
      eval(jscript);
      if (log) {GLog.write('photos eval ok? ' + DBinfo.photoCount+' photos in db');}
      DBinfoHTML =  DBinfo.photoCount + " photos in database; shot between " + DBinfo.firstDate + " and " + DBinfo.lastDate;
      // document.getElementById('DBinfo').innerHTML = DBinfoHTML;
      document.title = "Immu's photos on map - " + DBinfoHTML;
    }
  }
  request.send(null);
}



////////////////////////////////////////////////////////////////////////////
// 
function photoCountByMonth() {
  var getVars = 'method=photoCountByMonth';
  if (log) {GLog.write(phpurl+getVars);}
  //get the the points
  var request = GXmlHttp.create();
  request.open('GET', phpurl+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var jscript = request.responseText;
      if (log>1) {GLog.write(jscript);}
      eval(jscript);
      if (log) {GLog.write('photo count eval? ' + photoCountByMonth[0].year + ' is last picyear');}
    }
  }
  request.send(null);
}



////////////////////////////////////////////////////////////////////////////
// 
function drawQueryForm(type) {
  var HTML ='';
  switch (type) 
    {
    case 2:
      HTML = "<p><a href='javascript:void()' onclick='javascript:drawQueryForm(1)'>between dates</a> | by month | <a href='javascript:void()' onclick='javascript:drawQueryForm(3)'>all</a></p>";
      HTML += "<form name='dateForm'><select name='month'>";
      for (m in photoCountByMonth) {
	HTML += "<option name='"+ photoCountByMonth[m].yearmo +"' value='" + photoCountByMonth[m].yearmo +"'>" + photoCountByMonth[m].month +" "+ photoCountByMonth[m].year +" ("+ photoCountByMonth[m].photos +" photos)</option>";
      }
      HTML +="<input class='button' type='button' name='update' onclick ='markersByMonth(dateForm.elements.month.options[dateForm.elements.month.selectedIndex].value)' value='&larr; update map &nbsp;&nbsp;' />";
      HTML +="</select></form>";
      break;

    case 1:
      HTML = "<p> between dates | <a href='javascript:void()' onclick='javascript:drawQueryForm(2)'>by month</a> | <a href='javascript:void()' onclick='javascript:drawQueryForm(3)'>all</a></p><form name='dateForm'> <input class='text' type='text' id='sDate' name='sDate' size='8' value='"+ sDate +"'> and <input class='text' type='text' id='eDate' name='eDate'  size='8' value='"+ eDate +"'><input class='button' type='button' name='update' onclick ='markersByDate(dateForm.sDate.value,dateForm.eDate.value)' value='&larr; update map &nbsp;&nbsp;' /></form>";
      break;

    default:
      HTML = "<p> <a onclick='javascript:drawQueryForm(1)' href='javascript:void()'>between dates</a> | <a href='javascript:void()' onclick='javascript:drawQueryForm(2)'>by month</a> | all</p><p class='message'>show all photos</p><form name='dateForm'><input type='hidden' id='sDate' name='sDate' value='1.1.2004'><input type='hidden' id='eDate' name='eDate' value='1.1.2008'><input class='button' type='button' name='update' onclick ='markersByDate(dateForm.sDate.value,dateForm.eDate.value)' value='&larr; update map &nbsp;&nbsp;' /></form>";
      break;
    } 
  if (log) { alert(HTML); }
  document.getElementById('inputform').innerHTML = HTML;
  }


////////////////////////////////////////////////////////////////////////////
// 
function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight)
    return self.innerHeight;
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight)
    return y = document.documentElement.clientHeight;
  // IE 5
  if (document.body)
  return document.body.clientHeight;
// Just in case.
 return 0;
}

function handleResize() {
  var mapheight = windowHeight();
  mapheight -= document.getElementById('toolbar').offsetHeight + 20;
  var adheight = mapheight - document.getElementById('inputform').offsetHeight + document.getElementById('formheader').offsetHeight - 335;
  //GLog.write(adheight);
  adheight = Math.max(adheight, 150);
  document.getElementById('content').style.height = mapheight + 'px';
  //GLog.write(adheight);
  document.getElementById('pic-info').style.height = adheight + 'px';

}

////////////////////////////////////////////////////////////////////////////
// 
function init() {
  handleResize();
  //DBinfo to page header
  DBinfo();
  // months & photocount from database
  photoCountByMonth();

  // query from to sidebar
  drawQueryForm(0);

  //map & markers
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    if (log) { GLog.write('map ok'); }
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    var location = new GLatLng(centerLatitude, centerLongitude);
    map.setCenter(location, startZoom);
    map.setMapType(G_HYBRID_MAP);
    updateMarkers();

    /*    GEvent.addListener(map,'zoomend',function() {
	updateMarkers();
      });*/

    GEvent.addListener(map,'moveend',function() {
	updateMarkers();
	});
  }

}


window.onload = init;
window.onunload = GUnload;
window.onresize = handleResize;

