//the map object
var map = null;
var goto_llong = queryString('mapit');
var wrap_bound_layer = null;
var searchId = -1;
var pbound_layer = null;
var proj_layer = null;
var traffic_layer = null;

//load map    
function Page_Load() {  

   var begin_long = queryString('mapx');
   var begin_lat = queryString('mapy');
   

   if (queryString('searchId') != null && queryString('searchId') != '') {
       searchId = queryString('searchId');
   }
   
   if (begin_long=='' || begin_lat=='')
   {
      begin_long=start_lon;
      begin_lat=start_lat;
      begin_zoom=map_scale;
   }
   else
   {
      begin_zoom=12;
   }
   
    var mapArgs = new CK.VEMapArgs("myMap", new VELatLong(begin_lat, begin_long), begin_zoom, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDashboardSize.Normal, "ctl00_ContentPlaceholderMain_pnlPopup");
   
    map = new CK.VEMap(Ck.EntergyMapData, mapArgs, county_bounds, searchId);
    
   if (show_map_bounds)
   {
      wrap_bound_layer = new VEShapeLayer();
      var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, 'wrapbounds/' + wrap_descriptor + '.xml', wrap_bound_layer);
      map._map.ImportShapeLayerData(veLayerSpec, wrap_bounds_onload, false);
   }
   
   pbound_layer = new VEShapeLayer();
   var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, 'PropertyBoundaryFeed.aspx', pbound_layer);
   map._map.ImportShapeLayerData(veLayerSpec, prop_bounds_onload, false);


   if (show_icon)
   {
      var icon_style='width: 32px; height: 32px;';
      
      if (iever>-1 && iever<=7.0)
      {
         //alert("OLD");
         icon_style=icon_style + 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + icon_url + '\', sizingMethod=\'image\');';
      }
      else
      {
         //alert("NEWER");
         icon_style=icon_style + 'background-image: url(' + icon_url + ');'
      }

      var newShape = new VEShape(VEShapeType.Pushpin, new VELatLong(icon_lat, icon_lon)); 
      newShape.SetCustomIcon('<div style="' + icon_style + '"></div>');

      map._map.AddShape(newShape);
   }
}  

function wrap_bounds_onload(layer)
{
   var numShapes = layer.GetShapeCount();
   var shape;
   for(var i=0; i < numShapes ; ++i)
   {
      shape = layer.GetShapeByIndex(i);
      shape.SetLineWidth(4);
      shape.SetLineColor(new VEColor(0,0,255,0.8));
      shape.SetFillColor(new VEColor(0,0,0,0.0));
      shape.HideIcon();
   }
}

function prop_bounds_onload(layer)
{
   var numShapes = layer.GetShapeCount();
   var shape;
   for(var i=0; i < numShapes ; ++i)
   {
      shape = layer.GetShapeByIndex(i);
      shape.ShowDetailOnMouseOver=false;
      shape.HideIcon();
   }
}


//Clean up all objects
function Page_Unload() {
    if (map!=null) {
        map.Dispose();
        map = null;
    }
}

function findNearby(what) {
   if (map!=null) {
   map.FindNearby(what);
   //document.getElementById('debug').innerHTML = what;
   }
}

function AddCustomLayer(what) {
    if (map != null) {
   map.AddCustomLayer(what);
   offAllButtons('points');
   var btn = document.getElementById(what+'-item');
   btn.className='current';
   }
}

function AddTransportationTiles(stateid) {
   if (map!=null) {
      var btn = document.getElementById('transportation-item');
      var folder;
      var opac = 0.7;
      
      switch(stateid)
      {
         case 'louisiana':
            folder = 'http://geo.leo-llc.com/vetiles/etr_trans';
            break;
         case 'arkansas':
            folder = 'http://geo.leo-llc.com/vetiles/etr_artrans';
            break;
         case 'mississippi':
            folder = 'http://geo.leo-llc.com/vetiles/etr_mstrans';
            break;
         case 'texas':
            folder = 'http://geo.leo-llc.com/vetiles/etr_txtrans';
            break;
         default:
            return;
            break;
      }

      var imgtyp = '.png';

      if (btn.className == 'current')
      {
         //already on, turn off
         DeleteTiles();
      }
      else
      {
         var ver = getInternetExplorerVersion();
         
         if (ver < 7.0 && ver != -1)
         {
            if (stateid == 'louisiana') {
               //use jpegs
               imgtyp = '.jpg';
               opac = 0.5;
            }
            else {
               opac = 1;
            }
         }
         
         DeleteTiles();
         map.AddCustomTiles(folder + "/%4" + imgtyp,opac);
         LoadLegend(folder);
         btn.className='current';
      }
   }
}

