// javascript file to show the images from flickR
// this first calls the php file that populates a local xml file

  var divgalleries = document.getElementById('gallerylist');
  var galleryheader = document.getElementById('galleryheader');
  var divimages = document.getElementById('photolist');
  var imageheader = document.getElementById('photoheader');
  var mainimage = document.getElementById('featuredphoto');

  var thisphoto = 0;
  var photos;
  var ispause = 0;
  var savepause = 0;
  var oldtimer = 0;
  var quickload = 0;
  var saveimg;
  
  function showPhoto(i) {
    // alert(photos.length);
    if (photos.length) {
        var thumb = photos[i].getElementsByTagName("mediumurl")[0].childNodes[0].nodeValue;
        // alert("thumb = "+thumb);
        var fullpic = photos[i].getElementsByTagName("imageurl")[0].childNodes[0].nodeValue;
        // alert("fullpic = "+fullpic);
        var title = photos[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
        // alert("title = "+title);
        var newpic =  "<div id=\"newpicid\" class=\"photo\">" +
                           " <a href=\"" + fullpic + "\" target=\"_blank\">" +
                           " <img height=\"240px\" id=\"mainpic\" src=\"" +thumb + "\">" +  "</a><br />" +
                           "<span id=\"pictitle\" class=\"setfont\">"  + title + "</span><br />" + 
                      "</div>";
        newpic = newpic + '<a href="#" id="prev" onclick="prevPhoto()">&lt;&lt;Prev</a>&nbsp;&nbsp;';
        newpic = newpic + '<a href="#" id="stop" onclick="pausePic()">Stop</a>&nbsp;&nbsp;';
        newpic = newpic + '<a href="#" id="next" onclick="nextPhoto()">Next&gt;&gt;</a>&nbsp;&nbsp;';
        newpic = newpic + '<a href="#" id="resume" onclick="resumePic()">Resume</a><br /><br />';
        mainimage.innerHTML = newpic;
    }

    theimg = document.getElementById("mainpic");
    // theimg.onmouseover=pausePic;
    // theimg.onmouseout=resumePic;

  }
  
  function nextPhoto() {
    thisphoto++;
    if (thisphoto >= photos.length) thisphoto = 0;
    pausePic();

    // start with a hidden image
    // changeOpac(0, "mainpic");

    showPhoto(thisphoto);    
    // var thumb = photos[thisphoto].getElementsByTagName("mediumurl")[0].childNodes[0].nodeValue;
    // var title = photos[thisphoto].getElementsByTagName("title")[0].childNodes[0].nodeValue;
    // document.getElementById("mainpic").src = thumb;
    // document.getElementById("pictitle").innerHTML= title;

    // fade in the new pic
    // opacity("mainpic", 0, 100, 1000);
  }
  
  function prevPhoto() {
    if (thisphoto == 0) thisphoto = photos.length;
    thisphoto--;
    pausePic();

    // start with a hidden image
    // changeOpac(0, "mainpic");
        
    showPhoto(thisphoto);    
    // var thumb = photos[thisphoto].getElementsByTagName("mediumurl")[0].childNodes[0].nodeValue;
    // var title = photos[thisphoto].getElementsByTagName("title")[0].childNodes[0].nodeValue;
    // document.getElementById("mainpic").src = thumb;
    // document.getElementById("pictitle").innerHTML= title;

    // fade in the new pic
    // opacity("mainpic", 0, 100, 1000);
  }

  function cyclePhoto() {
    nextPhoto();
   
    // loop through the photos automatically every 5 seconds
    oldtimer = setTimeout("cyclePhoto()", 5000);
  }

  function pausePhoto() {
    ispause = 1;
    if (oldtimer != 0) clearTimeout(oldtimer);
  }
  
  function pausePic() {
    // saveimg = document.getElementById("mainpic").src;
    // document.getElementById("mainpic").src = "pause.jpg";
    // show the current picture with full opacity and pause to see
    ispause = 1;
    if (oldtimer != 0) {
      clearTimeout(oldtimer);
      oldtimer = 0;
    }
    changeOpac(100, "mainpic");
  }
  
  function resumePic() {
    // if (saveimg) document.getElementById("mainpic").src = saveimg;
    ispause = 0;
    if (oldtimer != 0) {
      clearTimeout(oldtimer);
      oldtimer = 0;
    }
    cyclePhoto();
  }
  
  var handlePhotos = function(o) {
    photos = o.responseXML.documentElement.getElementsByTagName("photo");
    mainimage.innerHTML = "Reading... ";

    if (oldtimer != 0) clearTimeout(oldtimer);
    thisphoto = 0;
    ispause = 0;
    savepause = 0;
    showPhoto(0);
    oldtimer = setTimeout("cyclePhoto()", 5000);
  }

  var photosCallback =
  {
    success:handlePhotos,
    failure:imageFailure,
    argument: 0,
    timeout: 8000
  };

  // make ajax call to show images from the selected gallery
  function showPics() {
    // alert("Requested to show a gallery with id= "+this.id);
    var fnUrl = "getPhotos.php?setid=" + this.id;
    var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, photosCallback);
  };

  // make ajax call to show previously saved images from gallery
  function initialPics(id) {
    // alert("Requested to show a gallery with id= "+this.id);
    // var fnUrl = "photos.xml";
    var fnUrl = "getPhotos.php?setid=" + id;
    var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, photosCallback);
  };

  var handleGalleries = function(o){

    var photos = o.responseXML.documentElement.getElementsByTagName("photoset");

    // alert("working");

    // get the images
    var maxlen = photos.length;

    // read the cookies
    var idcookie = ""
    var famcookie = "";
    if (document.cookie != "" ) {
      var thiscookie = document.cookie.split("; ");
      for (var cc=0; cc < thiscookie.length; cc++) {
        if (thiscookie[cc].split("=")[0] == "familyok") famcookie = thiscookie[cc].split("=")[1];
        if (thiscookie[cc].split("=")[0] == "setid") idcookie = thiscookie[cc].split("=")[1];
      }
    }

    // scan through the galleries and display them (for now - later buffer and flip through) 
    var photostr = "";
    var galcount = 0;
    rimg = 0;
    var kend = 0;
    var firstid = idcookie;
    for (var i= 0; i < maxlen; i++) {

	    var theid= photos[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;

	    var thumb = photos[i].getElementsByTagName("thumburl")[0].childNodes[0].nodeValue;
	    var fullpic = photos[i].getElementsByTagName("seturl")[0].childNodes[0].nodeValue;
	    var title = photos[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
	    var photocount = photos[i].getElementsByTagName("photos")[0].childNodes[0].nodeValue;

	    // if (firstid=="" && i==0) firstid = theid;
	    if ( firstid=="" && title.toLowerCase().indexOf("favorite") >=0 ) firstid = theid

	    // var photocount = photos[i].getElementsByTagName("count")[0].childNodes[0].nodeValue;
	    // if (i==0) alert(thumb + "\n" + fullpic + "\n" + title + "\n" + photocount);   

            // no need to do the familycookie check below - done in php file
            // if (famcookie != "yes" && (title=="Family" || title=="Reunion 2007") ) continue;
            
            if (thumb.length>0 && fullpic.length>0 && photocount>0) {
              galcount++;
              var newpic =  "<div class=\"gallery\">" +
                               "<img class=\"thumb\" id=\"" + theid + "\" src=\"" +thumb + "\">" +  "<br />" +
                               "<span class=\"setfont\">"  + title + "</span><br />" + 
                               "<span class=\"countfontb\">" + photocount +
                               "</span><span class=\"countfont\"> Photos</span></div>";

 	      // alert(newpic);
              photostr += newpic;
            }
    }

    // make sure we have something as the default
    if (firstid=="") firstid= photos[0].getElementsByTagName("id")[0].childNodes[0].nodeValue;

    galleryheader.innerHTML = "Galleries (" + galcount + ")";
    divgalleries.innerHTML = photostr;

    // set the image click function
    for (var j=0; j < document.images.length; j++) {
      theimg = document.images[j];
      if ( theimg.parentNode.tagName == "DIV" ) {
        theimg.onclick=showPics;
      }
    }

    // show the last pics displayed
    initialPics(firstid);

}

  var imageFailure = function(o){
	// YAHOO.log("The failure handler was called.  tId: " + o.tId + ".", "info", "example");
	// alert("Failure");
	divgalleries.innerHTML = "<ul><li>Transaction id: " + o.tId + "</li>";
	divgalleries.innerHTML += "<li>HTTP status: " + o.status + "</li>";
	divgalleries.innerHTML += "<li>Status code message: " + o.statusText + "</li></ul>";
  };

  var galleryCallback =
  {
    success:handleGalleries,
    failure:imageFailure,
    argument: 0,
    timeout: 30000
  };

  // longer slow load and read of full flickR content
  // also updates the local file for later quick load
  var showGalleries = function() {
    divgalleries.innerHTML = "<blink>Reading galleries from flickR...</blink>";
    var fnUrl = "getGalleries.php";
    var request = YAHOO.util.Connect.asyncRequest('GET', fnUrl, galleryCallback);
  }
// functions to do image crossfading taken from the following web site
// http://brainerror.net/scripts/javascript/blendtrans/

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function pause(millis) {
    var date = new Date();
    var curDate = null;
    
    do { curDate = new Date(); }
    while(curDate-date < millis);
} 

  // YAHOO.util.Event.addListener(window, "load", initialPics);
  YAHOO.util.Event.addListener(window, "load", showGalleries);
