﻿/* ===================================================
 * JS  for yapleo.smugmug.com
 * Copyright Payne Cheng
 * yapleo@gmail.com
 *
 * Last update: 06/20/2008
 * Edition:     Basic
 *
 * Thanks to those who provide tips/hacks in DGrin
 * =================================================== */

// ---------------------------------------------------
// filmStrip values you can override:
// ---------------------------------------------------
rightMoves = -5;
leftMoves  =  5;

// ---------------------------------------------------
// General FAQs
// ---------------------------------------------------
// FAQ 28: Hide text bubble when you mouse over images.
function delHover() {
  oLst = YD.getElementsBy(function(el) {return (YD.hasClass(el,'imgBorder') || YD.hasClass(el,'imgBorderOn'))},'img');
  for (i=0; i < oLst.length ; i++) {
      if (oLst[i].title && oLst[i].title != '') oLst[i].title = '';
      if (oLst[i].alt && oLst[i].alt != '') oLst[i].alt = '';
  }
}
YE.onContentReady('bodyWrapper', function() {if (!YD.hasClass (document.body, 'smugmug_ajax')) delHover()});
onPhotoShow.subscribe(function(){YE.onAvailable('mainImage', delHover)});


// ---------------------------------------------------
// Utility funcions 
// ---------------------------------------------------
//
// isClass - Mike Lane
//
function isClass(sClass) { 
  sClassName = document.body.className; 
  re = new RegExp(sClass + "( |$)")
  if (!sClassName) return false; 
  return re.test(sClassName); 
}

function hasPath(sPath)
{
  re = new RegExp("\/" + sPath + "(\/|$|#)");
  return re.test(window.location)
}


function addObjEvent(obj,type,fn){
    if(obj.addEventListener) obj.addEventListener(type,fn,false);
    else if(obj.attachEvent){
        obj["e"+type+fn]=fn;
        obj[type+fn]=function(){obj["e"+type+fn](window.event);}
        obj.attachEvent("on"+type,obj[type+fn]);
    }
}


// ---------------------------------------------------
// expandGalleryDescription - Payne Cheng
// ---------------------------------------------------
function expandGalleryDescription() {
  re1 = /^([^:]*)\s*:\s*(.*)/;
  re2 = /^(.*)\s*\.\.\.\s*(.*)/;
  divTags = document.getElementsByTagName("div");
  for (i=0; i<divTags.length; i++)
  {
    if (divTags[i].className == "miniBox")
    {
      dTags = divTags[i].getElementsByTagName("div");
      pTags = divTags[i].getElementsByTagName("p");

      aTags = dTags[0].getElementsByTagName("a");
      iTags = aTags[0].getElementsByTagName("img");

      if ( re1.exec(iTags[0].getAttribute("title")) ) { $desc = RegExp.$2;                      }
      if ( re2.exec(pTags[1].innerHTML)             ) { pTags[1].innerHTML = $desc + RegExp.$2; }
    }
  }
}


// ---------------------------------------------------
// expandPhotoDescription - Payne Cheng
// ---------------------------------------------------
function expandPhotoDescription() {
  re1 = /^(.*)>\s*(.*)/;
  re2 = /^(.*)\.\.\.$/;
  divTags = document.getElementsByTagName("div");
  for (i=0; i<divTags.length; i++)
  {
    if (divTags[i].className == "photo")
    {
      aTags = divTags[i].getElementsByTagName("a");
      dTags = divTags[i].getElementsByTagName("div");
      if ( ! aTags[0] || ! dTags[0]) continue;

      iTags = aTags[0].getElementsByTagName("img");
      if ( ! iTags[0]  ) continue;

      if ( re1.exec(iTags[0].getAttribute("title")) ) { $desc = RegExp.$2;                       }
      if ( re2.exec(dTags[0].innerHTML)             ) { dTags[0].innerHTML = $desc;              }
    }
  }
}

