

/****************************************************
function: load
description: sets up map and other stuff
****************************************************/
function load() {

// clear out forms
  $('searchQuery').value="";
  $('searchAbout').value="";

  $('progress').setOpacity(0.75);
  $('viewport-info').setOpacity(0.75);

  var clat = 43.32517768;
  var clon = 37.61718750;

  var zoom = 2;

  map = new GMap2( document.getElementById("map") );

	map.enableScrollWheelZoom();
	var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(15,200));
	var botLeftScale = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(200,20));
	map.addControl(new GLargeMapControl(), topLeft);
	map.addControl(new GScaleControl(), botLeftScale);

// limit zoom levels

  G_PHYSICAL_MAP.getMinimumResolution =  function () { return 2; };
  G_NORMAL_MAP.getMinimumResolution =    function () { return 2; };
  G_SATELLITE_MAP.getMinimumResolution = function () { return 2; };
  G_HYBRID_MAP.getMinimumResolution =    function () { return 2; };


// ====== set up marker mouseover tooltip div ======

  tooltip = document.createElement("div");
  map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
  tooltip.style.visibility="hidden";


	GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
		validate_tool_mode(newLevel);
	});

	GEvent.addListener(map, "infowindowclose", function() {
		cleanup_pending_edits();
	});


	GEvent.addListener(map, "moveend", function() {
  	update_coordinates();
    update_hotspot_viewport_delta();
	});

 	map.setCenter(new GLatLng(clat, clon), zoom);

	aviatlas_resize();
	show_login();

	map.setMapType(G_PHYSICAL_MAP);
	geocoder = new GClientGeocoder();

	update_coordinates();

  var token = parent.location.hash;

  if(token.length == 34){

    if (token.substring(1,2) == 'h') {

      set_mode_hotspot();

    } else {

      update_hotspot_viewport_delta();
    }

  } else {

    update_hotspot_viewport_delta();
  }


  crosshairs = new GScreenOverlay('images/crosshairs.png', new GScreenPoint(0.5, 0.5, 'fraction', 'fraction'), new GScreenPoint(0, 0), new GScreenSize(13, 13, 'pixels', 'pixels') );

  map.addOverlay(crosshairs);

}//end load

/****************************************************
function: show_address
description: jumps user to location
****************************************************/
function show_address(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 13);
//      	  update_coordinates();
        }
      }
    );
  }
}


/* function: map_nav_set_tab
description: set the navigtor mode
****************************************************/
function map_nav_set_tab(tab) {

  switch (tab) {

    case 'dms':

      $('map_nav_dec').className='map_nav_unsel';
      $('map_nav_dms').className='map_nav_sel';
      $('map_nav_lat_dec').style.display='none';
      $('map_nav_lng_dec').style.display='none';
      $('map_nav_lat_dms').style.display='';
      $('map_nav_lng_dms').style.display='';

    break;

    case 'dec':
    default:

      $('map_nav_dec').className='map_nav_sel';
      $('map_nav_dms').className='map_nav_unsel';
      $('map_nav_lat_dec').style.display='';
      $('map_nav_lng_dec').style.display='';
      $('map_nav_lat_dms').style.display='none';
      $('map_nav_lng_dms').style.display='none';

    break;
  }

  update_coordinates();
}

/* function: update_coordinates
description: display map center lat,lon
****************************************************/
function update_coordinates(){

	var center = map.getCenter();

	var lat = center.lat();
	var lng = center.lng();

	$('map_nav_lat').value=Math.round(lat*1000000) / 1000000;
	$('map_nav_lng').value=Math.round(lng*1000000) / 1000000;

// show in deg/min/sec

	var deg = Math.abs(center.lat());
	var hemi = (center.lat() < 0) ? 'S' : 'N';

  var d = Math.floor(deg);
  deg = 60 * (deg - d);
  var m = Math.floor(deg);
  deg = 60 * (deg - m);
  var s = Math.floor(deg);

	$('map_nav_lat1').value=d;
	$('map_nav_lat2').value=m;
	$('map_nav_lat3').value=s;
	$('map_nav_lat4').value=hemi;


	var deg = Math.abs(center.lng());
-87.728055
	var hemi = (center.lng() < 0) ? 'W' : 'E';

  var d = Math.floor(deg);
  deg = 60 * (deg - d);
  var m = Math.floor(deg);
  deg = 60 * (deg - m);
  var s = Math.floor(deg);

	$('map_nav_lng1').value=d;
	$('map_nav_lng2').value=m;
	$('map_nav_lng3').value=s;
	$('map_nav_lng4').value=hemi;
}


function map_nav_show_crosshairs() {

  if (crosshairs) {

    if ( $('map_nav_show_crosshairs').checked )
      crosshairs.show();
    else
      crosshairs.hide();
  }
}

