// *****************************************************************
//
// ContentPage_Class
// 
// Responsible for handling events and behaviours on the content 
// pages of the site.
//
// *****************************************************************

function ContentPage_Class() {
	// Element references used for toggling photos
	this.aTogglePhotos = null;
	this.divLevelTwoContent = null; 

	// Used for loading of new images
	this.loadedImage = 0;	
	this.newImages = null;
	this.oldImages = null;
}; // end ContentPage_Class()


// *****************************************************************
//
// Behaviour
//
// *****************************************************************

ContentPage_Class.prototype.behaviour = function() {
	var myRules = {
		"a.toggleText": function(el) {  
			el.onclick = function() {
				var target = this;
				oContentPage.toggleText(target);
			}
		},
		"a.togglePhotos": function(el) {  
			el.onclick = function() {
				var target = this;
				oContentPage.togglePhotos(target);
			}	
		},
		"a.aPhoto": function(el) {
			el.onclick = function() {
				var target = this;
				oContentPage.displayPhoto(target);
			}
		}
	};

	Behaviour.register(myRules);
}; // end ContentPage_Class.behaviour()



// *****************************************************************
//
// Event Handling Methods (with context)
//
// *****************************************************************

//
// Initialization method
//

ContentPage_Class.prototype.init = function() {
	this.expandEventContainers();
	this.behaviour();
}; // end ContentPage_Class.init()


// -----------------------------------------------------------------
//
// Collapse Event Containers 
//
// Add the eventContainerCollapse class to div.eventContainer elements 
// with a height greaterthan 200px, and unhide their corresponding 
// a.toggleText elements.
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.expandEventContainers = function() {
	var levelTwoContentDivs = $("div-Content").select("div.levelTwoContent");

	for (var i = 0; i < levelTwoContentDivs.length; i++) {
		var divEventContainer = levelTwoContentDivs[i].select("div.eventContainer");
		var pElems = $(divEventContainer[0]).select("p");
		var height = 0;

		for (var j = 0; j < pElems.length; j++) {
			height += pElems[j].getHeight();
		}

		if (height <= 200) {
			levelTwoContentDivs[i].removeClassName("levelTwoContentCollapse");
			var aToggleText = levelTwoContentDivs[i].select("a.toggleText");
			aToggleText[0].setStyle({display: "none"});
		}
	}
}; // end ContentPage_Class.collapseEventContainers()


// -----------------------------------------------------------------
//
// Toggle Text 
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.toggleText = function(myElement) {
	var toggle = myElement.getAttribute("toggle");
	var ancestors = $(myElement).ancestors();

	for (var i = 0; i < ancestors.length; i++) {
		if (ancestors[i].hasClassName("levelTwoContentCollapse") && toggle == "more") {
			ancestors[i].removeClassName("levelTwoContentCollapse");
			myElement.setAttribute("toggle", "less");
			myElement.innerHTML = "...less words (-)";
			break;
		}
		else if (ancestors[i].hasClassName("levelTwoContent") && toggle == "less") {
			ancestors[i].addClassName("levelTwoContentCollapse");
			myElement.setAttribute("toggle", "more");
			myElement.innerHTML = "...more words (+)";
			break;
		}
	}	
}; // end ContentPage_Class.toggleText()


// -----------------------------------------------------------------
//
// Toggle Photos
//
// Get list of available photos for the directory from the server.
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.togglePhotos = function(myElement) {
	var toggle = $(myElement).getAttribute("toggle");

	if (toggle == "more") {
		this.morePhotos(myElement);
	}
	else {
		this.lessPhotos(myElement);
	}
}; 


// -----------------------------------------------------------------
//
// More Photos methods
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.morePhotos = function(myElement) {
	var path = "";
	var ancestors = $(myElement).ancestors();

	for (var i = 0; i < ancestors.length; i++) {
		if (ancestors[i].hasClassName("levelTwoContent")) {
			this.aTogglePhotos = myElement;
			this.divLevelTwoContent = ancestors[i];
			path = ancestors[i].getAttribute("path");
			break;
		}
	}

	if (path) {
		new Ajax.Request(
			"resources/buffer/photoList.php", {
   				method: "get",
				parameters: "dir=" + path,
   				onSuccess: 
					function(transport) {
						oContentPage.morePhotos_onSuccess(transport);
					},
   				onFailure: 
					function(transport) {
						oContentPage.morePhotos_onFailure(transport);
					}
   			});
	}
	else {
		this.togglePhotos_onFailure();
	}
}; // ContentPage_Class.morePhotos()


