/*
 * Athena Gallery
 * Revision: 1.1.0
 */

var loadedImg = 0;
var topHeight = 0;
var fullscreen = false;
var galNext = null;
var galPrev = null;
var baseX = 0;
var baseY = 0;
var animA = null;
var animB = null;
var animationTime = 150;
var uploadType = 0;

// For the AED
var index = '';
var getData = "aed=1";
var addData = new Array();
addData[0] = "title";
addData[1] = "desc";
addData[2] = "link"; 

addEvent(window, 'load', init_gallery);

function init_gallery() {
	var fs = document.getElementById('fullscreen');
	if (!fs) return;
	if (fs.value) {
		fullscreen = true;
		topHeight = document.body.offsetHeight - 500;
		resize_window();
	}
	var thumbSize = parseInt(document.getElementById('thumbsize').value) + 50;
	document.getElementById('thumbCol').style.width = thumbSize + 'px';
}

function resize_window() {
	// Expand window to make it full-screen
	if (fullscreen) {
		var viewport = getViewportDimensions();
		var newHeight = viewport.height - topHeight;
		document.getElementById('thumbs').style.height = newHeight + 'px';
		document.getElementById('preview').style.height = newHeight + 'px';
	}
}


// Upload Window
function showUpload(t) {
	// Put the window in position
	openAthenaWindow('fileWindow');
	centerWindow('fileWindow');
	uploadType = t;
	if (t == 0) {
		document.getElementById('download').checked = false;
	} else if (t == 1) {
		document.getElementById('download').checked = true;
	}
}

function hideUpload() {
	closeAthenaWindow('fileWindow');
}

function uploadStart() {
	if (!document.getElementById('uploadFN').value) {
		alert('Please select a file');
		// document.getElementById('uploadFN').click();	// Buggy in IE and Fx
	} else if (!document.getElementById('uploadTitle').value) {
		alert('Please enter a title');
		//elAtt('uploadTitle');	// Buggy in IE
		document.getElementById('uploadTitle').focus();
	} else {
		document.getElementById('fileBox').style.display = 'none';
		document.getElementById('loadingBox').style.display = 'block';
		document.uploadForm.submit();
		checkUpload();
	}
}

function checkUpload() {
	var upKey = document.getElementById('upKey').value;
	ajaxCall(uri+'?action=progress&key='+upKey, 'uploadProgress');
}

function uploadProgress(json) {
	var stat = eval("("+json+")");
	var progress = stat['current'] / stat['total'];
	var elapsed = stat['time'] - stat['start_time'];
	var speed = elapsed == 0 ? 0 : (stat['current'] / elapsed);
	// Just in case progress returns before first update on the server
	if (speed < 0) {
		speed = 0;
		progress = 0;
	}
	var remaining = progress > 0 ? Math.round((elapsed * (1 / progress)) - elapsed) : 0;
	var pMeter = document.getElementById('progressMeter');
	var pSpeed = document.getElementById('progressSpeed'); 
	var pTime = document.getElementById('progressTime'); 
	pMeter.style.width = Math.round(268 * progress)+'px';
	pMeter.innerHTML = Math.round(progress * 100)+'%&nbsp;';
	pSpeed.innerHTML = speed.toSize()+'/s';
	pTime.innerHTML = remaining > 0 ? (remaining.toTime()+' remaining') : '&nbsp;';
	if (stat['current'] < stat['total']) setTimeout('checkUpload()', 100);
}

// Load an image
function loadImg(img) {
	ajaxCall(uri+'?action=loadImg&img='+img, 'img_callback', null, img);
}

function img_callback(txt, img) {
	document.getElementById('preview').innerHTML = txt;
	loadedImg = img;
	showBtn('btnEdit');
	showBtn('btnDel');
}

// Delete an image
function deleteImg() {
	if (!loadedImg) return;
	ajaxCall(uri+'?action=deleteImg&img='+loadedImg, 'imgdel_callback', null);
	var el = document.getElementById('img-'+loadedImg);
	el.parentNode.removeChild(el);
	document.getElementById('preview').innerHTML = "<p>Deleting..</p>";
	hideBtn('btnEdit');
	hideBtn('btnDel');
}

