var keywordsOn = false;
var generatedTable = new Array();
var yearOpen = new Array();
var monthOpen = new Array();

var monthNames = [ 'januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli',
                 'augusti', 'september', 'oktober', 'november', 'december' ];
var weekdayNames = [ 'l&ouml;rdag', 's&ouml;ndag', 'm&aring;ndag', 'tisdag', 'onsdag', 
                   'torsdag', 'fredag', 'l&ouml;rdag' ];

function getObj(name)
{
  if (document.getElementById)
  {
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
        this.obj = document.all[name];
        this.style = document.all[name].style;
  }
  else if (document.layers)
  {
        this.obj = document.layers[name];
        this.style = document.layers[name];
  }
}

function initMenu( menuName )
{
  // currentMenu = getObj( "menuItem-" + menuName );
  itemName = "menuItem-" + menuName;
  currentMenu = document.getElementById( "menuItem-" + menuName );
  currentMenu.className = "currentMenuItem";
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//

function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while (i < clen) {
    var j = i + alen;

    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);

    i = document.cookie.indexOf(" ", i) + 1;

    if (i == 0) break; 

  }

  return null;

}
/*
 *  Browser window size 
 *
 * Adapted from http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=16
 */
function getWindowWidth()
{
  if( typeof( window.innerWidth ) == 'number' )
    return window.innerWidth; // Mozilla
  else if( document.documentElement && document.documentElement.clientWidth )
    return document.documentElement.clientWidth;
  else if( document.body && document.body.clientWidth )
    return document.clientWidth;
  else
    return 0;
}

function getWindowHeight()
{
  if( typeof( window.innerHeight ) == 'number' )
    return window.innerHeight; // Mozilla
  else if( document.documentElement && document.documentElement.clientHeight )
    return document.documentElement.clientHeight; // IE 6+ compat mode
  else if( document.body && document.body.clientHeight )
    return document.body.clientWidth; // IE 4
  else
    return 0;
}


/*
 * Tab stuff
 */
var currentTabName = 'tab-1';
function selectTab(pageName) 
{
  //if (objPage) objPage.style.display = 'none';
  oldTab=document.getElementById( currentTabName );
  oldPage=document.getElementById( currentTabName + '-contents');

  oldTab.className= 'unselected tab';
  oldPage.className= 'unselected tab';
  // if (objPage) objPage.className = 'hiddenTab';

  objTab=document.getElementById(pageName);
  objPage=document.getElementById(pageName + '-contents');

  //objPage.style.display = 'block';
  objTab.className = 'selected tab';
  objPage.className = 'selected tab';

  currentTabName = pageName;
}

function rulesLen(){
 if (document.styleSheets){
  var s = document.styleSheets[0];
  if (s.cssRules){ 
   var r = s.cssRules;
  }
  else if (s.rules){ 
   var r = s.rules;
  }
 alert(r.length);
 }
 }
/* From http://dotnetjunkies.com/WebLog/warstar/ */
function StyleSheetChanger(cssClassName,toChange,changeTo)
{
  var ss;

  for( i = 0; document.styleSheets.length > i; i++) // IE
  {
    ss = document.styleSheets[i];

    if( ss.rules /* != undefined */)
    {
      var r = ss.rules;
       

      for(j = 0; r.length > j; j++)
      {
        selectorLowerCase = 
          document.styleSheets[i].rules[j].selectorText.toLowerCase();
                
        if( selectorLowerCase == cssClassName.toLowerCase())
        {
          document.styleSheets[i].rules[j].style[toChange] = changeTo;
          return;
        }
      }
    }  /* end of if rules are not undefined */
    else if(document.styleSheets[i].cssRules != undefined) // Firefox
    {
      for(j = 0; document.styleSheets[i].cssRules.length > j; j++)
      {
        if(document.styleSheets[i].cssRules[j].styleSheet != undefined ) // firefox
        {
          for( k = 0; 
            document.styleSheets[i].cssRules[j].styleSheet.cssRules.length > k; k++)
          {
            if(document.styleSheets[i].cssRules[j].styleSheet.cssRules[ k ].selectorText == cssClassName)
            {
              oldValue = document.styleSheets[i].cssRules[j].styleSheet.cssRules[ k ].style.cssText;
              str1 = new RegExp( toChange + ": .+;", "gi" );
              if( oldValue.search( str1 ) == -1 ) // then no match, append
                newValue2 = oldValue + toChange + ": " + changeTo + ";";
              else
                newValue2 = oldValue.replace( str1, 
                                              toChange + ": " + changeTo + ";");
//              newValue2 = oldValue.replace( str1, 
//                                            toChange + ": " + changeTo + ";");

//              alert( "changing at place 2, old value is '" + oldValue + 
//                     "', newValue='" + newValue + "', str1='" + str1 + 
//                     "', newValue2 = '" + newValue2 + "'" );
              
               document.styleSheets[i].cssRules[j].styleSheet.cssRules[ k ].style.cssText = newValue2;
              return;
            }
          }
          // if we get here and it was not found, add a rule (DO NEXT)
          document.styleSheets[i].cssRules[j].styleSheet.insertRule( cssClassName + " {" + toChange + ": " + changeTo+ "}", 0 ); 
          return;
        }

        if(document.styleSheets[i].cssRules[j].selectorText == cssClassName)
        {
          document.styleSheets[i].cssRules[j].style[toChange] = changeTo;
        }
      }
    } 
    else
    {
      window.alert("Your browser won't support the changing of a style " + 
                   "sheet by javascript!");
    }
  } /* end of for each style sheet */
}

