/* ImagePopup.js
 * 
 * Author: Michael Schmidt of Lockheed Martin
 * 
 * Developed for: DOE Hanford
 * 
 * 
 * Purpose of these functions are specific to the image gallery
 * 
 * 
 * 
 */
if ( !window.PhotoGalleryBaseLocation )
{
	PhotoGalleryBaseLocation =  "c.cfm/photogallery/";
}

if (!window.ImagePopup) {
	ImagePopup = {
		base : undefined,
		photoConst: 'hanfordPhoto',
		photoElementId: this.photoConst + '_photoContainer_' + new Date().getTime(), 
		overlayObjectID: this.photoConst + '_overlay_' + new Date().getTime(), 
		ImageToPopupClass: "ImageToPopup",
		ImageToPopupDoneClass: "ImageToPopupProcessed",
		ImagePopupClass: "ImagePopup",
		ImagePopupCloseClass: "ImagePopupClose",
		ImageDownloadClass: "ImageDownloadButton",
		ImageSlideShowNextClass: "ImageSlideShow",
		ImageSlidShowPauseHTML: "Pause Slide Show",
		ImageSlideShowPlayHTML: "Play Slide Show",
		OverlayClass: "ScreenOverlay",
		ImgLinkClass: "ImageLink",
		getConfigSettings: PhotoGalleryBaseLocation+ "getSettings.cfm",
		OverlayZindex: 1001,
		imageLibraryLoc: PhotoGalleryBaseLocation+ "img.cfm/",
		ScreenSizePath: "normal/",
		FullSizePath: "full/",
		FullSizeExt: "",
		ScreenSizeExt: "",
		PrintPath: PhotoGalleryBaseLocation + "print.cfm/",
		ImageInformationJSON: PhotoGalleryBaseLocation + "imgInfo.cfm/",
		galLink: PhotoGalleryBaseLocation + "gal.cfm/",
		tagLink: PhotoGalleryBaseLocation + "tags.cfm/",
		ImageLink: PhotoGalleryBaseLocation+ "imgView.cfm/",
		ImagePopupTemplate: PhotoGalleryBaseLocation + "imgPopup.cfm",
		ImagePopupCSS: PhotoGalleryBaseLocation + "style/imagePopup.css",
		CurrentImage: undefined,
		ImageListTag: "photo",
		ImageListArr: [],
		ImageListPtr: 0,
		SlideShowRunning: undefined,
		slideShowTimeSeconds: 5,
		nextImageClass: "nextImage",
		prevImageClass: "prevImage",
		nextImageVisClass: "nextImageVis",
		prevImageVisClass: "prevImageVis",
		ImagePrintClass: "printButton",
		loadIndicatorClass: "loadIndicator",
		allowForLinking: true,
		jsonPre: '//',
		photoOpen: false,
		currentY: 0,
		popupContent : "",
		cleanJSON: function(str){
			if (str.substr(0, this.jsonPre.length) == this.jsonPre) 
				str = str.substr(this.jsonPre.length);
			return str;
		},
		onGetSettings: function(transport){
			var resp = eval("(" + this.cleanJSON(transport.responseText) + ")");
			this.imageLibraryLoc = resp.IMGURL + "/";
			this.ScreenSizePath = resp.NORMPART + "/";
			this.ScreenSizeExt = resp.NORMEXT;
			this.FullSizePath = resp.FULLPART + "/";
			this.FullSizeExt = resp.FULLEXT;
		},
		initialize: function(){
			this.hideLoading();
			var tmpBases = document.getElementsByTagName("base");
			this.base = "";
			if (tmpBases.length > 0) 
				this.base = tmpBases[0].href;
			
			new Ajax.Request(this.base + this.getConfigSettings, {
				onSuccess: this.onGetSettings.bindAsEventListener(this)
			});
			
			var imgs = $$("." + this.ImageToPopupClass);
			for (var i = 0; i < imgs.length; i++) {
				if (!Element.hasClassName(imgs[i], this.ImageToPopupDoneClass)) {
					Event.observe(imgs[i], "click", this.imageClicked.bindAsEventListener(this));
					Element.addClassName(imgs[i], this.ImageToPopupDoneClass);
				}
			}
			
				this.initImageList();
			
			this.removeHrefLinks();
			
				
			new Ajax.Request(this.ImagePopupTemplate, {onSuccess: this.on_getPhotoLayout.bindAsEventListener(this)});
			Event.observe(document, "keypress", this.CheckKeyPress.bindAsEventListener(this));
			var elm = new Element("link", {rel:'stylesheet', href:this.ImagePopupCSS});
			var bodies = $$("body");
			bodies[0].insert(elm);
		},
		on_getPhotoLayout: function(transport)
		{			
			this.popupContent = transport.responseText;	
				this.autoLoadCheck();
		},
		CreatePhotoElement: function() {
			if ( ! this.basePath )
			{
					this.basePath = this.base;				
			}
			
			
			var elm = document.createElement("div");						
			elm.id = this.photoElementId;
			document.body.appendChild(elm);
			
			
			elm.style.zIndex = this.OverlayZindex+ 10;
			elm.style.position = "absolute";
			elm.style.top = 20;
			elm.style.left = (Element.getWidth(document.body) / 2 ) - 400;
			//elm.style.backgroundColor = 'silver';
			elm.className = "popupBackground"
			elm.style.width = '815px';
			Element.update(elm, this.popupContent);
			
			//elm.style.backgroundImage = "appimages/hanfordGov/gradated_background.jpg";
			//var style = "background-image:url("+ this.basePath + "/appimages/hanfordGov/gradated_background.jpg)";
			var style="background-color:#353535;border:thin solid white;padding-left:10px;";
			this.CreateStyle('#' + this.photoElementId, style);
			
			
			
			var objs = $$("." + this.ImagePopupCloseClass);
			
			if (objs.length > 0) 
				Event.observe(objs[0], "click", this.closePopup.bindAsEventListener(this));
			
			var objs = $$("." + this.ImageDownloadClass);
			if (objs.length > 0) 
				Event.observe(objs[0], "click", this.downloadImage.bindAsEventListener(this));
			
			objs = $$("." + this.ImagePrintClass);
			if (objs.length > 0) 
				Event.observe(objs[0], "click", this.printClicked.bindAsEventListener(this));
			
		
			objs = $$("." + this.prevImageClass);
			for (var i = 0; i < objs.length; i++) {
				/*Event.observe(objs[i], "mouseover", this.prevMouseOver.bindAsEventListener(this));
				 Event.observe(objs[i], "mouseout", this.prevMouseOut.bindAsEventListener(this));*/
				this.prevMouseOver();
				Event.observe(objs[i], "click", this.prevSlide.bindAsEventListener(this));
				
			}
			
			objs = $$("." + this.nextImageClass);
			for (var i = 0; i < objs.length; i++) {
				/*Event.observe(objs[i], "mouseover", this.nextMouseOver.bindAsEventListener(this));
				 Event.observe(objs[i], "mouseout", this.nextMouseOut.bindAsEventListener(this));*/
				this.nextMouseOver();
				Event.observe(objs[i], "click", this.nextSlide.bindAsEventListener(this));
				
			}
			
			Event.observe($("ImagePopupImg"), "load", this.imgLoadedF.bindAsEventListener(this));			
			
			var tmpElms = $$("." + this.ImageSlideShowNextClass)
				
			if (tmpElms.length > 0) {
				tmpElms[0].update(this.ImageSlideShowPlayHTML);
				Event.observe(tmpElms[0], "click", this.startStopSlideShow.bindAsEventListener(this));
			}
			
		},
		removeHrefLinks: function(){
			var objs = $$("." + this.ImgLinkClass);
			for (var i = 0; i < objs.length; i++) {
				objs[i].removeAttribute("href");
			}
		},
		autoLoadCheck: function(){
			if (this.allowForLinking) 
				this.checkHash();
		},
		updateHash: function(imgName){
			if (this.allowForLinking) {
				var thisLocation = window.location.toString();
				thisLocation = thisLocation.split("#");
				if (imgName.length > 0) 
					window.location.replace(thisLocation[0] + "#img=" + imgName);
				else 
					window.location.replace(thisLocation[0] + "#");
			}
			
		},
		
		checkHash: function(){
			var hashItems = {};
			if (window.location.hash != "" && window.location.hash != "#") {
			
				var itms = window.location.hash.substr(1).split("&");
				for (var i = 0; i < itms.length; i++) {
					if (itms[i] != "") {
						var itm = itms[i].split("=");
						if (itm.length > 1) {
							hashItems[itm[0]] = itm[1];
						}
						else {
							hashItems[itm[0]] = true;
						}
					}
				}
			}
			if (hashItems.img) {
				this.loadImage(hashItems.img);
				for (var i = 0; i < this.ImageListArr.length; i++) {
				
					if (unescape(this.ImageListArr[i]) == unescape(hashItems.img)) {
						this.ImageListPtr = i;
						break;
					}
				}
			}
			
		},
		
		imgLoadedF: function(){
			this.imgLoaded = true;
			this.checkDoneLoading();
			
			
			if (!$("ImagePopupImg").complete) {
				
				window.setTimeout(this.imgLoadedF.bindAsEventListener(this), 100);
				return;
			}

			$("ImagePopupImg").show();
			var maxH = window.height ? window.height : window.innerHeight ? window.innerHeight : document.body.clientHeight;
			var maxW = window.width ? window.width : window.innerWidth ? window.innerWidth : document.body.clientWidth;
			var heightResized = false;
			//maxH = maxH - 340;
			var elm = $$(".ImagePopupMeta")[0];
			maxH = maxH - elm.getHeight() - 100;
			maxW = maxW - 100;
			var imgHeight = $("ImagePopupImg").height;
			var imgWidth = $("ImagePopupImg").width;
			if (maxH < 130) {
				this.updateHash("");
				
				window.location = this.base + this.ImageLink + this.CurrentImage;
				
			} 
			
			if ((maxH) <= imgHeight) {
				$("ImagePopupImg").height = maxH;
				heightResized = true;
			}
			if ((maxW) <= imgWidth && !heightResized) 
				$("ImagePopupImg").width = maxW;
			
			$$(".imageSurround")[0].style.height = $("ImagePopupImg").height + 20;
			
			return;
	
			
		},
		
		printClicked: function(){
			window.open(this.base + this.PrintPath + this.CurrentImage);
		},
		
		nextMouseOver: function(){
			objs = $$("." + this.nextImageClass);
			for (var i = 0; i < objs.length; i++) {
				if (!Element.hasClassName(objs[i], this.nextImageVisClass)) {
					Element.addClassName(objs[i], this.nextImageVisClass);
				}
			}
		},
		
		nextMouseOut: function(){
			objs = $$("." + this.nextImageClass);
			for (var i = 0; i < objs.length; i++) {
				if (Element.hasClassName(objs[i], this.nextImageVisClass)) {
					Element.removeClassName(objs[i], this.nextImageVisClass);
				}
			}
		},
		
		prevMouseOver: function(){
			objs = $$("." + this.prevImageClass);
			for (var i = 0; i < objs.length; i++) {
				if (!Element.hasClassName(objs[i], this.prevImageVisClass)) {
					Element.addClassName(objs[i], this.prevImageVisClass);
				}
			}
		},
		
		prevMouseOut: function(){
			objs = $$("." + this.prevImageClass);
			for (var i = 0; i < objs.length; i++) {
				if (Element.hasClassName(objs[i], this.prevImageVisClass)) {
					Element.removeClassName(objs[i], this.prevImageVisClass);
				}
			}
		},
		
		initImageList: function(){
			var imgLists = document.getElementsByTagName(this.ImageListTag);
			this.ImageListArr = new Array();
			for (i = 0; i < imgLists.length; i++) {
				this.ImageListArr.push(imgLists[i].getAttribute("imgName"));
			}
			
			if (this.ImageListArr.length > 1) {
		
			}
			else {
			
				this.CreateStyle("." + this.nextImageClass, "display:none");
				this.CreateStyle("." + this.prevImageClass, "display:none");
				this.CreateStyle("." + this.ImageSlideShowNextClass, "display:none");
			}
		},
		startStopSlideShow: function(){
			var tmpElms = $$("." + this.ImageSlideShowNextClass)
			if (tmpElms.length > 0) {
				if (this.SlideShowRunning == undefined) {
					tmpElms[0].update(this.ImageSlidShowPauseHTML);
					
					this.SlideShowRunning = window.setTimeout(this.slideShowTimeEvent.bindAsEventListener(this), this.slideShowTimeSeconds * 1000);
				}
				else {
					window.clearInterval(this.SlideShowRunning);
					this.SlideShowRunning = undefined;
					tmpElms[0].update(this.ImageSlideShowPlayHTML);
				}
				
			}
		},
		slideShowTimeEvent: function(){
			this.nextSlide();
			
			this.SlideShowRunning = window.setTimeout(this.slideShowTimeEvent.bindAsEventListener(this), this.slideShowTimeSeconds * 1000);
		},
		
		prevSlide: function(){
			if ( ! this.ImageListArr.length ) 
				return;
			this.ImageListPtr--;
			if (this.ImageListPtr < 0) 
				this.ImageListPtr = this.ImageListArr.length - 1;
			if (this.ImageListPtr >= 0) 
				this.loadImage(this.ImageListArr[this.ImageListPtr]);
			
		},
		
		nextSlide: function(){
			if ( ! this.ImageListArr.length ) 
				return;
			this.ImageListPtr++;
			if (this.ImageListPtr >= this.ImageListArr.length) 
				this.ImageListPtr = 0;
			if (this.ImageListPtr >= 0) 
				this.loadImage(this.ImageListArr[this.ImageListPtr]);
			
		},
		
		hideLoading: function(){
			var objs = $$("." + this.nextImageClass);
			for (var i = 0; i < objs.length; i++) 
				Element.show(objs[i]);
			objs = $$("." + this.prevImageClass);
			for (var i = 0; i < objs.length; i++) 
				Element.show(objs[i]);
			
			 var lE = $$("." + this.loadIndicatorClass);
			//var lE = [];
			for (var i = 0; i < lE.length; i++) 
				Element.hide(lE[i]); 
			if ( $("ImagePopupImg"))
				{
				$("ImagePopupImg").show();
				//$$(".imageSurround")[0].style.height = $("ImagePopupImg").height + 20;
			 
				}
			
		},
		
		showLoading: function(){
			var objs = $$("." + this.nextImageClass);
			for (var i = 0; i < objs.length; i++) 
				Element.hide(objs[i]);
			objs = $$("." + this.prevImageClass);
			for (var i = 0; i < objs.length; i++) 
				Element.hide(objs[i]);

			if ( $("ImagePopupImg"))
				$("ImagePopupImg").hide();
			//var lE = $$("." + this.loadIndicatorClass);
			var lE = [];
			for (var i = 0; i < lE.length; i++) 
				Element.show(lE[i]);
			
		},
		
		loadImage: function(imgName){
			var i = 0;
			/*var lE = $$(". " + this.loadIndicatorClass);
			if (!lE.length) 
				window.location.href = base + this.ImageLink + imgName;
				*/
			this.updateHash(imgName);
			this.CurrentImage = imgName;
			this.imgLoaded = false;
			this.datLoaded = false;
			var imgParts = imgName.split("/");
				new Ajax.Request(this.base + this.ImageInformationJSON + imgName + "", {
				onSuccess: this.onGetImageInfo.bindAsEventListener(this),
				onFailure: this.onGetImageFailure.bindAsEventListener(this)
			});
			//this.loading();
			this.showLoading();
				if ( $(this.photoElementId))
			{
				$(this.photoElementId).show();
			} else {
				this.CreatePhotoElement();
			}
			
		
			if ($("ImagePopupImg")) {
				$("ImagePopupImg").removeAttribute("height");
				$("ImagePopupImg").removeAttribute("width");
				$("ImagePopupImg").src = this.imageLibraryLoc + imgParts[0] + "/" + this.ScreenSizePath + imgParts[1] + this.ScreenSizeExt;
			}
			if (!this.photoOpen) 
				this.currentY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

			
			this.photoOpen = true;
			this.ShowOverlay();

			
		},
		checkDoneLoading: function(){
			if (this.imgLoaded && this.datLoaded) 
				this.hideLoading();
		},
		
		onGetImageFailure: function(){
			alert("error occured retry.")
			this.closePopup();
		},
		imageClicked: function(event){
			var imgName = Event.element(event).getAttribute("imgName");
			
			for (var i = 0; i < this.ImageListArr.length; i++) {
				if (this.ImageListArr[i] == imgName) {
					this.ImageListPtr = i;
					break;
				}
			}
			this.loadImage(imgName);
			
		},
		loading: function(){
			document.getElementById("ImagePopupImg").src = "";
		},
		
		doneLoading: function(){
		
		},
		
		tagEncode: function(inStr){
			return inStr.replace(/\//gi, "!@!");
			
		},
		onGetImageInfo: function(transport){
			var resp = eval("(" + this.cleanJSON(transport.responseText) + ")");
			/* ImagePopupTitle
			 * ImagePopupImg
			 * ImagePopupName
			 * ImagePopupSize
			 * ImagePopupSummary
			 * ImagePopupDocDt
			 * ImagePopupKeywords
			 * ImagePopupDocNum
			 * ImagePopupArea
			 * ImagePopupBldg
			 */
			var objs = $$("." + this.ImagePopupClass);
			if (objs.length > 0) {
				Element.show(objs[0]);
				//objs[0].style.zIndex = this.OverlayZindex + 10;
				//objs[0].style.position = "absolute";
				//objs[0].style.top = 20;
				//objs[0].style.left = (Element.getWidth(document.body) / 2) - 400;
				
				
				$("ImagePopupTitle").update(resp["title"]);
				$("ImagePopupGalleryTitle").update("<a href=\"" + this.galLink + resp["gallery"] + "\">" + resp["gallerytitle"] + "</a>");
				$("ImagePopupDocNum").update(resp["docnumber"]);
				if (resp["docnumber"] == "") 
					$("ImagePopupItem_DocNum").hide();
				else 
					$("ImagePopupItem_DocNum").show();
				
				$("ImagePopupName").update(resp["title"]);
				if (resp["title"] == "") 
					$("ImagePopupItem_Name").hide();
				else 
					$("ImagePopupItem_Name").show();
				
				$("ImagePopupSize").update(resp["imagesize"]);
				if (resp["imagesize"] == "") 
					$("ImagePopupItem_Size").hide();
				else 
					$("ImagePopupItem_Size").show();
				
				$("ImagePopupSummary").update(resp["description"]);
				if (resp["description"] == "") 
					$("ImagePopupItem_Summary").hide();
				else 
					$("ImagePopupItem_Summary").show();
				
				$("ImagePopupDocDt").update(resp["docdate"]);
				if (resp["docdate"] == "") 
					$("ImagePopupItem_DocDt").hide();
				else 
					$("ImagePopupItem_DocDt").show();
				
				var kwordArr = resp["keywords"].split(",");
				resp["keywords"] = "";
				for (var i = 0; i < kwordArr.length; i++) {
					if (kwordArr[i] != "") {
						resp["keywords"] += "<a class=\"ImagePopupTag\" href=\"" + this.tagLink + this.trimAll(this.tagEncode(kwordArr[i])) + "/1\">" + this.trimAll(kwordArr[i]) + "</a>";
						if (i < (kwordArr.length - 1)) {
							resp["keywords"] += ", ";
						}
					}
				}
				
				$("ImagePopupKeywords").update(resp["keywords"]);
				if (resp["keywords"] == "") 
					$("ImagePopupItem_Keywords").hide();
				else 
					$("ImagePopupItem_Keywords").show();
				
				$("ImagePopupArea").update(resp["area"]);
				if (resp["area"] == "") 
					$("ImagePopupItem_Area").hide();
				else 
					$("ImagePopupItem_Area").show();
				
				$("ImagePopupBldg").update(resp["buildingnumber"]);
				if (resp["buildingnumber"] == "") 
					$("ImagePopupItem_Bldg").hide();
				else 
					$("ImagePopupItem_Bldg").show();
				
				//document.getElementById("ImagePopupImg").src = this.ScreenSizePath + resp["gallery"] + "/" +  escape(resp["image"]) + "";
				
				scroll(0, 0)
			}
			this.datLoaded = true;
			this.checkDoneLoading();
			this.doneLoading();
		},
		downloadImage: function(){
			var parts = this.CurrentImage.split("/");
			
			window.open(this.base + this.imageLibraryLoc + parts[0] + "/" + this.FullSizePath + parts[1] + this.FullSizeExt);
		},
		
		closePopup: function(event){
			if (this.SlideShowRunning) 
				this.startStopSlideShow();
			//var objs = $$("." + this.ImagePopupClass);
			this.updateHash("");
			if ($(this.photoElementId)) {
					Element.hide($(this.photoElementId));
			}
			this.HideOverlay();
			this.photoOpen = false;
			scroll(0, this.currentY)
		},
		
		HideOverlay: function()
		{
			
	
			if ( $(this.overlayObjectID))
				$(this.overlayObjectID).hide();
				
			if ( Prototype.Browser.IE )
			{
				var bod = document.getElementsByTagName('body')[0];
				
					bod.style.position = "relative";
					bod.style.width = "100%"
					bod.style.height= "100%"
					bod.style.overflow = "auto";
			}
			
		},
		
		ShowOverlay: function()
		{
			if ( $(this.overlayObjectID))
				$(this.overlayObjectID).show();
			else
				this.CreateOverlay();
				
				
			if (!Prototype.Browser.IE) {
				$(this.overlayObjectID).style.position = "fixed";
				
			}
			else {
				var bod = document.getElementsByTagName('body')[0];
				
				bod.style.position = "relative";
				bod.style.width = "100%"
				bod.style.height = "100%"
				bod.style.overflow = "hidden";
				
				var htmlElms = document.getElementsByTagName("html");
				if (htmlElms.length > 0) 
					htmlElms[0].style.height = "100%";
				htmlElms[0].style.overflow = "hidden";
			}
		},
		
		CreateOverlay: function()
		{		
			var elm = document.createElement("div");
			elm.id = this.overlayObjectID;
			document.body.appendChild(elm);
			var style = "position:absolute;	top:0;left:0;margin : 0 0 0 0;padding: 0 0 0 0;width:100%;height:100%;z-index:" + this.OverlayZindex+";background-color:#333;-moz-opacity: 0.8;	opacity:.80;filter: alpha(opacity=80);";
			this.CreateStyle('#' + this.overlayObjectID, style);	
			Event.observe(elm, "click", this.closePopup.bindAsEventListener(this))	
		},
		
		CreateStyle: function(selector, style){
			if ( !document.styleSheets) return;
			var thecss = new Array();
			var lastStyleSheet = document.styleSheets.length - 1;
			if ( lastStyleSheet > 1)
				lastStyleSheet = lastStyleSheet - 1;
			if ( document.styleSheets[lastStyleSheet] && document.styleSheets[lastStyleSheet].cssRules)
			{
				thecss = document.styleSheets[lastStyleSheet].cssRules;				
			} else {
				thecss = document.styleSheets[lastStyleSheet].rules;
			}
			if ( document.styleSheets[lastStyleSheet].insertRule)
				document.styleSheets[lastStyleSheet].insertRule(selector + '{' + style + '}', thecss.length);
			else 
				document.styleSheets[lastStyleSheet].addRule(selector, style, thecss.length);
			
		},
		
		
		trimAll: function(sString){
			while (sString.substring(0, 1) == ' ') {
				sString = sString.substring(1, sString.length);
			}
			while (sString.substring(sString.length - 1, sString.length) == ' ') {
				sString = sString.substring(0, sString.length - 1);
			}
			return sString;
		},
		CheckKeyPress: function(e){
			var kC = (window.event) ? event.keyCode : e.keyCode;
			var Esc = ( window.event) ? 27 : e.DOM_VK_ESCAPE;
			if ( kC == Esc && this.photoOpen)
				this.closePopup();
		}
		
		
	};
	Event.observe(document, "dom:loaded", ImagePopup.initialize.bindAsEventListener(ImagePopup));
	ImagePopup.removeHrefLinks();

};

