// *****************************************************************
//
// IndexPage_Class
// 
// Responsible for handling events and behaviours on the main 
// page of the site.
//
// *****************************************************************


function IndexPage_Class() {
	this.season = null;
	this.oImageList = null;

	// Keep track of anchor elements
	this.aThumbnails = null;
	this.loadedThumbnail = 0;

	this.viewTypes = {
		photo: "photoView",
		aboutMe: "aboutMeView",
		orderInfo: "orderInfoView",
		thankYou: "thankYou"
	};

	this.viewType = this.viewTypes.photo;

	this.priceBySize = {
		"greetingCard": {
			desc: "Greeting Card",
			price: 2.50
		},
		"photo5x7": {
			desc: "5x7 photo/Single mat and back/8x10 finished",
			price: 20.00
		},
		"photo8x12singleMat": {
			desc: "8x12 photo/Single mat and back/12x16 finished",
			price: 35.00
		},
		"photo8x12doubleMat": {
			desc: "8x12 photo/Double mat and back/12x16 finished",
			price: 45.00
		},
		"photo11x17singleMat": {
			desc: "11x17 photo/Single mat and back/16x22 finished - $65",
			price: 65.00
		},
		"photo11x17doubleMat": {
			desc: "11x17 photo/Double mat and back/16x22 finished",
			price: 75.00
		}
	};
		
} // end IndexPage_Class()



// *****************************************************************
//
// Behaviour
//
// *****************************************************************

IndexPage_Class.prototype.behaviour = function() {
	var myRules = {
		"#div-PhotoLinks a": function(el) {  
			el.onclick = changeSeason_click;
		},
		"#a-Footer-AboutMe": function(el) {
			el.onclick = function() { 
				oIndexPage.changeViewType(oIndexPage.viewTypes.aboutMe); 
			};
		},
		"#a-Footer-OrderInfo": function(el) {
			el.onclick = function() { 
				oIndexPage.changeViewType(oIndexPage.viewTypes.orderInfo); 
			};
		},
		"#a-OrderingInfo": function(el) {
			el.onclick = function() {
				closeDisplayPhoto_click();
				oIndexPage.changeViewType(oIndexPage.viewTypes.orderInfo); 
			};
		},
		"div#div-DisplayPhoto-OrderNow img": function(el) {
			el.onclick = function() {
				oIndexPage.addToCart();
			}
		}
	};

	Behaviour.register(myRules);
} // end IndexPage_Class.behaviour()



// *****************************************************************
//
// Event Handling Methods (with context)
//
// *****************************************************************

//
// Initialization method
//

IndexPage_Class.prototype.init = function() {
	this.aThumbnails = new Array();
	this.loadedThumbnail = 0;

	// If we're called with a viewType, change to that viewType and return
	// else determine the season and select the proper anchor element and 
	// get the thumbnails.

	var viewType = this.req("viewType");

	if (viewType == this.viewTypes.thankYou) {
		this.changeViewType(viewType);
	}
	else {
		var today = new Date();

		var month = today.getMonth() + 1;
		var day = today.getDate();
	
		if ((month == 1 || month == 2) || (month == 3 && day < 21)) {
			this.season = "Winter";
		}
		else if ((month == 3 && day > 21) || (month == 4 || month == 5) || (month == 6 && day < 21)) {
			this.season = "Spring";
		}
		else if ((month == 6 && day > 21) || (month == 7 || month == 8) || (month == 9 && day < 21)) {
			this.season = "Summer";
		}
		else {
			this.season = "Fall";
		}

		$("a-PhotoLink-" + this.season).addClassName("current");

		// Get thumbnails
		this.getThumbnails();
	}

	this.behaviour();

	// 4) Write the email address mailto link
	$("a-AboutMe-MailTo").href = "mai" + "lt" + "o:cather" + "ine@" + "cat" + "herinehe" + "wi" + "ns.com";
	$("a-AboutMe-MailTo").innerHTML = "&#099;&#097;&#116;&#104;&#101;&#114;&#105;&#110;&#101;&#064;&#099;&#097;&#116;&#104;&#101;&#114;&#105;&#110;&#101;&#104;&#101;&#119;&#105;&#110;&#115;&#046;&#099;&#111;&#109;";

	// IE6 fix so that the background images are always available
	try {
		document.execCommand("BackgroundImageCache", false, true)	
	}
	catch (exp) {
	}

} // end IndexPage_Class.init()


//
// Change View Type
//

IndexPage_Class.prototype.changeViewType = function(viewType) {
	if (this.season) {
		$("a-PhotoLink-" + this.season).removeClassName("current");
		this.season = null;
	}

	$("div-Container").removeClassName(this.viewType);
	this.viewType = viewType;
	$("div-Container").addClassName(this.viewType);
} // end IndexPage_Class.changeViewType()