function toggleAllPhotos()
{
//  document.styleSheets[0].cssRules[0].styleSheet.cssRules[61].style.cssText = "display: inline"; // selectorText == cssClassName)
  StyleSheetChanger( "ul.photoList li.extra", "display", "inline" );
/*
  cssRules = document.styleSheets[0].cssRules;

   var length = cssRules.length;
     
   for(i = 0; i < length; i++) {
     if(cssRules[i].selectorText == "ul.photoList li.extra") 
     {
       var rule = cssRules.item(i);
       break;
     }
   }

   rule.style[ 'display' ] = 'inline';
*/
}

function pageLoaded()
{
  div = document.getElementById( 'photoTableDiv' );
  window.alert("Page loaded!, photoDivWidth=" + div.width );
}

function populatePhotoTable( details )
{
  windowWidth = getWindowWidth();
  windowHeight = getWindowHeight();
  
  /* subtract the size of left menu and right adsense ad */
  tableWidth = windowWidth - 120 - 160; /* Guessing a bit */
  tableHeight = windowHeight - 190;
  photoTableCols = Math.floor( tableWidth / 190 );
  photoTableRows = Math.floor( tableHeight / 190 );
  if( photoTableCols < 1 )
    photoTableCols = 1;
  if( photoTableRows < 1 )
    photoTableRows = 1;

  viewPhotos = photoTableCols * photoTableRows;
  photoCount = photos.length;
  pageCount = Math.ceil( photoCount / viewPhotos );
  currentPage = 0;

  // div = document.getElementById( 'photoTableDiv' );
  table = document.getElementById('photoTable');
  firstRow = table.insertRow( 0 );

  cell = firstRow.insertCell(0);
  cell.colSpan = photoTableCols;
  cell.className = "firstRow";

  setPhotoTableHeading( details );

  photoIndex = 0;

  for( rowIndex = 1; rowIndex < (photoTableRows + 1); rowIndex++ )
  {
    row = table.insertRow( rowIndex );
    for( col = 0; col < photoTableCols; col++ )
    {
      // photo = photos[ photoIndex ];

      cell = row.insertCell( col );
      /*
      html = "<a class='thumbnail' href='image.php?photograph=" + photo + "'>";
      html = html + "<img src='digitalizationRedirect.php?photo=" +
              photo + "&maxWidth=160&maxHeight=160' " +
              "alt='photo'/>";
      html = html + "</a>\n";
      
      cell.innerHTML = html;
*/
      photoIndex++;
      if( photoIndex > photos.length )
        break;
    }
    if( photoIndex > photos.length )
      break;
  }

  setPhotoTableContents( details );

//  window.alert("Testing Alert! tw=" + tableWidth + ", th=" + tableHeight + " cols=" + cols + ", rows=" + rows );
}

var keywords = new Array();

function isUndefined( x )
{
  return typeof( x ) == 'undefined';
}

function getKeyword( number, name )
{
  keyword = keywords[ number ];
  if( isUndefined( keyword ) )
  {
    keyword = new Keyword( number, name );
    keywords[ number ] = keyword;
  }
  return keyword;
}

