currentImagePath  = null;
commentsHidden = true;
shortcutKeysEnabled = true;
activeCommentRequest = null;

function pageLoaded()
{
	disableShortcutsWhileInFocus();
	setEventListener(keyPressListener);
}
function disableShortcutsWhileInFocus()
{
	dis = function () {
		console.log("AA:!!!!");
		shortcutKeysEnabled = false;
	}
	var fnc = function(i, el){
		el.onfocus = function () { shortcutKeysEnabled = false;}
		el.onblur = function () { shortcutKeysEnabled = true;}
	};
	jQuery("input[type=text]").each (fnc);
	jQuery("textarea").each (fnc);
}
function toggleComments()
{
	toggleVisibility('commentsSlot');
}



minop = 0.0;
maxop = 1.0;
function arrowFadeout(id)
{
	new Effect.Opacity(id,
   		{ duration: 0.1,
     		transition: Effect.Transitions.linear, 
     		from: maxop, to: 0.6
     		 }
     	);
}
function arrowFadein(id)
{
	$(id).style.opacity = 1.0;
}

function navbarFadein()
{
	new Effect.Opacity('slideNavBar',
   		{ duration: 0.1,
     		transition: Effect.Transitions.linear, 
     		from: minop, to: maxop
     		 }
     	);
}
function navbarFadeout(delay)
{
	new Effect.Opacity('slideNavBar',
   		{ duration: 0.6, 
     		transition: Effect.Transitions.linear, 
     		from: maxop, to: minop }
     	);
}
		

function toggleVisibility(id)
{
	if (Element.visible(id))
		Element.hide(id);
	else
		Element.show(id);
}		

function keyPressListener(event) 
{
	if (!shortcutKeysEnabled)
		return false;
	if (typeof(zenGalleryKeyBindings) == 'undefined')
	{
		console.warn('zenGalleryKeyBindings is not defined, maybe page is not loaded yet.');
		return;
	}
	if (!event) event = window.event;
	if (!event) return;

	var keyCode = event.keyCode?event.keyCode:event.charCode;
  	key = String.fromCharCode(keyCode).toLowerCase();
  	
  	
  	if (typeof(zenGalleryKeyBindings[keyCode]) != 'undefined')
	{
		var f = zenGalleryKeyBindings[keyCode];
		f();
	}
	if (typeof(zenGalleryKeyBindings[key]) != 'undefined')
	{
		var f = zenGalleryKeyBindings[key];
		f();
	}
   return false;
}

function setEventListener(eventListener) {
  if (document.addEventListener) document.addEventListener('keypress', eventListener, true);
  else if (document.attachEvent) document.attachEvent('onkeydown', eventListener);
  else document.onkeydown = eventListener;
}
function unsetEventListener(eventListener)
{
	document.detachEvent('onkeydown', eventListener);
}

// unsetEventListener(keyPressListener);


//var ExifDialog = Class.create();
//
//ExifDialog.prototype = 
//{
//	initialize: function(id) 
//	{
//		if (typeof(id) == 'undefined' || id == null || id == '')
//			throw "Cannot initialize dialog with no ID";
//		this.id = id;
//	},
//	show: function() {
//		if (currentImagePath != null) 
//			Element.show(this.id); 
//	},
//	hide: function() { Element.hide(this.id);},
//	toggle: function() 
//	{ 	
//		if (currentImagePath == null && Element.visible(this.id) == false)
//			return;
//		this.refresh();
//		Element.toggle(this.id);
//	},
//	refresh: function() {
//		var keys = ['d', 'c', 's', 'a', 'fo', 'i', 'ev', 'fl', 'm'];
//		try 
//		{
//			var data = zenExifArray[currentImagePath];
//			for (i=0; i< keys.length; i++)
//			{
//				try {
//					var key = keys[i];
//					if (typeof(data[key]) == 'undefined' || data[key] == null)
//						throw "undefined value";
//					$('exif:' + key).innerHTML = data[key];
//				} 
//				catch (e) 
//				{
//					$('exif:' + key).innerHTML = 'N/A';
//				}
//			}
//		}
//		catch (e)
//		{
//			console.warn('Exif dialog refresh failed!');			
//		}
//	}
//};
//exifDialog = new ExifDialog('zen-img-exif-container');

