﻿// Slide.Show, version 1.0
// Copyright © Vertigo Software, Inc.
// This source is subject to the Microsoft Public License (Ms-PL).
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx.
// All other rights reserved.
// PicasaDataProvider Created by Wesley Riley @ http://www.wesleyriley.com
/// <reference path="SlideShow.js" />

/*******************************************
 * class: SlideShow.PicasaDataProvider
 *******************************************/
SlideShow.PicasaDataProvider = function(control, options)
{
 /// <summary>Provides album/slide data from Picasa.</summary>
 /// <param name="control">The Slide.Show control.</param>
 /// <param name="options">The options for the provider.</param>
 
 SlideShow.PicasaDataProvider.base.constructor.call(this, control);
 
 SlideShow.merge(this.options,
 {
  apiKey: "",
  userName: null,
  transition: "CrossFadeTransition"
 });
 this.setOptions(options);
 
 this.albums = {};
 this.data = { transition: this.options.transition, album: [] };
};

//PDP// **** Notice "Slide.Show.FlickrDataProvider" has changed to "Slide.ShowPicasaDataProvider"

SlideShow.extend(SlideShow.DataProvider, SlideShow.PicasaDataProvider,
{

//PDP// **** This subclass is identical to the FlickrDataProvider.
 getData: function(dataHandler)
 {
  /// <summary>Retrieves the data asynchronously and calls the specified event handler (with the data).</summary>
  /// <param name="dataHandler">The event handler to be called after the data is retrieved.</param>
  
  this.dataHandler = dataHandler;
  this.getUserId(this.options.userName);
 },


//PDP// **** This subclass attempts to make a json url call to picasa google retrieving a list of albums to ensure the username is valid. 
 getUserId: function(userName)
 {
  /// <summary>Gets the user ID corresponding to the specified Picasa username.</summary>
  /// <param name="userName">The Picasa username.</param>
  
  this.callPicasa(userName + "?kind=album&alt=json&hl=en_US&access=public", SlideShow.createDelegate(this, this.onUserIdCallback));
 },
 

//PDP// **** This subclass attempts to make a json url call to picasa google retreiving a list of albums associated with the username provided.
 getPhotosets: function(userId)
 {
  /// <summary>Gets all photosets for the specified Picasa user.</summary>
  /// <param name="userId">The Picasa user ID.</param>
  
  this.callPicasa(userId + "?kind=album&alt=json&hl=en_US&access=public", SlideShow.createDelegate(this, this.onPhotosetsCallback));
 },


//PDP// **** This subclass attempts to make a json url call to picasa google retreiving a list of photos for the specified photosetid. 
 getPhotos: function(photosetId)
 {
  /// <summary>Gets all photos for the specified Picasa photoset.</summary>
  /// <param name="photosetId">The Picasa photoset ID.</param>
  
  this.callPicasa(userId + "/albumid/" + photosetId + "?kind=photo&alt=json&hl=en_US&access=public", SlideShow.createDelegate(this, this.onPhotosCallback));
 },


//PDP// **** This subclass is used to make your httprequest to picasa google. 
 callPicasa: function(query, callbackHandler)
 {
  /// <summary>Calls a method from the Picasa API.</summary>
  /// <param name="query">The method and parameters to append to the REST endpoint URL.</param>
  /// <param name="callbackHandler">The event handler to be called when the callback event is fired.</param>
  
  var callback = SlideShow.getUniqueId("SlideShow_Callback_");
  var parser = new SlideShow.JsonParser();
  parser.addEventListener("callback", callbackHandler);
  test = "http://picasaweb.google.com/data/feed/base/user/" + query + "&callback=" + callback;
  parser.fromFeed("http://picasaweb.google.com/data/feed/base/user/" + query + "&callback=" + callback, callback);
 },


//PDP// **** This is a helper function used to build the photo albums.
//Note: NOtice, to parse the Location you have to parse it from the summary section of the json object. 
 buildAlbum: function(photoset)
 {
  /// <summary>Builds an album object from Picasa data.</summary>
  /// <param name="photoset">The photoset data.</param>
  /// <returns>The album object.</returns>
   
  var album = {};
  album.title = photoset.title.$t;
  if(photoset.summary.$t.indexOf("Location:") != -1){
      tempLocal = photoset.summary.$t.substr(photoset.summary.$t.indexOf('Location: </font><font color="#333333">') + 39)
      local = tempLocal.substring(0, tempLocal.indexOf("</font><br/>"))
  }
  else{
            local = "" 
  }
  album.description = "Taken in " + local + " on " + this.formatDate(photoset.published.$t);
  album.image = photoset.media$group.media$thumbnail[0].url;
  album.slide = [];
  return album;
 },


//PDP// **** This is a helper function used to build the Slide.Show slide. 
 buildSlide: function(photo)
 {
  /// <summary>Builds a slide object from Picasa data.</summary>
  /// <param name="photo">The photo data.</param>
  /// <returns>The slide object.</returns>
   
  var slide = {};
  slide.title = photo.title.$t;
  slide.description = "Taken on " + this.formatDate(photo.published.$t);
  slide.image = photo.content.src;
  return slide;
 },
 

//PDP// **** This is a helper function used to format the dates used in the Slide.Show.
 formatDate: function(theDate)
 {
  /// <summary>Formats datetime</summary>
  /// <param name="theDate">The date needing to be formatted.</param>
  /// <returns>String date.</returns>
     
  var m_names = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
  year = theDate.substr(0, 4);month = theDate.substr(5, 2);day = theDate.substr(8, 2);hours = theDate.substr(11, 2);minutes = theDate.substr(14, 2);seconds = 0;
     var d = new Date(year, month, day, hours, minutes, seconds);
     var curr_date = d.getDate();
     var sup = '';
     if (curr_date == 1 || curr_date == 21 || curr_date ==31){sup = 'st';}
     else if (curr_date == 2 || curr_date == 22){sup = 'nd';}
     else if (curr_date == 3 || curr_date == 23){sup = 'rd';}
     else{sup = 'th';}
     var a_p = "";
     var curr_hour = d.getHours();
     if (curr_hour < 12){a_p = "AM";}
     else{a_p = "PM";}
     if (curr_hour == 0){curr_hour = 12;}
     if (curr_hour > 12){curr_hour = curr_hour - 12;}
     var curr_min = d.getMinutes(); 
     curr_min = curr_min + ""; 
     if (curr_min.length == 1){curr_min = "0" + curr_min;}
     var curr_month = d.getMonth();
     var curr_year = d.getFullYear(); 
     var prettyDate = m_names[curr_month]+' '+curr_date+sup+' '+curr_year+' - '+curr_hour+":"+curr_min+a_p;
     return prettyDate;
 },
 

//PDP// **** This callback function ensures that the picasa username in the configuration file is valid.
 onUserIdCallback: function(sender, e)
 {
  /// <summary>Handles the event fired when the callback function is called for the "getUserId" method.</summary>
  /// <param name="sender">The event source.</param>
  /// <param name="e">The event arguments.</param>
  
  if (e.feed.entry.length != 0){
      userId = e.feed.author[0].uri.$t.substr(e.feed.author[0].uri.$t.indexOf("com/")+4);
   this.getPhotosets(userId);
  }
  else{
   throw new Error("Feed failed: " + e.message);
     }
 },


//PDP// **** This callback function creates an album and passes it to the the build album helper function to add the the album to the album object defined in the 

//main class.  
 onPhotosetsCallback: function(sender, e)
 {
  /// <summary>Handles the event fired when the callback function is called for the "getPhotosets" method.</summary>
  /// <param name="sender">The event source.</param>
  /// <param name="e">The event arguments.</param>
  
  if (e.feed.entry.length != 0)
  {
   this.albumCount = e.feed.entry.length;
   
   for (var i = 0, j = this.albumCount; i < j; i++)
   {
    var photoset = e.feed.entry[i];
    var album = this.buildAlbum(photoset);
    this.data.album.push(album);
    photosetId = photoset.id.$t.substring(photoset.id.$t.indexOf("albumid/") + 8, photoset.id.$t.indexOf("?alt"));
    this.albums[photosetId] = album;
    this.getPhotos(photosetId);
   }
  }
  else
  {
   throw new Error("Feed failed: " + e.message);
  }
 },


//PDP// **** This callback function creates a slide and passes it to the build slide helperfunction to add the slide to the album object defined in the main class. 
 onPhotosCallback: function(sender, e)
 {
  /// <summary>Handles the event fired when the callback function is called for the "getPhotos" method.</summary>
  /// <param name="sender">The event source.</param>
  /// <param name="e">The event arguments.</param>
  
  if (e.feed.entry.length != 0)
  {
      photosetId = e.feed.id.$t.substr(e.feed.id.$t.indexOf("albumid/") + 8);
   var album = this.albums[photosetId];
   
   for (var i = 0, j = e.feed.entry.length; i < j; i++)
   {
    var slide = this.buildSlide(e.feed.entry[i]);
    album.slide.push(slide);
   }
   
   if (--this.albumCount == 0)
    this.dataHandler(this, { data: this.data });
  }
  else
  {
   throw new Error("Feed failed: " + e.message);
  }
 }
});

