/*
 * Created on 25/04/2007
 *
 * File: utils.js
 * Author: Bryan Rentoul
 *
 * JavaScript utilities -- mainly to support ajax function provided
 * by prototype.js and rico.js
 *
 */

/**
 * Site wide constants
 */
var keyBlue = '#22479f';
var keyGreen = '#097f45';
var keyPurple = keyViolet = '#703f8b';
var keyYellow = keyAmber = keyMustard = '#e8af24';
var keyOrange = '#d0602e';

/**
 * Centers the supplied DIV object in the centre of the 
 * current viewport (x/y scroll positions included)
 */

function getFrameWidth() {
	if (self.innerWidth)
		return self.innerWidth;
	else if (document.documentElement 
			&& document.documentElement.clientWidth) 
		return document.documentElement.clientWidth;
	else if (document.body)
		return document.body.clientWidth;
}

function getFrameHeight() {
	if (self.innerHeight)
		return self.innerHeight;
	else if (document.documentElement 
			&& document.documentElement.clientHeight) 
		return document.documentElement.clientHeight;
	else if (document.body)
		return document.body.clientHeight;
}

/**
 * oContainer is an optional container div within which to center the image div (BJR)
 */
function centerDiv(oDiv, oContainer) {
	if (typeof(oDiv) != 'object' || oDiv.tagName != 'DIV') return;	
	if (typeof(oContainer) == 'undefined'
		|| oContainer == null 
		|| typeof(oContainer) != 'object' 
		|| oContainer.tagName != 'DIV') oContainer = null;	

	if (oContainer) { // scroll position not relavent if centering inside existing div
		var containerWidth = oContainer.clientWidth;
		var containerHeight = oContainer.clientHeight;
		var topOffset = oContainer.offsetTop;
		var	leftOffset = oContainer.offsetLeft;
		var width = oDiv.clientWidth;
		var height = oDiv.clientHeight;
		var top = topOffset + Math.floor(containerHeight / 2) - Math.floor(height / 2);
		var left = leftOffset + Math.floor(containerWidth / 2) - Math.floor(width / 2);
		if (top < 0) top = 0;
		if (left < 0) left = 0;			
	} else {		
		var frameWidth = getFrameWidth();
		var frameHeight = getFrameHeight();
		var	scrollXOffset = 0;
		var scrollYOffset = 0;
		var width = oDiv.clientWidth;
		var height = oDiv.clientHeight;
		var left = 0;
		var top = 0;

		// Find scroll positions
		if (window.innerHeight) {
			scrollXOffset = window.pageXOffset
			scrollYOffset = window.pageYOffset
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scrollXOffset = document.documentElement.scrollLeft;
			scrollYOffset = document.documentElement.scrollTop;
		} else if (document.body) {
			scrollXOffset = document.body.scrollLeft;
			scrollYOffset = document.body.scrollTop;
		}
	
		left = Math.floor((frameWidth / 2) - (width / 2));
		top = Math.floor((frameHeight / 2) - (height / 2));
	
		left += scrollXOffset;
		top += scrollYOffset;
	}
	
	$(oDiv).css({
		top: top+'px',
		left: left+'px',
		width: width+'px',
		height: height+'px'
	});
}
/**
 * Helper function for popupMessage. Adds a hidden message div to 
 * doc'.body if not already there
 */
function addPopupMsgDiv() {
	var msgDiv = document.getElementById('msgDiv')
	if (msgDiv) {
		msgDiv.innerHTML = '';
		msgDiv.style.width='300px';
		msgDiv.style.height='60px';
		return msgDiv;
	}

	var msgDiv = document.createElement('div');
	msgDiv.id = 'msgDiv';
	document.body.appendChild(msgDiv);
	return msgDiv;
}

/**
 * Implements a popup message window, which can auto-hide
 *
 * @param Message to dispaly
 * @param (optional) true = auto-hide, flase = stay visible. Use hidePopopMessage()
 *					 to manually hide.
 * @param (optional) time to stay visible in ms (default 1000)
 */