function Keyword( number, name )
{
  this.number = number;
  this.name = name;
}

/* majorKeywords and minorKeywords are arrays of Keyword */
function Thumbnail( photoNumber, majorKeywords, minorKeywords )
{
  this.photo = photoNumber;
  this.major = majorKeywords;
  this.minor = minorKeywords;
}

function setPhotoTableHeading( details )
{
  table = document.getElementById('photoTable');
  cell = table.rows[0].cells[0];

  if( photos.length < viewPhotos )
    html = photos.length + " photos";
  else
  {
    firstPhotoIndex = currentPage * viewPhotos;

    html = "Photos " + (firstPhotoIndex + 1) + "-" + 
           (firstPhotoIndex + viewPhotos) + " of " + photos.length + 
           " (page " + (currentPage + 1) + " of " + pageCount + ") ";
    if( currentPage > 0 )
      html += "<a href='javascript:changePhotoListPage(-1, "+details+");'>Previous</a> ";
    else
      html += "Previous "

    if( currentPage < (pageCount - 1))
      html += "<a href='javascript:changePhotoListPage( 1, "+details+");'>Next</a>";
    else
      html += "Next";
  }

  html += " <a href='javascript:toggleKeywords()'>Keywords</a>\n";
  cell.innerHTML = html;
  cell.align = "right";
}

function toggleKeywords()
{
  if( keywordsOn )
  {
    StyleSheetChanger( "table#photoTable div.thumbnailKeywords", "display", 
                       "none" );
    keywordsOn = false;
  }
  else
  {
    StyleSheetChanger( "table#photoTable div.thumbnailKeywords", "display", 
                       "block" );
    keywordsOn = true;
  }
}
function setPhotoTableContents( details )
{
  table = document.getElementById('photoTable');

  photoIndex = currentPage * viewPhotos;

  for( rowIndex = 1; rowIndex < (photoTableRows + 1); rowIndex++ )
  {
    // row = table.insertRow( rowIndex );
    for( col = 0; col < photoTableCols; col++ )
    {
      if( photoIndex >= photoCount )
        html = "";
      else
      {
        var thumbnail = photos[ photoIndex ];

        html = "<div class=tableThumbnail><a class='thumbnail' href='/" + lang + "/photos/" + thumbnail.photo + ".html'>";
        html = html + "<img src='/photos/" + thumbnail.photo + "-160x160.jpg' " +
                "alt='photo'/>";
        html = html + "</a></div>\n";
        if( details )
        { 
          html = html + "<div class=thumbnailKeywords>\n";

          for( var keyword in thumbnail.major )
          {
            html = html + "<br><a class='majorKeyword' href='" + 
                     thumbnail.major[ keyword ].number + ".html'><b>" + 
                     thumbnail.major[ keyword ].name + "</b></a></br>\n";
          }
          // html = html + "</div>\n<div class=thumbnailKeywords>\n";
          for( var keyword in thumbnail.minor )
          {
            html = html + "<br><a class='minorKeyword' href='" + 
                     thumbnail.minor[ keyword ].number +
                   ".html'>" + thumbnail.minor[ keyword ].name + "</a></br>\n";
          }
          html = html + "</div>\n";
        }
      }

      table.rows[ rowIndex ].cells[ col ].innerHTML = html;
 
      photoIndex++;
    }
  } /* row loop */
  /* do next-buffer */
  nextBuffer = new Array();
  for( ; (photoIndex < photoCount) && (photoIndex < ((currentPage + 2)*viewPhotos)); photoIndex++ )
  {
    // window.alert( "Buffering " + photoIndex );
    photo = photos[ photoIndex ].photo;
    image = new Image();
    image.src = "/photos/"+photo+"-160x160.jpg";
    nextBuffer.push( image );
  }
} /* setPhotoTableContents */

function changePhotoListPage( step, details )
{
  table = document.getElementById('photoTable');
  currentPage += step;

  setPhotoTableHeading( details );

  /* Update the images */
  setPhotoTableContents( details );
  //window.alert( "Current page: " + currentPage );
}