// ---------------------------------------------------
// addCategoryDescription - David Parry, Modified by Payne Cheng
// ---------------------------------------------------
function addCategoryDescription(desc){
  categoryDescription = desc;

  if ((isClass("category")) && (!isClass("subcategory")))
  {
 
    re = /category_(\S+)/i;
    re.exec(document.body.className);
 
  
    breadCrumb = document.getElementById("breadcrumb");
    if (breadCrumb && categoryDescription[RegExp.$1] )
    {
      divTag = document.createElement("div");
      divTag.id = "categoryDescription";
      divTag.setAttribute("class", "nav");
      divTag.appendChild(document.createTextNode(" - " + categoryDescription[RegExp.$1]));
      //breadCrumb.parentNode.insertBefore(divTag, breadCrumb.nextSibling);
      breadCrumb.appendChild(divTag);
      
      divTag = document.createElement("div");
      divTag.setAttribute("class", "spacer");
      breadCrumb.appendChild(divTag);
    }
  }
 
  if (isClass("homepage"))
  {
    re = /\>([\w\-]+)<\/a>/i;
 
    divTag = document.getElementById("categoriesBox");
    if (divTag)
    {
      divTags = divTag.getElementsByTagName("p");
 
      for (i=0; i<divTags.length; i++)
      {
        if (divTags[i].className == "albumTitle")
        {
          re.exec(divTags[i].innerHTML);
          if (categoryDescription[RegExp.$1]) {
            pTag = document.createElement("p");
            pTag.id = "categoryDescription_" + RegExp.$1;
            pTag.className = "description";
            pTag.appendChild(document.createTextNode(categoryDescription[RegExp.$1]));
            divTags[i].parentNode.insertBefore(pTag, divTags[i].nextSibling);
          }
        }
      }
    }
  }
}

// ---------------------------------------------------
// pageGalleries - Payne Cheng
// ---------------------------------------------------
function pageGalleries(current_page) {
  if (!current_page) current_page = 1;
  g_per_page   = 10

  divGBox = document.getElementById("galleriesBox");
  if (divGBox)
  {
    var pat = new RegExp("miniBox");

    pg_bar = document.getElementById("pageBar");
    if (! pg_bar)
    {
      pg_bar = document.createElement("div");
      pg_bar.className   = "pageBar";
      pg_bar.id          = "pageBar";
      pg_bar.style.align = "right";
      divGBox.insertBefore(pg_bar, divGBox.childNodes[1]);
    }
    else
    {
      if ( pg_bar.hasChildNodes() )
      {
        while ( pg_bar.childNodes.length >= 1 )
        {
          pg_bar.removeChild( pg_bar.firstChild );       
        } 
      }
    }

    divTags = divGBox.getElementsByTagName("div");
    g_total_count=0;
    for (i=0; i<divTags.length; i++)
    {
      //if (divTags[i].className == "miniBox")
      if (pat.test(divTags[i].className))
      g_total_count++;
    }
    
    first_page   = 1;
    last_page    = parseInt(g_total_count/g_per_page)+1;
    last_page    = Math.ceil(g_total_count/g_per_page);

    g_start = (current_page-1) * g_per_page;
    g_end   = g_start + g_per_page-1;


    // Description
    pg_desc = document.createElement("span");
    pg_desc.className = "pageDesc";    
    descText = document.createTextNode("(" + g_total_count + " galleries in " + last_page + " pages)");
    pg_desc.appendChild(descText);
    pg_bar.appendChild(pg_desc);

    // Header
    pg_head = document.createElement("span");
    pg_head.className = "pageHead";    
    headText = document.createTextNode("Page:   ");
    pg_head.appendChild(headText);
    pg_bar.appendChild(pg_head);

    /*
    if (current_page != first_page)
    {    
      link = document.createElement("a");
      link.className = "nav";
      link.setAttribute("href", "javascript:pageGalleries("+first_page+");");
      linkText = document.createTextNode("First");
      link.appendChild(linkText);
      pg_bar.appendChild(link);
    }
    */

    for (p=first_page; p<=last_page; p++)
    {
      pg_item = document.createElement("span");
      pg_item.className = "pageItem";

      Text = document.createTextNode(" "+p+" ");
      if (p != current_page)
      {
        link = document.createElement("a");
        link.className = "nav";
        link.setAttribute("href", "javascript:pageGalleries("+p+");");
        link.appendChild(Text);
        pg_item.appendChild(link);
      }
      else
      {
        pg_item.appendChild(Text);
      }
      pg_bar.appendChild(pg_item);

    }

    /*
    if (current_page != last_page)
    {    
      link = document.createElement("a");
      link.className = "nav";
      link.setAttribute("href", "javascript:pageGalleries("+last_page+");");
      linkText = document.createTextNode(" Last ");
      link.appendChild(linkText);
      pg_bar.appendChild(link);
    }
    */

    pg_all = document.createElement("span");
    pg_all.className = "pageItem";
    allText = document.createTextNode(" all ");
    if (current_page!=99999)
    {
      link = document.createElement("a");
      link.className = "nav";
      link.setAttribute("href", "javascript:pageGalleries(99999);");
      link.appendChild(allText);
      pg_all.appendChild(link);
    }
    else
    {
      pg_all.appendChild(allText);
    }
    pg_bar.appendChild(pg_all);

    divTags = divGBox.getElementsByTagName("div");
    count=0;
    for (i=0; i<divTags.length; i++)
    {
      //if (divTags[i].className == "miniBox")
      if (pat.test(divTags[i].className))
      {
        if ( current_page==99999 ||
             (count >= g_start && count <= g_end)
           )
        {
          divTags[i].style.display='block';
        }
        else
        {
          divTags[i].style.display='none';
        }
        count++;
      }
    }
  }
}