function initExifDialog() {
	if (typeof(exifDialog) == 'undefined')
	{
		exifDialog = ZenDialog.createFromElement('zen-img-exif-container', 'zen-img-exif-container', 'Exif',
		{
			closeIcon: true,
			minimizeLink: false
		});
		exifDialog.hide();
		exifDialog.toggle = function () { toggleExifDialog(); };
		exifDialog.refresh = function() {
			var keys = ['d', 'c', 's', 'a', 'fo', 'i', 'ev', 'fl', 'm'];
			try 
			{
				var data = zenExifArray[currentImagePath];
				for (i=0; i< keys.length; i++)
				{
					try {
						var key = keys[i];
						if (typeof(data[key]) == 'undefined' || data[key] == null)
							throw "undefined value";
						$('exif:' + key).innerHTML = data[key];
					} 
					catch (e) 
					{
						$('exif:' + key).innerHTML = 'N/A';
					}
				}
			}
			catch (e)
			{
				console.warn('Exif dialog refresh failed!');			
			}
		};
		exifDialog.show = function() {
			if (currentImagePath != null) 
				Element.show(this.id); 
		};
		exifDialog.hide = function() { Element.hide(this.id);};
		
		exifDialog.toggle = function()
		{ 	
			if (currentImagePath == null && Element.visible(this.id) == false)
				return;
			this.refresh();
			Element.toggle(this.id);
		};
		
	}
}	


function toggleExifDialog() 
{	
	exifDialog.toggle();
}

var ZenGallery = Class.create();

ZenGallery.prototype = 
{
	initialize: function()
	{
	},
	keys: { leftArrow: 37, rightArrow: 39}
};
zen = new ZenGallery();

var currImgIdx = 0;

function toggleSearchPanel() 
{
	if (!searchEnabled)
		return;
	Element.toggle('zen-search-bar');
	if (Element.visible('zen-search-bar'))
		$('zen-search-box').focus();  
}
function toggleGoogleTalkPanel () { Element.toggle('google-talk-chatbadge'); }
function toggleHelpPanel() { Element.toggle('helpContainer'); }
function toggleTagPanel() 
{	
	if (typeof(tagDialog) == 'undefined')
	{
		tagDialog = ZenDialog.createFromElement('tagList', 'tagList', 'Tag list',
		{
			closeIcon: true,
			minimizeLink: false
		});
		tagDialog.show();
	}
	else
		tagDialog.toggle();
}
function showLoadingInd()
{
	// Element.show('zen-loading');
}
function hideLoadingInd()
{
	// Element.hide('zen-loading');
}
function preloadPrevious()
{
	// preload neighbour images
	try {
		if (typeof(imgCacheArray[0]) != 'undefined')
			imgCacheArray[0] = imgCacheArray[1];
		else
		{	
			var img = new Image();
			img.onload = function() 
			{ 
				// console.log('img preloaded!' + this.src);
			};
			// console.log('preloading img: ' +
			// zen_sir_imgList[currImgIdx-1].f);
			img.src = zen_sir_imgList[currImgIdx+1].f;
			imgCacheArray[0] = img;
		}
	}
	catch(e) {};
	try {	
		var img = new Image();
		img.onload = function() 
		{ 
			// console.log('img preloaded!' + this.src);
		};
		// console.log('preloading img: ' + zen_sir_imgList[currImgIdx-2].f);
		img.src = zen_sir_imgList[currImgIdx-2].f;
		imgCacheArray[1] = img;
	}
	catch(e) {};
}
function preloadNext()
{
	
	try {
		if (typeof(imgCacheArray[3]) != 'undefined')
			imgCacheArray[2] = imgCacheArray[3];
		else
		{
			var img = new Image();
			img.onload = function() 
			{ 
				// console.log('img preloaded!' + this.src);};
				hideLoadingInd();
			}
			// console.log('preloading img: ' +
			// zen_sir_imgList[currImgIdx+1].f);
			showLoadingInd();
			img.src = zen_sir_imgList[currImgIdx+1].f;
			console.log("complete?" + img.complete);
			if (img.complete)
				hideLoadingInd();
			imgCacheArray[2] = img;
		}
	}
	catch(e) {};
	
	try {
		var img = new Image();
		img.onload = function() { 
		// console.log('img preloaded!' + this.src);
		};
		// console.log('preloading img: ' + zen_sir_imgList[currImgIdx+2].f);
		img.src = zen_sir_imgList[currImgIdx+2].f;
		imgCacheArray[3] = img;
	}
	catch(e) {};
}