function map_nav_go() {

  if( $('map_nav_lat_dms').style.display=='') {


    var lat = parseInt($('map_nav_lat1').value) + ( ( parseInt($('map_nav_lat2').value) * 60) + parseInt($('map_nav_lat3').value) ) / 3600.0;
    var lng = parseInt($('map_nav_lng1').value) + ( ( parseInt($('map_nav_lng2').value) * 60) + parseInt($('map_nav_lng3').value) ) / 3600.0;

//    alert(lat);
//    alert(lng);

    if ( $('map_nav_lat4').value == 'S') {
      lat = -lat;
    }

    if ( $('map_nav_lng4').value == 'W') {
      lng = -lng;
    }

//    alert(lat);
//    alert(lng);

    var ctr = new GLatLng(lat, lng);

//    alert(ctr);

    map.setCenter( ctr );

  } else {

    var lat = $('map_nav_lat').value;
    var lng = $('map_nav_lng').value;
    var ctr = new GLatLng(lat, lng);
    map.setCenter( ctr );
  }
}

function map_nav_check_enter(event) {

  var event = new Event(event);

  if (event.key == 'enter') {

    map_nav_go();

    return true;
  }
  return false;
}

/* function: aviatlas_resize
description: adjust the layout when the browser resizes
****************************************************/
function aviatlas_resize() {

	if ($('hotspot-popup').style.display == 'block') {

    center_hotspot();

	} else if ($('profile-popup').style.display == 'block') {

    center_profile();

	} else if ($('welcome-message').style.display == 'block') {

    $('welcome-message').style.left = ((window.getWidth() - $('welcome-message').offsetWidth) / 2) + 'px';
    $('welcome-message').style.top = ((window.getHeight() - $('welcome-message').offsetHeight) / 2) + 'px';
	}

	if ($("TB_overlay")) {

    TB_overlaySize();
	}
}

/* function: center_hotspot
description: force the hotspot form to the center of the map
****************************************************/
function center_hotspot() {

	var width=$('map').offsetWidth - ($('tab-content-wrapper').offsetWidth + $('tab-content-wrapper').style.right);
	var height=$('map').offsetHeight;

  var left = (width / 2) - ($('hotspot-popup').offsetWidth / 2);
  var top = 38 + ( (height / 2) - ($('hotspot-popup').offsetHeight / 2) );

  $('hotspot-popup').style.left = left + 'px';
  $('hotspot-popup').style.top =  top + 'px';

}

/* function: clear_quick_message
description: clear out the quick message area
****************************************************/
function clear_quick_message() {
  $('quick-message').innerHTML = "";
  $('quick-message').style.display = "none";
}

/* function: clear_map_markers
description: clear all overlay markers from the map
****************************************************/
function clear_map_markers() {

  while (gmarkers.length > 0) {

    var marker = gmarkers.pop();
    map.removeOverlay(marker.tooltip);
    map.removeOverlay(marker);
  }

  gmarkersIds = [];
}

/* function: set_mode_people
description: display people on the map
****************************************************/
function set_mode_people(callback, param) {

  map_mode = MAP_MODE_PEOPLE;

  clear_map_markers();
  parent.location.hash = "#";

  var myXHR = new XHR({method:'post',onSuccess:function(response){

		var res = Json.evaluate(response);

		if (res["success"]==true){

		  var users = res["users"];

		  for (var i = 0; i < users.length; i++) {

    	  var point = new GLatLng(users[i].lat,	users[i].lng);

    		var info=Array();

    		info["id"] = users[i].id;
    		info["name"] = users[i].name;

    		var marker = user_create_marker(point, info);
    		map.addOverlay(marker);
    		gmarkers[i]=marker;
		  }
    	if (callback && param) {
    	  callback(param);
    	}

		} else {

      alert(res["message"]);
		}

  }}).send('/php/controller_user.php?action=get_all');

  $('sn-view-mode-hotspot').className='';
  $('sn-view-mode-people').className='sel';
  $('sn-view-mode-none').className='';
  $('view-mode').innerHTML='People';
  $('viewport-info').style.display='none';
  $('viewport-info').innerHTML='';
}

/* function: set_mode_none
description: clear out the map
****************************************************/
function set_mode_none() {

  map_mode = MAP_MODE_NONE;
  clear_map_markers();
  parent.location.hash = "#";
  $('sn-view-mode-hotspot').className='';
  $('sn-view-mode-people').className='';
  $('sn-view-mode-none').className='sel';
  $('view-mode').innerHTML='None';
  $('viewport-info').style.display='none';
  $('viewport-info').innerHTML='';
}


