﻿/**
 * Inside this file you can find common functions to control map initialization
 * behavior, and features.
 */
var map = null;
var layer01=null;
var pinID = 0;
var endPanAction=0;
var changeViewAction=0;
var mapPopupID=0;
var iLoadError=0;
var tmpShapeToPopup=null;
var objCoords=null;

/**
 * This function initializes the map.
 */
function GetMap()
{
	try{
		map = new VEMap("mapVE");
		//map.onLoadMap = EventMapLoad;
		//map.SetDashboardSize(VEDashboardSize.Small);
		map.onLoadMap = onMapLoaded;
		map.LoadMap(new VELatLong(13.4419, -89.1419), 5 ,'a' , false);//h for hybrid and r for road
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    map.HideDashboard();
    //map.ShowMiniMap(-15, 262);
    map.AttachEvent('onendcontinuouspan', HandleEndPan);
    map.AttachEvent('onchangeview', HandleChangeView);
      
      
    //map.AttachEvent("onclick", ShapeLayerAlert);
      
    //remember that you need a fuckin timeout to manage layer!!
    layer01 = new VEShapeLayer();
    layer01.SetTitle("layer01");
    map.AddShapeLayer(layer01);
    map.ClearInfoBoxStyles();
    //AddMyLayer(VEDataType.GeoRSS);
    //GetTiles();		
      
      
      // On mouse over
      
      var moved = false;
      
      function OnMouseOver(e)
        
      {
        
        if(!moved)
          
        {
          
          map.Pan(1, 1);
          
          map.Pan(-1, -1);
          
          moved = true;
          
        }
        
      }
      
      
      
      
      
      
      
		}
	catch(err)
{
    if (iLoadError < 2)
    {
      iLoadError++;
      setTimeout("GetMap()",2000);
    }else
    {
      //alert("The Mapping Control failed to load.");
    }
}	
}  
 
/**
 * This function overlay lidar tiles.
 */
function GetTiles()
{
  var bounds = [new VELatLongRectangle(new VELatLong(60,-175),new VELatLong(0,-67))];
  
  var tileSourceSpec = new VETileSourceSpecification("lidar", 
                                                     "http://cimss.ssec.wisc.edu/tropic/real-time/atlpac/winds/wg810vor.GIF");
  tileSourceSpec.NumServers = 1;
  tileSourceSpec.Bounds = bounds;
  tileSourceSpec.MinZoomLevel = 4;
  tileSourceSpec.MaxZoomLevel = 18;
  tileSourceSpec.Opacity = 0.4;
  tileSourceSpec.ZIndex = 100;
  
  map.AddTileLayer(tileSourceSpec, true);
} 

/**
 * Zoom in the map
 */
function MapZoomIn(){
  map.ZoomIn();
}
/**
 * Zoom out the map
 */
function MapZoomOut(){
  map.ZoomOut();
}

/**
 * Dispose map on exit
 */
function MapDispose(){
  if (map!=null)
  {
    map.Dispose();
    map = null;
  }
}
function HandleEndPan(e)
{
  EndPanManager();
} 
function HandleChangeView(e)
{
  ChangeViewManager();
} 

/**
 * This function fixes PNG transparency bug for pinpoint icons on IE < 7
 * @param {Shape} VE Shape
 * @param {sIcon} Source icon image
 */