function refreshIPTC()
{
	var iptc = zen_sir_imgList[currImgIdx].i;
	// console.log("refreshIPTC(): currImgIdx: " + currImgIdx + ", iptc: " +
	// iptc.t + ", " + iptc.c + ", " + iptc.l);
	
	try { $('iptc_title').innerHTML = emptyStr(iptc.t); } catch(e) {};
	try { $('iptc_caption').innerHTML = emptyStr(iptc.c); } catch(e) {};
	try { $('iptc_location').innerHTML = emptyStr(iptc.l); } catch(e) {};
	try { 
		$('iptc_tags').innerHTML = emptyStr(iptc.tg);
		if ($('iptc_tags').innerHTML == "")
			$('tags_c').style.visibility = 'hidden';
		else
			$('tags_c').style.visibility = 'visible';
		
		} catch(e) {}; 
	try { $('iptc_time').innerHTML = emptyStr(iptc.tm); } catch(e) {};
}
function refreshComments()
{
	var cell = $('cmtLst');
   	if ( cell.hasChildNodes() )
   	{
   	    while ( cell.childNodes.length >= 1 )
   	    {
   	        cell.removeChild( cell.firstChild );       
   	    } 
   	}
   	
   	$('commentsLoading').style.display = '';
   	
   	$('cmtCountHolder').style.display = 'none';
   	
	var f = zen_sir_imgList[currImgIdx];
	var url = '?action:getCommentsForImageJSON&id=' + f.id;
	if (activeCommentRequest != null)
		activeCommentRequest.abort();
	activeCommentRequest = new Ajax.Request(url, {
			  method: 'get',
			  onSuccess: function(transport) {
			   	// zenThumbDialog.show();
			   	console.log('ok! Loading image comments for id: ' + f.id + ' finished! Lets refresh!');
			   	var commentArray = eval(transport.responseText);
			   	
			   	

			   	
			   	
			   	$('cmtCount').innerHTML = commentArray.length; 
			   	
			   	if (commentArray.length > 0)
			   		$('cmtCountHolder').style.display = '';
			   	
			   	var tplEl = $('commentTemplate');
			   	for (i=0; i < commentArray.length; i++)
			   	{
			   		var data = commentArray[i];
			   		$('cmtTplBody').innerHTML = data.c;
			   		$('cmtTplLink').href = data.s;
			   		$('cmtTplName').innerHTML = data.n;
			   		$('cmtTplTs').innerHTML = data.t;
			   		var newNode = tplEl.cloneNode(true);
			   		// console.log("TEST:" +
					// newNode.getElementById('cmtTplBody'));
			   		// console.log(data);
			   		newNode.id = 'comment' + i;
			   		newNode.style.display = '';
			   		// console.log("parent: " + $('cmtLst'));
			   		$('cmtLst').appendChild(newNode);
			   		
			   	}
			   	$('commentsLoading').style.display = 'none';
			   	console.log(respObj);
			  },
			  onFailure: function() { alert('fail#1'); }
			});
			 
			// req.abort();
			// console.log("REQUEST:" + );
}
function isFirstImage()
{
	console.log('currImgIdx:' + currImgIdx);
	return (currImgIdx == 0);
}
function isLastImage()
{
	return (typeof(zen_sir_imgList[currImgIdx + 1]) == 'undefined');
}
function zenRefreshImg()
{
	if (isLastImage())
		disableNextArrow();
	if (isFirstImage())
		disablePrevArrow();
	// console.debug('zenRefreshImg()');
	restoreImg();
	// alert('was: ' + currentImagePath + ', is: ' +
	// zen_sir_imgList[currImgIdx].f);
	currentImagePath = zen_sir_imgList[currImgIdx].f;
	$('imageId').value = zen_sir_imgList[currImgIdx].id;
	// console.debug('current img path: ' + currentImagePath);
	/*
	 * if ($('sirImg').src != currentImagePath) { console.log('Setting current
	 * img to : ' + currentImagePath); $('sirImg').src = currentImagePath; }
	 */
	var ii = new Image();
	ii.id = 'sirImg2';
	
	ii.onload = function () {
		wp_w = ii.width;
	   	wp_h = ii.height;
	// console.log('determined img size: ' + wp_w + ', ' + wp_h);
	   	$('sirImg').width = wp_w;
	   	$('sirImg').height = wp_h;
	   	resized = false;
   
   		$('sirImg').src = ii.src;
   		// console.log('id:' + id);
   		// console.log("refreshing EXIF panel");
   		
   		initExifDialog();
		exifDialog.refresh();
		// console.log("refreshing IPTC panel");
		refreshIPTC();
		refreshComments();
		// resizeIPTCDialog()
		$('img-info-only').width = wp_w + 'px';
	}
	ii.src = currentImagePath;
	// var par = $('sirImg').parentNode;
	// par.appendChild(ii);

}
function loadImageFromUrl()
{
	// console.log("Trying to load image from URL");
	var l = window.location.href;
	var pos = l.search(/#(.*)$/);
	if (pos == -1) 
		return; 
	var id = l.substr(pos + 1);
	// console.log('image id from url:' + id);
	var img = null;
	var found = false;
	for (i=0; i < zen_sir_imgList.length; i++)
	{
		if (zen_sir_imgList[i].id == id)
		{	// img = zen_sir_imgList[i];
			// console.log("Found image by id: " + id + ", idx: " + i);
			currImgIdx = i;
			found = true;
			break;
		}
	} 
	// if (found == false)
		// console.log('ID not extracted from URL');
}
function updateNavLinks()
{
	try {
		var id = zen_sir_imgList[currImgIdx - 1].id;
		// var newLink =
	   	$('navPreviousLink').href = '#' + id;
	   	var lo = window.location.href; 
	   	var idx = lo.indexOf('#');
	   	if (idx != -1)
	   	{
	   		var nl = lo.substr(0, idx) + '#' + zen_sir_imgList[currImgIdx].id;
	   		window.location.replace(nl);
	   		
	   	}
	   	else
	   		window.location.replace(lo + '#' + zen_sir_imgList[currImgIdx].id);
   	} catch(e) {}
   	try {
		var id = zen_sir_imgList[currImgIdx + 1].id;
   		$('navNextLink').href = '#' + id
   		var lo = window.location.href; 
	   	var idx = lo.indexOf('#');
	   	if (idx != -1)
	   	{
	   		var nl = lo.substr(0, idx) + '#' + zen_sir_imgList[currImgIdx].id;
	   		window.location.replace(nl);
	   	}
	   	else
	   		window.location.replace(lo + '#' + zen_sir_imgList[currImgIdx].id);
   	}
   	catch(e) {} ;
}
function disablePrevArrow() {
	//$('prevImg').src = 'images/arrowl_dis.png';	
	$('prevImg').src = 'images/arrow-left-disabled.png';
}
function enablePrevArrow() {
	$('prevImg').src = 'images/arrow-left.png';	
}
function disableNextArrow() {
	$('nextImg').src = 'images/arrow-right-disabled.png';	
}
function enableNextArrow() {
	$('nextImg').src = 'images/arrow-right.png';	
}
function zenNavPreviousImg() 
{
	enableNextArrow();
	
	if (currImgIdx > 0)
		--currImgIdx;
	if (currImgIdx == 0)
		disablePrevArrow();
	
	zenRefreshImg();
	refreshComments();
	updateNavLinks();
   	
	preloadPrevious();
	preloadNext();
	try { updateSlide(); } catch (e) { console.info ('Error: ' + e); }
}

function zenNavNextImg() 
{
	if (typeof(zen_sir_imgList[currImgIdx + 1]) == 'undefined')
		return;
	enablePrevArrow();
	++currImgIdx;
	if (typeof(zen_sir_imgList[currImgIdx + 1]) == 'undefined')
		disableNextArrow();

	zenRefreshImg();
	refreshComments();
	updateNavLinks();
   	
	preloadNext();
	preloadPrevious();
	try { updateSlide(); } catch (e) { console.info ('Error: ' + e); }
}

function toggleAlbumsPanel()
{
	if (typeof(albumDialog) == 'undefined')
	{
		var url = '?action:ajaxAlbumList';// /proxy?url=' +
											// encodeURIComponent('http://www.google.com/search?q=Prototype');
		// notice the use of a proxy to circumvent the Same Origin Policy.
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) {
		    albumDialog = ZenDialog.createFromElement(null, 'albumList', 'Albums',{
		    	minimizeLink: false,
		    	useOverlayBackground: true});
		    albumDialog.setContent(transport.responseText);
		    albumDialog.show();
		  },
		  onFailure: function() { alert('fail#2'); }
		});
		
	}
	else
		albumDialog.toggle();
}

