     var map=null;
     var geocoder=null;    
     var lastMarker = null;

     var RADIUS = "50mi";
     var DELAY = 9000;
     var COUNT = 50;

     var showAuthors = false;
     var showTexts = false;

     var tmt = null;
     var store = null;
     var currentIndex = 0; 
     var lastInfo = null;

     var currentLat, currentLng;

     var research = true;

     var mutex = false;

     function load(lat,lng,zml)
     {
       if(GBrowserIsCompatible())
        {
         var opts = {
           googleBarOptions : {
           style : 'new',
           adsOptions : {
            client : 'partner-pub-9490590989861158'
           }
          }
         }

         map=new GMap2(document.getElementById("map"), opts);
         geocoder=new GClientGeocoder();

         map.addMapType(G_SATELLITE_3D_MAP);

         map.enableScrollWheelZoom();
         map.enableContinuousZoom();

         initMap(lat,lng,zml);

         map.addControl(new GLargeMapControl());
         map.addControl(new GOverviewMapControl(new GSize(250,135)));
         map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
                
         map.enableGoogleBar(); 

         if (mrk)
         {
          var point = new GLatLng(lat, lng);
          lastMarker = new GMarker(point);
          map.addOverlay(lastMarker);
          GEvent.addListener(lastMarker, 'click', function() {
           changeLocation();
         });

         }

         GEvent.addListener(map,"moveend",function()
         {
          var lat = map.getCenter().lat();
          var lng = map.getCenter().lng();
          //setCookie('gllat',lat,365);
          //setCookie('glltd',lng,365);
          //setCookie('glzml',map.getZoom(),365);
          if (mrk)
          {
           if (lastMarker) map.removeOverlay(lastMarker);
           var point = new GLatLng(lat, lng);
           var t = "Lat:"+lat + " Lng:"+lng;
           lastMarker = new GMarker(point,{title:t});
           map.addOverlay(lastMarker);
           GEvent.addListener(lastMarker, 'click', function() {
            changeLocation();
            });

          }
         });
       
         GEvent.addListener(map, "click", clickFunction);

         map.addOverlay(new GLayer("com.panoramio.all"));
         
         var publisher_id = "pub-9490590989861158"; 

         var adPos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 70)); 

         adsManagerOptions = {
         maxAdsOnMap : 2,
         style: 'adunit',
         channel: '', 
         position: adPos
        };

      adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
      adsManager.enable();

      currentLat = map.getCenter().lat();
      currentLng = map.getCenter().lng();

      var sHtml = "<div style='font-weight:bold'><center>"
                    + "Current position is:<br/>"
                    + "("+currentLat+","+currentLng+")"
                    + "<br/><br/>"
                    + "For changing it just move the map and hit marker icon on the top"
                    + "<br/><br/>"
                    + "Let us see more pictures ..."
                    + "</center></div>"
                    + "<br/><br/>";

      map.closeInfoWindow();
      map.openInfoWindowHtml(new GLatLng(currentLat, currentLng),sHtml,{maxWidth:150});

      setTimeout("searchTwitter()",6000);

        }       
      }

     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()+" Reason: "+addresses.Status.code);
          }
          else 
          { address = addresses.Placemark[0];
            var myHtml = address.address;
            map.openInfoWindow(latlng, myHtml); }
        });
      }
    }

     function SetMarker(map)
     {
        var lat = map.getCenter().lat();
        var lng = map.getCenter().lng();

        if (mrk) 
        {
          mrk = false;
          if (lastMarker)
          {
             map.removeOverlay(lastMarker);
             lastMarker = null;
          }
        }
        else
        {
          mrk = true; 
          
          var point = new GLatLng(lat, lng);
          var t = "Lat:"+lat + " Lng:"+lng;

          lastMarker = new GMarker(point,{title:t});
          map.addOverlay(lastMarker);

          GEvent.addListener(lastMarker, 'click', function() {
           changeLocation();
         });


          
          changePosition(lat, lng);                    
        }         
     }

     function changePosition(lat,lng)
     {
          currentLat = lat;
          currentLng = lng;

          research = true;

          var sHtml = "<div style='font-weight:bold'><center>"
                    + "Position has been changed to:<br/>"
                    + "("+lat+","+lng+")"
                    + "<br/><br/>"
                    + "Let us see ..."
                    + "</center></div>"
                    + "<br/><br/>";

          map.closeInfoWindow();
          map.openInfoWindowHtml(new GLatLng(lat, lng),sHtml,{maxWidth:150});

          if (tmt)
           clearTimeout(tmt);

          setCookie('gllat',lat,365);
          setCookie('glltd',lng,365);
          setCookie('glzml',map.getZoom(),365);

          setTimeout("searchTwitter()",2000);
     }

     function changeLocation()
     {
       if (lastMarker)
       {
         var latlng = lastMarker.getLatLng();
         changePosition(latlng.lat(), latlng.lng());
        }
     }

     function initMap(_lat,_lng,_zml)
     {
      var lat,lng,zml;

      if (_lat) lat = _lat;
      else 
       lat = getCookie('gllat');

      if (google.loader) 
       if (google.loader.ClientLocation)
	 if (lat.length==0) lat = google.loader.ClientLocation.latitude; 

      if (lat.length==0) lat = 55.68455275165637;

      if (_lng) lng = _lng;
      else 
       lng = getCookie('glltd');

      if (google.loader) 
       if (google.loader.ClientLocation)
	      if (lng.length==0) lng = google.loader.ClientLocation.longitude;

      if (lng.length==0) lng = 37.733917236328125;

      if (_zml) zml = _zml;
      else 
       zml = getCookie('glzml');

      if (zml.length==0) zml=10;

      map.setCenter(new GLatLng(lat,lng),parseInt(zml));
     }

      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;
     }

   function beforeAction()
   {
     document.body.style.cursor = 'wait';
   }

   function afterAction()
   {
     document.body.style.cursor = 'default';
   }

   function handlerFunction(txt, xmlDoc)
   {
     sendMail(txt);
   } 

   function handlerFunction1(txt, xmlDoc)
   {
     sendFacebook(txt);
   } 

   function handlerFunction2(txt, xmlDoc)
   {
     sendTwitter(txt);
   } 

   function errorFunction()
   {
     alert("Could not create URL for this map");
   }


   function sendMail(sUrl)
   {

     var subjectLine='Take a look at this map from http://photomap.linkstore.ru'; 
     var bodyText='You can see this map 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 sendTwitter(sUrl)
   { 
     var bodyText='look at this map: '+sUrl;

     var message='http://twitter.com/home?status='+escape(bodyText);

     location.href=message; 
   }

  function sendFacebook(sUrl)
  {
    var u=sUrl; t='Big map';
    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 getUrl(map)
   {
    var center = map.getCenter();
    var sUrl="http://photomap.linkstore.ru/index.jsp?"
                 +"lng="+center.lng()
                 +"&lat="+center.lat()
                 +"&zml="+map.getZoom();
    if (mrk) sUrl+="&mrk=1";

    return sUrl;
   }


   function MailTo(map)
   {    
     var sUrl=getUrl(map);

     cjAjaxEngine("tinyurl.jsp?"+sUrl,handlerFunction,errorFunction,beforeAction,afterAction);
   }

   function sendFace(map)
   {
     var sUrl=getUrl(map);

     cjAjaxEngine("tinyurl.jsp?"+sUrl,handlerFunction1,errorFunction,beforeAction,afterAction);
   }

   function sendTwit(map)
   {
     var sUrl=getUrl(map);

     cjAjaxEngine("tinyurl.jsp?"+sUrl,handlerFunction2,errorFunction,beforeAction,afterAction);
   }

   function AddressDialog(map)
   {
      var o = document.getElementById("addressbar");
      if (o.style.display=='none') 
      {
        o.style.display="block";
        document.getElementById("idaddress").focus();
      }
      else                         o.style.display="none";
   }

   function lookupAddress(map)
   {
     var s = document.getElementById("idaddress").value;
     if (s!='')
       geocoder.getLocations(s,findCallback);
   }

  function findCallback(response)
  {
   if (!response) alert("Sorry, unable to find this");
   else
     if (response.Status.code!=200) 
       alert("Sorry, unable to find this"); 
     else
     {
       var place = response.Placemark[0];
       var lat = place.Point.coordinates[1];
       var lng = place.Point.coordinates[0];
      
       moveMap(lat,lng,15); 
       AddressDialog(map); 
     } 
  }

    function moveMap(lat,lng,zoom,mt)
    {
       var z;
       if (zoom) z = eval(zoom);
       else      z = map.getZoom();

       var m;

       if (mt) m = getGoogleMapType(mt);
       else    m = map.getCurrentMapType();

       map.setCenter(new GLatLng(eval(lat),eval(lng)),z,m);
    }
    
   function getGoogleMapType(mapType)
   {
     if (mapType=='0') return G_NORMAL_MAP;
     else
      if (mapType=='1') return G_SATELLITE_MAP;
      else
       if (mapType=='2') return G_HYBRID_MAP;

     return G_NORMAL_MAP;
   }


   function getTwitter(query)
    {
      var cbscript = document.createElement("script");
      cbscript.src = query;
      cbscript.type = 'text/javascript';
      document.body.appendChild(cbscript);
    }

   function searchTwitter()
   {
     if (mutex) return;

     mutex=true; 

     var query="twitpic+OR+yfrog";
     var lat = map.getCenter().lat();
     var lng = map.getCenter().lng();

     var s = "http://search.twitter.com/search.json?lang=all&q="+query+"&rpp="+COUNT;

     s+="&geocode="+lat+"%2C"+lng+"%2C"+RADIUS;
 
     store = new Array();         
     currentIndex = 0;
     research = false; 

//alert("Search:"+s);

     getTwitter(s+"&callback=results");
   }

   function results(t)
    {
       var v = t.results;

       mutex = false; 

       if (v.length==0)
       {
         var sHtml = "No pictures from Twitter"
                   + "<br/>" 
                   + "Try to move map and change position"
                   + "<br/><br/>"; 

         map.closeInfoWindow();
         map.openInfoWindowHtml(new GLatLng(currentLat, currentLng),sHtml,{maxWidth:200});
      
         return;
       }
       else
       {
         for (var i=0; i<v.length; i++)
         { 
          var entry = v[i];
          var txt = entry.text;
          if (txt.indexOf("http://twitpic.com")>=0 || txt.indexOf("http://yfrog.com")>=0)
          {  
           store[currentIndex]=entry;
           currentIndex++;
          }

         }

       } 

//alert("Res:"+currentIndex+" "+store.length+" "+store[0]);

      if (currentIndex!=0) 
      {
        currentIndex=0;
        showPictures(); 
      } 
      else
        setTimeout("searchTwitter()",DELAY);
    }

    function showPictures()
    {
      if (research) searchTwitter();
      else
      { 
       var entry = store[currentIndex];

//alert("Show:"+entry);

       displayEntry(entry);
      }      
    }

    function displayEntry(entry)
    {
      var loc = entry.location;

      var latlng = getLocation(loc);

//alert(loc+":"+latlng);

      var sHtml = getEntry(entry); 

      map.closeInfoWindow();
      map.openInfoWindowHtml(latlng,sHtml,{maxWidth:200});
      
      currentIndex++;
      if (currentIndex>=store.length) setTimeout("searchTwitter()",DELAY);
      else
      {
        if (research) searchTwitter();
        else          tmt = setTimeout("showPictures()",DELAY); 
      }
    }

    function getEntry(entry)
    {
       var sText = '';

       var sPic = proceedPics(entry.text);

           if (sPic!=entry.text) 
           {
             sText+=sPic; 
             sText += "<br/>";
           }

          if (showAuthors)
          {
           sText +="<a style='text-decoration:none' href='http://tinfo.linkstore.ru?u="+entry.from_user+"' target='_blank'><img src='"+entry.profile_image_url+"' style='float:left;padding-right:7px' border='0' width='48' height='48'/></a>"; 
          }
  
          if (showTexts)
          { 
           sText +=proceedUrl(entry.text) + "<br/>";
          }
          
           sText+="<center><span style='font-size:80%;color:#555555'>"+dateDiff(new Date(entry.created_at), new Date());
 
          if (entry.from_user) 
             sText+=" by <a href='http://twitter.com/"+entry.from_user+"' target='_blank'>"+entry.from_user+"</a>";

           sText+="<br/>";
           sText+="<a href='http://twitter.com/home?status=@"+entry.from_user+"&in_reply_to_status_id="+entry.id+"&in_reply_to="+entry.from_user
            +"' target='_blank' title='Reply to '"+entry.from_user+"'>Reply</a> "; 
           sText+="&nbsp;";
           sText+=" <a href='http://twitter.com/"+entry.from_user+"/statuses/"+entry.id
                 +"' target='_blank' title='Show tweet'>View tweet</a>";

           sText+="</span></center>";

           sText+="<br/><br/>";

           return sText;
    }

    function proceedPics(text)
    {
        var tweet = text;
     
        re = new RegExp("(http://twitpic.com/)([0-9a-zA-Z]*)");
	var m = re.exec(tweet);
	if  (!m || m.length == 0 || m[2] == "photos" || m[2] == "photo" || m[2] == "tag") {} 
	else {tweet = '<center><a href="http://twitpic.com/' + m[2] + '" target="_blank"><img src="http://twitpic.com/show/thumb/' + m[2] + '" border=0 height=150 width=150></a></center>';}	

        re = new RegExp("(http://yfrog.com/)([0-9a-zA-Z]*)");
	var m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = '<center><a href="http://yfrog.com/' + m[2] + '" target="_blank"><img src="http://yfrog.com/' + m[2] + '.th.jpg" border=0 height=150 width=150></a></center>';}	

      return tweet;
    }

    function proceedUrl(text)
    {
        var tweet = text;
        var re = new RegExp("(([a-zA-Z]+:\/\/)([a-zA-Z][a-zA-Z0-9_\.-]*[a-zA-Z]{2,6})([a-zA-Z0-9~\#\/\._\?\&%-=]*[a-zA-Z0-9~\#\/_\?\&%-=]))", "g");
        tweet = tweet.replace(re, '<a style="' + 'text-decoration:none;" target="_new" href=$1 >$1</a>');
        re = new RegExp("@([a-zA-Z0-9_]+)", "g");
	tweet = tweet.replace(re, '@<a style="' + 'text-decoration:none;" target="_new" href=http://twitter.com/$1>$1</a>');
        tweet = tweet.replace(/&/g, '&');

        return tweet; 
    }


 function dateDiff(d1, d2)
   {
     var diff  = new Date();

     diff.setTime(Math.abs(d1.getTime() - d2.getTime()));

     var timediff = diff.getTime();

     var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
     timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

     var days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
     timediff -= days * (1000 * 60 * 60 * 24);

     var hours = Math.floor(timediff / (1000 * 60 * 60)); 
     timediff -= hours * (1000 * 60 * 60);

     var mins = Math.floor(timediff / (1000 * 60)); 
     timediff -= mins * (1000 * 60);

     var secs = Math.floor(timediff / 1000); 
     timediff -= secs * 1000;

     var ans ="";
     if (weeks!=0) ans+=weeks+" weeks ";

     if (days!=0)  ans+=days+" days ";

     if (hours!=0) ans+=hours+" hours ";
     else
     {
       if (mins!=0)  ans+=mins+" mins ";   
       else
          ans += secs +" secs "    
     }

     return ans+"ago";
   }

   function getLocation(loc)
   {
     if (loc.indexOf(",")<=0) return new GLatLng(currentLat, currentLng);
 
     re = new RegExp("([-]?[0-9]{1,3}.[0-9]+),([-]?[0-9]{1,3}.[0-9]+)","g");

//alert(loc+":"+loc.match(re));

     var s=loc.match(re);
     if (s) 
     {
       var i = s.indexOf(',');
       if (i>0)
        return new GLatLng(s.substring(0,i), s.substring(i+1));
     }

     return GLatLng(currentLat, currentLng);        
   }




