// Loads our gallery
var gallery = null;

function getQueryVariable(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return null;
}


function initGallery(transport) {
	var response = transport.responseXML.documentElement;
	var old_album_id = null;
	if (gallery) {
		old_album_id = gallery.curr_album_id;
	}
	gallery = new Gallery(response);

	var album_id = getQueryVariable("album_id") ? parseInt(getQueryVariable("album_id")) : null;
	var photo_id = getQueryVariable("photo_id") ? parseInt(getQueryVariable("photo_id")) : null;

	if (!album_id) {
		album_id = old_album_id;
	}

	if (album_id && photo_id) {
		viewAlbum(album_id);
		viewPhoto(album_id, photo_id);
	}
	else if (album_id) {
		viewAlbum(album_id);
	}
	else {
		viewAlbum(gallery.albums[0].id);
	}
}

function displayEdit(transport) {
	var response = transport.responseXML.documentElement;

	var name = response.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	var caption = response.getElementsByTagName("caption")[0].childNodes[0].nodeValue;
	var album_id = response.getElementsByTagName("album_id")[0].childNodes[0].nodeValue;
	var photo_id = response.getElementsByTagName("photo_id")[0].childNodes[0].nodeValue;
  var in_slideshow = response.getElementsByTagName("in_slideshow")[0].childNodes[0].nodeValue;

	if( caption == "::NILL::" ) {
		caption = "";
	}

	var form = document.getElementById("photo_edit_form");
	var nameInput = document.getElementById("photo_edit_name");
	var captionTA = document.getElementById("photo_edit_caption");
	var photoIdInput = document.getElementById("photo_edit_photoid");
  var inSSCheckbox = document.getElementById("photo_in_slideshow");
	var albumIdInput = document.getElementById("photo_edit_albumid");
	var submitButton = document.getElementById("photo_edit_submit");

	nameInput.value = name;
	captionTA.value = caption;
	albumIdInput.value = album_id;
	photoIdInput.value = photo_id;

  if( in_slideshow == 1 ) {
    inSSCheckbox.checked = true;
  }
  else {
    inSSCheckbox.checked = false;
  }

	form.style.display = "block";
	if (document.getElementById("photo_edit_link")) {
	    document.getElementById("photo_edit_link").style.display = "none";
    }
}

function displayAlbumEdit(transport) {
	var response = transport.responseXML.documentElement;

	var name = response.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	var album_id = response.getElementsByTagName("album_id")[0].childNodes[0].nodeValue;
	var pr_id = response.getElementsByTagName("pr_id")[0].childNodes[0].nodeValue;

	if( pr_id == "::NILL::" ) {
		pr_id = "";
	}

	var form = document.getElementById("album_edit_form");
	var nameInput = document.getElementById("album_edit_name");
	var prSelect = document.getElementById("album_edit_pr");
	var albumIdInput = document.getElementById("album_edit_albumid");
	var submitButton = document.getElementById("album_edit_submit");

	nameInput.value = name;
  albumIdInput.value = album_id;

  var foundMatch = 0;
  for(var i = 0;i < prSelect.options.length; i++) {
    if( prSelect.options[i].value == pr_id ) {
      if( prSelect.selectedIndex != i ) {
        prSelect.selectedIndex = i;
      }

      foundMatch = 1;
      break;
    }
  }

  if( !foundMatch ) {
    if( prSelect.selectedIndex != 0 ) {
      prSelect.selectedIndex = 0;
    }
  }

	form.style.display = "block";
	if (document.getElementById("album_edit_link")) {
	    document.getElementById("album_edit_link").style.display = "none";
    }
}

function reset()
{
    // Let's get our gallery information...
    new Ajax.Request('photos-albums.php',
      { method:'get',
        onSuccess: initGallery,
        onFailure: function() { alert('Error reading gallery.'); }
        /* onComplete: function(transport) { alert(transport.responseText); }*/
      });
}

function newAlbum(album_name,pr_id) {
	if (album_name == "") {
		alert("Please enter album name.");
		return false;
	}

  var name = escape(album_name);
	new Ajax.Request('/include/photosFunc.php?action=newAlbum&album_name=' + name + '&pr_id=' + pr_id,
      { method:'get',
        onSuccess: reset,
        onFailure: function() { alert('Error creating new album.'); throw new Error("Failed to send newAlbum request"); }
      });

	return false;
}

function parseAlbumSuccess(transport)
{
	var response = transport.responseXML;
  
  var code = response.getElementsByTagName("code")[0].childNodes[0].nodeValue;
  var text = response.getElementsByTagName("text")[0].childNodes[0].nodeValue;

  if( code != 0 ) {
    alert(text);
    throw new Error("Failed to create new album: " + text);
  }
  else {
    reset();
  }

  return false;
}