function emptyStr(str)
{
	if (typeof(str) == 'undefined' || str == null)
		return '';
	else
		return str;
}

_slidebar_close_timer = null;
function showSlideBar()
{
	// console.log('show slidebar');
	clearTimeout(_slidebar_close_timer);
	// console.log('_slidebar_close_timer:' + _slidebar_close_timer);
	if (_slidebar_close_timer == null)
	{
		try {
			new Effect.Appear('albumNav', { duration: 0.2, from: 0.05, to: 1.0 });
		}
		catch(e) { // may be not loaded yet
		}
		try { 
			new Effect.Appear('zen-gallery-copyright', { duration: 0.2, from: 1.0, to: 0 });
		}
		catch(e) { // may be not loaded yet
		}
	}
}
function slidebarFadeout()
{
	new Effect.Appear('albumNav', { duration: 0.3, from: 1.0, to: 0.05 });
	clearTimeout(_slidebar_close_timer);
	_slidebar_close_timer = null;
	new Effect.Appear('zen-gallery-copyright', { duration: 0.2, from: 0, to: 1 });
}
function hideSlideBar()
{
	// console.log('hide slidebar');
	_slidebar_close_timer = setTimeout("slidebarFadeout()", 500);
}
function startZen()
{
	
	buildSlidebar();
	if (zen_sir_imgList.length > 0) 
		initExifDialog();
	
	lightboxKeyBindings['f'] = function() {fitCurrentImageToWindow();}
	lightboxKeyBindings['r'] = function() {restoreImage();}
	try {
		$(imageLoadedOnStartup).onclick();
	}
	catch (e) {}
	
	zenGalleryKeyBindings  = {
		't': toggleTagPanel,
		'h': toggleHelpPanel,
		'?': toggleHelpPanel,
		'e': function () { exifDialog.toggle(); },
		'i': function () { exifDialog.toggle(); },
		37: zenNavPreviousImg,
		'j': zenNavPreviousImg,
		39: zenNavNextImg,
		'k': zenNavNextImg,
		'f': fitImgToWindow,
		'r': restoreImg,
		's': toggleSearchPanel,
		'g': toggleGoogleTalkPanel,
		'c': toggleComments 
	}
	if (albumsEnabled) 
		zenGalleryKeyBindings['a'] = toggleAlbumsPanel;
	
	
	/*
	cdlg = new ZenDialog.createFromElement('commentsSlot', 'commentsSlot', 'Comments',{
		closeIcon: true,
		minimizeLink: false
	});*/
}

