// JavaScript Document for MONA portfolio
TransitionSpeed = 250;

// Calls AJAX to preload images for a given portfolio
function preloadPortfolioImgs(page) {
	AJAX_sendRequest(true, '/pages/portfolio.php?page=' + page + '&fetch=PreloadImages', 'preloadPortfolioImgs_action(response)');
	
	// open first portfolio image
	setPortfolioImg(document.getElementById('PortfolioThumb0'), page);
}

// Preload images
// No errors from AJAX here, should fail gracefullyi
function preloadPortfolioImgs_action(ImgList) {
	ImgTmpElmnt1 = new Array();
	ImgTmpElmnt2 = new Array();
	ImgTmpElmnt3 = new Array();
	
	ImgArray    = ImgList.split('|');
	for (var i in ImgArray) {
		ImgTmpElmnt1[i]     = document.createElement('img');
		ImgTmpElmnt1[i].src = ImgArray[i];
		
		ImgTmpElmnt2[i]     = document.createElement('img');
		ImgTmpElmnt2[i].src = ImgArray[i].replace('.jpg', '_thumb.jpg');
		
		ImgTmpElmnt3[i]     = document.createElement('img');
		ImgTmpElmnt3[i].src = ImgArray[i].replace('.jpg', '_large.jpg');
	}
}

// Set the portfolio image to the selected thumbnail
function setPortfolioImg(ThumbObj, page) {
	
	fadeObj('PortfolioMainImg', 95, 0, TransitionSpeed);
	fadeObj('PortfolioItemDesc', 100, 0, TransitionSpeed);
	fadeObj('PortfolioLoadingNote', 0, 100, TransitionSpeed);
	
	// fetch and set image
	setTimeout("AJAX_sendRequest(true, '/pages/portfolio.php?page=" + page + "&fetch=Image&ImageNum=" + ThumbObj.src.substr(ThumbObj.src.lastIndexOf('/')+1).substr(0,3) + "'," +
	
	// This doesn't seem to preload the image automatically, so wait half a second before displaying the iomage
	"\"if (response.substr(0,7) == 'OUTPUT:') { setPortfolioImg_Action(response); } else { alert(response); }\")", TransitionSpeed + 100);
}

function setPortfolioImg_Action(output) {
	OutputArray = response.substr(7).split('|');
	
	with (document) {
		getElementById('PortfolioMainImg').src        = OutputArray[0];
		getElementById('PortfolioItemDesc').innerHTML = OutputArray[1];
		getElementById('PortfolioEnlargeLink').href   = "javascript: overlayImgOpen('" + OutputArray[0].replace('.jpg', '_large.jpg') + "', '', '" + OutputArray[2] + "')";
	}
	
	setTimeout("fadeObj('PortfolioMainImg', 0, 95, TransitionSpeed); " +
		   "fadeObj('PortfolioItemDesc', 0, 100, TransitionSpeed);" +
		   "fadeObj('PortfolioLoadingNote', 100, 0, TransitionSpeed);",
		   
		   TransitionSpeed * 2);
}

// navigate backwards or forwards through portfolio thumbnails
function setPortfolioNav(Forward, page, Max) {

	ThumbSteps = 3;
	
	// Loop through for initial actions
	for (var i = 0; i < ThumbSteps; i++) {
	
		// get base number
		if (i == 0) {
			ThumbObj   = document.getElementById('PortfolioThumb0');
			srcBaseNum = parseFloat(ThumbObj.src.substr(ThumbObj.src.lastIndexOf('/')+1).substr(0,3));
		}
		
		// beginning/backwards, end/forwards; just kill for now, it might loop around later
		if ((srcBaseNum == 1 && !Forward) || ((srcBaseNum + 2) >= Max && Forward))
			return;
		
		// fade out
		fadeObj('PortfolioThumb' + i, 75, 0, TransitionSpeed);
	}
	
	// Get next/prev set of thumbs
	AJAX_sendRequest(true, '/pages/portfolio.php?page=' + page + '&fetch=ThumbSet&Forward=' + Forward + '&srcBaseNum=' + srcBaseNum, 'setPortfolioNav_action(response)');
}