function setImage( img, id, imgWidth, imgHeight, frameWidth, frameHeight )
{
  frameAspect = frameWidth / frameHeight;
  photoAspect = imgWidth / imgHeight;

  if( frameAspect < photoAspect )
  {
    width = frameWidth;
    scaling = width / imgWidth;
    height = scaling * imgHeight;
  }
  else
  {
    height = frameHeight;
    scaling = height / imgHeight;
    width = scaling * imgWidth;
  }

  megaPixels = selectStandardMegapixels( width * height / 1000000.0 );

  img.src = 'http://bilderna.bilderna.nu/' + id + '-' + megaPixels + 'MPix.jpg';
  img.width = width;
  img.height = height;
}

/*
   Given a frame size, and a photo size, will return the million pixel size 
   of the photo scaled to fit the frame
*/
function calcMegamixels( frameWidth, frameHeight, photoWidth, photoHeight )
{
  frameAspect = frameWidth / frameHeight;
  photoAspect = photoWidth / photoHeight;

  if( frameAspect < photoAspect )
  {
    width = frameWidth;
    scaling = width / photoWidth;
    height = scaling * photoHeight;
  }
  else
  {
    height = frameHeight;
    scaling = height / photoHeight;
    width = scaling * photoWidth;
  }

  return width * height / 1000000.0;
}

function selectStandardMegapixels( megaPixels )
{
  if( megaPixels < 0.5 )
    return 0.5;
  else if( megaPixels < 1 )
    return 1;
  else if( megaPixels < 2 )
    return 2;
  else
    return 4;
}

function populatePhotoTableByDate()
{
  windowWidth = getWindowWidth();
  windowHeight = getWindowHeight();
  
  /* subtract the size of left menu and right adsense ad */
  tableWidth = windowWidth - 260; /* Guessing a bit */
  tableHeight = windowHeight - 100;
  photoTableCols = Math.floor( tableWidth / 80 );
  photoTableRows = Math.floor( tableHeight / 180 );
  // alert( "Table height: " + tableHeight );
  if( photoTableCols < 1 )
    photoTableCols = 1;
  if( photoTableRows < 1 )
    photoTableRows = 1;

  // alert( "Table cols: " + photoTableCols );

  table = document.getElementById('photoTable');
  // firstRow = table.insertRow( 0 );

  isLatestMonth = true;
  isLatestYear = true;
  rowIndex = 0;
  for( var year in photos )
  {
    if( year == 'extend' )
      continue;

    row = table.insertRow( rowIndex );
    row.id = "photoYear" + year;

    rowIndex++;
    yearCell = row.insertCell( 0 );
    yearCell.colSpan = photoTableCols;
    yearCell.className = "year";
    // cell.innerHTML = year;
    yearPhotoCount = 0;
    
    for( var month in photos[ year ] )
    {
      if( month == 'extend' )
        continue;

      row = table.insertRow( rowIndex );
      rowIndex++;
      // row.className = "y" + year + " month" + (isLatestYear ? "" : " hidden");
      row.className = "y" + year;
      // row.className = "y" + year + " month";
      row.id = "row" + year + "-" + month;

      monthCell = row.insertCell( 0 );
      monthCell.colSpan = photoTableCols;
      monthCell.className = "y" + year + " month";
      // monthCell.innerHTML = month;
      monthPhotoCount = 0;

      row = table.insertRow( rowIndex );
      row.className = "y" + year;
      rowIndex++;
      columnIndex = 0;
      currentDayOfMonth = 0;

      if( isLatestMonth )
      {
        monthPhotoCount = generateMonthThumbnailTable( year, month );
        isLatestMonth = false;
        wasLatestMonth = true;
        monthOpen[ "y" + year + "m" + month ] = true;
      }
      else
      {
        for( var index in photos[ year ][ month ] )
        {
          if( index == 'extend' )
            continue;
          monthPhotoCount++;
        }
        wasLatestMonth = false;
        monthOpen[ "y" + year + "m" + month ] = false;
      }

      yearPhotoCount += monthPhotoCount;
/*
        "<a href='javascript:byDateShowMonth(" + year + ", " + month + ");'>("+
        monthPhotoCount + " foton)</a></span>";
*/
      monthCell.innerHTML = "<a href='javascript:byDateShowMonth(" + year + 
        ", " + month + ");'>" +
        "<img id='openCloseMonth" + year + "m" + month + 
          "' class='imageWidget' src='images/" + 
          (wasLatestMonth ? "open" : "closed" ) + "Section-16x16.png' " + 
          " alt='" + (wasLatestMonth ? "D&ouml;lj" : "Visa") + "' " +
          "title='" + (wasLatestMonth ? "D&ouml;lj" : "Visa") + 
            " bilderna f&ouml;r " + monthNames[ month - 1 ] + " " + year + 
        "'/></a> " +
        "<a href='javascript:slideshowMonth(" + year + ", " + month + ")'>" +
        "<img class='imageButton' src='images/slideshow.png' height=16px " +
          "alt='Bildspel' title='Bildspel &ouml;ver " + 
          monthNames[ month - 1 ] + " " + year + "'/></a> " +
        "<span class=monthName>" + monthNames[ month - 1 ] +
        "</span> <span class=monthPhotoCount>(" + monthPhotoCount + 
        " foton)</a></span>";
    } // end of for each month

      innerHTML = "<a href='javascript:byDateShowYear( "+ year + " );'>"+
      "<img id='openCloseYear" + year + "' class='imageWidget' src='images/" + 
        (isLatestYear ? "open" : "closed" ) + 
        "Section-16x16.png' " +
        "alt='" + (isLatestYear ? "D&ouml;lj" : "Visa") + "' " +
        "title='" + (isLatestYear ? "D&ouml;lj" : "Visa") + 
        " bilderna f&ouml;r " + year + "'/></a> " +
        "<a href='javascript:slideshowYear(" + year + ")";
/*
ear + "&photoList=";
      isFirstB = true;
      for( monthB in photos[ year ] )
      {
        if( monthB == 'extend' )
          continue;
        for( var index in photos[ year ][ monthB ] )
        {
          if( index == 'extend' )
            continue;
          if( isFirstB )
            isFirstB = false;
          else
            innerHTML += ",";
          innerHTML += photos[ year ][ monthB ][ index ].id;
        }
      }
*/
      innerHTML += "'><img class='imageButton' src='images/slideshow.png' height=16px " +
      "alt='Bildspel' title='Bildspel &ouml;ver " + year + "'/></a> " +
      "<span class=year> " + year + " </span>" +
      "<span class='yearPhotoCount'>(" + yearPhotoCount + " foton)</span>";

    yearCell.innerHTML= innerHTML;

    if( isLatestYear )
    {
      yearOpen[ year ] = true;
      isLatestYear = false;
      StyleSheetChanger( "tr.y" + year, "display", "table-row" );
    }
    else
    {
      yearOpen[ year ] = false;
      StyleSheetChanger( "tr.y" + year, "display", "none" );
    }
  }

}

