dojo.require("dijit.Dialog");
dojo.require("hunggar.PicViewer");

var maxImgHeight = 700;
var maxImgWidth = 1024;

var numPages = 0;
var pageTxt = "";

var isPlaying = false;

var waitingGif = "<img alt='Please Wait...' src='img/misc/waiting.gif'/>";

var imageCache = null;

var directions = {
										"left"	:	{ 
													        marginLeft: -1550,
													        opacity: 0
													     },
										"right"	:	{ 
													        marginLeft: 1550,
													        opacity: 0
													     },
										"none":	{ 
													        opacity: 0
													     },
									};

dojo.addOnLoad(function() {
									var gallery = window.location.search.substring(1).split("=")[1];
									if (gallery) {displayGallery(gallery);}
							});

var imgSrcArr = new Array();
var currIdx = 0;

// Hides waitGif and sets off next slide if is playing
function fadeInImage() {
	var imageModal = dijit.byId("imageModal");
	
	imageModal.waiterNode.style.display = "none";
	imageModal.containerNode.style.display = "block";
	
	var currImage = dojo.query("img", imageModal.containerNode)[0];
	
	var onEndFunction = function() {
												var currImage = dojo.query("img", imageModal.containerNode)[0];
												currImage.style.opacity = 1;
												if (isPlaying) {
													nextSlide();
												}
											};
	
	dojo.fadeIn({	node: currImage,
								duration: 1250,
								onEnd: onEndFunction,
								onStop: onEndFunction
              }).play();
}

// displays the image of the given imgIdx and makes the transition
function displayImage(imgIdx, direction) {
	if (!direction || direction == undefined) {
		direction = "none";
	}
	
	preloadPages();
	
	currIdx = imgIdx;
	
	if ((imgSrcArr != null) && (imgSrcArr.length > 0)) {
		var imageModal = dijit.byId('imageModal');
		
		imageModal.show();
		
		var image = imgSrcArr[currIdx];
		var width = image.width;
		var height = image.height;
		var topMargin = 0;
		
		if (image.width > maxImgWidth) {
			width = maxImgWidth;
			height = height*(maxImgWidth / width);
		}
		
		if (height > maxImgHeight) {
			width = width*(maxImgHeight / height);
			height = maxImgHeight;
		} else {
			topMargin = (maxImgHeight - height) / 2;
		}
		imageModal.waiterNode.style.display = "block";	
	
		var showImage = function() {																		// Common Display Image code for both paths
			var imageModal = dijit.byId('imageModal');
			imageModal.containerNode.style.display = "none";
			imageModal.containerNode.innerHTML = "<a title=\"Next Image\" onclick=\"showNextImage();return false;\" href=\"#\"><img style=\"opacity:0;\" alt=\"next Image\" onload='fadeInImage()' height='" + height + "' width='" + width + "' style='margin-top:" + topMargin + "px;' src='" + image.path + "'></a>";;
		};
		
		var currImage = dojo.query("#imageModal .containerNode img");
		
		if (currImage && (currImage.length > 0)) {
			dojo.animateProperty({																				// Fade out and slide
			    node: currImage[0],
			    duration: 1250,
			    onEnd: showImage,
			    onStop: showImage,
			    properties: directions[direction],
			}).play();
		} else {
			showImage();
		}
	} else {
		alert("Cannot find images");
	}
}

// increments to show the next image
function nextImage() {
	var idx = currIdx + 1;
	displayImage((imgSrcArr.length > idx) ? idx : 0, "left");
}

// decrements to show the last image
function lastImage() {
	var idx = currIdx - 1;
	displayImage((0 > idx) ? imgSrcArr.length - 1 : idx, "right");
}

// displays gallery
function displayGallery(galleryName) {
	dojo.byId("gallery").innerHTML = waitingGif;
	
	dojo.byId("index").style.display = "none";
	dojo.byId("gallery").style.display = "block";
	
	dojo.xhrPost ({
        url: "common/gallery.php",
        preventCache: true,
        sync: false,
        content: {"galleryName": galleryName},
        
        load: function (data) {
            dojo.byId('gallery').innerHTML = data;
            
            if (dojo.isIE) {
            	window.execScript(data.match(/(.*imgSrcArr.*)/)[0]);
            	window.execScript(data.match(/(.*rowsPerPage.*)/)[0]);
            	window.execScript(data.match(/(.*numPages.*)/)[0]);
            	window.execScript(data.match(/(.*pageTxt.*)/)[0]);
            } else {
            	dojo.forEach(dojo.query("#gallery script"), function(scriptTag) {
            																								window.eval(scriptTag.innerHTML);
            																						});
						}
						
						drawPageControls();						
        },
        error: function (data) {
            console.error('Error: ', data);
        }
    });
}