// ---------------------------------------------------
// changeCategoryInfo - David Parry
// ---------------------------------------------------
function changeCategoryInfo()
{
  re = /^([0-9]+ )(galler(y|ies))/;

  divTag1 = document.getElementById("categoriesBox");
  divTag2 = document.getElementById("subcategoriesBox");
  if ((divTag1)|| (divTag2))
  {
    if (divTag1)
      divTags = divTag1.getElementsByTagName("div");
    else
      divTags = divTag2.getElementsByTagName("div");

    for (i=0; i<divTags.length; i++)
    {
      if (divTags[i].className == "miniBox")
      {
        pTags = divTags[i].getElementsByTagName("p");
        re.exec(pTags[1].innerHTML);
        pTags[1].innerHTML = RegExp.$1 + RegExp.$2;
      }
    }
  }
}

// ---------------------------------------------------
// addSimpleViewerContainer - Payne Cheng
// ---------------------------------------------------
function addSimpleViewerContainer(viewer_url, gallery_url){
  svc = document.getElementById("svContainer");
  if (svc)
  {
    var fo = new SWFObject(viewer_url, "viewer", "100%", "100%", "7", "#181818");
    fo.addVariable("preloaderColor", "0xffffff");
    fo.addVariable("xmlDataPath", gallery_url); 
    fo.write("svContainer");
  }
}


// ---------------------------------------------------
// addRecentFeatured
// ---------------------------------------------------
// Automatic "Recent" Featured Gallery using Timeline 
function addRecentFeatured(text, days, thumbUrl) {
  if (YD.hasClass(document.body, "homepage")) {
    divTags = YD.getElementsByClassName("boxBottom", "div", YD.get("featuredBox"));

    for (i=0; i<divTags.length; i++) {
      miniBox = document.createElement("div");
      miniBox.className = "miniBox";

      photoBox = document.createElement("div");
      photoBox.className = "photo";
      miniBox.appendChild(photoBox);

      photoLink = document.createElement("a");
      photoLink.setAttribute("href", "javascript:showRecent(" + days + ");");
      photoBox.appendChild(photoLink);

      photoImg = document.createElement("img");
      photoImg.setAttribute("border", "0");
      photoImg.setAttribute("alt", text);
      photoImg.setAttribute("title", text);
      photoImg.src = thumbUrl;
      photoImg.className = "imgBorder";
      photoLink.appendChild(photoImg);

      albumTitle = document.createElement("p");
      albumTitle.className = "albumTitle";
      miniBox.appendChild(albumTitle);
      albumLink = document.createElement("a");
      albumLink.className = "nav";
      albumLink.setAttribute("href", "javascript:showRecent(" + days + ");");
      albumTitle.appendChild(albumLink);

      albumLinkText = document.createTextNode(text);
      albumLink.appendChild(albumLinkText);
      spacerDiv = document.createElement("div");
      spacerDiv.className = "spacer";
      miniBox.appendChild(spacerDiv);

      divTags[i].insertBefore(miniBox, divTags[i].childNodes[1]);

      break;
    }
  }
}

