﻿
    var map;
    var gdir;
    var geocoder = null;

    var wiki = null;
    var panoramio = null;  
    
    var M_UA="Unknown address.\n Error code: ";
    var M_UNA="The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: "
    var M_SE="Google server error.\n Error code: "; 
    var M_MQ="No address.\n Error code: ";
    var M_BK="Bad google key.\n Error code: ";
    var	M_BR="Bad request.\n Error code: ";
    var	M_UD="Unknown direction. Could not route (yet?).\n Error code: ";
    var	M_TMQ="Limit for requests is reached.\n Error code: ";
    var M_UE="Unknown error.\n Error code: ";

    var defLat=55.75222;
    var defLng=37.61556; 

    var lcs;
	   
    GSearch.setOnLoadCallback(initialize);
    
    function initialize() {
      if (GBrowserIsCompatible()) {      
        //map = new google.maps.Map2(document.getElementById("map_canvas"));
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        geocoder = new GClientGeocoder();

        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // added to trigger marker swap

        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));

	map.setCenter(new GLatLng(defLat,defLng),10);

        var options = {
            resultList : google.maps.LocalSearch.RESULT_LIST_SUPPRESS
        };

        lcs = new google.maps.LocalSearch(options);
        map.addControl(lcs);

        GEvent.addListener(map, "click", clickFunction);

//        setDirections(ifrom,ito,'ru');

      }
    }

    function setDirections(fromAddress, toAddress, locale, walk) {
     if (walk)
      gdir.load(fromAddress + toAddress, { "locale": locale, travelMode:G_TRAVEL_MODE_WALKING});
     else 
      gdir.load(fromAddress + toAddress, { "locale": locale });
    }

    function clickFunction(overlay, latlng) {
      if (latlng) 
      {
        geocoder.getLocations(latlng, function(addresses) {
          if(addresses.Status.code != 200) {
            alert("Google reverse geocoder failed to find an address for " + latlng.toUrlValue());
          }
          else 
          { address = addresses.Placemark[0];
            var myHtml = address.address;
            map.openInfoWindow(latlng, myHtml); }
        });
      }
    }

	
    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert(M_UA + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert(M_SE + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert(M_MQ + gdir.getStatus().code);

	   //else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)
	   //  alert(M_UNA + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert(M_BK + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert(M_BR + gdir.getStatus().code);
	    
	   else if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS)
	     alert(M_UD + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_TOO_MANY_QUERIES)
	     alert(M_TMQ + gdir.getStatus().code);

	   else alert(M_UE + gdir.getStatus().code);
	   
	}

	function onGDirectionsLoad(){ 
        // Use this function to access information about the latest load()
        // results.

          postMap(ip);              
	}

	function OnSubmitDirectionForm(form, locale)
        {
          var from = form.street1.value+' '+form.bld1.value+' '+form.city1.value+' '+form.country1.value;
          var to = form.street2.value+' '+form.bld2.value+' '+form.city2.value+' '+form.country2.value;
          var via = form.street0.value+' '+form.bld0.value+' '+form.city0.value+' '+form.country0.value;

          document.getElementById("share").style.display="none";
         
          if (trimResponse(from)!='' && trimResponse(to)!='')
          {
           from = "from: "+from;
           
           via = trimResponse(via);

           var sTo="";

           if (via!='')
             sTo=" to: "+via;

           sTo+=" to: "+to;
                     
     	   setDirections(from, sTo, locale, form.walk.checked);
          }

          if (form.pan.checked)
          {
           panoramio = new GLayer("com.panoramio.all")
           map.addOverlay(panoramio);
          }
          else 
          {
           if (panoramio!=null)
             map.removeOverlay(panoramio);

           panoramio = null;  
          }

          if (form.wik.checked)
          {
           wiki = new GLayer("org.wikipedia."+locale)
           map.addOverlay(wiki);
          }
          else 
          {
           if (wiki!=null)
             map.removeOverlay(wiki);

           wiki = null;  
          }

          return false;
	}

       function getLocale()
       {
        if ( navigator ) {
           if ( navigator.language ) {
             return navigator.language;
        }
        else if ( navigator.browserLanguage ) {
          return navigator.browserLanguage;
        }
        else if ( navigator.systemLanguage ) {
           return navigator.systemLanguage;
        }
        else if ( navigator.userLanguage ) {
          return navigator.userLanguage;
        }
       }

       return "en";
      }

      function showOpt()
        {
          var oimg = document.getElementById("opt_img");
          var otxt = document.getElementById("opt_txt");
          var o = document.getElementById("opt");
          var o1 = document.getElementById("opt1");
          if (o.style.display=='block')
          { 
            o.style.display='none';
            o1.style.display='none';
            oimg.src="triangle.gif";
            otxt.innerHTML="<em>More details</em>";
          }
          else
          {
            o.style.display='block'; 
            o1.style.display='block'; 
            oimg.src="opentriangle.gif";
            otxt.innerHTML="";
          }
        }

///////////////////////////////////////////////////////////////////////
// The add-on code for draggable markers
// Esa 2008
//
	var newMarkers = [];
	var latLngs = [];
	var icons = [];
	
	// Note the 'addoverlay' GEvent listener added inside initialize() function

	function onGDirectionsAddOverlay(){ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++) 
	{map.removeOverlay(newMarkers[i]);
	}

	// Loop through the markers and create draggable copies
	for (var i=0; i<=gdir.getNumRoutes(); i++) 
		{
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
		map.addOverlay(newMarkers[i]);

		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i], "dragend", function()
		  {
		var points = [];
		for (var i=0; i<newMarkers.length; i++) 
			{
		points[i]= newMarkers[i].getLatLng();
			}
		gdir.loadFromWaypoints(points);
		  });

		//Bind 'click' event to original hidden marker
		copyClick(newMarkers[i],originalMarker);
		
		// hide or remove the original marker
		//originalMarker.hide();
		map.removeOverlay(originalMarker);

                 var search = document.forms['dirform'].poi.value;
 
                 if (search) 
                 {
                   lcs.execute(search);
                 }
		}
		
		function copyClick(newMarker,oldMarker){
		GEvent.addListener(newMarker, 'click', function()
		  {GEvent.trigger(oldMarker,'click');
		  });
		}