function drawPageControls() {
	var pages = dojo.query(".gallery .page");
	var pageLists = dojo.query(".pageControls .pageList");
	var controls = "";

	for (var m = 0 ; m <= numPages ; m++) {							// Create link string
		controls += "<a class='pageLnks' title='Page " + (m + 1) + "' onclick=\"showPage('" + m + "'); return false;\" href='#'><img alt='Page " + (m + 1) + "' class='numbers' width='35' height='35' src='img/misc/numbers/" + (m+1) + ".gif'/></span></a>";
	}

	dojo.forEach(pageLists, function(pageList) {					// set string to both page controls
														pageList.innerHTML = controls;
													});
											
	var pageControls = dojo.query(".pageControls");
	dojo.forEach(pageControls, function(pageControl) {		// adjust width
															pageControl.style.width = (dojo.coords(pageLists[0]).w + (dojo.coords(dojo.query(".pageControls img")[0]).w * 2)) + "px";
															});
	
	showPage(0);																					// start on first page
}

function preloadPages() {
	if (dojo.byId("hiddenPages").innerHTML == "") {				// only if it has not been preloaded
		dojo.byId("hiddenPages").innerHTML = pageTxt;
	}
}

function displayIndex() {
	dojo.byId("gallery").style.display = "none";
	dojo.byId("index").style.display = "block";
}

var pageIdx = 0;																				// current page index for pagination
function nextPage() {
	preloadPages();
	
	var pages = dojo.query(".gallery .page");
	
	dojo.addClass(pages[pageIdx], "hiddenPage");					// hide old
	turnOff(pageIdx);
	
	pageIdx = (pageIdx + 1) % pages.length;
	
	dojo.removeClass(pages[pageIdx], "hiddenPage");				// show next
	turnOn(pageIdx);
}

function previousPage() {																// Back 1 page
	preloadPages();
	
	var pages = dojo.query(".gallery .page");
	
	dojo.addClass(pages[pageIdx], "hiddenPage");
	turnOff(pageIdx);
	
	pageIdx = (pageIdx <= 0) ? (pages.length - 1) : pageIdx - 1;
	
	dojo.removeClass(pages[pageIdx], "hiddenPage");
	turnOn(pageIdx);
}

function showPage(idx) {																// Show page idx
	if (idx > 0) {
		preloadPages(); 
	}
	var pages = dojo.query(".gallery .page");
	
	dojo.addClass(pages[pageIdx], "hiddenPage");
	turnOff(pageIdx);
	
	pageIdx = idx;
	
	dojo.removeClass(pages[pageIdx], "hiddenPage");
	turnOn(pageIdx);
}

function turnOff(idx) {
	var pageControls = dojo.query(".pageControls");
	var pic = parseInt(idx) + 1;
	
	dojo.forEach(pageControls,function(pageControl) {
															var buttons = dojo.query(".numbers", pageControl);														
															buttons[idx].src = "img/misc/numbers/" + pic + ".gif";
															
	});
}

function turnOn(idx) {
	var pageControls = dojo.query(".pageControls");
	var pic = parseInt(idx) + 1;
	
	dojo.forEach(pageControls,function(pageControl) {
															var buttons = dojo.query(".numbers", pageControl);
															buttons[idx].src = "img/misc/numbers/" + pic + "-on.gif";
															
	});
}

function nextSlide() {
	if (isPlaying) {
		setTimeout(	function() { 
									if (isPlaying) {
										nextImage();
									}
							}, 3800);
	}
}

function playSlideShow() {
	var imageModal = dijit.byId('imageModal');
	imageModal.slidePlayShowNode.style.display = "none";
	imageModal.slidePauseShowNode.style.display = "block";
	
	if (imageCache == null) {																			// Cache all images the first time
		imageCache = new Array();
		dojo.forEach(imgSrcArr, function(currImage, idx) {
			console.log("currImage.path");
			imageCache[idx] = new Image();
			imageCache[idx].src = currImage.path;
		});
	}
	
	isPlaying = true;
	
	nextSlide();
}

function pauseSlideShow() {
	var imageModal = dijit.byId('imageModal');
	imageModal.slidePauseShowNode.style.display = "none";
	imageModal.slidePlayShowNode.style.display = "block";
	
	isPlaying = false;
}

function showNextImage() {
	if (isPlaying) {
		pauseSlideShow();
	} else {
		nextImage();
	}
}

function hideViewer(viewerId) {
	pauseSlideShow();
	dijit.byId(viewerId).hide();
}

function fadeSlideControls(controls) {
	controls.style.opacity = 0.5;
	
	if (controls.filters) {
		controls.filters.alpha.opacity = 50;
	}
}
function showSlideControls(controls) {
	controls.style.opacity = 1.0;
	
	if (controls.filters) {
		controls.filters.alpha.opacity = 100;
	}
}