function setPortfolioNav_action(output) {
		
	// expected output
	if (output.substr(0,7) == 'OUTPUT:') {
		
		ThumbList = output.substr(7).split('|');
		
		// fewer than X thumbnails, made blank ones invisible
		if (ThumbList.length < ThumbSteps) {
			for (var i = ThumbSteps-1; i >= (ThumbSteps - 1) - ThumbList.length; i--)
				document.getElementById('PortfolioThumb' + i).style.visibility = 'hidden';
		}
		
		// replace thumbnails with new list
		for (var i in ThumbList) {
			
			// make visible
			document.getElementById('PortfolioThumb' + i).style.visibility = 'visible';
			
			// replace thumbnail
			setTimeout("document.getElementById('PortfolioThumb" + i + "').src = ThumbList[" + i + "]; ", TransitionSpeed + 10);
			
			// fade in
			setTimeout("fadeObj('PortfolioThumb" + i + "', 0, 75, TransitionSpeed); ", TransitionSpeed * 2);
		}
	}
	
	// error
	else
		alert('error fetching thumbnails:' + output);
}

// add leading zeros to number
function addLeadingZeros(Num, TotalLength) {
	Zeros = '';
	for (var z = String(Num).length; z < TotalLength; z++) Zeros += '0';
	return Zeros + String(Num);
}