// End of draggable markers code
// Esa 2008
///////////////////////////////////////////////////////////////////////
	}


function postMap(ip)
{
  var o = document.forms['dirform'];

  var query = 'country1='+encodeURIComponent(o.country1.value);
      query+= '&country2='+encodeURIComponent(o.country2.value);
      query+= '&city1='+encodeURIComponent(o.city1.value);
      query+= '&city2='+encodeURIComponent(o.city2.value);
      query+= '&street1='+encodeURIComponent(o.street1.value);
      query+= '&street2='+encodeURIComponent(o.street2.value);
      query+= '&bld1='+encodeURIComponent(o.bld1.value);
      query+= '&bld2='+encodeURIComponent(o.bld2.value);
      query+= '&poi='+encodeURIComponent(o.poi.value);
      query+= '&c='+ip;

  var uri = '/myway/savenote.jsp';

  var beforeAction = function() 
  { document.getElementById("indicator").style.display="inline"; };

  var afterAction = function() 
  { document.getElementById("indicator").style.display="none"; };

  noteAjaxEnginePost(uri, query, noteHandlerFunction, noteErrorFunction, beforeAction, afterAction);
}

function noteErrorFunction(){  alert("Could not save results ...");}

function noteHandlerFunction(txt, xmlDoc)
{ if (txt)
  { var s = trimResponse(txt);
    var res = eval("("+s+")");

    s = res.tiny; 
    var ans="<strong>Share:</strong> ";
    ans+="<a href='javascript:void(0)' onClick=\"sendMail('"+s+"');\">email</a>";
    ans+="&nbsp;&nbsp;"
    ans+="<a href='javascript:void(0)' onClick=\"sendTwit('"+s+"');\">twitter</a>";
    ans+="&nbsp;&nbsp;"
    ans+="<a href='javascript:void(0)' onClick=\"sendFace('"+s+"');\">facebook</a>";

    document.getElementById("share").innerHTML = ans;
    document.getElementById("share").style.display="inline";

    setCookie('myway', res.id, 365);
  }
}

function noteAjaxEnginePost(uri, query, handlerFunction, errorFunction, beforeAction, afterAction)
{
    var contentType = "application/x-www-form-urlencoded; charset=UTF-8";

    if (handlerFunction==null)  handlerFunction = function() {};
    if (errorFunction==null)    errorFunction = function () {};
    if (beforeAction == null) beforeAction = function() {};
    if (afterAction == null) afterAction = function() {};  
    if (query==null) query="";
    var r = (window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
    if (r) { r.onreadystatechange = function()
      {	if (r.readyState == 4)
        {afterAction();
         if (r.status == 200)
  	 { xmlDoc = r.responseXML; txt = r.responseText;
           handlerFunction(txt, xmlDoc);}
         else          errorFunction();
        } }

     beforeAction(); r.open("POST", uri, true);
     r.setRequestHeader("Content-Type", contentType);
     r.setRequestHeader("Content-length", query.length);
     r.setRequestHeader("Connection", "close");
     r.send(query); return true;
  } else { afterAction(); errorFunction(); return false; }}

function trimResponse(s0)
{ if (s0==null) return s0; s=s0;

  var s1 = ' ';
  while (s.length>0 && s1==' ')
  {
   s1 = s.substring(s.length-1); 
   if (s1==' ' || s1=='\r' || s1=='\n' || s1=='\t') { s=s.substring(0,s.length-1); s1=' '; }      
  }

  while (s.length>0)
  { s1=s.substring(0,1);
    if (s1==' ' || s1=='\r' || s1=='\n' || s1=='\t') s=s.substring(1);
    else  return s; }

  return '';}

function sendMail(sUrl)
{    var subjectLine='Take a look at this map'; 
     var bodyText='You can see this note at: '+sUrl;

     var message='mailto:?subject='+escape(subjectLine)+'&body='+escape(bodyText);
     var messageIE='mailto:?subject='+(subjectLine)+'&body='+escape(bodyText);     

     if(document.all) location.href=messageIE; 
     else  location.href=message; }

function sendTwit(sUrl)
{    var bodyText='a map for your: '+sUrl;

     var message='http://twitter.com/home?status='+escape(bodyText);

     location.href=message; }

function sendFace(sUrl)
{
 var u=sUrl; t='Secure note';
 window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
 return false;
}

function getExpirydate( nodays)
      {
        var UTCstring;
        Today = new Date();
        nomilli=Date.parse(Today);
        Today.setTime(nomilli+nodays*24*60*60*1000);
        UTCstring = Today.toUTCString();
        return UTCstring;
      }

      function getCookie(cookiename) 
      {
      var cookiestring=""+document.cookie;
       var index1=cookiestring.indexOf(cookiename);
       if (index1==-1 || cookiename=="") return ""; 
       var index2=cookiestring.indexOf(';',index1);
       if (index2==-1) index2=cookiestring.length; 
       return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
      }

     function setCookie(name,value,duration)
     {
      cookiestring=name+"="+escape(value)+";EXPIRES="+getExpirydate(duration);
      document.cookie=cookiestring;
     }