function scrollToTop()
{
	scroll(0,0);
}
function setCookie(cookieName,cookieValue,nDays) {
		 var today = new Date();
		 var expire = new Date();
		 if (nDays==null || nDays==0) nDays=1;
		 expire.setTime(today.getTime() + 3600000*24*nDays);
		 document.cookie = cookieName 
		 		+ "="+escape(cookieValue)
                + ";expires="+expire.toGMTString();
}
function getCookie(cookieName) {
	 var theCookie=""+document.cookie;
	 var ind=theCookie.indexOf(cookieName);
	 if (ind==-1 || cookieName=="") return ""; 
	 var ind1=theCookie.indexOf(';',ind);
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function getDimensionsForPrescaledImg(windowDimensions, availablePrescaledDimensions)
{
	var w;
	var h;
	
	var wd = windowDimensions;
	
	for (var i= availablePrescaledDimensions.length - 1; i >= 0; i--)
	{
		var ad = availablePrescaledDimensions[i]; 
		// console.debug('available: ' + ad.w + 'x' + ad.h);
		if (ad.w <= wd.w && ad.h <= wd.h)
		{
			// console.debug('found: ' + ad.w + 'x' + ad.h);
			return {w: ad.w, h: ad.h};
		}
	}
	// console.debug('no suitable dimensions found!');
}
function windowSizeHasChanged()
{
	var cookieId = 'zen_window_dimensions';
	var wdimCookie = getCookie(cookieId);
	if (wdimCookie == '')
		return true;
	else
	{
		var code = 'var arg = ' + wdimCookie + ';';
		eval(code);
		var wd = getWindowDimensions();
		if (arg.w !=  wd.w || arg.h != wd.h)
			return true;
		else
			return false;
	}
}
	
function updateImageList(tag,album)
{
		var wd = getWindowDimensions();
		var scrSizeCookie = '{"w": ' + wd.w + ', "h": ' + wd.h + '}';
		
		setCookie(cookieId, scrSizeCookie, 100);
		
		var url = '?action:currenItemListJSON&size=' + wd.w + 'x' + wd.h;
		if (tag)
		{
			url += '&tag=' + tag;
		}
		if (album)
		{
			url += '&album=' + album;
		}
		// alert(url);
		try {
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) {
		  	
		  	// alert('currImgIdx:' + currImgIdx);
		  	zen_sir_imgList = eval(transport.responseText);
		  	// console.debug('got updated zen_sir_imgList');
		  	// alert(zen_sir_imgList[currImgIdx].f);
		  	zenRefreshImg();
		  	// alert('refreshed');
		  	updateSlidebarWithResizedImages();
		  },
		  onFailure: function() { alert('fail#3'); }
		});
		}
		catch(e)
		{
		alert('klaida');
		}
	}
	
	