var popupMessageTimer = null;
var popupDelayTimer = null;
function popupMessage(sMsg, bAutoHide, iTimeout) {
	if (typeof bAutoHide == 'undefined') bAutoHide = true;
	if (typeof iTimeout == 'undefined') iTimeout = 1000;

	var msgDiv = addPopupMsgDiv(); 	// if not already there

	if (popupMessageTimer)
		clearTimeout(popupMessageTimer);
	if (popupDelayTimer)
		clearTimeout(popupDelayTimer);

	msgDiv.innerHTML = sMsg;
	centerDiv(msgDiv);
	msgDiv.style.visibility = 'visible';
	msgDiv.style.cursor = 'pointer';
	msgDiv.title = 'click to close';		
	msgDiv.onclick = function() { this.style.visibility = 'hidden'; }
	if (bAutoHide) popupMessageTimer = setTimeout('hidePopupMessage()', iTimeout);
}

function delayedPopupMessage(sMsg, iDelay) {
	if (typeof iDelay == 'undefined') iDelay = 1200; // 1.2 second default delay

	if (popupDelayTimer) clearTimeout(popupDelayTimer);
	popupDelayTimer = setTimeout('popupMessage(\''+sMsg+'\', false)', iDelay)	
}
	
function hidePopupMessage() {
	if (!document.getElementById('msgDiv')) return;
	if (popupDelayTimer) clearTimeout(popupDelayTimer);
	if (popupMessageTimer) clearTimeout(popupMessageTimer);
	document.getElementById('msgDiv').style.visibility = 'hidden';
}

/**
 * BEGIN: Fullsize iamge window functions. (Pre and post jQuery hybrid. Needs tidying up, maybe)
 */