//
// Display a larger image
//

IndexPage_Class.prototype.displayPhoto = function(imageListIndex) {
	var bNoEffects = false;

	// Just display the larger image in a separate window for IE6.
	if ($(document.body).hasClassName("v6")) {
		var height = this.oImageList[imageListIndex].largeFileSizeY;
		var width = this.oImageList[imageListIndex].largeFileSizeX;
		var heightWindow = parseInt(height) + 56 + 40 + 6 + 80;
		var widthWindow = parseInt(width) + 45 + 80 + 6 + 40;

		var url = 
			"largePhoto.php?src=" + this.oImageList[imageListIndex].largeFileName +
			"&width=" + width + 
			"&height=" + height;
			
		window.open(url, "LargePhoto", "scrollbars=yes,left=90,top=90,width=" + widthWindow + ",height=" + heightWindow);
		return false;
	}
	else if ($(document.body).hasClassName("safari")) {
		bNoEffects = true;
	}

	//
	// 1) Create the Shadow div
	//

	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_click);


	//
	// 2) Reset the Display Photo elements
	//

	var height = parseInt(this.oImageList[imageListIndex].largeFileSizeY) + 45;  // + all vertical space
	var width = parseInt(this.oImageList[imageListIndex].largeFileSizeX) + 16;  // + all horizontal space

	$("div-DisplayPhoto").setStyle({display: "block", width: width + "px", height: height + "px"});

	if (bNoEffects == false) {
		$("div-DisplayPhoto").addClassName("loading");
	}

	$("div-DisplayPhoto-InnerDiv").setStyle({width: (width - 2) + "px", height: (height - 2) + "px"});

	var imgTitle = this.parseTitle(this.oImageList[imageListIndex].largeFileName);
	$("span-Title").innerHTML = imgTitle;
	$("a-CloseWindow").observe("click", closeDisplayPhoto_click);

	if (bNoEffects == true) {
		$("img-DisplayPhoto").setStyle({
			display: "inline",
			width: parseInt(this.oImageList[imageListIndex].largeFileSizeX) + "px",
			height: parseInt(this.oImageList[imageListIndex].largeFileSizeY) + "px"
		});
	}
	else {
		$("img-DisplayPhoto").setStyle({
			display: "none",
			width: parseInt(this.oImageList[imageListIndex].largeFileSizeX) + "px",
			height: parseInt(this.oImageList[imageListIndex].largeFileSizeY) + "px"
		});
		$("img-DisplayPhoto").setAttribute("alt", imgTitle);
	}
	$("img-DisplayPhoto").setAttribute("src", this.oImageList[imageListIndex].largeFileName);

	if (bNoEffects == true) {
		$("a-OrderNow").setStyle({display: "inline"});
	} 
	else {
		$("a-OrderNow").setStyle({display: "none"});
	}
	$("a-OrderNow").observe("click", orderNow_click);

	$("div-DisplayPhoto-OrderNow").setStyle({display: "none"});

	document.body.appendChild(divShadowBg);


	//
	// 3) Position the image div 90 px below the top of the document 
	//

	var scrollTop = 90;

	if (typeof(window.pageYOffset) == "number" ) {
		scrollTop += window.pageYOffset;
	} 
	else if (document.body && document.body.scrollTop) {
    	//DOM compliant
		scrollTop += document.body.scrollTop;
	} 
	else if (document.documentElement && document.documentElement.scrollTop) {
    	// IE6 standards compliant mode
    	scrollTop += document.documentElement.scrollTop;
	}

	$("div-DisplayPhoto").setStyle({top: scrollTop + "px"});


	//
	// 4) Fade in the image once it is loaded or immediately if already loaded.
	//

	// IE6 doesn't work well at all with these effects, so we just don't use them
	// for the ancient browser.  Also Safari for Windows doesn't fire the onload
	// event handler.  So for those browsers, we just display the larger image.
	//

	function myAppear() {
		if ($("div-DisplayPhoto")) {
			try {
				$("div-DisplayPhoto").removeClassName("loading");

				Effect.Appear($("img-DisplayPhoto"), {
					afterFinish: 
						function() {
							$("a-OrderNow").setStyle({display: "inline"});
						}
				});
			}
			catch (exp) {
				$("div-DisplayPhoto").removeClassName("loading");
				$("img-DisplayPhoto").setStyle({display: "inline"});
				$("a-OrderNow").setStyle({display: "inline"});
			}
		} // end div-DisplayPhoto exists.
	} // end myAppear() 
	
	if (bNoEffects == false) {
		try {
			if ($(document.body).hasClassName("safari") || $(document.body).hasClassName("ie")) {
				window.setTimeout(myAppear, 1000);
			}
			else if (! $("img-DisplayPhoto").complete) {
				$("img-DisplayPhoto").observe("load", myAppear);
			}
			else {
				myAppear();
			}
		}
		catch (exp) {
			myAppear();
		}
	}
} // end IndexPage_Class.displayPhoto()