function generateMonthThumbnailTable( year, month )
{
  if( generatedTable[ "y" + year + "m" + month ] )
    return;

  generatedTable[ "y" + year + "m" + month ] = true;

  table = document.getElementById('photoTable');
  monthRow = document.getElementById( "row" + year + "-" + month );
  rowIndex = monthRow.rowIndex + 1;
  // alert( "rowIndex = " + rowIndex );
  currentDayOfMonth = 0;
  photoCount = 0;
  columnIndex = photoTableCols;

  for( var index in photos[ year ][ month ] )
  {
    if( index == 'extend' ) // what the heck is this needed for?
      continue;

    photo  = photos[ year ][ month ][ index ];

    if( photo.dayOfMonth != currentDayOfMonth )
    {
      if( columnIndex >= photoTableCols )
      {
        row = table.insertRow( rowIndex );
        row.className = "y" + year + " y" + year + "m" + month;
        rowIndex++;
        columnIndex = 0;
      }

      cell = row.insertCell( columnIndex );
      cell.className = "calendarCell dateCell";
      cell.colSpan = 1;
      isSunday = photo.dayOfWeek == 1;

      cell.innerHTML = "<span class='dateCell weekday" + 
                      (isSunday ? " holiday" : "") + "'>" + 
                       weekdayNames[ photo.dayOfWeek ] + "</span>\n" +
                       "<span class='dateCell dayOfMonth" + (isSunday ? " holiday" : "") + "'>" + 
                      photo.dayOfMonth + "</span>\n" +
                      "<span class='dateCell month'>" + 
                      monthNames[ month - 1 ] + "</span>\n" + 
                      "<span class='dateCell year'>" + year + "</span>\n";
      columnIndex++;
      // alert( "innerHTML: " + cell.innerHTML );

      currentDayOfMonth = photo.dayOfMonth;
    }

    if( columnIndex >= photoTableCols )
    {
      row = table.insertRow( rowIndex );
      row.className = "y" + year + " y" + year + "m" + month;
      rowIndex++;
      columnIndex = 0;
    }

    cell = row.insertCell( columnIndex );

    columnIndex++;

    cell.className = "calendarCell " + year + "-" + month; 
// <a class='thumbnail' " +
//                     "href='/" + lang + "/photos/" + photo.photo + ".html'>" + 
// </a>
    if( (photo.orientation != null) && (photo.orientation != "FIRSTROW_IS_TOP") )
      isPortrait = photo.height < photo.width;
    else
      isPortrait = photo.height > photo.width;
 
    cell.id = 'photo' + photo.id + 'c';
    title = "";
    isFirstAlbum = true;
    for( var albumIndex in digAlbums[ photo.id ] )
    {
      if( albumIndex != 'extend' )
      {
        if( isFirstAlbum )
          isFirstAlbum = false;
        else
          title = title + ", ";
        title = title + albums[ digAlbums[ photo.id ][ albumIndex ].folder ][0].name;
      }
    }

    if( title != "" )
      title = "Album: " + title;
// 

    cell.innerHTML = "<span class='photoTime'>" + photo.time + "</span>"+
                     "<div class='tableThumbnail' id='photox" + photo.id + "'>" +
                     "<img class='thumbnail draggable " + 
                       (isPortrait ? "portrait" : "landscape") + 
                     "' src='http://bilderna.bilderna.nu/" + photo.id + 
                     "-160x160.jpg' id='photo" + photo.id + "' " +
                     "title='" + title + "' " +
                     "alt='photo'/>" +
                     "<a href='bilder/" + photo.id + "/bilden.html'>X</a>" +
                     "</div>";
      new Draggable( 'photo' + photo.id, {revert:true, reverteffect: function( element, top_offset, left_offset ) { new Effect.MoveBy(element, -top_offset, -left_offset, { duration: 0.0 } );}});
//                     "-160x160.jpg' onMousedown='dragPhoto(" + photo.id +"); return true;'"+
     
    dragDiv = document.getElementById( "photo" + photo.id );
    dragDiv.photoID = photo.id;

    photoCount++;
  }

  return photoCount;
}

