/** 
 * Embody Imagery
 * Designed by Digital Maelstrom LLC 
 * @author Jeff Hall
 * @last-modified Mon Jul 19 01:14:56 2010 -0500
 * @version $Id: 3e50dbb8eab63a1706aa7839410d5d56fd4b4e60 $
 */
var config = {
    "base_url" : "http://api.flickr.com/services/rest/",
    "method"   : "flickr.photosets.getPhotos",
    "format"   : "json",
    "api_key"  : "e05bab99c1d18c3897b3dbeadf3cda12",
    "sq_width" : 75,
    "sq_height": 75
};

var currentPage = "",
    currentImages = [],
    images = [];

function log() {
    if(window.console) {
        window.console.log(arguments);
    }
}

function showPage(selector) {
    if("" == selector) {
      $('div.frame').hide();
      $('div#gallery').show();
      $('#in-focus').show();
    } else {
      $('div.frame').hide();
      $('div#gallery').hide();
      $('#in-focus').hide();
      $(selector).toggle("slide");  
    }
}

var flickrPhotoUrl = function(farm, server, id, secret, size) {
    return  "http://farm" + farm +
            ".static.flickr.com/" +
            server + "/" +
            id + "_" + secret + "_" +
            size + ".jpg";
            
}

var flickrPhotoUrlForItem = function(item, size) {
    return flickrPhotoUrl(item.farm_id, item.server, item.id, item.secret, size);
};

function preloadImage(element, url, loader_url) {
    var l_url = (undefined == loader_url) ? 'images/ajax-loader.gif' : loader_url,
    img = document.createElement('img');
    if(undefined == element.nodeName ||
        "IMG" != element.nodeName.toUpperCase()) {
            return;
    }

    $(img).load(function(){
        element.src = url;
        $(element).css('max-width: 815px;')        
    });
    element.src = l_url;
    img.src = url;
    images.push(img);
    return img;
}

function onFocus(farm_id, server, id, secret) {
    var container = document.getElementById('in-focus') 
    //$(container).css("display","block");
    preloadImage(container,
        flickrPhotoUrl(farm_id, server, id, secret, "b"));
};

/*
var flickrImageTagForItem = function(item) {
  var tag = document.createElement('img');
  tag.src = flickrPhotoUrlForItem(item, "s");
  tag.width = config["sq_width"];
  tag.height = config["sq_height"];
  return tag;  
};
*/


var galleryLinkForItem = function(item) {
    var tag = document.createElement('a');
    tag.href = "#" + item.id;
    
    jQuery(tag).click(function(){
        $('div.frame').hide();
        $('div#gallery').show();
        displayPhotoset(item.id);
        //preparePage();
    });
    
    jQuery(tag).html(item.title._content);
    return tag;
}

    function thumbnailHtml(idx, item) {
      var li = document.createElement('li');
      //var a = document.createElement('a');
      var   img = document.createElement('img');
       
      img.src = item.url_sq;
      img.width = config["sq_width"];
      img.height = config["sq_height"];
      
      //$(a).append(img);
      $(li).addClass('thumb').append(img);
      return li;
    }
    
    function itemSelected(idx, obj) {
      var value = currentImages[idx];
      log(obj, "Item selected", idx, value);
      
      onFocus(value.farm, value.server, value.id, value.secret);
      
    }
    
    function gallery(container, data) {
      
      $(container).html('');
      var ol = document.createElement('ol');
      $(container).append(ol);

      jQuery.each(data, function(index, value) {
        $(ol).append(thumbnailHtml(index, value));
      });

      var carousel = new YAHOO.widget.Carousel(container,{
        isCircular: true,
        animation: {speed: 0.5},
        selectOnScroll: false
      });
      
      if(data.length > 10) {
        carousel.set("numVisible", 10);
        log(data.length);
      } else {
        carousel.set("numVisible", data.length);
        log(data.length);
      }
      carousel.addListener("itemSelected", itemSelected, carousel);
      carousel.set("revealAmount", 25);
      carousel.render();
      carousel.show();
      return carousel;
    }

var flickrPhotosetForId = function(photoset_id, container, callback) {
     var collection_callback = function(data) {   
        if(data.photoset == undefined || data.photoset.photo == undefined) {
          log("[flickrPhotosetForId]", photoset_id, container, " Flickr error: ", data)
          throw "No or invalid data returned from Flickr API";
        }
        
        /*
        jQuery.each(data.photoset.photo, function(index, value) {
           var image = document.createElement('img');
           //preloadImage(image, value.url_sq);
           image.src = value.url_sq;
           var link = document.createElement('li');
           link.appendChild(image);
           $(image).click(function() {
               onFocus(value.farm, value.server, value.id, value.secret);
           });
           carousel.jcarousel('add', index,link);
           //$(link).appendTo(container);
        });
        */
        currentImages = data.photoset.photo;
        showPage("");
        gallery(document.getElementById('gallery'), currentImages);
      
      /*  
      $(container).jcarousel({
			wrap: 'both',
			scroll: 9,
		});
		*/
		/*
		if(undefined != callback) {
		    callback.call(data);
	    }
	    */
    };
    
    var url     = config["base_url"] + "?" + 
    "method="   + config["method"] +
    "&format="  + config["format"] + 
    "&api_key=" + config["api_key"] +
    "&photoset_id=" + photoset_id +
    "&extras=url_m,url_sq" +
    "&jsoncallback=?";
    jQuery.getJSON(url, collection_callback);      	    
};

var flickrPhotosetsForUser = function(nsid, container, callback) {
    var collection_callback = function(data) {
        //cache.photosets = data.photosets;
        if(data.photosets == undefined || data.photosets.photoset == undefined) {
          log("[flickrPhotosetsForUser]", nsid, container, " Flickr error: ", data)
          throw "No or invalid data returned from Flickr API";
        }
        jQuery(container).html('');
        jQuery.each(data.photosets.photoset, function(index, value) {
           var link = jQuery('<li>').html(galleryLinkForItem(value));
           link.appendTo(container); 
        });
        if(undefined != callback) {
            callback.call(data);
        }
    };
    
    var url     = config["base_url"] + "?" + 
    "method="   + "flickr.photosets.getList" +
    "&format="  + config["format"] + 
    "&api_key=" + config["api_key"] +
    "&user_id=" + nsid +
    "&jsoncallback=?";
    jQuery.getJSON(url, collection_callback);      	    
};
var displayPhotoset = function(id,callback) {
    var selector = "#photos";
    jQuery(selector).html('');
    flickrPhotosetForId(id, selector);
};

function preparePage() {
  try {
  var hash_id = window.location.hash.split("#")[1];
  } catch(err) {
    log(err);
  }
  if(undefined == hash_id) {
     return; 
  }
  
  log("Loading set " + hash_id);
  
  displayPhotoset(hash_id);
  showPage("");
}