function SetCustomIcon(shape,sIcon) {
  // check for IE<7
	if(/MSIE (\d+\.\d+);/.test(navigator.userAgent) &&((new Number(RegExp.$1))<7)){
    shape.SetCustomIcon("<div style=\"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sIcon+"', sizingMethod='image');height:40px;width:35px;\"></div>");
  }else {  
    shape.SetCustomIcon(sIcon);
  }
}

/**
 * This function draw polygons using the specified points, line width and line 
 * color
 * @param {number} id FIX! this parameter is not used
 * @param {VELatLong[]} points Shape perimeter points
 * @param {number} width Line width
 * @param {VEColor} color Line color
 */
function DrawPoly(id,points,width,color)
{
  shape = new VEShape(VEShapeType.Polyline, points);
  //shape.SetCustomIcon("<span style='font-family:Arial;font-size:12px;color:Blacssk;'><img src='../../_structure/img/markers/squareblu2.gif'/>poly01</span>");
  //shape.SetIconAnchor(inTheLake); 
  shape.HideIcon();
  shape.SetLineWidth(width);
  shape.SetLineColor(color);
  shape.SetFillColor(new VEColor(0,100,150,0.5));
  map.AddShape(shape);
}


/**
 * This function draw polygons using the specified layer, points, line width
 * line color, fill color, info box title, info box description and pinpoint
 * icon.
 * @param {VEShapeLayer} objLayer Layer to append generated shape
 * @param {VELatLong[]} points Shape perimeter points
 * @param {number} lineWidth Line width
 * @param {VEColor} lineColor Line color
 * @param {VEColor} fillColor Fill color
 * @param {string} sTitle Info box title
 * @param {string} sDesc Info description
 * @param {string} sIcon Source image shape icon
 * @return {VEShape} created shape
 */
function DrawPolyEx(objLayer,points,lineWidth,lineColor,fillColor,sTitle,sDesc,sIcon)
{
		var shape = new VEShape(VEShapeType.Polygon, points);
		shape.HideIcon();
		shape.SetLineWidth(lineWidth);
		shape.SetLineColor(lineColor);
		shape.SetFillColor(fillColor);
		if(sIcon.length>0) {
      SetCustomIcon(shape,sIcon);
		}
		if(sTitle.length>0 || sDesc.length>0){
			shape.ShowIcon();
			shape.SetTitle(sTitle);
			shape.SetDescription(sDesc);
		}
		objLayer.AddShape(shape);
	return shape;
}

/**
 * This function draw circles using the specified location, radius, line width
 * line color, fill color, info box title, info box description and pinpoint
 * icon.
 * @param {number} id FIX! parameter not used
 * @param {VELatLong} loc Center point
 * @param {number} radius Circle radius
 * @param {number} lineWidth Line width
 * @param {VEColor} lineColor Line color
 * @param {VEColor} fillColor Fill color
 * @param {string} sTitle Info box title
 * @param {string} sDesc Info box description
 * @param {string} sIcon Source image shape icon
 * @return {VEShape} created shape
 */
function DrawCircle(id, loc, radius, lineWidth, lineColor,fillColor,sTitle,sDesc,sIcon)
{
  
  var latin = loc.Latitude;
  var lonin = loc.Longitude;
  
  var R = 6371; // earth's mean radius in km
  var lat = (loc.Latitude * Math.PI) / 180; //rad
  var lon = (loc.Longitude * Math.PI) / 180; //rad
  var d = parseFloat(radius)/R;  // d = angular distance covered on earth's surface
  var locs = new Array();
  
  for (x = 0; x <= 360; x+=10) 
  { 
    var p2 = new VELatLong(0,0)            
    brng = x * Math.PI / 180; //rad
    p2.Latitude = Math.asin(Math.sin(lat)*Math.cos(d) + Math.cos(lat)*Math.sin(d)*Math.cos(brng));
    p2.Longitude = ((lon + Math.atan2(Math.sin(brng)*Math.sin(d)*Math.cos(lat), Math.cos(d)-Math.sin(lat)*Math.sin(p2.Latitude))) * 180) / Math.PI;
    p2.Latitude = (p2.Latitude * 180) / Math.PI;
    locs.push(p2);
  }
  shape = new VEShape(VEShapeType.Polygon, locs);
  shape.HideIcon();
  shape.SetLineWidth(lineWidth);
  shape.SetLineColor(lineColor);
  shape.SetFillColor(fillColor);
  if(sIcon.length>0) {
		SetCustomIcon(shape,sIcon);
  }
  if(sTitle.length>0 || sDesc.length>0){
		shape.ShowIcon();
		shape.SetIconAnchor(new VELatLong(latin,lonin));
		shape.SetTitle(sTitle);
		shape.SetDescription(sDesc);
	}
  map.AddShape(shape);
  return  shape;
}


/**
 * This function adds a pinpoint using the specified latitude, longitude,
 * info box title, info box description and pinpoint icon.
 * @param {number} sLat pinpoint latitude
 * @param {number} sLon pinpoint longitude
 * @param {string} sImgPath Source image pinpoint icon
 * @param {string} sTitle Info box title
 * @param {string} sText Info box description
 * @return {number} created shape id
 */
function addPin(sLat,sLon,sImgPath,sTitle,sText)
{   
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong((sLat), -(-sLon)));
	shape.SetTitle(sTitle);
	shape.SetDescription(sText);
	SetCustomIcon(shape,sImgPath);
	layer01.AddShape(shape)         
    var RetVal =(shape.GetID() + '_' + (10000 + pinID) + '_l');
	pinID++;
	return RetVal;
	
}