function addFullImgDiv() {
	// remove any existing image window div
	if ($('#fullImageWindow')[0]) $('#fullImageWindow').remove();

	if (!$('#imageOverlay')[0]) {
		var imageOverlayDiv = document.createElement('div');
		imageOverlayDiv.id ='imageOverlay';
		imageOverlayDiv.style.visibility = 'hidden';
		document.body.appendChild(imageOverlayDiv);
	} else {
		var imageOverlayDiv = $('#imageOverlay')[0];
	}
	$('#imageOverlay')[0].style.width = $(document.body).innerWidth() + 'px';
	$('#imageOverlay')[0].style.height = $(document.body).innerHeight() + 'px';

	var fullImageDiv = document.createElement('div');
	fullImageDiv.id = 'fullImageWindow';
	fullImageDiv.style.visibility = 'hidden';

	var titleBar = document.createElement('div');
	titleBar.id = 'fullImageTitleBar';

	var imgTitle = document.createElement('div');
	imgTitle.id = 'fullImageTitle';
	titleBar.appendChild(imgTitle);

	var closeButton = document.createElement('div');
	closeButton.id = 'fullImageTitleButton';
	closeButton.className = 'fullImageTitleButton'; // must be class for hover to work *shrug*
	titleBar.appendChild(closeButton);
	$(closeButton).hover( 
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
	fullImageDiv.appendChild(titleBar);

	var imgDiv = document.createElement('div');
	imgDiv.id = 'fullImageWindowImageDiv';	
	fullImageDiv.appendChild(imgDiv);
	
	$(fullImageDiv).bind('click', function(e) {
		closeFullImage();
	});
	
	document.body.appendChild(fullImageDiv);
}

/**
 * oDiv is an optional div within which to center the image div
 * Uses ajax to retrieve image dimensions if iWidth and iHeight are 0
 */
function showFullImage(sPath, sTitle, iWidth, iHeight, oDiv) {
	if (typeof iWidth == 'undefined') iWidth = 0;
	if (typeof iHeight == 'undefined') iHeight = 0;
	if (typeof oDiv == 'undefined') oDiv = null;

	// *** Open window straight away so "Loading..." appears for when ajax call takes a while.
		addFullImgDiv();	// replaces existing one if it's already there
		
		$('#fullImageWindowImageDiv').html('<table height="100%" width="100%"><tr><td align="center" valign="middle">'
			+'<img src="images/wait16trans.gif" align="absmiddle"> Loading...'
			+'</td></tr></table>'); // easiest way to vetically centre. I know! Lazy of me. Oh well.
		$('#fullImageTitle').html(sTitle);
	
		centerDiv($('#fullImageWindow')[0], oDiv);
		$('#imageOverlay').css('visibility', 'visible');
		$('#fullImageWindow').css('visibility', 'visible');
	// ***
	
	if (iWidth + iHeight == 0) {
		$.ajax({
			url: '/imageServer.php',
			type: 'GET',
			dataType: 'json',
			data: {
				action: 'getImageSize',
				src: sPath
			},
			success: function(result) {
				if (result) {
					iWidth = result.width;
					iHeight = result.height;
				} 
				_showFullImage(sPath, sTitle, iWidth, iHeight, oDiv);
			},
			error: function(xhr, status) { alert('ERROR:\n\n'+xhr.responseText); }
		});
	} else {
		_showFullImage(sPath, sTitle, iWidth, iHeight, oDiv);
	}
}
function _showFullImage(sPath, sTitle, iWidth, iHeight, oDiv) {
	if (typeof oDiv == 'undefined') oDiv = null;
		
	var maxWidth = 600; // These should probably not be hard-coded. *shrug*
	var maxHeight = 500;
		
	var divWidth = Math.min(maxWidth, Math.max(140, iWidth));
	$('#fullImageWindowImageDiv').css('width', divWidth+'px'); 
	$('#fullImageWindow').css('width', divWidth+'px');

	var divHeight = Math.min(maxHeight, Math.max(100, iHeight));  // allow for title div
	$('#fullImageWindowImageDiv').css('height', divHeight+'px');
	$('#fullImageWindow').css('height', 
		(divHeight + $('#fullImageTitleBar')[0].clientHeight)+'px');
	if (divHeight == 100) $('#fullImageWindowImage').css('margin-top', 
		Math.floor((divHeight-iHeight)/2));
	
	// preload image to allow for "Loading..." message on larger image files over slower connections.
	var img = new Image();
	img.id="fullImageWindowImage";
	img.width=iWidth; // display full-size -- scrollbars will appear if larger that viewing frame
	img.height=iHeight;
	img.style.cursor='pointer';
	img.title='click to close';
	if (iHeight < 100) $(img).attr('vspace', Math.floor((divHeight - iHeight) / 2)); 		 
	$(img).bind('load', function(e) {
		$('#fullImageWindowImageDiv').html('');
		$('#fullImageWindowImageDiv').append(this);
	});
	img.src = '/imageLib'+sPath; // Must be done after event assignment (race condition)
		
	$('#fullImageTitle').html(sTitle);

	centerDiv($('#fullImageWindow')[0], oDiv);
	$('#fullImageWindow').css('visibility', 'visible');
}

/**
 * Allow super-short-form 'onlick' code for images, EG. onclick="fullsize(this)"
 */
function fullsize(img) {
	var src = img.src.match(/^.+\/imageLib(\/.*)/);
	var thumbPath = src[1].replace(/%20/, ' ');
	var fullPath = thumbPath.replace(/\/\.thumbs/, '');
	var title = (img.alt == '') ? 'Enlarged Image' : img.alt;
	showFullImage(fullPath, title);
}
  
function closeFullImage() {
	$('#imageOverlay').css('visibility', 'hidden');
	if ($('#fullImageWindow')[0]) $('#fullImageWindow').remove();
}

function showImageLib() {
	var win = window.open(
		'/control/imageSelect.php', 
		'imageLib', 
		'width=880,height=410'
	);
	win.focus();
	return win;
}

/**
 * END: Fullsize iamge window functions. (Pre and post jQuery hybrid. Needs tidying up, maybe)
 */