function AddCustomTiles(whichOnes) {
   if (map!=null) {
      var btn = document.getElementById(whichOnes+'-item');
      var folder = 'http://geo.leo-llc.com/vetiles/etr_' + whichOnes
      var imgtyp = '.png';
      var opac = 0.6;

      if (whichOnes == 'la_elev' || whichOnes == 'la_flood') {
          opac = 1;
      }
   
      if (btn.className=='current') {
         //already on, turn off
         DeleteTiles();
         btn.className='noclass';
      } else {
         DeleteTiles();
         map.AddCustomTiles(folder + "/%4" + imgtyp,opac);
         LoadLegend(folder);
         btn.className='current';
      }
   }
}

function AddStiTiles()
{
   if (map)
   {
      var varid = document.getElementById('sel_sti_layer').value;
      if (varid=='none')
      {
         alert('You must select a layer first.\nPlease try again.');
         return;
      }

      var tileurl = 'http://geo.leo-llc.com/vetiles/sti/' + state_abbr + '/' + varid + '/tiles/%4.png';
      DeleteTiles();
      map.AddCustomTiles(tileurl, 1.0);
      document.getElementById('btn_sti').className='current';
      LoadLegend('http://geo.leo-llc.com/vetiles/sti/' + state_abbr + '/' + varid);
      map._max_zoom = 12;
   }
}

function LoadLegend(folder) {
   var legDiv = document.getElementById("myLegend");
   legDiv.innerHTML = "<img src=\""+folder+"/legend.png\" />";
   map.ShowLegend();
}


function DeleteTiles() {
   offAllButtons('tiles');
   map.DeleteTiles();
   
   map.LegendMessage(null);
   map._max_zoom = 0;
}

function ResetMap() {
    _lastfindresults = null;
   offAllButtons();
   map.DeleteFindResults();
   map.ResetZoomAndCenter();
}

function offButton(itemDivId) {
   var d = document.getElementById(itemDivId);
   if (d)
   {
      d.className='noclass';
   }
   
}

function offAllButtons(whichKind) {
   if (whichKind=='tiles') {
      offButton('transportation-item');
      offButton('parish-item');
      offButton('arcounty-item');
      offButton('mscounty-item');
      offButton('txcounty-item');
      offButton('popdensity-item');
      offButton('arpopdens-item');
      offButton('mspopdens-item');
      offButton('txpopdens-item');
      offButton('ecodevregions-item');
      offButton('btn_sti');
      offButton('la_flood-item');
      offButton('la_elev-item');
      if (document.getElementById('aedczoning-item')!=null)
      {
         offButton('aedczoning-item');
         offButton('aedcflood-item');
         offButton('aedcindsuit-item');
         offButton('aedccomsuit-item');
      }
      if (document.getElementById('stm_suit_ind-item')!=null)
      {
         offButton('stm_suit_ind-item');
      }
   } else {
      offButton('ports-item');
      offButton('schools-item');
      offButton('fire-item');
      offButton('colleges-item');
      offButton('colleges-tech-item');
      offButton('colleges-community-item');
      offButton('colleges-public-item');
      offButton('colleges-private-item');
      offButton('colleges-senior-item');
      offButton('hospitals-item');
   }
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
function checkVersion()
// i don't use this code, it's just here to show usage
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 6.0 ) 
      msg = "You're using a recent copy of Internet Explorer."
    else
      msg = "You should upgrade your copy of Internet Explorer.";
  }
  alert( msg );
}

function PageQuery(q)
   {
      if(q.length > 1) this.q = q.substring(1, q.length);
      else this.q = null;
      this.keyValuePairs = new Array();

      if(q) {
         for(var i=0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
         }
      }
      
      this.getKeyValuePairs = function() { return this.keyValuePairs; }
      
      this.getValue = function(s) {
         for(var j=0; j < this.keyValuePairs.length; j++) {
            if(this.keyValuePairs[j].split("=")[0] == s)
               return this.keyValuePairs[j].split("=")[1];
         }
         return false;
      }

      this.getParameters = function() {
         var a = new Array(this.getLength());
         for(var j=0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
         }
         return a;
      }

      this.getLength = function() { return this.keyValuePairs.length; }
   }

function queryString(key) {
      var page = new PageQuery(window.location.search);
      return URLDecode(page.getValue(key));
   }
   
function displayItem(key) {
      if(queryString(key)=='false')
         {
            document.write("you didn't enter a ?name=value querystring item.");
         }
         else {
            document.write(queryString(key));
         }
   }
   