var _modernBrowser =
(
function() 
{
	var m, u = navigator.userAgent.toLowerCase();
	function ua(s) {return u.indexOf(s) >= 0;}
	if (ua('opera') || ua('konqueror')) 
	{
		return false;
	} 
	else if (m = u.match(/safari\/(\d+)/)) 
	{
		return (Number(m[1]) >= 412);
	} else if (m = u.match(/msie (\d)\.(\d)/)) {
		return (Number(m[1]) >= 6);
	} else if (ua('gecko')) {
		m = u.match(/rv:(\d)\.(\d)/)
	return Number(m[1]) >= 2 || (Number(m[1]) == 1 && Number(m[2] >= 8));
	}
	return false;
})();


function updateSlidebarWithResizedImages()
{
	console.log('updateSlidebarWithResizedImages()');
	var l = zen_sir_imgList;
	
	try {
	jQuery('#bottom_slide_carousel > li div a').each (
		function(i)
		{
			this.href = zen_sir_imgList[i].f;
		}
	);
	}
	catch(e) { console.warn('klaida ar pan' + e.message); } 
	/*
	 * for(i=0; i < l.length; i++ { }
	 */
}
function minimizeSlidebar()
{
	console.log("minimizeSlidebar()");
	var p = $('bottom_slide_carousel'); 
	p.style.left = oldleft;
	p.style.width = oldwidth;
	var div = $('albumNav');
	// div.style.position = 'relative';
	div.style.top = '10px';
	div.style.left = '10px';
	div.style.bottom = '10px';
	div.style.overflow = 'hidden';
	$('slidebarToggleLink').onclick = expandSlidebar;
	$('expImg').src = 'images/arrow-up.gif';
	$('albumNav').onmouseover = showSlideBar;
	$('albumNav').onmouseout = hideSlideBar;
}
function expandSlidebar()
{
	console.log("expandSlidebar()");
	var p = $('bottom_slide_carousel'); 
	oldleft = p.style.left;
	oldwidth = p.style.width; 
	p.style.left = 'auto';
	p.style.width = 'auto';
	var div = $('albumNav');
	// div.style.position = 'absolute';
	div.style.top = 'auto';
	div.style.left = '10px';
	div.style.bottom = '30px';
	div.style.overflow = 'auto';
	$('slidebarToggleLink').onclick = minimizeSlidebar;
	$('expImg').src = 'images/arrow-down.gif';
	showSlideBar();
	$('albumNav').onmouseover = null;
	$('albumNav').onmouseout = null;
	console.log(slidebar);
}


/** *********** Zen dialog ************** */

var ZenDialog = Class.create();

ZenDialog.focusedDialog = null;
ZenDialog.defaultOptions = {
	minimizeLink: false,
	closeIcon: true,
	useOverlayBackground: false,
	overlayBackgroundAsCloseLink: false
}

