﻿var addressList = null;
var markerList = null;
var geocoder = null;
var arrayInit = null;
var arrayInitIndex = 0;

function pageLoad()
{
  addressList = new Array();
  markerList = new Array();
  setFocus();
  
  if (GBrowserIsCompatible()) {
    var lat = parseFloat($get('m_C_mapLatitude').value);
    var lng = parseFloat($get('m_C_mapLongitude').value);
    var zoom = parseInt($get('m_C_mapZoomLevel').value);
    var mapType = parseInt($get('m_C_mapMapType').value);
    var route = $get('m_C_hRoute').value;
    
    mapdiv = document.getElementById("map");
    map = new google.maps.Map2(mapdiv);
    map.setUIToDefault(); 

    directionsPanel = $get("directionsPanel");  
    directions = new GDirections(map, directionsPanel);  
    GEvent.addListener(directions, "load", onGDirectionsLoad);
    GEvent.addListener(directions, "error", onGDirectionsError);
    
    geocoder = new GClientGeocoder();
    
   
    var start = new GLatLng(lat, lng);
    switch (mapType)
    {
      case 2:
        map.setCenter(start, zoom, G_SATELLITE_MAP);
        break;
      case 3:
        map.setCenter(start, zoom, G_HYBRID_MAP);
        break;
      default:
        map.setCenter(start, zoom, G_NORMAL_MAP);
        break;
    }
    showLatLng(start);
    showZoom();
    
    //GEvent.addDomListener(mapdiv, "DOMMouseScroll", map.wheelZoom); // Firefox 
    //GEvent.addDomListener(mapdiv, "mousewheel", map.wheelZoom); // IE 
   
    GEvent.addListener(map, "mousemove", function(point) { 
      showLatLng(point);
    }); 

    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
      showZoom();
    });
    
    if (route != "")
    {
      try
      {
        route = Base64.decode(route);
      }
      catch (err)
      {
        route = "";
      }
      if (route != "")
      {
        try
        {
          arrayInit = route.split("|");
          arrayInitIndex = 0;
          if (arrayInit.length > 0)
          {
            if (arrayInit[0] != "")
            {
              var tbAddr = $get('m_L_tbAddAddress');
              tbAddr.value = arrayInit[0];
              addAddress(arrayInit[0]);
            }
          }
        }
        catch (err)
        {
          clearAddress();
        }
      }
    }
    
  }
}

function pageUnload()
{
  GUnload();
}

function addAddress(address)
{ 
  if (address == '')
  {
    alert("Írj be egy címet!");
  }
  else
  {
    if (geocoder) 
    {
      $get('m_up1').style.display = 'block'; 
      geocoder.setBaseCountryCode("HU");
      geocoder.getLocations(
        address,
        function(response) 
        {
          $get('m_up1').style.display = 'none'; 
          if (!response || response.Status.code != 200) 
          {
            alert("Ez a cím, ebben a formában nem található! ("+response.Status.code+")\nEllenőrizd, hogy nem gépelted-e el a címet, vagy próbáld másképpen írni, vagy próbáld rövidebben írni (pl.: házszám, vagy utca név nélkül).\nA címeket ilyen formában adhatod meg:\n- Szőlő utca 25, 1034 III. kerület, Budapest, Hungary\n- Budapest, Szőlő utca 25\n- Budapest");
          } 
          else 
          {
            if (response.Placemark.length != 1)
            {
              showList(response);
            }
            else
            {
              clearList();
              
              var place = response.Placemark[0];
              var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
              map.setCenter(point, 16);
              
              Array.add(addressList, place.address);
              
              var markerText = '<div style="font-size:11pt;font-weight:bold;">Útvonaltervező</div>';
              markerText += "<b>" + place.address + "</b><br />";
              markerText += "Szélességi fok: " + point.lat() + " ";
              markerText += "Hosszúsági fok: " + point.lng() + "<br /><br />";
              
              markerText += "<a href='mailto:?body=http://www.ittvoltam.hu/utcakereso.aspx?address=" + Base64.encode(place.address) + "'>";
              markerText += "<img src='http://i.ittvoltam.hu/button/006b.jpg' align=absmiddle border=0>";
              markerText += " küldd el e-mail-ben ezt a helyet";
              markerText += "</a>";

              markerText += "<br />";

              markerText += "<a href='http://www.ittvoltam.hu/default.aspx?latitude=" + point.lat() + "&longitude=" + point.lng() + "&zoom=16'>";
              markerText += "<img src='http://i.ittvoltam.hu/button/002b.jpg' align=absmiddle border=0>";
              markerText += " új hely felvétele erre a pontra";
              markerText += "</a>";
              
              var icon = new GIcon();
              icon.image = "http://i.ittvoltam.hu/icon/green.png";
              icon.shadow = "http://i.ittvoltam.hu/icon/shadow.png";
              icon.iconSize = new GSize(20, 34);
              icon.shadowSize = new GSize(37, 34);
              icon.iconAnchor = new GPoint(9, 34);
              icon.infoWindowAnchor = new GPoint(9, 2);
              icon.infoShadowAnchor = new GPoint(18, 25);

              var marker = new GMarker(point, icon);
              
              GEvent.addListener(marker, "click", 
                function()
                {
                  marker.openInfoWindowHtml(markerText);  
                }
              );
              map.addOverlay(marker);
              
              Array.add(markerList, marker);
              var tb = $get('m_L_tbAddAddress');
              tb.value = '';
              showMap();
              showAddress();
              changeEnabled();
              
              $get('resultXml').style.display = 'none';
              $get('sendroute').innerHTML = '';
              
              if (arrayInit != null)
              {
                arrayInitIndex++;
                if (arrayInitIndex < arrayInit.length)
                {
                  if (arrayInit[arrayInitIndex] != "")
                  {
                    var tbAddr = $get('m_L_tbAddAddress');
                    tbAddr.value = arrayInit[arrayInitIndex];
                    addAddress(arrayInit[arrayInitIndex]);
                  }
                  else
                  {
                    getDirections();  
                  }
                }
              }
              
            }
          }
        }
      );
      
    }
  }  
  setFocus();
}