function showRecent(days) {
  endDate = new Date();
  oneDay = 1000*60*60*24;
  startDate = new Date(endDate.getTime() - (parseInt(days) * oneDay));
 
  sUrl = "/date/";
  sUrl += startDate.getFullYear() + "-" + padDate(startDate.getMonth() + 1) + "-" + padDate(startDate.getDate());
  sUrl += "/";
  sUrl += endDate.getFullYear() + "-" + padDate(endDate.getMonth() + 1) + "-" + padDate(endDate.getDate());
 
  window.location = sUrl;
}

function padDate(datePart) {
  if (datePart.toString().length != 1)
    return datePart
 
  return "0" + datePart;
}


// ---------------------------------------------------
// addKeywordFeatured
// ---------------------------------------------------
function addKeywordFeatured(text, description, keyword, thumbUrl)
{
  if (isClass("homepage"))
  {
    divTag = document.getElementById("featuredBox");

    if (divTag)
    {
      divTags = divTag.getElementsByTagName("div");

      for (i=0; i<divTags.length; i++)
      {
        if (divTags[i].className == "boxBottom")
        {
          miniBox = document.createElement("div");
          miniBox.className = "miniBox";

          photoBox = document.createElement("div");
          photoBox.className = "photo";
          miniBox.appendChild(photoBox);

          photoLink = document.createElement("a");
          photoLink.setAttribute("href", "/keyword/" + keyword);
          photoBox.appendChild(photoLink);

          photoImg = document.createElement("img");
          photoImg.setAttribute("border", "0");
          photoImg.setAttribute("alt", text);
          photoImg.setAttribute("title", text);
          photoImg.src = thumbUrl;
          photoImg.className = "imgBorder";
          photoLink.appendChild(photoImg);

          albumTitle = document.createElement("p");
          albumTitle.className = "albumTitle";
          miniBox.appendChild(albumTitle);

          albumLink = document.createElement("a");
          albumLink.className = "nav";
          albumLink.setAttribute("href", "/keyword/" + keyword);
          albumTitle.appendChild(albumLink);

          albumLinkText = document.createTextNode(text);
          albumLink.appendChild(albumLinkText);
          
          albumDescription = document.createElement("p");
          albumDescription.className = "description";
          miniBox.appendChild(albumDescription);

          albumDescriptionText = document.createTextNode(description);
          albumDescription .appendChild(albumDescriptionText);

          spacerDiv = document.createElement("div");
          spacerDiv.className = "spacer";
          miniBox.appendChild(spacerDiv);

          divTags[i].insertBefore(miniBox, divTags[i].childNodes[1]);


          break;
        }
      }
    }
  }
}

function OnLoadHandler()
{
  // modify the addKeywordFeatured function call to customize your keyword gallery
  // Variables are (in order): the title of your gallery, the description of your gallery, 
  //                           the keyword to find the pictures, 
  //                           the path to the thumbnail for the gallery.
  // addKeywordFeatured('Recipe', 'Collection of our homemade dishes', 'Recipe', 'photos/270668681_rnhWR-Ti.jpg'); 
}
  

// ---------------------------------------------------
// RECENT GALLERIES HACK - darryl, Modified by Payne Cheng
// ---------------------------------------------------

// This hack replaces your Featured Galleries with Recent Galleries as determined by the RSS feed.
//
// RSS parsing code from Paul Sobocinski found here:
// http://www.xml.com/pub/a/2006/09/13/rss-and-ajax-a-simple-news-reader.html?page=5

// NOTE: You must have one gallery set to featured, as a placeholder to make the Featured Box show up
// This placeholder gallery will not show up once the hack is in place.

// Rename Featured Galleries to Recent Galleries
YE.onContentReady('datesTitle', function() {this.innerHTML='Recent Galleries'});

// Specify how many recent galleries you'd like to see
var rsscount = 7 ;

// Specify your RSS feed for Recent Galleries (replace XXXXXX with your site name)
// ImageCount needs to be "padded" if you have a lot of private galleries mixed in with your public 
// galleries.  If you are not seeing 6 (or however many) recent galleries, try increasing ImageCount
//
// NOTE:  If you are using a CNAME, you need to change http://XXXXXX.smugmug.com to 
// http://yourcustomdomain.com

var xhr;
var rssurl = "http://yapleo.smugmug.com/hack/feed.mg?Type=nickname&Data=yapleo&format=rss200&ImageCount=10";

// Added a line to the doOnLoad function that is also used by the removeLinkFromImg() function and others.  
// So you may only need to append the if//getRSS clause below.