function addPhotoSuccess(transport)
{
	return false;
}

// Takes the form element
function newPhoto(photoFrm) {
	var errs = "";
	if (photoFrm.photo_name == "") {
		errs += "Please enter a name for your photo.\n";
	}
	if (photoFrm.photo_caption == "") {
		errs += "Please enter a caption for your photo.\n";
	}
	if (photoFrm.photo_file == "") {
		errs += "Please select an image file to upload.";
	}
	if (errs != "") {
		alert(errs);
		return false;
	}

    photoFrm.album_id.value = gallery.curr_album_id;

//	$('album_id').value = gallery.curr_album_id;
	return true;
}

function delAlbum(album_id) {
	var answer = confirm("Delete album '" + gallery.findAlbumById(album_id).name + "'?");
	if (answer) {
		new Ajax.Request('/include/photosFunc.php?action=delAlbum&album_id=' + escape(album_id),
	      { method:'get',
	        onSuccess: function() { gallery.curr_album_id = null; reset(); },
	        onFailure: function() { alert('Error deleting album.'); }
	      });
	}
	else {
		return false;
	}

	return false;
}

function delPhoto() {
	var photo = gallery.curr_photo; // gallery.findAlbumById(gallery.curr_album_id).findPhotoById(photo_id);
	var answer = confirm("Delete photo '" + photo.name + "'?");
	if (answer) {
		new Ajax.Request('/include/photosFunc.php?action=delPhoto&photo_id=' + escape(photo.id),
	      { method:'get',
	        onSuccess: reset,
	        onFailure: function() { alert('Error deleting photo.'); }
	      });
	}
	else {
		return false;
	}

	return false;
}


function editPhoto() {
	var photo = gallery.curr_photo;
	new Ajax.Request('/include/photosFunc.php?action=getEdit&photo_id=' + escape(photo.id),
		{ method:'get',
			onSuccess: displayEdit,
			onFailure: function() { alert('Error editing photo.'); }
		});
}

function editAlbum(album_id) {
	var album = gallery.findAlbumById(album_id);
	new Ajax.Request('/include/photosFunc.php?action=getAlbumEdit&album_id=' + escape(album.id),
		{ method:'get',
			onSuccess: displayAlbumEdit,
			onFailure: function() { alert('Error editing album.'); }
		});
}


function viewAlbum(album_id)
{
	if (album_id == null) {
		if (gallery.albums[0]) {
			album_id = gallery.albums[0].id;
		}
		else {
			alert("Error: No Photo Albums Found");
		}
	}

	// First set up the div for our actual album...
	var thumb_doc = $('thumbnails').contentWindow.document;
	var album = gallery.findAlbumById(album_id);
	if (album) {
		$('album_name').innerHTML = album.name;
		album.displayThumbnails(thumb_doc.getElementById('albums'));
		gallery.curr_album_id = album.id;
		viewPhoto(album.id, null);

    // set up press release div
    if( album.pr_name == "" ) {
      $('press_release').innerHTML = album.pr_name;
    }
    else {
      $('press_release').innerHTML = 'Read the Press Release:<br/><a href="news-pr.php?id=' + album.pr_id + '">' + album.pr_name + '</a>';
    }
	}

	// Resize if necessary...
	if (album.photos.length <= 10) {
		var num_rows = Math.floor((album.photos.length + 1) / 2);
		var new_height = (num_rows * (58 + 14)) + 28; // img height + padding
		if (num_rows > 10) {
			new_height = (10 * (58 + 12)) + 20; // img height + padding
		}
		$('thumbnails').height = (new_height < 100) ? 100 : new_height;
	}
	else {
		$('thumbnails').height = 500;
	}

	// Then set up the link divs for the other albums...
	var other_albums_html = "";
	var i=0;
	for (i=0; i<gallery.albums.length; i++) {
		if (gallery.albums[i].id != gallery.curr_album_id) {
			other_albums_html += '<div class="album_header" onclick="viewAlbum(' +
			 					 gallery.albums[i].id + ');">' +
								 gallery.albums[i].name + " (" +
								 gallery.albums[i].photos.length + ")" +
								 "</div>\n";
		}
	}
	$('other_albums').innerHTML = other_albums_html;
}

function resizePhoto()
{
//	alert($('photo_img').height);
//	alert($('photo_img').width);
	var target_width = 505;
	var target_height = 406;
}