/* function: map_zoom_to_bounds
description: adjust the map to best show this bouding region
****************************************************/
function map_zoom_to_bounds(minlat, minlng, maxlat, maxlng) {

  if (minlat == maxlat && minlng == maxlng) {

    map.setZoom(13);
    map.setCenter(new GLatLng(minlat, minlng));

  } else {

    var bounds = new GLatLngBounds();

    bounds.extend(new GLatLng(minlat, minlng) );
    bounds.extend(new GLatLng(maxlat, maxlng) );

    map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
    map.setCenter(bounds.getCenter());
  }
}


/****************************************************
function: select_map_tool
description: set the active map tool mode when charting a route
****************************************************/
function select_map_tool(map_tool){

  map_tool_mode = map_tool;
  $('map_tool_pan').className = 'maptool tool_pan';
  $('map_tool_waypoint').className = 'maptool tool_waypoint';
  $('map_tool_polyline').className = 'maptool tool_polyline';
  $('map_tool_polygon').className = 'maptool tool_polygon';

  switch(map_tool) {

    case MAP_TOOL_WAYPOINT:

      $('map_tool_waypoint').className = 'maptool tool_waypoint_active';
      waypoint_enable_add_point_mode();

      break;

    case MAP_TOOL_POLYLINE:

      $('map_tool_polyline').className = 'maptool tool_polyline_active';
      waypoint_enable_add_polyline_mode();

      break;

    case MAP_TOOL_POLYGON:

      $('map_tool_polygon').className = 'maptool tool_polygon_active';
      waypoint_enable_add_polygon_mode();
      break;

    default:

      $('map_tool_pan').className = 'maptool tool_pan_active';

      reset_map_mode();
//      waypoint_disable_polyline_add_mode();
      map.enableDoubleClickZoom();
      break;

  }
}

function checkEnter(event, callback, param) {

  var event = new Event(event);

  if (event.key == 'enter') {

    if (callback) {

      callback(param);

    } else {

      return true;
    }
  }
  return false;
}

function set_map_mode(mode) {

  map.setMapType(mode);

  switch (mode) {

    case G_SATELLITE_MAP:

      $('sn-map-mode-map').className='';
      $('sn-map-mode-sat').className='sel';
      $('sn-map-mode-hyb').className='';
      $('sn-map-mode-ter').className='';
      $('map-mode').innerHTML='Satellite';
      $('tos_footer').className='footer_satellite_hybrid';
      break;

    case G_HYBRID_MAP:

      $('sn-map-mode-map').className='';
      $('sn-map-mode-sat').className='';
      $('sn-map-mode-hyb').className='sel';
      $('sn-map-mode-ter').className='';
      $('map-mode').innerHTML='Hybrid';
      $('tos_footer').className='footer_satellite_hybrid';
      break;

    case G_NORMAL_MAP:

      $('sn-map-mode-map').className='sel';
      $('sn-map-mode-sat').className='';
      $('sn-map-mode-hyb').className='';
      $('sn-map-mode-ter').className='';
      $('map-mode').innerHTML='Map';
      $('tos_footer').className='footer_map_terrain';
      break;

    case G_PHYSICAL_MAP:
    default:


      $('sn-map-mode-map').className='';
      $('sn-map-mode-sat').className='';
      $('sn-map-mode-hyb').className='';
      $('sn-map-mode-ter').className='sel';
      $('map-mode').innerHTML='Terrain';
      $('tos_footer').className='footer_map_terrain';
      break;
  }
}

/*
function: linkXXX
description: display the object token as a url hash
  display the object name in the document title
****************************************************/
function linkhotspot(token, title){

  parent.location.hash = 'h' + token;
  document.title = 'Aviatlas: ' + title;
}


function linktrip(token, title){

  parent.location.hash = 't' + token;
  document.title = 'Aviatlas: ' + title;
}

/*
function: cleanup_pending_edits
description: remove any undefined overlays from map
****************************************************/
function cleanup_pending_edits() {

	if (undefined_hotspot) {
	  map.removeOverlay(undefined_hotspot);
	  undefined_hotspot=null;
	}

	if (undefined_profile) {
	  map.removeOverlay(undefined_profile);
	  undefined_profile=null;
	}

	if (undefined_waypoint) {

	  map.removeOverlay(undefined_waypoint);
	  undefined_waypoint=null;
	}
}

/* function: welcome_hide
description: hide lightbox and welcome message
****************************************************/
function welcome_hide() {

  $('welcome-message').style.display = 'none';
  TB_zIndex = 100;
  TB_marginTop = 73;
  TB_remove();
}