function addRecentDates() {
  if (YD.hasClass(document.body, "homepage")) //
     getRSS();
}

//OBJECTS

//objects inside the RSS2Item object
function RSS2Enclosure(encElement)
{
  if (encElement == null)
  {
    this.url = null;
    this.length = null;
    this.type = null;
  }
  else
  {
    this.url = encElement.getAttribute("url");
    this.length = encElement.getAttribute("length");
    this.type = encElement.getAttribute("type");
  }
}

function RSS2Guid(guidElement)
{
  if (guidElement == null)
  {
    this.isPermaLink = null;
    this.value = null;
  }
  else
  {
    this.isPermaLink = guidElement.getAttribute("isPermaLink");
    this.value = guidElement.childNodes[0].nodeValue;
  }
}

function RSS2Source(souElement)
{
  if (souElement == null)
  {
    this.url = null;
    this.value = null;
  }
  else
  {
    this.url = souElement.getAttribute("url");
    this.value = souElement.childNodes[0].nodeValue;
  }
}

//object containing the RSS 2.0 item
function RSS2Item(itemxml)
{
  //required
  this.title;
  this.link;
  this.description;

  //optional vars
  this.author;
  this.comments;
  this.pubDate;

  //optional objects
  // this.category;
  this.enclosure;
  this.guid;
  this.source;

  var properties = new Array("title", "link", "description", "author", "comments", "pubDate");
  var tmpElement = null;
  for (var i=0; i<properties.length; i++)
  {
    tmpElement = itemxml.getElementsByTagName(properties[i])[0];
    if (tmpElement != null)
      eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
  }

  // this.category = new RSS2Category(itemxml.getElementsByTagName("category")[0]);
  this.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName("enclosure")[0]);
  this.guid = new RSS2Guid(itemxml.getElementsByTagName("guid")[0]);
  this.source = new RSS2Source(itemxml.getElementsByTagName("source")[0]);
}

//objects inside the RSS2Channel object
function RSS2Category(catElement)
{
  if (catElement == null)
  {
    this.domain = null;
    this.value = null;
  }
  else
  {
    this.domain = catElement.getAttribute("domain");
    this.value = catElement.childNodes[0].nodeValue;
  }
}

//object containing RSS image tag info
function RSS2Image(imgElement)
{
  if (imgElement == null)
  {
  this.url = null;
  this.link = null;
  this.width = null;
  this.height = null;
  this.description = null;
  }
  else
  {
    imgAttribs = new Array("url","title","link","width","height","description");
    for (var i=0; i<imgAttribs.length; i++)
      if (imgElement.getAttribute(imgAttribs[i]) != null)
        eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
  }
}

//object containing the parsed RSS 2.0 channel
function RSS2Channel(rssxml)
{
  //required
  this.title;
  this.link;
  this.description;

  //array of RSS2Item objects
  this.items = new Array();

  //optional vars
  this.language;
  this.copyright;
  this.managingEditor;
  this.webMaster;
  this.pubDate;
  this.lastBuildDate;
  this.generator;
  this.docs;
  this.ttl;
  this.rating;

  //optional objects
  // this.category;
  this.image;

  var chanElement = rssxml.getElementsByTagName("channel")[0];
  var itemElements = rssxml.getElementsByTagName("item");

  for (var i=0; i<itemElements.length; i++)
  {
    Item = new RSS2Item(itemElements[i]);
    this.items.push(Item);
    //chanElement.removeChild(itemElements[i]);
  }

  var properties = new Array("title", "link", "description", "language", "copyright", "managingEditor", "webMaster", "pubDate", "lastBuildDate", "generator", "docs", "ttl", "rating");
  var tmpElement = null;
  // this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
  this.image = new RSS2Image(chanElement.getElementsByTagName("image")[0]);
}

//PROCESSES

//uses xmlhttpreq to get the raw rss xml
function getRSS()
{
  //call the right constructor for the browser being used
  if (window.ActiveXObject)
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  else if (window.XMLHttpRequest)
    xhr = new XMLHttpRequest();
  else
    alert("not supported");

  //prepare the xmlhttprequest object
  xhr.open("GET",rssurl,true);
  xhr.setRequestHeader("Cache-Control", "no-cache");
  xhr.setRequestHeader("Pragma", "no-cache");
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4)
    {
      if (xhr.status == 200)
      {
        if (xhr.responseText != null)
          processRSS(xhr.responseXML);
        else
        {
          alert("Failed to receive RSS file from the server - file not found.");
          return false;
        }
      }
      else
        alert("Error code " + xhr.status + " received: " + xhr.statusText);
    }
  }

  //send the request
  xhr.send(null);
}