ZenDialog.registry = new Array();
ZenDialog.maxZIndex = 1;
ZenDialog.closeById = function (id)
{
	var instance = ZenDialog.registry[id];
	instance.hide();
};
ZenDialog.close = function (id)
{
	Element.hide(id);
};
ZenDialog.createFromElement = function (id, elementId, title, options)
{
		if (!id)
			id = 'zenDialog_' + elementId;
		var dlg = new ZenDialog(id, title, options);

		var content = $(elementId);
		var p = content.parentNode;
		
		p.removeChild(content);
		dlg.setContent(content.innerHTML);
		
		return dlg;
};
ZenDialog.prototype = 
{
	initialize: function(id, title, options)
	{
		Object.extend(this.options, ZenDialog.defaultOptions);
		Object.extend(this.options, options || {});
		var div = document.createElement('div');
		div.id = id;
		this.id = id;
		div.className = "zen-dialog";
	
		if (this.options.minimizeLink)
		{
			var minimizeBarHTML = '\
				<div>\
				<a onclick="ZenDialog.closeById(\'' + id + '\'); return false;" href="#">\
					<div class="minimize-dlg-bar">&nbsp;</div>\
				</a>\
				</div>\
				';	
			div.innerHTML = minimizeBarHTML;
		}
			
		var divTitleBar  = document.createElement('div');
		divTitleBar.id = id + '-titlebar';
		divTitleBar.className = 'zen-dlg-titlebar';
		
		 
		var divTitle = document.createElement('div');
		divTitle.className = "dialog-title";
		divTitle.innerHTML = title;
		var notitle = false;
		if (typeof(title) == 'undefined' || title == null || title == '')
		{
			 divTitle.style.display = 'none';
			 notitle = true;
		}
		divTitleBar.appendChild(divTitle);
		
		if (this.options.closeIcon)
		{
			/*
			 * 
			 * var closeIcon = document.createElement('div');
			 * closeIcon.className = 'zen-dlg-close-icon'; closeIcon.innerHTML = '<a
			 * href="#" onclick="ZenDialog.closeById(\'' + id + '\'); return
			 * false;" alt="[x]"><img src="images/dlg_close.png"/></a>';
			 * divTitleBar.appendChild(closeIcon);
			 */
			var closeIcon = document.createElement('A');
			closeIcon.className = 'zen-dlg-close-icon';
			closeIcon.setAttribute('onclick', 'ZenDialog.closeById(\'' + id + '\'); return false;');
			closeIcon.setAttribute('href', '#');
			closeIcon.setAttribute('alt', '[x]');
			var closeIconImg = document.createElement('IMG');
			closeIconImg.setAttribute('src', 'images/closebox-s.png');
			closeIcon.appendChild(closeIconImg);
			divTitleBar.appendChild(closeIcon);
		}	
		
		div.appendChild(divTitleBar);
		if (notitle)
			div.appendChild(document.createElement('br'));
			
		var spanContent = document.createElement('div');
		spanContent.id = id + '-content';
		spanContent.className = 'dialog-content';
		this.contentId = spanContent.id;
		div.appendChild(spanContent);
		document.body.appendChild(div);
		/** blur other dialogs ***/
//		for (el in ZenDialog.registry)
//		{
//			alert(ZenDialog.registry[el]);
//		}
		ZenDialog.registry[id] = this;
		
	},
	options: {},
	focused: false,
	createOverlayBackground: function () {
		console.debug('>>>createOverlayBackground()');
		var overlay = document.createElement('div');
		var id = 'zen-dialog-overlay';
		overlay.id = id;
		var arrayPageSize = getPageSize();
		document.body.appendChild(overlay);
//		Element.setWidth(id, arrayPageSize[0]);
//		Element.setHeight(id, arrayPageSize[1]);
		console.debug('<<<createOverlayBackground()');
	},
	destroyEverlayBackground: function()
	{
		console.debug('>>>destroyEverlayBackground()');
		try
		{
			var el = $('zen-dialog-overlay');
			document.body.removeChild(el);
		}
		catch (e) {
			console.warn('ERROR: destroyEverlayBackground():' + e.message);
		};
		console.debug('<<<destroyEverlayBackground()');
	},
	focus: function ()
	{
		if (!this.focused)
		{
			this.initialZIndex = $(this.id).style.zIndex;
			$(this.id).style.zIndex = 80;
			this.focused = true;
		}
		
		for (idx in ZenDialog.registry) { 
			if (idx != this.id) {
				try {
					ZenDialog.registry[idx].hide();
				}
			  	catch (e) {};
			}
			  
		}
		 
	},
	blur: function()
	{
		if (this.focused)
		{
			$(this.id).style.zIndex = this.initialZIndex; 
			this.focused = false;
		}
	},
	getId: function()
	{
		return this.id;
	},
	setContent: function (content)
	{
		console.log("CONTENT: " + content);
		console.log("this.contentId: " + this.contentId);
		console.log("$(this.contentId): " + $(this.contentId));
		$(this.contentId).innerHTML = content;
	},
	setContentElement: function (content)
	{
		$(this.contentId).appendChild(content);
	},
	toggle: function() 
	{
		console.log('toggle()');
		console.debug('toggle()');
		if (Element.visible(this.id))
		{
			console.debug('hide ' + this.id);
			this.hide();
		}
		else 
		{
			console.log('show ' + this.id);
			this.show();
			this.focus();
		}
	},
	show: function() {	
		console.log('>>>show()');
		console.log('this.options.useOverlayBackground: ' + this.options.useOverlayBackground);
		if (this.options.useOverlayBackground)
			this.createOverlayBackground();
		Element.show(this.id);
		this.focus();	
		console.log('<<<show()');
	},
	hide: function() 
	{
		console.log('>>>hide()');	
		if (this.options.useOverlayBackground)
			this.destroyEverlayBackground();
		Element.hide(this.id);
		this.blur();	
		console.log('<<<hide()');
	}
};