/**
 * This function adds a pinpoint using the specified latitude, longitude,
 * info box title, info box description and pinpoint icon.
 * @param {number} sLat pinpoint latitude
 * @param {number} sLon pinpoint longitude
 * @param {string} sImgPath Source image pinpoint icon
 * @param {string} sTitle Info box title
 * @param {string} sText Info box description
 * @return {VEShape} created shape
 */
function addPinShape(sLat,sLon,sImgPath,sTitle,sText)
{   
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong((sLat), -(-sLon)));
	shape.SetTitle(sTitle);
	shape.SetDescription(sText);
	SetCustomIcon(shape,sImgPath);
	layer01.AddShape(shape)      
    return shape;
}

/**
 * This function adds a pinpoint using the specified layer, latitude,
 * longitude, info box title, info box description and pinpoint icon.
 * @param {VEShapeLayer} objLayer Layer to append generated shape
 * @param {number} sLat pinpoint latitude
 * @param {number} sLon pinpoint longitude
 * @param {string} sImgPath Source image pinpoint icon
 * @param {string} sTitle Info box title
 * @param {string} sText Info box description
 * @return {number} created shape id
 */
function addPinEx(objLayer,sLat,sLon,sImgPath,sTitle,sText)
{   
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong((sLat), -(-sLon)));
	shape.SetTitle(sTitle);
	shape.SetDescription(sText);
	shape.HideIcon();
	SetCustomIcon(shape,sImgPath);
	objLayer.AddShape(shape);         
	var RetVal =(shape.GetID() + '_' + (10000 + pinID) + '_l');
	pinID++;
	return RetVal;
}

/**
 * This function adds a pinpoint using the specified layer, latitude,
 * longitude, info box title, info box description and pinpoint icon.
 * @param {VEShapeLayer} objLayer Layer to append generated shape
 * @param {number} sLat pinpoint latitude
 * @param {number} sLon pinpoint longitude
 * @param {string} sImgPath Source image pinpoint icon
 * @return {number} created shape id
 */
// addPin_Pub(objLayer, sLat, sLon, sImgPath)
function addPin_Pub(objLayer,sLat,sLon,sImgPath,sTitle)
{   
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong((sLat), -(-sLon)));
	shape.SetTitle(sTitle);
//	shape.SetDescription(sText);
	shape.HideIcon();
	SetCustomIcon(shape,sImgPath);
	objLayer.AddShape(shape);         
	var RetVal =(shape.GetID() + '_' + (10000 + pinID) + '_l');
	pinID++;
	return RetVal;
}

/**
 * This function adds a pinpoint using the specified layer, latitude,
 * longitude, info box title, info box description and pinpoint icon.
 * @TODO: check this function vs addPinEx because 
 *        appears to do the same operation
 * @param {VEShapeLayer} objLayer Layer to append generated shape
 * @param {number} sLat pinpoint latitude
 * @param {number} sLon pinpoint longitude
 * @param {string} sImgPath Source image pinpoint icon
 * @param {string} sTitle Info box title
 * @param {string} sText Info box description
 * @param {VEShapeLayer} objLayer Layer to append generated shape
 * @return {number} created shape id
 */