//processes the received rss xml
function processRSS(rssxml)
{
  RSS = new RSS2Channel(rssxml);
  showRSS(RSS);
}

//shows the RSS content in the browser
function showRSS(RSS)
{
    divTags = YD.getElementsByClassName("boxBottom", "div", YD.get("datesBox"));
    
    //populate the items
    for (var j=0; j<divTags.length; j++)
    {
      if (divTags[j].className == "boxBottom")
      {
        rdiv = divTags[j].firstChild

        for (var i=0; i<rsscount && i<RSS.items.length; i++)
        {
          galimage = RSS.items[i].description;

          galimage = galimage.replace(/^.+src="(.*?)" .*/, "$1") ;
          galimage = galimage.replace(/(.*-)Th(-\d+)?(\.\w+)/i, "$1Ti$2$3") ;

          pubdate = RSS.items[i].pubDate ;
          pubdate.match(/^\w{3}, (\d\d) (\w{3}) (\d{4}) (\d\d):(\d\d):\d\d -\d\d\d\d/) ;

          // Fix up date formatting
          if (RegExp.$4>12) { meridian = 'pm'; hrs = RegExp.$4-12 } else { meridian = 'am'; if (RegExp.$4==0) { hrs = 12 } else { hrs = RegExp.$4-0 }} ;

          fixdate = "updated: " + RegExp.$2 + " " + RegExp.$1 + ", " + RegExp.$3 + " " + hrs + ":" + RegExp.$5 + meridian + " PST" ;

          miniBox = document.createElement("div");
          miniBox.className = "miniBox miniminiBox";

          photoBox = document.createElement("div");
          photoBox.className = "photo";
          miniBox.appendChild(photoBox);

          photoLink = document.createElement("a");
          photoLink.setAttribute("href", RSS.items[i].link);
          photoBox.appendChild(photoLink);

          photoImg = document.createElement("img");
          photoImg.setAttribute("border", "0");
          photoImg.setAttribute("alt", RSS.items[i].title);
          photoImg.setAttribute("title", RSS.items[i].title);
          photoImg.src = galimage;
          photoImg.className = "imgBorder";
          photoLink.appendChild(photoImg);

          /*
          albumTitle = document.createElement("p");
          albumTitle.className = "albumTitle";
          miniBox.appendChild(albumTitle);
          albumLink = document.createElement("a");
          albumLink.className = "nav";
          albumLink.setAttribute("href", RSS.items[i].link);
          albumTitle.appendChild(albumLink);

          albumLinkText = document.createTextNode(RSS.items[i].title);
          albumLink.appendChild(albumLinkText);

          albumUpdated = document.createElement("p");
          albumUpdated.className = "updated";
          miniBox.appendChild(albumUpdated);
          albumUpdatedText = document.createTextNode(fixdate);
          albumUpdated.appendChild(albumUpdatedText);

          
          spacerDiv = document.createElement("div");
          spacerDiv.className = "spacer";
          miniBox.appendChild(spacerDiv);
          */

          divTags[j].insertBefore(miniBox, rdiv);
        }
        spacerDiv = document.createElement("div");
        spacerDiv.className = "spacer";
        divTags[j].insertBefore(spacerDiv, rdiv);
      }
    }
    //we're done
    return true;
}


// ---------------------------------------------------
// filmStrip values you can override:
// ---------------------------------------------------


nickname     = "yapleo";
galleryPath  = "5905416_jfTY8";
FirstMonth   = 200001;


apiKey       = "H57C0LjpPMwc6HFdSHv31mBLX2cbw7Tx"; // SmugLuv's API key
//imagoURL     = "http://cs.ucla.edu/~pccheng/smugmug/yapleo.googlepages.com/imago.html";
imagoURL     = "http://cs.ucla.edu/~pccheng/smugmug/imago.html";
cb_yearmon   = "";
AlbumsByDate = { 'time'   :  0, 'albums' :  {}, 'index'  :  { year : {}, mon  : {}, day  : {} }, 'yearmon':  {} };