/* Show the months for the given year */
function byDateShowYear( year )
{
  if( yearOpen[ year ] )
  {
    // hide it
    // currentDisplay = document.getElementById('photoTable');
    StyleSheetChanger( "tr.y" + year, "display", "none" );
    // StyleSheetChanger( "tr.y" + year, "height", "1px" );
    yearOpen[ year ] = false;

    // alert( "Hide year before for-loop" );
    // hide all months
    for( month = 1; month <= 12; month++ )
    {
      selector = "tr.y" + year + "m" + month + ".y" + year;

      // alert( "SSC selector " + selector + " none" );
      StyleSheetChanger( selector, "display", "none" );
    }
 
    // change open/close widget to closed
    widget = document.getElementById('openCloseYear' + year);
    widget.src = 'images/closedSection-16x16.png';
    widget.title = 'Visa bilderna f&ouml;r ' + year;
    widget.alt = 'Visa';
  }
  else
  {
    // show it
    StyleSheetChanger( "tr.y" + year, "display", "table-row" );
    // StyleSheetChanger( "tr.y" + year, "height", "auto" );
    yearOpen[ year ] = true;

    // show all month that are open
    for( month = 1; month <= 12; month++ )
    {
      if( monthOpen[ "y" + year + "m" + month ] )
        StyleSheetChanger( "tr.y" + year + "m" + month + ".y" + year, 
                           "display", "table-row" );
    }

    widget = document.getElementById('openCloseYear' + year);
    widget.src = 'images/openSection-16x16.png';
    widget.title = 'D&ouml;lj bilderna f&ouml;r ' + year;
    widget.alt = 'D&ouml;lj';
  }
  // table = document.getElementById('photoTable');
  // yearRow = document.getElementById('photoYear' + year);
  // rowIndex = yearRow.rowIndex;
  // table.insertRow( 
}