function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   
   return plaintext;
}

//set page event handlers
if (window.attachEvent) {
	window.attachEvent("onload", Page_Load);
	window.attachEvent("onunload", Page_Unload);	
} else {
	window.addEventListener("DOMContentLoaded", Page_Load, false);
	window.addEventListener("unload", Page_Unload, false);
}

function loadProjects(btn)
{

   //alert(btn.className);
   
   if (proj_layer && proj_layer.IsVisible())
   {
      proj_layer.Hide();
      btn.parentNode.className='';
   }
   else
   {
      if (proj_layer && !proj_layer.IsVisible())
      {
         btn.parentNode.className='current';
         proj_layer.Show();
      }
      else
      {
         btn.parentNode.className='current';
   
         proj_layer = new VEShapeLayer();
         var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, 'ProjectFeed.aspx', proj_layer);
         map._map.ImportShapeLayerData(veLayerSpec, onProjectLoad, false);
      }
   }
}

function loadTraffic() {
    if (traffic_layer) {
        traffic_layer.Hide();
        traffic_layer = null;
    }
    var parishCode = $('#ctl00_ContentPlaceholderMain_trafficParishList').val();
    if (parishCode > '00') {
        traffic_layer = new VEShapeLayer();
        var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, 'TrafficFeed.aspx?pc=' + parishCode, traffic_layer);
        map._map.ImportShapeLayerData(veLayerSpec, onTrafficLoad, false);
    }
}


function toggleTrafficParish(btn) {

    if (traffic_layer && traffic_layer.IsVisible()) {
        traffic_layer.Hide();
        btn.parentNode.className = '';
        document.getElementById("traffic-parish").style.display='none';
    }
    else {
        document.getElementById("traffic-parish").style.display='block';
        btn.parentNode.className = 'current';
        if (traffic_layer && !traffic_layer.IsVisible()) {
            traffic_layer.Show();
        }
        else {
            $('#ctl00_ContentPlaceholderMain_trafficParishList').val('');
            loadTraffic();
        }
    }
}

function onProjectLoad(layer)
{
   var icon_style='width: 24px; height: 24px;';
      
   if (iever>-1 && iever<=7.0)
   {
      icon_style=icon_style + 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/construction.png\', sizingMethod=\'image\');';
   }
   else
   {
      icon_style=icon_style + 'background-image: url(images/construction.png);'
   }

   var count=layer.GetShapeCount();
   
   for (i=0; i<count ; i++)
   {
      var shp = layer.GetShapeByIndex(i);
      shp.SetCustomIcon('<div style="' + icon_style + '"></div>');
   }}

function onTrafficLoad(layer) {
    var count = layer.GetShapeCount();
    for (i = 0; i < count; i++) {
        var shp = layer.GetShapeByIndex(i);
        shp.SetCustomIcon('<div style="width: 17px; height: 17px; background-image: url(images/car.png);"></div>');
    }
}

   
function ExportFindResults()
{
    if (_lastfindresults != null && _lastfindresults.length > 0) {
        var form = document.forms[0];

        var el = document.getElementById("ExportData");
        el.value = SerializeResults(_lastfindresults);
      
        setTimeout('document.forms[0].submit();', 500);
    }
}

function SerializeResults(results) {
    var master = document.createElement("Results");

    for (var i = 0; i < results.length; i++) {
        var result = results[i];

        var child = document.createElement("Result");
        
        var name = document.createAttribute("Name");
        var description = document.createAttribute("Description");
        var latitude = document.createAttribute("Lat");
        var longitude = document.createAttribute("Long");
        var phone = document.createAttribute("Phone");
        
        name.value = result.Name;
        description.value = result.Description;
        latitude.value = result.LatLong.Latitude;
        longitude.value = result.LatLong.Longitude;
        phone.value = result.Phone;

        child.setAttributeNode(name);
        child.setAttributeNode(description);
        child.setAttributeNode(latitude);
        child.setAttributeNode(longitude);
        child.setAttributeNode(phone);

        master.appendChild(child);
    }

    var dummy = document.createElement("dummy");

    dummy.appendChild(master);
    
    return dummy.innerHTML;
}


function loadPhotoMap(result){
   var photo_map = new VEMap('div_map_photo');
   photo_map.SetDashboardSize(VEDashboardSize.Tiny);
   var my_map_options = new VEMapOptions();
   my_map_options.BirdseyeOrientation = result.map_dir;
   photo_map.LoadMap(new VELatLong(result.map_x, result.map_y), result.map_zoom, result.map_style, true, VEMapMode.Mode2D, false, 0, my_map_options);
}
            


if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