// 
// albumCallback - process received album information
//
function albumCallback(albums)
{
  //alert('got');
  var currentTime = new Date();

  //for (var counter = 0; counter < 10; counter++)
  for (var counter = 0; counter < albums.length; counter++)
  {
    current_album = albums[counter];

    // Parse date string
    var datePart = albums[counter]['Title'].match(/^(\d{4}).(\d{2}).(\d{2})/);   
    if (datePart)
    {
      var year = datePart[1];
      var mon  = datePart[2];
      var day  = datePart[3];
      var yearmon    = year + "" + mon;
      var yearmonday = year + "" + mon + "" + day;

      current_album['date'] = yearmonday;
      AlbumsByDate['albums'][current_album.id] = current_album;

      // Generate indexes
      if (! AlbumsByDate['index']['year'][year])      { AlbumsByDate['index']['year'][year]      = {'count':0,'id':[],'albums':{}}; }
      if (! AlbumsByDate['index']['mon'][yearmon])    { AlbumsByDate['index']['mon'][yearmon]    = {'count':0,'id':[],'albums':{}}; }
      if (! AlbumsByDate['index']['day'][yearmonday]) { AlbumsByDate['index']['day'][yearmonday] = {'count':0,'id':[],'albums':{}}; }

      AlbumsByDate['index']['year'][year]['count']++;
      AlbumsByDate['index']['year'][year]['id'].push(current_album.id);
      AlbumsByDate['index']['year'][year]['albums'][current_album.id]      = current_album.id;

      AlbumsByDate['index']['mon'][yearmon]['count']++;
      AlbumsByDate['index']['mon'][yearmon]['id'].push(current_album.id);
      AlbumsByDate['index']['mon'][yearmon]['albums'][current_album.id]    = current_album.id;

      AlbumsByDate['index']['day'][yearmonday]['count']++;
      AlbumsByDate['index']['day'][yearmonday]['id'].push(current_album.id);
      AlbumsByDate['index']['day'][yearmonday]['albums'][current_album.id] = current_album.id;
    }
  }
  AlbumsByDate['time'] = currentTime.getTime();
  //showDateGalleries('200808');
  showCalendarGalleries(cb_yearmon);
}

//
// hideCalendarImages - hide popup album div
//
function hideCalendarImages()
{
  var divPopup = document.getElementById("popup_cal_album");
  if (divPopup)
  {
    divPopup.style.visibility = 'hidden';
  }
}

//
// showCalendarImages - create a popup div to show selected album
//
function showCalendarImages(index)
{
  var divCalendar = document.getElementById("calendar");
  if (divCalendar)
  {
    var divAnchor = document.getElementById("anchor_cal_album");
    if (! divAnchor)
    {
      divAnchor = document.createElement("a");
      divAnchor.id = "anchor_cal_album";
      //divCalendar.appendChild(divAnchor);
      divCalendar.insertBefore(divAnchor, divCalendar.childNodes[0]);
    }
    var divPopup = document.getElementById("popup_cal_album");
    if (! divPopup)
    {
      divPopup = document.createElement("div");
      divPopup.innerHTML = '<DIV id=popup_cal_album style="WIDTH: 1036; height: 746; VISIBILITY: hidden; position: absolute; top: 100px; margin-left: -150px; BACKGROUND-COLOR: #EEEEFF"></DIV>';
      divCalendar.insertBefore(divPopup, divCalendar.childNodes[0]);
    }
  }

  // Create PopupWindow objects
  var popup = new PopupWindow("popup_cal_album");
  popup.autoHide();

  var gpath = "" + index + "_" + AlbumsByDate['albums'][index]['Key'];
  var mpath = "settings.mg?AlbumID=" + index + "&AlbumKey=" + AlbumsByDate['albums'][index]['Key'];
  popup.populate('<center>' +
                 '<table>' +
                 '<tr><td align="right">' + 
                 '<span onclick="window.open(\'/gallery/' + mpath + '\')"><input type="button" name="CUSTOMIZE" value="CUSTOMIZE"/></span>' + 
                 '<span onclick="window.open(\'/gallery/' + gpath + '\')"><input type="button" name="VIEW"      value="SMUGMUG VIEW"/></span>' + 
                 '<span>&nbsp;&nbsp;&nbsp;</span>' + 
                 '<span onclick="hideCalendarImages()"><input type="button" name="CLOSE" value="CLOSE"/></span>' + 
                 '</td></tr>' + 
                 '<tr><td><iframe frameborder=0 width="1020" height="700" src="' + imagoURL +'?' + index +'"></iframe></td></tr>' +
                 '</table>' +
                 '</center>' 
                );
  popup.showPopup("anchor_cal_album");
  delete popup;
}