function imgdel_callback(txt) {
	document.getElementById('preview').innerHTML = txt;
	loadedImg = 0;
}

// Edit an image
function editImg() {
	if (!loadedImg) return;
	index = loadedImg;
	ajaxCall(uri+'?aed=1&action=3&index='+loadedImg, 'imgedit_callback', null);
	hideBtn('btnEdit');
}

function imgedit_callback(txt) {
	var el = document.getElementById('preview');
	el.innerHTML = txt;
}

// Load a gallery image
function viewGallery(id) {
	baseX = 500;
	baseY = 285;

	// Modal box must exist first
	if (!document.getElementById('modalBox')) document.body.innerHTML += '<div id="modalBox">&nbsp;</div>';

	// Check for window and create if needed
	var win = document.getElementById('galleryWin');	
	if (!win) {
		document.body.innerHTML += '\
			<div class="puBox" id="galleryWin">\
				<div class="puHeader" id="galleryWin-head">Gallery</div>\
				<div class="puBody" id="galleryWin-body">\
					<div id="galleryWin-face">\
						<a href="javascript://" id="galLink"><img id="galImg" src="/usr/common/images/null.gif" /></a>\
						<div id="galDesc"></div>\
						<div class="galBtns" id="galBtns">\
							<a href="#" onclick="loadSecondary(galPrev); return false;" class="round_button disabled" id="btnGalPrev">&laquo; Previous</a>\
							<a href="#" onclick="closeGallery(); return false;" class="round_button">Close</a>\
							<a href="#" target="_blank" class="round_button hidden" id="btnDownload">Download</a>\
							<a href="#" onclick="loadSecondary(galNext); return false;" class="round_button" id="btnGalNext">Next &raquo;</a>\
						</div>\
					</div>\
				</div>\
			</div>';
		//win = document.getElementById('galleryWin');
		setTimeout('viewGallery('+id+')', 100);
		return;
	}
	
	// Disable buttons
	document.getElementById('btnGalPrev').className = 'round_button disabled';
	document.getElementById('btnGalNext').className = 'round_button disabled';

	changeOpac('galleryWin-face', 0);
	var img = document.getElementById('galImg');
	img.onload = null;
	img.src = '/usr/common/images/null.gif';

	win.style.width = baseX + 'px';
	win.style.height = baseY + 'px';
	var winHead = document.getElementById('galleryWin-head');
	winHead.style.width = baseX - 20 + 'px';
	winHead.innerHTML = '...loading...';

	openModalDialogue('galleryWin');
	ajaxCall('/_std.ajax?action=13&id='+id, 'gallery_load');
}

// Display the gallery
function gallery_load(txt) {
	// JSON receiver
	if (txt == 'ERR') {
		alert('An error occured trying to access this image');
		closeGallery();
		return;
	} else if (txt == 'NOACCESS') {
		alert('You do not have access to this image');
		closeGallery();
		return;
	}
	var row;
	try {
		row = eval("("+txt+")");
	} catch (e) {
		alert(txt);
		return;
	}
	
	galNext = row['next'] ? row['next'] : null;
	galPrev = row['prev'] ? row['prev'] : null;

	var winHead = document.getElementById('galleryWin-head');
	winHead.innerHTML = row['title'];


	var viewport = getViewportDimensions();

	var img = document.getElementById('galImg');
	img.src = '/_std.ajax?action=26&fn=/'+usr()+'images/gallery/'+row['image']+'&att='+(viewport.width-30)+','+(viewport.height-170)+',2';
	img.onload = function() {
		if (this.src == '/usr/common/images/null.gif') return;
		var d = new Date();
		animA = setTimeout("galleryLoadA("+d.getTime()+", "+animationTime+")", 10); 
	};

	var desc = document.getElementById('galDesc');
	desc.innerHTML = row['desc'];
	
	var link = document.getElementById('galLink');
	link.href = row['link'] ? row['link'] : 'javascript://';
	
	// Disable buttons
	if (galPrev) document.getElementById('btnGalPrev').className = 'round_button';
	if (galNext) document.getElementById('btnGalNext').className = 'round_button';
	
	// Download link
	var dLink = row['download'];
	var dEl = document.getElementById('btnDownload');
	var bEl = document.getElementById('galBtns');
	if (dLink.length) {
		dEl.className = "round_button";
		dEl.href = dLink;
		bEl.className = "galBtns download";
	} else {
		dEl.className = "round_button hidden";
		dEl.href = "javascript://";
		bEl.className = "galBtns";
	}
}