function byDateShowMonth( year, month )
{
  // global monthNames;

  if( monthOpen[ "y" + year + "m" + month ] )
  {
    selector = "tr.y" + year + "m" + month + ".y" + year;
    // alert( "SSC selector " + selector + " none" );
    StyleSheetChanger( selector, "display", "none" );
    monthOpen[ "y" + year + "m" + month ] = false;

    widget = document.getElementById('openCloseMonth' + year + "m" + month );
    widget.src = 'images/closedSection-16x16.png';
    widget.title = 'Visa bilderna f&ouml;r ' + monthNames[ month - 1 ] + " " + year;
    widget.alt = 'Visa';
  }
  else
  {
    generateMonthThumbnailTable( year, month );

    StyleSheetChanger( "tr.y" + year + "m" + month + ".y" + year, 
                       "display", "table-row" );
    monthOpen[ "y" + year + "m" + month ] = true;

    widget = document.getElementById('openCloseMonth' + year + "m" + month );
    widget.src = 'images/openSection-16x16.png';
    widget.title = 'D&ouml;lj bilderna f&ouml;r ' + monthNames[ month - 1 ] + " " + year;
    widget.alt = 'D&ouml;lj';
  }
}

function buildAlbumList()
{
  ul = document.getElementById( "albumList" );

  if( albums.length == 0 )
  {
    li = document.createElement( "li" );
    li.innerHTML = "Inga Album";
    ul.appendChild( li );
  }
  else
    for( var album in albums )
    {
      if( album == 'extend' ) // what the heck is this needed for?
        continue;
      li = document.createElement( "li" );
      li.className = 'album';
      id = "album" + album;
      li.id = id;
      // li.id = id;
      // alert( "id='" + id + "', album=" + album );
      li.innerHTML = "<div id='" + id + "div'><table class='albumList'>\n" +
                     "<tr>\n" +
                     "<td rowspan=2>\n" +
                    "<img src='images/folder_01.png' class='albumIcon'/>\n" + 
                    "<a href='javascript:slideshowAlbum(" + album + ");'>" +
                    "<img src='images/slideshow.png' class='albumIcon imageButton'/>\n" + 
                   "</a>" +
                   "</td>\n" +
                   "<td>" + albums[ album ][0].name + "</td></tr>\n" +
                   "<tr><td id='album" + album + "PhotoCount'>" + 
                   albums[ album ][0].count + " bilder</td></tr>\n";
                   "</table></div>\n";
/*
<script type="text/javascript">
Droppables.add('cart', 
               {accept:'products', 
                onDrop:function(element)
                  {new Ajax.Updater('items', '/demos/shop/add', 
                     {onLoading:function(request){Element.show('indicator')}, 
                      onComplete:function(request){Element.hide('indicator')}, 
                      parameters:'id=' + encodeURIComponent(element.id), 
                      evalScripts:true, 
                      asynchronous:true})}, 
                hoverclass:'cart-active'})</script>
*/
/*
      li.innerHTML = albums[ album ].name; //  + "<br/>" + albums[ album ].count + 
//                   " bilder";
*/
      ul.appendChild( li );
      Droppables.add( id, { accept:'tableThumbnail',
                          hoverclass:'dropready',
                          droppableAlbum:album,
                          onDrop:function(element) { addPhotoToAlbum( element.photoID, this.droppableAlbum ); }
                        } );
    }
}

function addPhotoToAlbum( photo, album )
{
  // alert( "addPhotoToAlbum( " + photo + ", " + album + ")" );

  // extract the photo's id number from the photoELemen
  // call the server with xmlhttp to add the photo to the album
  xmlhttp = newXMLRequest();
  
  xmlhttp.open( "POST", "addPhotoToAlbum.php", false );
  xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

  xmlhttp.send( "album=" + album + "&photo=" + photo );

  // if we get an error, then show an alert
  if( xmlhttp.status != 200 )
    alert( xmlhttp.responseText );
  else
  {
    // increase the album's photo count
    albums[album][0].count++;
    td = document.getElementById( "album" + album + "PhotoCount" );
    td.innerHTML = albums[ album ][0].count + " bilder";
    // alert( "Success, status=" + xmlhttp.status + ", Status=" + xmlhttp.Status + ", response=" + xmlhttp.responseText );
  }
}

function folderMouseEnter()
{
  document.body.style.cursor = 'e-resize'; // 'url(images/folder_01.png)';
}