/* function: welcome_show
description: show lightbox and welcome message
****************************************************/
function welcome_show() {

  if (parent.location.hash.length < 2) {

    $('welcome-message').style.position = 'absolute';
    $('welcome-message').style.display = 'block';
    $('welcome-message').style.left = ((window.getWidth() - $('welcome-message').offsetWidth) / 2) + 'px';
    $('welcome-message').style.top = ((window.getHeight() - $('welcome-message').offsetHeight) / 2) + 'px';

    $('welcome-message').style.display = 'block';

    TB_zIndex = 400;
    TB_marginTop = 0;
    TB_show_full(welcome_hide);

    $('welcome-message').style.display = 'block';
  }
}

var viewportXHR = null;

/* function: update_hotspot_viewport
description: update the hotspots currently visible on the map
****************************************************/
function update_hotspot_viewport_delta(callback, param)
{

  if (viewportXHR && viewportXHR.running) {

    viewportXHR.cancel();
    delete viewportXHR;
    viewportXHR = null;
  }

  if (map_mode == MAP_MODE_HOTSPOT) {

    $('progress').style.display='';

  //create the boundry for the data to provide initial filtering
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&z=' + map.getZoom();

    viewportXHR = new XHR({method:'post', async:true ,onSuccess:function(response){

    	var data = Json.evaluate(response);

    	if (data['s']==true) {

    	  //remove all existing hotspots outside the viewport

    	  var viewport = map.getBounds();
        var new_markers = [];
        var new_markerIds = [];

        var id;

// create an array of all the hotspots that should be on the map
      	for (i = 0; i < data['h'].length; i++) {
          new_markerIds.push( parseInt(data['h'][i].i) );
      	}

        for (i = 0; i < gmarkers.length; i++) {

          if ( viewport.containsLatLng(gmarkers[i].getLatLng() ) && new_markerIds.indexOf( gmarkers[i].hotspot_id ) != -1   ) {
// keep it if it's still within the current viewport and it's in the top 150
            new_markers.push(gmarkers[i]);

          } else {
// remove it
            map.removeOverlay(gmarkers[i].tooltip);
            map.removeOverlay(gmarkers[i]);
          }
        }


        gmarkers = new_markers;

      	for (i = 0; i < data['h'].length; i++) {

// only add the marker if it's not already on the map!

          id = parseInt(data['h'][i].i);

          if ( gmarkersIds.indexOf(id) == -1  ) {

        		var info=Array();

        		info['id'] = id;
        		info['name'] = data['h'][i].n;
        		info['token'] = data['h'][i].t;
         		info['r'] = data['h'][i].r;
         		info['c'] = data['h'][i].c;

        		var marker = hotspot_create_marker(new GLatLng(data['h'][i].a, data['h'][i].o), info);
        		map.addOverlay(marker);
        		gmarkers.push(marker);
            gmarkersIds.push(id);
          }
      	}
        gmarkersIds = new_markerIds;

        var tot = parseInt(data['t']);

        if (gmarkers.length != tot) {

          $('viewport-info').innerHTML = 'Viewing top ' + gmarkers.length + ' hotspots, zoom in to see more';

        } else {

          $('viewport-info').innerHTML = 'Viewing ' + gmarkers.length + ' hotspots';
        }

//        $('viewport-info').innerHTML = 'added: ' + added + ' - removed: ' + removed;
        $('viewport-info').style.display='';
        $('progress').style.display='none';

       	if (callback && param) {
      	  callback(param);
      	}

   	} else{

  			alert(return_obj["message"]);
    	}

    }}).send('/php/controller_hotspot.php?action=getviewport', getVars);
  }

}

/* function: set_mode_hotspot
description: display hotspots on the map
****************************************************/
function set_mode_hotspot(callback, param) {

  map_mode = MAP_MODE_HOTSPOT;

  clear_map_markers();
  var hotspot_token = parent.location.hash;

  if(hotspot_token.length == 34 && hotspot_token.substring(1,2) == 'h') {

    hotspot_token = hotspot_token.substring(2);

    var myXHR = new XHR({method:'post',onSuccess:function(response){

    	var data = Json.evaluate(response);

    	if (data['success']==true) {

    	  map.setZoom(12);

    	  id = data['id'];

//    	  alert(id);

        update_hotspot_viewport_delta(hotspot_show, id);

    	} else {

        update_hotspot_viewport_delta();
    	}

    }}).send('/php/controller_hotspot.php?action=getidfromtoken', 'token=' + hotspot_token );

  } else {

    update_hotspot_viewport_delta(callback, param);
  }

  $('sn-view-mode-hotspot').className='sel';
  $('sn-view-mode-people').className='';
  $('sn-view-mode-none').className='';
  $('view-mode').innerHTML='Hotspots';
  $('viewport-info').innerHTML='';
  $('viewport-info').style.display='none';
}



function search_about_go() {

  set_active_tab($('tab-search'));
  $('searchQuery').value = $('searchAbout').value;
  search_go(1);
}