ContentPage_Class.prototype.morePhotos_onSuccess = function(transport) {
	var oImageList = eval(transport.responseText);
	this.divMoreLevelTwoPhotos = this.divLevelTwoContent.select("div.moreLevelTwoPhotos")[0];
	$(this.divMoreLevelTwoPhotos).setStyle({height: "auto"});

	this.loadedImage = 0;	
	this.newImages = new Array();

	while (this.divMoreLevelTwoPhotos.childNodes[0]) {
		this.divMoreLevelTwoPhotos.removeChild(this.divMoreLevelTwoPhotos.childNodes[0]);
	}

	var aImgList = this.divLevelTwoContent.select("div.levelTwoPhotos a.aPhoto");

	// Set the height of the div.moreLevelTwoPhotos ahead of time for FireFox as that 
	// browser makes the footer image appear "shaky" when expanding the height of the 
	// div.moreLevelTwoPhotos element. It will be set back to auto when we're done.

	if ($(document.body).hasClassName("mozilla")) {
		var numNewPhotos = oImageList.length - aImgList.length;
		var height = parseInt(140 * (parseInt(numNewPhotos / 4) + (numNewPhotos % 4 > 0 ? 1 : 0)));
		$(this.divMoreLevelTwoPhotos).setStyle({height: height + "px;"});	
	}

	for (var i = 0; i < oImageList.length; i++) {
		if (i >= aImgList.length) {
			var title = this.parseTitle(oImageList[i].fileName);

			var imgElem = 
				new Element("img", {
					"src": (oImageList[i].thumbFileName ? oImageList[i].thumbFileName : oImageList[i].fileName), 
					"style": "width:" + oImageList[i].thumbFileSizeX + "px; height:" + oImageList[i].thumbFileSizeY + "px; ",
					"largewidth": + oImageList[i].fileSizeX,
					"largeheight": + oImageList[i].fileSizeY
			});	
		
			var aElem = new Element("a", {
				"class": "aPhoto", 
				href: "javascript:void(0);", 
				style: "display: none;",
				title: title
			});
			aElem.appendChild(imgElem);

			this.divMoreLevelTwoPhotos.appendChild(aElem);

			this.newImages.push(aElem);
		}	
	}
		
	var brClear = new Element("br", {"class": "clear"});
	this.divMoreLevelTwoPhotos.appendChild(brClear);
	
	this.aTogglePhotos.innerHTML = "... less photos (-)";
	this.aTogglePhotos.setAttribute("toggle", "less");
	this.aTogglePhotos = null;

	this.displayThumbnails();

}; // end ContentPage_Class.morePhotos_onSuccess()


ContentPage_Class.prototype.morePhotos_onFailure = function(transport) {
	alert("Unable to get more photos!  Sorry.");
}; // end ContentPage_Class.togglePhotos_onFailure()


//
// Display Thumbnails and apply behaviour when done
//

ContentPage_Class.prototype.displayThumbnails = function() {
	if (this.loadedImage < this.newImages.length) {
		Effect.Grow(this.newImages[this.loadedImage], {
			direction: "center",
			fps: 50,
			duration: 0.40, 
			afterFinish: 
				function() {
					oContentPage.loadedImage++;
					oContentPage.displayThumbnails.apply(oContentPage, []);
				}
		});
	}
	else {
		if ($(document.body).hasClassName("mozilla")) {
			$(this.divMoreLevelTwoPhotos).setStyle({height: "auto;"});
			this.divMoreLevelTwoPhotos = null;
		}
		Behaviour.apply();
	}
}; // end ContentPage_Class.displayThumbnails()


//
// Parse a title name from the file name
//

ContentPage_Class.prototype.parseTitle = function(fileName) {
	var retTitle = "No title";

	try {
		// Get ride of the rest of the path, keeping only the file name.	
		var fileNameArray = fileName.split("/");
		fileName = fileNameArray[fileNameArray.length - 1];

		// remove JPG extension and get the parts (e.g. 2006-06-30-02-EastSnowmassUnnamedPass.JPG)
		fileName = fileName.replace(/\.JPG/i, "");
		var parts = fileName.split("-");
	
		// text part (e.g. EastSnowmassUnnamedPass)

		// Insert a space between a lower case character followed by a upper case character
		// and two adjacent upper case characters.

		var words = parts[parts.length - 1];
		words = words.replace(/([a-z])([A-Z])/g, "$1 $2");
		words = words.replace(/([A-Z])([A-Z])/g, "$1 $2");
	
		// date part
		var year = parts[0] * 1;
		var month = parts[1] * 1;	
		var day = parts[2] * 1;	
		var dateStr = month + "/" + day + "/" + year;

		retTitle = words + ", " + dateStr;
	}
	catch (exp) {
		// do nothing, unable to parse the fileName
	} 
	
	return retTitle;
}; // end ContentPage_Class.parseTitle()


