/*
 * Handwritten JS for the origin page
 */


/*
 CUSTOM MARKER 
*/



/******************************************************************************************************************/

var __load_callback ; 

function __initialize_map__ (lwt_wakener) {
    __load_callback = lwt_wakener ;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&callback=__load_callback";
    script.id = "google_map_script" ;
    document.body.appendChild(script);
}

var initialLocation ;
var geocoder ;
var map ;

function __map__address_reposition (address,wakener) {


  CustomMarker.prototype = new google.maps.OverlayView();

  CustomMarker.prototype.draw = function() {
      var me = this;
      
      // Check if the div has been created.
      var div = this.div_;

      if (!div) {
          // Create a overlay text DIV
          div = this.div_ = document.createElement('div');
          // Create the DIV representing our CustomMarker
          div.id = "localisation_marker";
          div.style.position = "absolute" ;

          var img = document.createElement ('img') ; 
          img.style.position = "relative" ;
          img.style.top = "-33px";
          img.style.left = "-13px";

          img.src = '/img/geomarker.png' ; 

          div.appendChild (img) ;
          // Then add the overlay to the DOM
          
          var panes = this.getPanes();
          panes.overlayImage.appendChild(div);
      }

      // Position the overlay 
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);

      if (point) {
          div.style.left = point.x + 'px';
          div.style.top = point.y + 'px';
      }
  };
  
  function CustomMarker(latlng,  map) {
      this.latlng_ = latlng;
      
      // Once the LatLng and text are set, add the overlay to the map.  This will
      // trigger a call to panes_changed which should in turn call draw.
      this.setMap (map); 
      
  }

  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
      this.setMap(null);
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };

   geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);

      if (typeof(marker_search_localisation) == "object") {
        marker_search_localisation.remove ();
      }
      marker_search_localisation = new CustomMarker (results[0].geometry.location, map);
      wakener ()

    } else {
      alert("Geocode was not successful for the following reason: " + status);
      wakener ()
    }
  });
  return ;
}

function __map__reposition (lat, lon) {
  var location = new google.maps.LatLng(lat,lon);
  map.setCenter(location);
}

function __map__geolocalise () {
    
  CustomMarker.prototype = new google.maps.OverlayView();

  CustomMarker.prototype.draw = function() {
      var me = this;
      
      // Check if the div has been created.
      var div = this.div_;

      if (!div) {
          // Create a overlay text DIV
          div = this.div_ = document.createElement('div');
          // Create the DIV representing our CustomMarker
          div.id = "localisation_marker";
          div.style.position = "absolute" ;

          var img = document.createElement ('img') ; 
          img.style.position = "relative" ;
          img.style.top = "-33px";
          img.style.left = "-13px";

          img.src = '/img/geomarker.png' ; 

          div.appendChild (img) ;
          // Then add the overlay to the DOM
          
          var panes = this.getPanes();
          panes.overlayImage.appendChild(div);
      }

      // Position the overlay 
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);

      if (point) {
          div.style.left = point.x + 'px';
          div.style.top = point.y + 'px';
      }
  };
  
  function CustomMarker(latlng,  map) {
      this.latlng_ = latlng;
      
      // Once the LatLng and text are set, add the overlay to the map.  This will
      // trigger a call to panes_changed which should in turn call draw.
      this.setMap (map); 
      
  }

  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
      this.setMap(null);
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };
     // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            map.setCenter(initialLocation);
            var custommarker = new CustomMarker (initialLocation, map); 
            
        }, function() {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
            map.setCenter(initialLocation);
        }, function() {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
    
    function handleNoGeolocation(errorFlag) {
        if (errorFlag == true) {
            alert("Geolocation service failed.");
            initialLocation = newyork;
        } else {
            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
            initialLocation = siberia;
        }
        map.setCenter(initialLocation);
    } 

}