//
// Add an image to the cart at PayPal
//

IndexPage_Class.prototype.addToCart = function() {
	var imgType = $("sel-DisplayPhoto-PhotoType").value;
	var price = this.priceBySize[imgType].price;
	var desc = this.priceBySize[imgType].desc;
	var item = $("span-Title").innerHTML;

	closeDisplayPhoto_click();

	var url = "https://www.paypal.com/cgi-bin/webscr?";
	url += "add=1";
	url += "&cmd=_cart";
	url += "&upload=1";
	url += "&business=catherinepmcd@earthlink.net";
	url += "&return=http://www.catherinehewins.com/thankyou.html";
	url += "&cancel=http://www.catherinehewins.com";
	url += "&shopping_url=http://www.catherinehewins.com";
	url += "&item_name=" + item + ": " + desc;
	url += "&amount=" + price;
	url += "&quantity=1";
	url += "&currency_code=USD";

	window.open(url, "paypal");

	return false;
} // end IndexPage_Class.addToCart()



// *****************************************************************
//
// Event Handling Methods (with out context / this = target element)
//
// *****************************************************************

//
// Display a larger image
//

function displayPhoto_click(myEvent) {		
	oIndexPage.displayPhoto.apply(oIndexPage, [this.imageListIndex]);
} // end displayPhoto_click()


//
// Remove the div-DisplayPhoto element
//

function closeDisplayPhoto_click(myEvent) {
	$("div-DisplayPhoto").setStyle({display: "none"});
	$("img-DisplayPhoto").setStyle({display: "none"});
	$("img-DisplayPhoto").setAttribute("src", "");
	$("div-ShadowBg").remove();
} // end closeDisplayPhoto_click()


//
// Expand the Order Now div
//

function orderNow_click(myEvent) {
	var oldHeight = parseInt($("div-DisplayPhoto-InnerDiv").getStyle("height"));
	$("div-DisplayPhoto-InnerDiv").setStyle({height: (oldHeight + 20) + "px"});

	var oldHeight = parseInt($("div-DisplayPhoto").getStyle("height"));
	$("div-DisplayPhoto").setStyle({height: (oldHeight + 20) + "px"});

	$("a-OrderNow").setStyle({display: "none"});

	Effect.BlindDown($("div-DisplayPhoto-OrderNow"), {duration: 1});
} // end orderNow_click()


//
// Display a new season's thumbnails 
//

function changeSeason_click(myEvent) {
	oIndexPage.changeViewType(oIndexPage.viewTypes.photo);

	oIndexPage.oImageList = null;
	oIndexPage.oImageList = new Array();
	oIndexPage.aThumbnails = null;
	oIndexPage.aThumbnails = new Array();
	oIndexPage.loadedThumbnail = 0;

	var el = this;
	var oldSeasonElem = $("a-PhotoLink-" + oIndexPage.season);

	if (el != oldSeasonElem) {
		// Unset the old current season
		if ($(oldSeasonElem)) {
			$(oldSeasonElem).removeClassName("current");
		}

		// Get the new season
		oIndexPage.season = el.id.split("-")[2];
		$("a-PhotoLink-" + oIndexPage.season).addClassName("current");
	
		// Remove the old anchor elements
		var divThumbnails = $("div-Thumbnails");	
		while (divThumbnails.childNodes[0]) {
			divThumbnails.removeChild(divThumbnails.childNodes[0]);
		}
	
		// Add the loading class
		$(divThumbnails).addClassName("loading");
	
		// Get the new season's thumbnails...
		// (Note we're using apply to be called with the context of the oIndexPage object!)
		oIndexPage.getThumbnails.apply(oIndexPage, []);

	} // end a new season was clicked
} // end IndexPage_Class.changeSeason_click()



// *****************************************************************
//
// Rendering Methods
//
// *****************************************************************

//
// Display the thumbnail images
//