// -----------------------------------------------------------------
//
// Less Photos methods
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.lessPhotos = function(myElement) {
	var ancestors = $(myElement).ancestors();
	this.divLevelTwoContent = null;

	for (var i = 0; i < ancestors.length; i++) {
		if (ancestors[i].hasClassName("levelTwoContent")) {
			this.divLevelTwoContent = ancestors[i];
			break;
		}
	}

	this.aTogglePhotos = myElement;
	this.divMoreLevelTwoPhotos =  this.divLevelTwoContent.select("div.moreLevelTwoPhotos")[0];
	this.oldImages = this.divLevelTwoContent.select("div.moreLevelTwoPhotos a.aPhoto");

	var height = $(this.divLevelTwoContent).getHeight();
	$(this.divLevelTwoContent).setStyle({height: height + "px"});

	this.removeThumbnails();

}; // end ContentPage_Class.lessPhotos();


ContentPage_Class.prototype.removeThumbnails = function() {
	if (this.oldImages.length) {
		var last = this.oldImages.length - 1;

		Effect.DropOut(this.oldImages[last], {
			duration: 0.25, 
			afterFinish: 
				function() {
					var last = oContentPage.oldImages.length - 1;
					$(oContentPage.oldImages[last]).remove();
					oContentPage.oldImages.splice(last, 1);
					oContentPage.removeThumbnails.apply(oContentPage, []);
				}
		});
	}
	else {
		$(this.aTogglePhotos).innerHTML = "... more photos (+)";
		$(this.aTogglePhotos).setAttribute("toggle", "more");

		Behaviour.apply();

		$(this.divLevelTwoContent).setStyle({height: "auto"});
		this.aTogglePhotos = null;
		this.oldImages = null;
		this.divMoreLevelTwoPhotos = null;
		this.divLevelTwoContent = null;
	}
}; // end ContentPage_Class.removeThumbnails()


// -----------------------------------------------------------------
//
// Display a larger image
//
// -----------------------------------------------------------------