function __map__geolocalise_no_reposition () {
    
  CustomMarker.prototype = new google.maps.OverlayView();

  CustomMarker.prototype.draw = function() {
      var me = this;
      
      // Check if the div has been created.
      var div = this.div_;

      if (!div) {
            // Create a overlay text DIV
            div = this.div_ = document.createElement('div');
            // Create the DIV representing our CustomMarker
            div.id = "localisation_marker";
            div.style.position = "absolute" ;
            
            var ul = document.createElement ('ul') ; 
            var li1 = document.createElement ('li') ; 
            var li2 = document.createElement ('li') ; 
            
            var img = document.createElement ('img') ; 

            img.src = '/img/bullet-localisation.png' ; 

            
            li1.style.margin = "15px 0 0 15px" ;
            li1.style.position = "absolute" ; 
            li1.style.top = "-21px" ; 
            li1.style.left = "-21px" ; 
            li1.appendChild (img) ;
            
            li2.style.width = "21px" ;
            li2.style.height = "21px" ;
            li2.style.position = "relative" ;
            li2.style.top = "-21px" ;
            li2.style.left = "-21px" ;
            li2.style.backgroundColor = "#d42027" ; 
            li2.style.borderRadius = "45px"; 
            li2.setAttribute ("animation", "fadeLocalisation 1s infinite ease alternate"); 
            li2.style.opacity = "0.5" ; 
            
            var blink = function (op, incr) {

                if (op <= 0.2) { 
                    li2.style.opacity = "0.3" ;
                    setTimeout (function () { blink (0.3, 0.1); }, 100) ; }
                else if (op >= 0.5) { 
                    
                    li2.style.opacity = "0.4";
                    setTimeout (function () { blink (0.4, -0.1); }, 100) ; }
                else { 
                    li2.style.opacity = (op + incr)+'' ; 
                      setTimeout (function () { blink (op + incr, incr) ; }, 100); 
                }; } ; 
            
            setTimeout (function () { blink (0.5, 0.1); }, 100) ; 
            ul.appendChild (li1) ;
            ul.appendChild (li2) ;
            div.appendChild (ul) ;
            // Then add the overlay to the DOM
          var panes = this.getPanes();
          panes.overlayImage.appendChild(div);
      }

      // Position the overlay 
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);

      if (point) {
          div.style.left = point.x + 'px';
          div.style.top = point.y + 'px';
      }
  };
  
  function CustomMarker(latlng,  map) {
      this.latlng_ = latlng;
      
      // Once the LatLng and text are set, add the overlay to the map.  This will
      // trigger a call to panes_changed which should in turn call draw.
      this.setMap (map); 
      
  }

  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
      this.setMap(null);
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };
     // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            var custommarker = new CustomMarker (initialLocation, map); 
            
        }, function() {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
            
        }, function() {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
    
    function handleNoGeolocation(errorFlag) {
        if (errorFlag == true) {
            alert("Geolocation service failed.");
            initialLocation = newyork;
        } else {
            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
            initialLocation = siberia;
        }
        
    } 

}


function __map_resolve_address (address, wakener) {
     geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         
        wakener ([results[0].geometry.location.lat(), results[0].geometry.location.lng() ]) ; 
       
      } else {
          wakener ([0,0]) ;
      }
    });
}

function __map__set_zoom (zoom_level) {
    map.setZoom (zoom_level); 
}

function __setup_about_map__ () {
  
  geocoder = new google.maps.Geocoder();
  
  var myOptions = {
      zoom: 12,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("mapAbout"), myOptions)
}

function __setup_map__(wakener) {
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();

    geocoder = new google.maps.Geocoder();

   
    CustomMarker.prototype = new google.maps.OverlayView();

    CustomMarker.prototype.draw = function() {
        var me = this;
        
        // Check if the div has been created.
        var div = this.div_;

        if (!div) {
            // Create a overlay text DIV
            div = this.div_ = document.createElement('div');
            // Create the DIV representing our CustomMarker
            div.id = "localisation_marker";
            div.style.position = "absolute" ;
            
            var ul = document.createElement ('ul') ; 
            var li1 = document.createElement ('li') ; 
            var li2 = document.createElement ('li') ; 
            
            var img = document.createElement ('img') ; 

            img.src = '/img/bullet-localisation.png' ; 

            
            li1.style.margin = "15px 0 0 15px" ;
            li1.style.position = "absolute" ; 
            li1.style.top = "-21px" ; 
            li1.style.left = "-21px" ; 
            li1.appendChild (img) ;
            

            li2.style.width = "21px" ;
            li2.style.height = "21px" ;
            li2.style.position = "relative" ;
            li2.style.top = "-11px" ; 
            li2.style.left = "-11px" ;
            li2.style.backgroundColor = "#d42027" ; 
            li2.style.borderRadius = "45px"; 
            li2.setAttribute ("animation", "fadeLocalisation 1s infinite ease alternate"); 
            li2.style.opacity = "0.5" ; 
            
            var blink = function (op, incr) {
            
                           if (op <= 0.2) { 
                               li2.style.opacity = "0.3" ;
                               setTimeout (function () { blink (0.3, 0.1); }, 100) ; }
                           else if (op >= 0.5) { 
                               
                               li2.style.opacity = "0.4";
                               setTimeout (function () { blink (0.4, -0.1); }, 100) ; }
                           else { 
                               li2.style.opacity = (op + incr)+'' ; 
                                 setTimeout (function () { blink (op + incr, incr) ; }, 100); 
                           }; } ; 
                       
                       setTimeout (function () { blink (0.5, 0.1); }, 100) ; 
            ul.appendChild (li1) ;
            ul.appendChild (li2) ;
            div.appendChild (ul) ;
            // Then add the overlay to the DOM
            
            var panes = this.getPanes();
            panes.overlayImage.appendChild(div);
        }

        // Position the overlay 
        var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);

        if (point) {
            div.style.left = point.x + 'px';
            div.style.top = point.y + 'px';
        }
    };
    
    function CustomMarker(latlng,  map) {
        this.latlng_ = latlng;
        
        // Once the LatLng and text are set, add the overlay to the map.  This will
        // trigger a call to panes_changed which should in turn call draw.
        this.setMap (map); 
        
    }
    



  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
      this.setMap(null);
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };

    var myOptions = {
        zoom: 12,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var awaked = false ;
    google.maps.event.addListener(map, 'tilesloaded', 
                                  function () { 
                                      try { wakener (); return; } catch (e) { return ;} })  ; 
    
    // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            map.setCenter(initialLocation);
            var custommarker = new CustomMarker (initialLocation, map); 
            

        }, function() {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
            map.setCenter(initialLocation);
        }, function() {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
    
    function handleNoGeolocation(errorFlag) {
        if (errorFlag == true) {
            alert("Geolocation service failed.");
            initialLocation = newyork;
        } else {
            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
            initialLocation = siberia;
        }
        map.setCenter(initialLocation);
    } 

}