function clearList()
{
  var responseList = $get("responseList");
  responseList.innerHTML = "";
}

function showList(response)
{
  var s = "<br><b>Válassz az alábbi címek közül:</b><br>";
  var place;
  var responseList = $get("responseList");
  for (i=0; i<response.Placemark.length; i++)
  {
    place = response.Placemark[i];
    s += '<br>• <a href="." onclick="addAddress(\''+place.address+'\'); event.returnValue = false; return false;">';
    s += place.address;
    s += "</a><br>";
  }
  responseList.innerHTML = s;
}

function showMap()
{
  if (markerList.length > 0)
  {
    var zoom = map.getZoom();
    if (zoom < 8)
    {
      zoom = 16;
    }
    
    var latMin = 1000;
    var latMax = -1000;
    var lngMin = 1000;
    var lngMax = -1000;
    var latlng;
    for (i=0; i<markerList.length; i++)
    {
      latlng = markerList[i].getPoint();
      if (latlng.lat() < latMin)
      {
        latMin = latlng.lat();
      }
      if (latlng.lat() > latMax)
      {
        latMax = latlng.lat();
      }
      if (latlng.lng() < lngMin)
      {
        lngMin = latlng.lng();
      }
      if (latlng.lng() > lngMax)
      {
        lngMax = latlng.lng();
      }
    } 
  
    var gbounds = new GLatLngBounds(new GLatLng(latMin, lngMin), new GLatLng(latMax, lngMax));
    map.setCenter(gbounds.getCenter(), map.getBoundsZoomLevel(gbounds));
  }
}  
  

function changeEnabled()
{
  var ButtonClearAddress = $get('ButtonClearAddress');
  var ButtonGetDirections = $get('ButtonGetDirections');
  
  if (addressList.length > 0)
  {
    ButtonClearAddress.disabled = '';
    if (addressList.length > 1)
    {
      ButtonGetDirections.disabled = '';
    } 
    else
    {
      ButtonGetDirections.disabled = 'disabled';
    } 
  }
  else
  {
    ButtonClearAddress.disabled = 'disabled';
    ButtonGetDirections.disabled = 'disabled';
  } 
}

function showAddress()
{
  var s = '';
  if (addressList.length > 0)
  {
    s = "<b>Útvonalterv:</b><br>";
    for (i=0; i<addressList.length; i++)
    {
      s += '• ';
      if (i==0)
      {
        s += '<b>indulás:</b> ';
      }
      else
      {
        if (i==addressList.length-1)
        {
          s += '<b>érkezés:</b> ';
        }
        else
        {
          s += '<b>megálló:</b> ';
        }
      }
      s += addressList[i];
      s += ' <a href="#" title="törlés" onClick="removeAddress(' + i + ');event.returnValue = false; return false;">(x)</a>';
      s += '<br/>';
    }
  }
  $get('addressList').innerHTML = s;
}

function removeAddress(i)
{
  map.removeOverlay(markerList[i]);
  Array.removeAt(addressList, i);
  Array.removeAt(markerList, i);
  showMap();
  showAddress();
  changeEnabled();
  directions.clear();
  $get('addressResult').innerHTML = '';
}

function clearAddress()
{
  map.clearOverlays();
  Array.clear(addressList);
  Array.clear(markerList);
  changeEnabled();
  directions.clear();
  $get('addressList').innerHTML = '';
  $get('addressResult').innerHTML = '';
  $get('resultXml').style.display = 'none';
  $get('sendroute').innerHTML = '';
  clearList();
  arrayInit = null;
}