// showCalendarGalleries() - Overlay albums on calendar
function showCalendarGalleries(index)
{
  divGBox = document.getElementById("photos");
  if (divGBox)
  {
    // Clear child nodes
    while (divGBox.childNodes[0]) 
    {
      divGBox.removeChild(divGBox.childNodes[0]);
    }

    // Hide useless nav bar
    var divNavBt = document.getElementById("albumNav_bottom");
    if (divNavBt)
    {
      divNavBt.style.display="none";
    }
    
    if (! AlbumsByDate['index']['mon'][index] ) { return; }

    // Calculate number of albums for each date
    var count = {};
    for (var i in AlbumsByDate['index']['mon'][index]['albums'])
    {
      var album = AlbumsByDate['albums'][i];
      if (! count[album['date']]) { count[album['date']] = 1;  }
      else                        { count[album['date']] += 1; }
    }

    // For each album in this month, overlay the album cover on the calendar
    for (var i in AlbumsByDate['index']['mon'][index]['albums'])
    {
      var album = AlbumsByDate['albums'][i];

      // Locate the div container for thie album (on a specific date)
      var calCell = document.getElementById("CalCell_" + album['date']);
      if (! calCell) { return; }

      // Prepare photobox
      var text = album['Title'];
      var thumbUrl = "http://" + nickname + ".smugmug.com/photos/random.mg?AlbumID=" + album['id'] + "&Size=Tiny&AlbumKey=" + album['Key']; 
      var photoUrl = "http://" + nickname + ".smugmug.com/gallery/" + album['id'] + "_" + album['Key'];

      photoBox = document.createElement("span");
      photoBox.id        = "Anchor_Tiny_" + album['id'];
      photoBox.className = "CalCellAlbum";

      var size = photoBox.style.width = ( count[album['date']] <= 1 ) ? 100 : 48;
      photoBox.innerHTML = "<span style=\"cursor:pointer; border:1px solid #FFFFFF\" onclick=\"showCalendarImages('"+ album['id']  +"')\">" +
                           "<img src='" + thumbUrl + "' width='" + size + "px' height='" + size + "px' alt='" + album['Title'] + "'/>" +
                           "</span>";

      /*
      if ( count[album['date']] > 1 )
      {
        var calCellExtra = document.getElementById("CalCellExtraText_" + album['date']);
        if (calCellExtra)
        {
          calCellExtra.innerHTML(count[album['date']]);
        }
      } 
      */
      //photoBox.className="photo size_Tiny";

      /*
      var link = document.createElement("a");
      link.className = "nav";
      link.setAttribute("href", "javascript:addDateGalleries();");
      linkText = document.createTextNode(album['Title']);
      link.appendChild(linkText);
      photoBox.appendChild(link);
      */

      //divGBox.appendChild(photoBox);
      calCell.appendChild(photoBox);
    }
//    keys.sort( function (a, b){return (a > b) - (a < b);} );
//    alert(jsDump.parse(keys));
  }
}


function CalendarCallback(arg)
{
  var divId = "calendar";
  var smugwrap    = null;
  var currentTime = new Date();

  cb_yearmon = arg['yearmon'];

  // Get current day and month for comparison
  try 
  {
    if ( currentTime.getTime() > AlbumsByDate['time'] + 5*60*1000 )
    {
      AlbumsByDate['time'] = currentTime.getTime();

      smugwrap = new SmugWrap(divId, apiKey, albumCallback, null);
      smugwrap.GetAlbums(nickname);
    }
    else
    {
      showCalendarGalleries(cb_yearmon);
    }
  } catch (e)
  {
    alert("error:" + jsDump.parse(e));
  }
}



function addCalendarGalleries()
{

  //
  // Initialize 
  //

  // Gallery Path
  if (! hasPath(galleryPath)) { return }
  
  Calendar('calendar');
}

// vim: sw=2 ts=2 sts=2 expandtab 