function closeGallery() {
	closeModalDialogue('galleryWin');
}

// Special function to do two elements in one
function galleryLoadA(startTime, animTime) {
	var d = new Date();
	var t = d.getTime();

	var img = document.getElementById('galImg');
	var desc = document.getElementById('galDesc');
	var x = Math.max(img.offsetWidth + 22, 400);
	var y = Math.max(img.offsetHeight + desc.offsetHeight + 94, 50);
	
	var win = document.getElementById('galleryWin');
	var winHead = document.getElementById('galleryWin-head');
	var winBody = document.getElementById('galleryWin-body');
	var winFace = document.getElementById('galleryWin-face');
	
	if (t >= startTime + animTime) {
		// Last call - fix size and load the fade-in
		win.style.width = x + 'px';
		win.style.height = y + 'px';
		winBody.style.height = (y - 55) + 'px';
		winHead.style.width = (x-20) + 'px';
		winBody.style.width = (x-20) + 'px';
		winFace.style.width = (x-20) + 'px';
		animB = setTimeout("galleryLoadB("+t+", "+animTime+")", 10); 
	} else {
		var progress = (t - startTime) / animTime;
		win.style.width = (baseX + Math.floor((x - baseX) * progress)) + 'px';
		win.style.height = (baseY + Math.floor((y - baseY) * progress)) + 'px';		
		winBody.style.height = (baseY + Math.floor((y - baseY) * progress) - 55) + 'px';		
		winHead.style.width = (baseX + Math.floor((x - baseX) * progress) - 20) + 'px';
		winBody.style.width = (baseX + Math.floor((x - baseX) * progress) - 20) + 'px';
		winFace.style.width = (baseX + Math.floor((x - baseX) * progress) - 20) + 'px';
		
		// Queue up next frame
		animA = setTimeout("galleryLoadA("+startTime+", "+animTime+")", 10); 
	}
	centerWindow('galleryWin');
}

// Fade in the image
function galleryLoadB(startTime, animTime) {
	var d = new Date();
	var t = d.getTime();
	if (t >= startTime + animTime) {
		// Last call - finish off
		changeOpac('galleryWin-face', 1);
	} else {
		var progress = (t - startTime) / animTime;
		changeOpac('galleryWin-face', progress);
		// Queue up next frame
		animB = setTimeout("galleryLoadB("+startTime+", "+animTime+")", 10); 
	}
}

function loadSecondary(id) {
	if (!id) return;
	
	if (animA) clearTimeout(animA);
	if (animB) clearTimeout(animB);

	// Disable buttons
	document.getElementById('btnGalPrev').className = 'round_button disabled';
	document.getElementById('btnGalNext').className = 'round_button disabled';
	
	galNext = null;
	galPrev = null;
	
	changeOpac('galleryWin-face', 1);
	var img = document.getElementById('galImg');
	var desc = document.getElementById('galDesc');
	baseX = Math.max(img.offsetWidth + 22, 400);
	baseY = Math.max(img.offsetHeight + desc.offsetHeight + 94, 50);

	var winHead = document.getElementById('galleryWin-head');
	winHead.innerHTML = '...loading...';

	var d = new Date();
	var t = d.getTime();
	setTimeout("galleryUnload("+t+", "+animationTime+", " + id + ")", 10); 
}

// Fade out the image
function galleryUnload(startTime, animTime, id) {
	var d = new Date();
	var t = d.getTime();
	if (t >= startTime + animTime) {
		// Last call - finish off and 
		changeOpac('galleryWin-face', 0);
		ajaxCall('/_std.ajax?action=13&id='+id, 'gallery_load'); 
	} else {
		var progress = (t - startTime) / animTime;
		changeOpac('galleryWin-face', 1-progress);
		// Queue up next frame
		setTimeout("galleryUnload("+startTime+", "+animTime+", " + id+")", 10); 
	}
}