function __map__displayTweet(tweet_text, lat, lng, clb) {
    var contentString = '<div id="tweet_content">' + tweet_text + '</div>' ; 
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });


    var myLatlng = new google.maps.LatLng(lng,lat); // ok it's reversed ..
  
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });

    google.maps.event.addListener(marker, 'click', clb) ; 
}



function __map_set_autocomplete (e) {
    var defaultBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(initialLocation.lat () - 1, initialLocation.lng () - 1),
        new google.maps.LatLng(initialLocation.lat () + 1, initialLocation.lng () + 1)) ;
        
    var options = {
        bounds: defaultBounds,
        types: ['establishment']
    };
    
    new google.maps.places.Autocomplete(e, options);
}


function __map_custom_pin (size, lat, lon, box) {
  CustomPin.prototype = new google.maps.OverlayView();    

  CustomPin.prototype.draw = function() {
      var me = this;

      // Check if the div has been created.
      var div = this.div_;

      if (!div) {
          this.div_ = box ;
          div = box ;
          var panes = this.getPanes();
          panes.overlayImage.appendChild(div);
      }

      // Position the overlay 
      var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);

      if (size == 1 && point) {
          div.style.left = point.x + 'px';
          div.style.top = (point.y  - 63) + 'px';
      }
      if (size == 2 && point) {
          div.style.left = point.x + 'px';
          div.style.top = (point.y  - 40) + 'px';
      }
      if (size == 3 && point) {
          div.style.left = point.x + 'px';
          div.style.top = (point.y  - 27) + 'px';
      }
  };

  function CustomPin(latlng,  map) {
      this.latlng_ = latlng;

      // Once the LatLng and text are set, add the overlay to the map.  This will
      // trigger a call to panes_changed which should in turn call draw.
      this.setMap (map); 

  }

  CustomPin.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    }
  };

  CustomPin.prototype.getPosition = function() {
   return this.latlng_;
  };
    
    var loc = new google.maps.LatLng(lat, lon);
    var custommarker = new CustomPin (loc, map); 

}



/* pretty date */

function __prettyDate(time) {
  var date = new Date(time) ;
  var now = new Date () ;
  var now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
	var diff = (now.getTime() - date.getTime()) / 1000 ;
	var day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return "";

	var r = day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
    return r ;
}

/* callback ************************************************************************************************************************/

var __uploaded_callback__ ; 

function set_uploaded_callback (f) {
  __uploaded_callback__ = function (id, data)
  { 
      var args = new Array ();
      args[1]=id ;
      args[2]=data ; 
      f(args) ; 
  } ;
}

/* localisation ********************************************************************************************************************/
/* we should put a timeout on the wakener call */

function __current_country (wakener) {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                var latlng = new google.maps.LatLng (position.coords.latitude, position.coords.longitude);
                geocoder.geocode({ 'latLng': latlng },
                                 function(results, status) {
                                     if (status == google.maps.GeocoderStatus.OK) {
                                         var len = results[0].address_components.length;
                                         for(var i=0; i<len; i++) {
                                             var tylen = results[0].address_components[i].types.length ; 
	                                       for (var j=0; j<tylen; j++) {
                                                 if (results[0].address_components[i].types[j] == "country") {
                                                     wakener (results[0].address_components[i].short_name) ;
                                                     return ; 
                                                 }
                                             }
                                         } ; 
                                         wakener ("") ;
                                         return ; ;
                                     }}); 
            }, function () { wakener ("") ; })
    }
}

function test (obj) {
}


/* events management */
/*
function fireEvent(element,event){
    if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    }
    else{
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
    }
}

*/

function __fire_text (text) { 
  
    var eventObject = document.createEvent('KeyboardEvent');
    eventObject.initKeyboardEvent('keydown',
                                  false,             //  in boolean canBubbleArg,                                                        
                                  false,             //  in boolean cancelableArg,                                                       
                                  null, 
                                  'c', 
                                  0) ;  
                                  
    
    var e = document.getElementById ('_test_input') ;
    if (!e) alert ('no e') ;
    return !e.dispatchEvent(eventObject);
}

function __prevent_default(e) {
    if (!e) e = window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}

function __cancel_event(e) {
    if (!e) e = window.event;
    if (e.stopImmediatePropagation) {
        e.stopImmediatePropagation();
    } else {
        e.returnValue = false;
    }
}