function addPinOnLayer(sLat,sLon,sImgPath,sTitle,sText,objLayer)
{   
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong((sLat), -(-sLon)));
	shape.SetTitle(sTitle);
	shape.SetDescription(sText);
	SetCustomIcon(shape,sImgPath);
  objLayer.AddShape(shape);     
    var RetVal =(shape.GetID() + '_' + (10000 + pinID) + '_l');
	pinID++;
	return RetVal;
}	


/**
 * Shows a popup window at the specified latitude and longitude.
 * @param {number} tmpID Temporal popup id
 * @param {number} sLat popup anchor latitude
 * @param {number} sLon popup anchor longitude
 */
function showPopup(tmpID,sLat,sLon){
  
  try{
    
    //endPanAction=1;
    changeViewAction=1;
    mapPopupID=tmpID;	
    objCoords=new VELatLong((sLat), -(-sLon));
    //map.SetCenter(objCoords);
    map.SetCenterAndZoom(objCoords, 10);
    //setTimeout("document.getElementById('"+tmpID+"_"+map.GUID+"').onmouseover();",1500);
	}
	catch(ex){alert(ex.message)}
}

/**
 * @TODO: Explain this function.
 */
function ChangeViewManager(){
  
	switch (changeViewAction)
	{
    case 1:
      //setTimeout("document.getElementById('"+mapPopupID+"_"+map.GUID+"').onmouseover();",800);
      //document.getElementById(mapPopupID+"_"+map.GUID).onmouseover();
      try{
        tmpShapeToPopup = map.GetShapeByID(mapPopupID);
        setTimeout("map.ShowInfoBox(tmpShapeToPopup,new VEPixel(400,200))",700);
        //there is a bug in VE with x coord, is locked to low values.
      }
      catch(ex){
        
      }
      break;
	}
	changeViewAction=0;
	//alert('shape: ' + mapPopupID + '   shapeID: ' )
}

/**
 * @TODO: Explain this function.
 */
function EndPanManager(){
	switch (endPanAction)
	{
    case 1:
      //setTimeout("document.getElementById('"+mapPopupID+"_"+map.GUID+"').onmouseover();",800);
      //document.getElementById(mapPopupID+"_"+map.GUID).onmouseover();
      //var shape = map.GetShapeByID(mapPopupID);
      //setTimeout("map.ShowInfoBox(shape)",2000);
      break;
	}
	endPanAction=0;
}

/**
 * Shows map controls
 */
function ShowControl()
{
	map.ShowDashboard();
}

/**
 * hides map controls
 */
function HideControl()
{
	map.HideDashboard();
}

/**
 * @TODO: Explain this function.
 */
function ShapeLayerAlert(e)
{
  if(e.elementID != null)
  {
    shape = map.GetShapeByID(e.elementID);
    layer = shape.GetShapeLayer();
    alert("Shape ID " + e.elementID + "\nbelongs to shape layer '" + layer.GetTitle() + "'.");
  }
}

/*
 * This function overlays the specified layer to the map.
 */
function OverlayWMS(layerName) {

  var layer = map.GetTileLayerByID(layerName);
  if(layer==null) {
    var tileSourceSpec = new VETileSourceSpecification(layerName,"/tiles/%4.xpng?layer="+layerName);
    tileSourceSpec.NumServers = 1
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.Opacity = 0.4;
    tileSourceSpec.ZIndex = 100;
    map.AddTileLayer(tileSourceSpec, true);
  } else {
    if(layer.isHidden) {
      map.ShowTileLayer(layerName);
      layer.isHidden=false;
    } else {
      map.HideTileLayer(layerName);
      layer.isHidden = true;
    }
  }
}