ContentPage_Class.prototype.displayPhoto = function(el, bNav) {
	var imgElem = ($(el).select("img"))[0];

	//
	// 1) Create the Shadow div
	//

	if (! bNav) {
		var divShadowBg = new Element("div", {"id": "div-ShadowBg"});
		var dimensionsViewPort = document.viewport.getDimensions() 
		var dimensionsBody = $(document.body).getDimensions()
	
		var height = (
			dimensionsViewPort.height > dimensionsBody.height + 40 ?  
			dimensionsViewPort.height : 
			dimensionsBody.height + 40
		);
	
		$(divShadowBg).setStyle({height: height + "px"});	
		$(divShadowBg).observe("click", closeDisplayPhoto);

		document.body.appendChild(divShadowBg);
	}

	//
	// 2) Set up the navigation
	//

	this.photoIndex = null;
	this.aPhotoElems = $("div-Content").select("a.aPhoto");

	for (var i = 0; i < this.aPhotoElems.length; i++) {
		if (this.aPhotoElems[i] == el) {
			this.photoIndex = i;
			break;
		}
	}

	this.applyPhotoNavClass();
	

	//
	// 3) Reset the Display Photo elements
	//

	var src = $(imgElem).getAttribute("src");
	src = src.replace(/thumbnails\//, "");
	var largeWidth = parseInt($(imgElem).getAttribute("largewidth"));
	var largeHeight = parseInt($(imgElem).getAttribute("largeheight"));

	var height = largeHeight + 55;  // + all vertical space
	var width = largeWidth + 18;  // + all horizontal space

	$("div-DisplayPhoto").setStyle({display: "block", "width": width + "px", "height": height + "px"});
	$("div-DisplayPhoto").addClassName("loading");
	$("div-DisplayPhoto-InnerDiv").setStyle({width: (width - 2) + "px", height: (height - 2) + "px"});

	var imgTitle = this.parseTitle(src);

	$("span-Title").innerHTML = imgTitle;
	$("span-Title").setStyle({display: "none"});
	$("a-CloseWindow").observe("click", closeDisplayPhoto);

	$("img-DisplayPhoto").setStyle({display: "none", width: largeWidth + "px", height: largeHeight + "px"});
	$("img-DisplayPhoto").setAttribute("alt", "");
	$("img-DisplayPhoto").setAttribute("src", src);


	//
	// 4) Position the image div 90 px below the top of the 
	// document and in the center of the screen
	//

	var oScrollOffset = document.viewport.getScrollOffsets();
	var oDimensions = document.viewport.getDimensions();
	var left = parseInt((oDimensions.width - width) / 2);
	
	$("div-DisplayPhoto").setStyle({top: (oScrollOffset.top + 90) + "px", left: left + "px"});


	//
	// 5) Fade in the image once it is loaded or immediately if already loaded.
	//

	function myAppear() {
		if ($("div-DisplayPhoto")) {
			try {
				$("div-DisplayPhoto").removeClassName("loading");
				Effect.Appear(
					$("img-DisplayPhoto"), {
					afterFinish: function() { 
						$("span-Title").setStyle({display: "block"});
					}
				});
			}
			catch (exp) {
				$("div-DisplayPhoto").removeClassName("loading");
				$("img-DisplayPhoto").setStyle({display: "block"});
				$("span-Title").setStyle({display: "block"});
			}
		} // end div-DisplayPhoto exists.
	} // end myAppear() 

	
	try {
		if (bNav == true) {
			window.setTimeout(myAppear, 1750);
		}
		// else if ($(document.body).hasClassName("safari") || $(document.body).hasClassName("ie")) {
		else if ($(document.body).hasClassName("ie")) {
			window.setTimeout(myAppear, 1000);
		}
		else if (! $("img-DisplayPhoto").complete) {
			$("img-DisplayPhoto").observe("load", myAppear);
		}
		else {
			myAppear();
		}
	}
	catch (exp) {
		myAppear();
	}
}; // end ContentPage_Class.displayPhoto()


//
// Apply the appropriate photo navigation classes
//

ContentPage_Class.prototype.applyPhotoNavClass = function() {
	if (this.photoIndex == 0) {
		$("div-DisplayPhoto-InnerDiv-Nav").removeClassName("last");
		$("div-DisplayPhoto-InnerDiv-Nav").addClassName("first");
		$("a-Next").observe("click", nextDisplayPhoto);
	}
	else if (this.photoIndex == this.aPhotoElems.length - 1) {
		$("div-DisplayPhoto-InnerDiv-Nav").removeClassName("first");
		$("div-DisplayPhoto-InnerDiv-Nav").addClassName("last");
		$("a-Prev").observe("click", prevDisplayPhoto);
	}
	else {
		$("div-DisplayPhoto-InnerDiv-Nav").removeClassName("first");
		$("div-DisplayPhoto-InnerDiv-Nav").removeClassName("last");
		$("a-Prev").observe("click", prevDisplayPhoto);
		$("a-Next").observe("click", nextDisplayPhoto);
	}
}; // end ContentPage_Class.applyPhotoNavClass()


//
// Navigate to the previous photo
//

function prevDisplayPhoto(e) {
	Event.stop(e);
	oContentPage.prevDisplayPhoto();
} // end function prevDisplayPhoto()

ContentPage_Class.prototype.prevDisplayPhoto = function() {
	this.photoIndex--;
	this.displayPhoto(this.aPhotoElems[this.photoIndex], true);
	return;
}; // end ContentPage_Class.prevDisplayPhoto()


//
// Navigate to the next photo
//

function nextDisplayPhoto(e) {
	Event.stop(e);
	oContentPage.nextDisplayPhoto();
} // end function nextDisplayPhoto()

ContentPage_Class.prototype.nextDisplayPhoto = function() {
	this.photoIndex++;
	this.displayPhoto(this.aPhotoElems[this.photoIndex], true);
	return;
}; // end ContentPage_Class.nextDisplayPhoto()


//
// Close the photo
//

function closeDisplayPhoto(e) {
	$("div-DisplayPhoto").setStyle({display: "none"});
	$("img-DisplayPhoto").setStyle({display: "none"});
	$("img-DisplayPhoto").setAttribute("src", "");
	$("div-ShadowBg").remove();
	Event.stop(e);
}; // end ContentPage_Class.closeDisplayPhoto_click()



// *****************************************************************
//
// Global Instance
//
// *****************************************************************

var oContentPage = new ContentPage_Class();

window.onload = function() { 
	oCommon.writeEmail();
	oContentPage.init(); 
};