// RELIES on global named "gallery"
function viewPhoto(album_id, photo_id)
{
	if (!gallery) {
		alert("Error: viewPhoto called with no gallery object defined.");
	}
	// Give defaults if we pass in null values...
	album_id = album_id ? album_id : gallery.albums[0].id;

//	alert(gallery.albums[0].photos.length);
//	alert(gallery.albums[0].name);

	if (gallery.findAlbumById(album_id).photos.length == 0) {
		$('photo').innerHTML = "<p>No photo selected.</p>";
		$('photo_caption').innerHTML = "";
		return false;
	}

	photo_id = photo_id ? photo_id : gallery.findAlbumById(album_id).photos[0].id;

	var photo = gallery.findAlbumById(album_id).findPhotoById(photo_id);
	if (photo == null) {
		alert("Error: Requested photo #" + photo_id + " in album " + album_id + " was not found.");
	}
	else {
		$('photo_name').innerHTML = photo.name
		$('photo').innerHTML = '<img id="photo_img" class="photo" src="' + photo.src + '"/>';		
//		alert($('photo_caption').innerHTML);
        $('photo_caption').innerHTML = "<p></p>";
	    $('photo_caption').innerHTML = "<p>" + photo.caption + "</p>";
      if( photo.in_ss == 1 ) {
        $('photo_ss_status').innerHTML = "<p>Photo is in homepage slideshow</p>";
      }
      else {
        $('photo_ss_status').innerHTML = "<p></p>";
      }
		gallery.curr_photo_id = photo.id;
		gallery.curr_photo = photo;		
	}
	setTimeout("resizePhoto()", 1000);

    if (document.getElementById("photo_edit_form")) {
	    document.getElementById("photo_edit_form").style.display = "none";
	}
    if (document.getElementById("photo_edit_link")) {
	    document.getElementById("photo_edit_link").style.display = "inline";
    }
}


function Gallery_findAlbumById(album_id) {
	var i = 0;
	for (i=0; i<this.albums.length; i++) {
		if (this.albums[i].id == album_id) {
			return this.albums[i];
		}
	}
	return null;
}

function Gallery(xmlNode)
{
	this.albums = new Array();
	var album_nodes = xmlNode.getElementsByTagName('album');
	var i = 0;
	for(i=0; i<album_nodes.length; i++) {
  		this.albums[i] = new Album(album_nodes[i]);
	}
	this.findAlbumById = Gallery_findAlbumById;
}

// Pass both the album ID and the photo ID.  Have methods that extract the right photo
// and album by searching on ID.
function Album_findPhotoById(photo_id) {
	var i = 0;
	for (i=0; i<this.photos.length; i++) {
		if (this.photos[i].id == photo_id) {
			return this.photos[i];
		}
	}
	return null;
}

// Yes, we should use prototypes, but the Prototype library messes with JS object behavior
// in some quirky ways, so this is to make things simpler and just bypass all that.
function Album_displayThumbnails(div_el) {
	var i=0;
	var img_html = "<style type='text/css'>" +
				   " img.thumb { padding: 6px 6px 6px 6px; max-width: 58px; max-height: 58px;} " +
				   " body {font: 9pt Myriad Web, Verdana, Georgia, Arial, Helvetica, sans-serif;} " +
				   "</style>";
	if (this.photos.length == 0) {
		img_html += "<p>This album has no photos</p>";
	}
	else {
		img_html += "<table>";
		for(i=0; i<this.photos.length; i++) {
			if ((i % 2) == 0) { img_html += "<tr>"; }
			img_html += '<td align="center"><a href="javascript:window.parent.viewPhoto(' +
						this.id + ', ' + this.photos[i].id + ');"><img class="thumb" border="0" src="' +
						this.photos[i].thumb_src + '"/></a></td>';
			if ((i % 2) == 1) { img_html += "</tr>"; }
		}
		img_html +="</table>";
	}
	div_el.innerHTML = img_html; //  "<b>Hi</b>";
}

function Album(xmlNode)
{

	this.photos = new Array();
	this.id = xmlNode.getAttribute("id");
	this.name = xmlNode.getAttribute("name");

  this.pr_id = xmlNode.getAttribute("pr_id");
  if( !this.pr_id ) {
    this.pr_id = -1 // explicitly set to -1 on null
  }

  this.pr_name = xmlNode.getAttribute("pr_name");
  if( !this.pr_name ) {
    this.pr_name = "";  // explicitly set to empty string on null
  }

	var photo_nodes = xmlNode.getElementsByTagName('photo');
//	if (photo_nodes) {
		var i = 0;
		for(i=0; i<photo_nodes.length; i++) {
			this.photos[i] = new Photo(photo_nodes[i]);
		}
//	}
	this.displayThumbnails = Album_displayThumbnails
	this.findPhotoById = Album_findPhotoById
}


function Photo(xmlNode)
{
	attributes = ["id", "name", "src", "thumb_src", "height", "width", "caption", "in_ss"];
	var i = 0;
	for(i=0; i<attributes.length; i++) {
		this[attributes[i]] = xmlNode.getAttribute(attributes[i]);
	}
}