IndexPage_Class.prototype.renderThumbnails = function() {
	var divThumbnails = $("div-Thumbnails");

	// Add the new anchor and image elements...
	var maxWidth = 1000;
	var currentWidth = 0;

	for (var i = 0; i < this.oImageList.length; i++) {
		currentWidth += parseInt(this.oImageList[i].smallFileSizeX) + 10 + 20;

		if (currentWidth > maxWidth) {
			divThumbnails.appendChild(this.brClear());
			currentWidth = parseInt(this.oImageList[i].smallFileSizeX) + 10 + 20;
		}

		var title = this.parseTitle(this.oImageList[i].largeFileName);

		var displayStyle = ($(document.body).hasClassName("v6") ? "block" : "none");
	
		this.aThumbnails[i] = 
			new Element("a", 
				{"class": "thumbnail", href: "javascript:void(0);", title: title, style: "display:" + displayStyle + ";" }
		);

		this.aThumbnails[i].imageListIndex = i;
		var imgElem = 
			new Element("img", {
				src: this.oImageList[i].smallFileName, 
				style: "height: " + this.oImageList[i].smallFileSizeY + 
					"px; width: " + this.oImageList[i].smallFileSizeX + "px;",
				"imgIndex": i 
			});

		this.aThumbnails[i].appendChild(imgElem);
		divThumbnails.appendChild(this.aThumbnails[i]);

		// Behaviour can't find these if they're not displayed?  
		$(this.aThumbnails[i]).observe("click", displayPhoto_click);
	}

	var brClear = new Element("br", {"class": "clear"});
	divThumbnails.appendChild(brClear);

	// Finally, remove the loading class and display the thumbnails.
	$(divThumbnails).removeClassName("loading");

	if (! $(document.body).hasClassName("v6")) {
		this.displayThumbnails();
	}
} // end IndexPage_Class.renderThumbnails()


//
// Display the thumbnails one by one, in order, after 
// they've been added to the DOM.  
//

IndexPage_Class.prototype.displayThumbnails = function() {
	if (this.loadedThumbnail < this.aThumbnails.length) {
		Effect.Grow(this.aThumbnails[this.loadedThumbnail], {
			direction: "center",
			fps: 50,
			duration: 0.40, 
			afterFinish: 
				function() {
					oIndexPage.loadedThumbnail++;
					oIndexPage.displayThumbnails.apply(oIndexPage, []);
				}
		});
	}
} // end IndexPage_Class.displayThumbnails()



// *****************************************************************
//
// Misc Methods
//
// *****************************************************************


IndexPage_Class.prototype.brClear = function() {
	return new Element("br", {"class": "clear"});
} 

IndexPage_Class.prototype.parseTitle = function(imgSrc) {
	var titleArray = imgSrc.split("/");
	var title = "";

	try {	
		title = titleArray[3];
		title = decodeURIComponent(title);
		title = title.replace(/\.jpg/ig, "");
		title = title.replace(/_/g, " ");
		title = title.replace(/\bco\b/ig, "Colo.");
		title = title.replace(/\bnm\b/ig, "N.M.");
		title = title.replace(/\bnj\b/ig, "N.J.");
	}
	catch (exp) {
		title = "";
	}
	
	return title;
} // end IndexPage_Class.parseTitle()


IndexPage_Class.prototype.req = function(variable) {
	var retVal = "";

	try {
		var urlString = window.location.href;
		var aQueryString = urlString.split("?");

		if (aQueryString.length > 1) {
			var aParamString = aQueryString[1].split("&");
	
			for (var i = 0; i < aParamString.length; i++) {
				if (aParamString[i].match(variable)) {
					retVal = (aParamString[i].split("="))[1];
					break;
				}
			} // end iteration thru parameter string
		} //
	}
	catch (exp) {
		retVal = "";
	}

	return decodeURIComponent(retVal);
} // end IndexPage_Class.req()





// *****************************************************************
//
// Data Methods
//
// *****************************************************************

IndexPage_Class.prototype.getThumbnails = function() {
	new Ajax.Request(
		"buffer/photoList.php", {
    		method: "get",
			parameters: "dir=" + this.season.toLowerCase(),
    		onSuccess: this.getThumbnails_onsuccess,
    		onFailure: this.getThumbnails_onfailure
    	}
	);
} // end IndexPage_Class.getThumbnails()


// MDD - TODO - It would be so GREAT if we had some context here...

IndexPage_Class.prototype.getThumbnails_onsuccess = function(transport, oJson) {
	oIndexPage.oImageList = eval(transport.responseText);
	oIndexPage.renderThumbnails();
} // end IndexPage_Class.getThumbnails_onsuccess()


IndexPage_Class.prototype.getThumbnails_onfailure = function(transport) {
	alert("IndexPage_Class.getThumbnails_onfailure(): " + transport.status + " - " + transport.statusText);
} // end IndexPage_Class.getThumbnails_onfailure()



// *****************************************************************
//
// Global Instance
//
// *****************************************************************

var oIndexPage = new IndexPage_Class();

window.onload = function() { 
	oIndexPage.init(); 
};


