// $Id;

Drupal.behaviors.live_from_mars = function (context) {
  Drupal.live_from_mars = new Drupal.live_from_mars(Drupal.settings.live_from_mars);
};

/**
 * Constructor
 */
Drupal.live_from_mars = function(params){
  var self = this;

  this.params = params;
  
  this.scrollspeed = 33; //Lower is faster
  this.scrollstep=1;

  this.contentwidth = 0;
  this.topimage = 0;
  this.position = 0;
  this.scrolltimer = 0;
  this.imgs = Array(new Image(), new Image());
  this.contentobj = $(this.params.selector + " .lfm-content");
  this.image1     = $(this.params.selector + " .lfm-image");
  this.image2     = $(this.params.selector + " .lfm-nimage");
  
  $(this.contentobj).css({'height':this.params.height, 'width':'100%'});
  $(".lfm-container").css({'height':this.params.height, 'width':'100%'});


  
  // Bind controls
  $(".lfm-scroller").mouseover(function(){
    $(".lfm-controls").css({'display':'block'});
  }).mouseout(function(){
    $(".lfm-controls").css({'display':'none'});
  });
  $(".lfm-left").click(function(){
    self.left();
  });
  $(".lfm-right").click(function(){
    self.right();
  });
  $(".lfm-stop").click(function(){
    self.stop();
  });
  
  // Only do GE stuff if we're given an API key
  // if (self.params.gapi_key) {
  //   
  //   $.getScript('http://www.google.com/jsapi?key=' + self.params.gapi_key, function(){
  //     google.load("earth", "1", {'callback' : function(){
  //       
  //       // Load GE
  //       if (typeof google.earth.createInstance == 'function') {
  //         google.earth.createInstance('map', initCB, failureCB, { database: "http://khmdb.google.com/?db=mars" });
  //       }
  //       function initCB(instance) {
  //         self.ge = instance;
  //         self.ge.getWindow().setVisibility(true);
  //         // self.ge.getNavigationControl().setVisibility(self.ge.VISIBILITY_SHOW);
  //       }
  //       function failureCB(errorCode) {
  //         $('#map').hide();
  //       }

  //     }});
  //     
  //   });
  //   
  // }

  // Retrieve feed
  this.getFeed();  

};

Drupal.live_from_mars.prototype.getFeed = function(){
  var self = this;
  var url = "/livefrommars/feed/json";
  if (self.params.callback) {
    url += "?callback=?";
  }
  $.getJSON(url,
    function(data) {
      $.each(data, function(i, img){
        var item = {
          'image': img.file_id,
          'desc': img.description,
          'date': img.start_time,
          'url': img.imgurl.replace('300', self.params.height),
          'lat': img.ct_lat,
          'lon': img.ct_lon
        };
        self.feed.push(item);
      });
      self.nextImage();
    }
  ); 
};

Drupal.live_from_mars.prototype.feed = Array();

Drupal.live_from_mars.prototype.nextImage = function () {
  var self = this;
  // Load the next image, and start pre-loading the one after it.
	if (self.scrollstep < 0) {	// If we're going backwards, skip back two images
		self.topimage = self.topimage -2;
		if (self.topimage < 0) self.topimage += self.feed.length;
	}

  self.imgs[0].onload = self.getContentWidth;
	self.imgs[0].src = self.feed[self.topimage].url;
	self.imgs[1].src = self.feed[(self.topimage+1) % self.feed.length].url;

	$(self.image1).attr('src', self.imgs[0].src);
	$(self.image2).attr('src', self.imgs[1].src);

	self.topimage = (self.topimage + 1) % self.feed.length;

	if (self.scrollstep < 0) {	// if we're going backwards, start at the end
		self.position = -self.imgs[0].width+1;
	} else {
		self.position = 0;
	}
	$(self.contentobj).css({'left':self.position + "px"});

  // Set meta fields
  $('#lfm-img').text(self.feed[self.topimage].image);
  $('#lfm-desc').text(self.feed[self.topimage].description);
  $('#lfm-date').text(self.feed[self.topimage].date);
  $('#lfm-loc').html(self.feed[self.topimage].lat + "&deg;, " + self.feed[self.topimage].lon + "&deg;");
  
  // Pan google earth
  // if (typeof self.ge.getWindow == "function") {
  //   var lookAt = self.ge.getView().copyAsCamera(self.ge.ALTITUDE_RELATIVE_TO_GROUND);
  //   // var camera = self.ge.getView().copyAsCamera(self.ge.ALTITUDE_RELATIVE_TO_GROUND);
  //   lookAt.setLatitude(self.feed[self.topimage].lat);
  //   lookAt.setLongitude(self.feed[self.topimage].lon);
  //   lookAt.setAltitude(400.0 * 1000);
  //   // Update the view in Google Earth
  //   self.ge.getView().setAbstractView(lookAt);
  // }

};

// When our main image is through loading, 
// get the image size, and start scrolling it.
Drupal.live_from_mars.prototype.getContentWidth = function() {
  var self = Drupal.live_from_mars;
  if (self.imgs[0].width == 0) {				// Not ready yet.  Come back
    setTimeout("Drupal.live_from_mars.getContentWidth()",1000);
  } else {
    self.contentwidth=self.imgs[0].width;
    self.scrolltimer = setTimeout("Drupal.live_from_mars.scrollit()", self.scrollspeed);
  }
};

Drupal.live_from_mars.prototype.scrollit = function() {
  var self = this;
  if (self.position > 0) { // Do nothing because we'll fall off the left end
    self.nextImage();
	} else if (self.position-self.scrollstep < -self.contentwidth) { // hit the right end
    self.nextImage();
  } else {
    self.position -= self.scrollstep;
    $(self.contentobj).css({'left': self.position + "px"});
    self.scrolltimer = setTimeout("Drupal.live_from_mars.scrollit()", self.scrollspeed);
  }
};

Drupal.live_from_mars.prototype.doscroll = function() { 	// This is used to turn the timer back on when we stop
	if (this.scrolltimer == 0) {
		this.scrollit();
	}
};

// Control button callbacks
Drupal.live_from_mars.prototype.left = function() { 
  this.scrollstep = this.scrollstep >= 0 ? -1 : this.scrollstep-1; this.doscroll();
};

Drupal.live_from_mars.prototype.right = function() {
  this.scrollstep = this.scrollstep <= 0 ? 1 : this.scrollstep+1; this.doscroll();
};

Drupal.live_from_mars.prototype.stop = function() {
  this.scrollstep = 0;
  clearTimeout(this.scrolltimer);
  this.scrolltimer=0;
};

// Google Earth object
Drupal.live_from_mars.prototype.ge = Object();
;