/*
   Given a frame size, and a photo size, will return the million pixel size 
   of the photo scaled to fit the frame
*/
function calcMegamixels( frameWidth, frameHeight, photoWidth, photoHeight )
{
  frameAspect = frameWidth / frameHeight;
  photoAspect = photoWidth / photoHeight;

  if( frameAspect < photoAspect )
  {
    width = frameWidth;
    scaling = width / photoWidth;
    height = scaling * photoHeight;
  }
  else
  {
    height = frameHeight;
    scaling = height / photoHeight;
    width = scaling * photoWidth;
  }

  return width * height / 1000000.0;
}

function selectStandardMegapixels( megaPixels )
{
  if( megaPixels < 0.5 )
    return 0.5;
  else if( megaPixels < 1 )
    return 1;
  else if( megaPixels < 2 )
    return 2;
  else
    return 4;
}

function slideshowMonth( year, month )
{
  slideshowPhotos = new Array();

  // Create a list of photos, and call the generic slideshow function
  for( var index in photos[ year ][ month ] )
  {
    if( index == 'extend' )
      continue;

    photo = photos[ year ][ month ][ index ];
    if( photo == null )
      alert( "slideshowMonth( " + year + ", " + month + "): index=" + index +
             ", photo==null" );
    if( photo.id == undefined )
      alert( "slideshowMonth( " + year + ", " + month + "): index=" + index +
             ", photo.id==undefined" );

    slideshowPhotos.push( photo.id );
  }

  // The photos will be in reverse order, reverse the array
  // This will show the photos in chronological order
  slideshowPhotos.reverse();

  startSlideshow( monthNames[ month ] + " " + year );
}

function slideshowYear( year )
{
  // build URL with list of photos
  // do window.open with this URL

  // url = "slideshow.php?title='" + year + "'&digList=";

  slideshowPhotos = new Array();

  // Create a list of photos, and call the generic slideshow function
  // isFirst = true;
  for( var month in photos[ year ] )
  {
    if( month == 'extend' )
      continue;

    for( var index in photos[ year ][ month ] )
    {
      if( index == 'extend' )
        continue;
      photo = photos[ year ][ month ][ index ];
      if( photo == null )
        alert( "slideshowYear: index=" + index + ", year=" + year + ", month=" + month );

      //if( isFirst )
      //  isFirst = false;
      // else
      //  url += ",";
      //url += photo.id;
      slideshowPhotos.push( photo.id );
    }
  }

  // window.location.href= url; // , '', 'fullscreen=yes,titlebar=no,scrollbars=auto,maximize=1');

  // The photos will be in reverse order, reverse the array
  // This will show the photos in chronological order
  slideshowPhotos.reverse();

  startSlideshow( year );    
}

function slideshowAlbum( album )
{
  slideshowPhotos = new Array();

  for( var index in albumPhotos[ album ] )
  {
    if( index == 'extend' )
      continue;

    slideshowPhotos.push( albumPhotos[ album ][ index ].photo );
  }
  slideshowPhotos.reverse();

  startSlideshow( albums[ album ][0].name );
}

function startSlideshow( title )
{
  // build URL with list of photos
  // do window.open with this URL

  url = "slideshow.php?title=" + title + "&digList=";

  // Create a list of photos, and call the generic slideshow function
  isFirst = true;
  for( var index in slideshowPhotos )
  {
    if( index == 'extend' )
      continue;

    if( isFirst )
      isFirst = false;
     else
      url += ",";
    url += slideshowPhotos[ index ];
  }

  window.location.href= url; // , '', 'fullscreen=yes,titlebar=no,scrollbars=auto,maximize=1');

  // The photos will be in reverse order, reverse the array
  // This will show the photos in chronological order
}

function newXMLRequest()
{
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }

  return xmlhttp;
}



function guiCreateFolder()
{
  nameInput = document.getElementById( "newAlbumName" );
  folderName = nameInput.value;
  alert( "Create folder '" + folderName + "'" );
  // submit request to server.
  xmlhttp = newXMLRequest();
  
  xmlhttp.open( "POST", "createAlbum.php", false );
  xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
  // should URL-encode the name
  xmlhttp.send( "user=1&name=" + escape( folderName ) );

  alert( "Folder creation: " + xmlhttp.responseText );
}