// fadeObj() and changeOpac() functions from http://brainerror.net/scripts/javascript/blendtrans/
function fadeObj(id, opacStart, opacEnd, millisec) {
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        
        for(var i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
        
    } else if(opacStart < opacEnd) {
    
        for(var i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

// change the opacity for different browsers
function changeOpac(setOpac, id) {
	with (document.getElementById(id).style) {
		opacity		= (setOpac / 100);
		MozOpacity	= (setOpac / 100);
		KhtmlOpacity	= (setOpac / 100);
		filter		= "alpha(opacity=" + setOpac + ")";
	}
}

// Function to create image overlay
// Supports embedding a youtube video with VIDEOSRC:http://www.youtube.com/...
function overlayImgOpen(ImgSrc, ImgLabel, ImgText) {
	
	IsYoutubeVideo = ImgSrc.substr(0,9) == 'VIDEOSRC:';

	with (document) {
		NewContainerDiv	= createElement('div');
		NewDisableDiv	= createElement('div');
		NewLoadingDiv   = createElement('div');
		NewImg		= createElement('img');
		NewXImg		= createElement('img');
		NewTextContainerDiv = createElement('div');
	}
	
	with (NewImg) {
		src		= ImgSrc;
		style.cursor	= 'pointer';
		style.display	= 'block';
	
		TmpLabel = ((ImgLabel)?ImgLabel + ' ':'') + '[click to close]';		
		setAttribute('alt', TmpLabel);
		setAttribute('title', TmpLabel);
		setAttribute('id', 'MainImg');
	}
	
	with (NewXImg) {
		src = '/images/x.gif';
		
		style.position	= 'absolute';
		style.margin	= '-20px 0px 0px ' + ((IsMSIE7 && IsYoutubeVideo)?'5':NewImg.width-10) + 'px';
		style.cursor	= 'pointer';
		
		setAttribute('width', '30');
		setAttribute('height', '35');
		setAttribute('alt', 'close');
		setAttribute('title', 'close');
		setAttribute('id', 'XImg');
	}
	
	setEvent(NewImg, 'onClick', 'overlayImgClose()');
	setEvent(NewXImg, 'onClick', 'overlayImgClose()');
	
	if (NewImg.width == 0 && !IsYoutubeVideo) {
		setTimeout('overlayImgOpen("' + ImgSrc + '", "' + ImgLabel + '", "' + ImgText + '")', 500);
		return;
	}
	else if (IsYoutubeVideo)
		NewImg.width = 425;
	
	with (NewTextContainerDiv.style) {
		width  = (NewImg.width - 20) + 'px';
		margin = '10px 10px 5px 10px';
	}	

	setLeft = (Math.round(document.body.clientWidth / 2)*1)/1 - ((NewImg.width + 10) / 2);
	setLeft = ((String(setLeft).indexOf('.') == -1)?String(setLeft):String(setLeft).substr(0, String(setLeft).lastIndexOf('.'))) + 'px';
	
	setTop = String(document.documentElement.scrollTop + 35) + 'px';
	
	// IE doesn't get a loading div because it's retarded (doesn't set "left" property, for no obvious reason)
	if (!IsMSIE) {
		with (NewLoadingDiv) {
			style.position        = 'absolute';
			style.border          = '1px solid #DD5900';
			style.backgroundColor = '#000000';
			style.color           = '#A0A0A0';
			style.padding         = '20px';
			style.width           = '200px';
			style.left            = (Math.round(document.body.clientWidth / 2) - 110) + 'px';
			style.textAlign       = 'center';
			style.zIndex          = '22';
			style.marginTop       = '300px';
			
			setAttribute('id', 'LoadingContainer');
			innerHTML = '[loading]';
		}
	}
	
	with (NewContainerDiv) {
		setAttribute('id', 'MainImgContainer');
		
		style.position	= 'absolute';
		style.top	= setTop;
		style.left	= setLeft;
		style.zIndex	= '22';
		style.background= '#FFFFFF';
		style.fontFamily= 'Arial';
		style.fontSize	= '12px';
		style.padding   = '5px';
		
		// IE's too retarded to display the XImg properly when the overlay fades in, so IE doesn't get a fade.  Boo-hoo.
		if (!IsMSIE) {
			style.opacity      = 0
			style.MozOpacity   = 0
			style.KhtmlOpacity = 0
			style.filter       = "alpha(opacity=0)";
			
			style.display = 'none';
		}
	}
	
	with (NewDisableDiv.style) {
		top        = '0px';
		left       = '0px';
		width      = '100%';
		position   = 'absolute';
		height     = String(document.documentElement.scrollHeight) + 'px';
		background = '#000000';
		zIndex     = '21';
		
		if (IsMSIE) {
			//toggleSelectMenuVisibility(true, 'hidden');
			filter = 'alpha(opacity=50)';
		}
		else {
			setProperty('-moz-opacity', '.50', ''); 
			setProperty('opacity', '.50', '');			
		}			
	}
	
	NewDisableDiv.setAttribute('id', 'DisableDiv');
	
	with (document.body) {
		appendChild(NewDisableDiv);
		appendChild(NewContainerDiv);
		
		if (!IsMSIE)
			appendChild(NewLoadingDiv);
	}
	
	if (IsYoutubeVideo) {
		NewContainerDiv.innerHTML
		= '<object width="425" height="344" style="margin-bottom: 20px"><param name="movie" value="' + ImgSrc.substr(9) + '"></param>'
		+ '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>'
		+ '<embed src="' + ImgSrc.substr(9) + '" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" '
		+ 'allowfullscreen="true" style="margin-bottom: 20px"></embed></object>';
		
		NewContainerDiv.appendChild(NewXImg);
	}
	else {
		//NewContainerDiv.appendChild(NewXImg);
		NewContainerDiv.appendChild(NewImg);
	}
	
	ImgText += '<div style="text-align: center; margin-top: 10px; font-size: 10px; color: #808080">[click image to close]</div>';
	NewContainerDiv.appendChild(NewTextContainerDiv);
	NewTextContainerDiv.innerHTML = ImgText;
	
	if (!IsMSIE)
		setTimeout("document.getElementById('MainImgContainer').style.display = 'block'; fadeObj('MainImgContainer', 0, 100, TransitionSpeed); " +
		           "document.body.removeChild(document.getElementById('LoadingContainer')); ", TransitionSpeed * 10);
}

// Function to close overlay
function overlayImgClose() {
	DeleteCodeExec = "document.body.removeChild(document.getElementById('DisableDiv')); document.body.removeChild(document.getElementById('MainImgContainer'));";
	
	if (!IsMSIE) {
		fadeObj('MainImgContainer', 100, 0, TransitionSpeed);
		setTimeout(DeleteCodeExec, TransitionSpeed + 100)
	}
	else
		eval(DeleteCodeExec);
}


// ASSIGNS A JAVASCRIPT EVENT TO A SPECIFIED OBJECT ACCORDING TO THE BROWSER
function setEvent(Obj, Event, Action) {
	
	// For IE, use attachEvent
	if (IsMSIE) {
		eval("Obj.attachEvent('" + Event.toLowerCase() + "', function() { " + Action + " });");
	}
	
	// For proper browsers, simply use setAttribute
	else
		Obj.setAttribute(Event, Action);
}