function getDirections()
{
  if (addressList.length > 1)
  {
    var ButtonGetDirections = $get('ButtonGetDirections');
    ButtonGetDirections.disabled = 'disabled';
    $get('m_up1').style.display = 'block'; 
    
    clearList();
    map.clearOverlays();
    var s = "from: " + addressList[0];
    var route = addressList[0] + "|";
    for (i=1; i<addressList.length; i++)
    {
      s += " to: " + addressList[i];
      route += addressList[i] + "|";
    }

    var tm;
    if ($get('m_L_rbCar').checked == true)
    {
      tm = G_TRAVEL_MODE_DRIVING;
    }
    else
    {
      tm = G_TRAVEL_MODE_WALKING;
    }
    directions.load(s, { "travelMode": tm, "avoidHighways": !$get('m_L_cbHighway').checked });
    
    var sendrouteText = "";
    sendrouteText += "<div style='margin-top:4px;text-align:center;font-weight:bold'>";
    sendrouteText += "<span style='color:red;font-family:webdings;font-size:12pt;'>4</span> ";
    sendrouteText += "<a href='mailto:?body=http://www.ittvoltam.hu/utvonaltervezo.aspx?route=" + Base64.encode(route) + "'>";
    sendrouteText += "útvonalterv küldése<br />e-mail-ben";
    sendrouteText += "</a></div>";    
    $get('sendroute').innerHTML = sendrouteText;
    
  }
}

function onGDirectionsError()
{
  $get('m_up1').style.display = 'none'; 
  $get('sendroute').innerHTML = "";
  var ButtonGetDirections = $get('ButtonGetDirections');
  ButtonGetDirections.disabled = '';
  alert("Sajnáljuk, de a megadott címek között nem sikerült útvonalat tervezni!");
}

function setFocus()
{
  var tb = $get('m_L_tbAddAddress');
  tb.focus();
}

function onGDirectionsLoad()
{ 
  arrayInit = null;
  document.documentElement.scrollTop = 200;
  var ButtonGetDirections = $get('ButtonGetDirections');
  ButtonGetDirections.disabled = '';
  $get('m_up1').style.display = 'none';


  var min = parseInt(directions.getDuration().seconds / 60);
  var hour = parseInt((min / 60 * 10)) / 10;
  var km = parseInt(directions.getDistance().meters / 1000);
  $get('addressResult').innerHTML = "<br><b>Eredmény:</b><br />• távolság: " + km + " km<br />• idő: " + min + " perc (" + hour + " óra)";
  
  /*
  var route, step;
  var place, point;
  var html = '<?xml version="1.0" encoding="utf-8" ?>\n'
  + '<directions>\n';
  html += '  <summary>\n';
  html += '    ' + directions.getSummaryHtml() + '\n';
  html += '  </summary>\n';
  html += '  <meters>\n';
  html += '    ' + directions.getDistance().meters + '\n';
  html += '  </meters>\n';
  html += '  <seconds>\n';
  html += '    ' + directions.getDuration().seconds + '\n';
  html += '  </seconds>\n';
  for (i=0; i<directions.getNumRoutes(); i++)
  {
    route = directions.getRoute(i);
    html += '  <route>\n';
    html += '    <index>\n';
    html += '      ' + i + '\n';
    html += '    </index>\n';

    place = route.getStartGeocode();
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    html += '    <start>\n';
    html += '      ' + place.address + '\n';
    html += '    </start>\n';
    html += '    <startLatitude>\n';
    html += '      ' + point.lat() + '\n';
    html += '    </startLatitude>\n';
    html += '    <startLongitude>\n';
    html += '      ' + point.lng() + '\n';
    html += '    </startLongitude>\n';
    
    place = route.getEndGeocode();
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    html += '    <end>\n';
    html += '      ' + place.address + '\n';
    html += '    </end>\n';
    html += '    <endLatitude>\n';
    html += '      ' + point.lat() + '\n';
    html += '    </endLatitude>\n';
    html += '    <endLongitude>\n';
    html += '      ' + point.lng() + '\n';
    html += '    </endLongitude>\n';
    
    html += '    <summary>\n';
    html += '      ' + route.getSummaryHtml() + '\n';
    html += '    </summary>\n';
    html += '    <meters>\n';
    html += '      ' + route.getDistance().meters + '\n';
    html += '    </meters>\n';
    html += '    <seconds>\n';
    html += '      ' + route.getDuration().seconds + '\n';
    html += '    </seconds>\n';
    for (l=0; l<route.getNumSteps(); l++)
    {
      step = route.getStep(l);
      html += '    <step>\n';
      html += '      <index>\n';
      html += '        ' + l + '\n';
      html += '      </index>\n';
      html += '      <latitude>\n';
      html += '        ' + step.getLatLng().lat() + '\n';
      html += '      </latitude>\n';
      html += '      <longitude>\n';
      html += '        ' + step.getLatLng().lng() + '\n';
      html += '      </longitude>\n';
      html += '      <description>\n';
      html += '        ' + step.getDescriptionHtml().replace(/</g, '&lt;').replace(/>/g, '&gt;') + '\n';
      html += '      </description>\n';
      html += '      <meters>\n';
      html += '        ' + step.getDistance().meters + '\n';
      html += '      </meters>\n';
      html += '      <seconds>\n';
      html += '        ' + step.getDuration().seconds + '\n';
      html += '      </seconds>\n';
      html += '    </step>\n';
    }
    html += '  </route>\n';
  }  
  html += '</directions>\n';
  $get('m_C_tbResultXml').value = html; 
  $get('resultXml').style.display = 'block';
  */
}



if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