/** ********************************************************** */
function openThumnailDialog()
{
	if (typeof(zenThumbDialog) == 'undefined')
	{ 
		zenThumbDialog = new ZenDialog('thumb-dlg', '', 
			{
				closeIcon: false,
				minimizeLink: true,
				useOverlayBackground: false
			});
		zenThumbDialog.hide();
		
		var orig = $('bottom_slide_carousel').parentNode;
		// console.log(ul);
		var origDiv = orig.cloneNode(true);
		// console.log("HTML:" + ul.outerHTML);
		var n = origDiv.firstChild;
		n.setAttribute('id', 'expandedBottomSlide');
		n.style.width = 'auto';
		n.style.height = 'auto';
		n.style.left = null;
		// console.log(n.innerHTML);
		// query for css = jcarousel-item, set width: auto, height:auto,
		// padding: 2(?)px
		zenThumbDialog.setContentElement(origDiv);
		// jQuery('#thumb-dlg > li').hide();
		myLightbox.updateImageList();
		
		zenThumbDialog.show();

		/*
		 * var url = '?action:ajaxAlbumList'; new Ajax.Request(url, { method:
		 * 'get', onSuccess: function(transport) {
		 * zenThumbDialog.setContent(transport.responseText);
		 * zenThumbDialog.show(); }, onFailure: function() { alert('fail#'); }
		 * });
		 */
	}
	else
	{
		zenThumbDialog.show();
	}
	scrollToTop();
}

function zenZoomIn()
{
	var f = zen_sir_imgList[currImgIdx];
	var url = '?action:getBiggerImage&id=' + f.id;
			new Ajax.Request(url, {
			  method: 'get',
			  onSuccess: function(transport) {
			    // zenThumbDialog.setContent(transport.responseText);
			   	// zenThumbDialog.show();
			   	console.log('ok!');
			  },
			  onFailure: function() { alert('fail#4'); }
			});
	console.log('zenZoomIn();');
}
function zenZoomOut()
{
	console.log('zenZoomOut();');
}
function dump(o)
{
	var ret = '';
	for (idx in o)
	{
		ret += idx + ' => ' + o[idx] + "\r\n";
	}
	return ret;
}
function openCurrentImageInLightbox()
{
	var currLightboxImg = this;
	var f = zen_sir_imgList[currImgIdx];
	var q = '#bottom_slide_carousel a[href="' + f.f + '"]';
	var anchor = jQuery(q);
	anchor.click();
 
}

function buildSlidebar()
{
	if ( jQuery("#bottom_slide_carousel").length > 0 ) {
		jQuery('#bottom_slide_carousel').jcarousel({
			initCallback: function(carousel)
			{
			    updateSlide = function() {
			        carousel.scroll(currImgIdx, 0);
			        return false;
			    }; 
			    Element.show('albumNav');
			}
		});
	}
	else 
	{
		console.debug('Slide bar not exists/disabled.');
		updateSlide = function () {};
	}
		
}

function submitComment(btn)
{
	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

	var url = '?action:postComment';
	
	url += '&imageId=' + $('imageId').value;
	url += '&name=' + $('name').value;
	url += '&site=' + $('site').value;
	url += '&email=' + $('email').value;
	url += '&commentBody=' + $('commentBody').value;
	
	if ($('name').value.trim() != "" && $('commentBody').value.trim() != "" && $('email').value.trim() != "")
	{
	
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				$('commentBody').innerHTML = '';
				$('commentBody').value = '';
				console.log('finished posting comment');
				refreshComments();
			},
			onFailure: function() { alert('fail#5'); }
		});
	}
	else
	{
		alert('"Name", "Email" and "Comment" fields are mandatory!');
	};
// btn.form.submit();
}
