//  blindmicemedia.com Portfolio behaviors
//  February 2008
//  
//  Makes use of Prototype 1.6.0 (http://prototypejs.org)
//  and Scriptaculous 1.8.1 (http://script.aculo.us).
//

var tileNames = [
//	"gmx",
	"ascent_nab2007",
	"redpouch",
	"nestea",
	"viia_ui",
	"borran",
	"stevenspring",
	"viia_id",
	"sleepypaws",
	"productdose",
	"fox",
	"gougeon",
	"atlas",
	"poshpapoose",
	"parknfly",
	"imperium",
	"dublin",
	"yeahthatcommercial",
	"torontozoo",
	"ecofo"
];

var baseURLPath = "portfolio/content/";
var baseExtension = ".htmlfragment";

var categories = ["consulting", "ia", "identity", "web", "interactive", "print", "all"];
var categorySubnav, allCategoryLinks, activeCategoryLink, lastCategory, galleryIntervalID;
var currentTiles = getAllTiles();
var tileDuration = 0.15;
var mode = "serial";
var galleryInterval = 50;
var moveSpeed, mouseX, mouseY = 0;
var easeDistance = 0;
var hasPageLoaded = 0;

function blindmicemediaPortfolioInit(){	
	var containerDiv = $('container');
	containerDiv.insert({ top: "<div id=\"overlay_foreground\"></div><div id=\"overlay_background\" title=\"Close this portfolio item\"></div>"});
	
	// Hide overlay elements as the page loads
	$('overlay_background').toggle();
	$('overlay_foreground').toggle();
	setOverlayPosition();
	
	// Subnav and scrolling setup
	lastCategory = 'all';
	activeCategoryLink = $$('#subnav ul li a.active').pop();
	allCategoryLinks = $$('#subnav ul li a');
	categorySubnav = $$('#subnav ul').pop();
	currentTiles = getAllTiles();

	// Adjust the overlay and gallery when the window is scrolled or resized
	window.onscroll = function() {
		setOverlayPosition();
	}
	window.onresize = function(){
		setOverlayPosition();
		setupGallery(10);
	}

	// When the overlay background itself is clicked, hide the overlay again
	$('overlay_background').onclick = function(){
		hideOverlay();
		$$('#overlay_foreground a.close').pop().addClassName('active');
	}	
	
	// Make all tiles hoverable and clickable, and extend the gallery tiles wrapper to fit the total number of tiles defined in the html document
	allTiles = getAllTiles();
	var totalTileWidth = 0;
	for (i=0; i<allTiles.length; i++){
		allTiles[i].onmouseover = function(){this.addClassName('active');}
		allTiles[i].onmouseout = function(){this.removeClassName('active');}
		allTiles[i].onclick = new Function ("showOverlay(\"" + i + "\")"); // String hack to avoid closure scope issue:
		totalTileWidth += Number(allTiles[i].getWidth()) + Number(allTiles[i].getStyle('margin-right').gsub('px', '').strip());
	}
	totalTileWidth = totalTileWidth + "px";
	$$('#portfolio_tiles div.wrapper')[0].setStyle({'width':totalTileWidth});
	
	// Setup the gallery
	setupGallery(10);
	$('container').observe('mousemove', respondToMouseMove);
	setIntervalID = setInterval("slideGalleryTrigger()", 50);
	updateGalleryNumber();
	
	// 2008 03 18 - RY - Added for direct access to portfolio items
	if ((queryString('pid') != 'false') && (hasPageLoaded == 0)) {
		//alert(queryString('pid'));
		showOverlay(getTileNumberByName(queryString('pid')));
		//showOverlay(queryString('pid'));
		hasPageLoaded = 1;
	}
}

function tileURL(n){
	var path = baseURLPath + tileNames[n] + "/" + tileNames[n] + baseExtension;
	return path;
}

function setupGallery(margin){
	// Margin is a hack to prevent a ghost scrollbar in browsers with slower javascript engines.
	// It keeps the gallery container from going all the way to the right edge of the window.
	if (pageBorder()) $('portfolio_tiles').setStyle({'width':(1000 + pageBorder() - margin) +'px'});
}

function respondToMouseMove(event){
	mouseX = Event.pointerX(event);
	mouseY = Event.pointerY(event);
}

function slideGalleryTrigger(){
	var leftEdge = pageBorder();
	var rightEdge = document.viewport.getWidth();
	var topEdge = 10;
	var bottomEdge = topEdge + 378;
	
	var speedLimit = 6.5;
	var exponent = 3;
	
	if ((mouseX > leftEdge) && 
	    (mouseX < rightEdge) && 
	    (mouseY > topEdge) && 
	    (mouseY < bottomEdge) &&
	    (!(Element.visible($('overlay_foreground'))))
	) {
		var root = (mouseX - pageBorder()) / Number(rightEdge - leftEdge) - 0.5;
		moveSpeed = Math.pow(root, exponent)*-200;
		if (moveSpeed > speedLimit) moveSpeed = speedLimit;
		if (moveSpeed < (0 - speedLimit)) moveSpeed = (0 - speedLimit);
		if ((exponent % 2 == 0) && (root < 0)) moveSpeed *= -1;
		slideGallery();
	} else {
		//slowToAStop(moveSpeed) - only if it was just moving of course;
		// 2008 03 17 - RY - Added to smooth abupt stop on mouseout
		if (Math.abs(moveSpeed) > 0.5) {
			if (moveSpeed > 0) moveSpeed -= 0.2;
			if (moveSpeed < 0) moveSpeed += 0.2;
			slideGallery();
		}

	}
}

function slideGallery(){
	var edgeShoulder = 100;
	var widthOfCurrentTiles = 0;
	for (var i = 0; i < (currentTiles.length-1); i++){
		widthOfCurrentTiles += Number(currentTiles[i].getWidth()) + Number(currentTiles[i].getStyle('margin-right').gsub('px', '').strip());
	}
	var maxLeft = 0;
	var minLeft = 0 - widthOfCurrentTiles + 500;
	var moveStep = 5;
	
	// 2008 03 17 - RY - do not move if the width of tiles fits on screen already
	//if (widthOfCurrentTiles > 750) {
		var oldLeft = $$('#portfolio_tiles div.wrapper').pop().getStyle('left').gsub('px', '').strip();
		
		/*if (oldLeft < (minLeft + 100)) {
			slowDown += 1;
			moveSpeed += slowDown;
		} else if (oldLeft > (maxLeft - 100)) {
			slowDown -= 1;
			moveSpeed -= slowDown;
		} else {
			var slowDown = 0;
		}*/
		
		var newLeft = Number(oldLeft) + (moveStep * moveSpeed);
	
		if (newLeft < minLeft) newLeft = minLeft;
		if (newLeft > maxLeft) newLeft = maxLeft;
	
		$$('#portfolio_tiles div.wrapper').pop().setStyle({'left': newLeft + 'px'});
	//}
}

function getWidthOfCurrentTiles() {
	var widthOfCurrentTiles = 0;
	for (var i = 0; i < (currentTiles.length-1); i++){
		widthOfCurrentTiles += Number(currentTiles[i].getWidth()) + Number(currentTiles[i].getStyle('margin-right').gsub('px', '').strip());
	}
	return widthOfCurrentTiles;
}

function pageBorder(){
	// Returns the distance between the 1000px-wide content area and the edge of the browser window, if larger than 1000px.
	if (document.viewport.getWidth() > 1000) return (document.viewport.getWidth() - 1000)/2;
	else return 0;
}

function hideOverlay(){
	Effect.Fade($('overlay_foreground'), {duration:0.3});
	//Effect.Fade($('overlay_foreground'), {duration:0.5});
	setTimeout(function(){Effect.Fade($('overlay_background'), {duration:0.3});}, 0.3*1000);
	window.setTimeout(function(){$('overlay_foreground').update("");}, 1.0*1000);
}

function setOverlayPosition(){
	var totalHeight = document.viewport.getHeight() + document.viewport.getScrollOffsets()[1];
	$('overlay_background').setStyle({'height':totalHeight + 'px'});
	$('overlay_background').setStyle({'top':'0px', 'left':'0px'});
	
	var foregroundWidth = $('overlay_foreground').getWidth();
	var foregroundLeft = (document.viewport.getWidth() - foregroundWidth)/2 + document.viewport.getScrollOffsets()[0];
	$('overlay_foreground').setStyle({'left':foregroundLeft + 'px'});
	
/*
	// 2008 03 17 - RY - get the dynamic height of the foreground
	var foregroundHeight = $('overlay_foreground').getHeight();
	
	*
	var foregroundWidth = 900;
	
	// 2008 03 17 - RY - only center vertically if foreground is smaller than viewport
	if (document.viewport.getHeight() > foregroundHeight) {
		var foregroundTop = (document.viewport.getHeight() - foregroundHeight)/2 + document.viewport.getScrollOffsets()[1];
	}
	var foregroundLeft = (document.viewport.getWidth() - foregroundWidth)/2 + document.viewport.getScrollOffsets()[0];
	$('overlay_foreground').setStyle({'top':foregroundTop + 'px', 'left':foregroundLeft + 'px'});
*/
}

function showOverlay(tile){
	//var content = '<img class="loading" src="loading.gif" alt="Loading" />';
	var content = '';	
	var overlayForeground = $('overlay_foreground');
	overlayForeground.update(content);
	
	Effect.Appear($('overlay_background'), {duration:0.3});
	//Effect.Appear($('overlay_foreground'), {duration:0.3});
	setTimeout(function(){Effect.Appear($('overlay_foreground'), {duration:0.3});}, 0.3*1000);
	
	new Ajax.Request(tileURL(tile), {
		method: 'get',
		onSuccess: function(transport){		
			overlayForeground.update(transport.responseText);
			overlayForeground.removeClassName("loading");
			blindmicemediaPortfolioPageInit();
		},
		onFailure: function(transport){
			// 2008 03 18 - RY - deal with failure case here...
			overlayForeground.update('Error ' + transport.status + ' -- ' + transport.statusText);
			overlayForeground.removeClassName("loading");
			// alert('onFailure');
		}
	});
}

function getBottomScrollLimit(tileHeight){
	var value = (Math.floor(currentTiles.length / 3)) * tileHeight + 65;
	return value;
}

function getCategoryNumber(c){
	for (var i=0; i<categories.length; i++){
		if (categories[i].toLowerCase() == c.toLowerCase()) {
			return i;
		}
	}	
}

function setActiveStatus(category){
	var liHeight = 21;
	t = getCategoryNumber(category);
	activeCategoryLink.removeClassName('active');
	allCategoryLinks[t].addClassName('active');
	activeCategoryLink = allCategoryLinks[t];
	$('subnav_indicator').morph({'top': (t*liHeight) + 'px'});
}

function getAllTiles(){
	return $$('div#portfolio_tiles div.tile');
}

function showTiles(t){
	$$('#portfolio_tiles div.wrapper').pop().setStyle({'left': 0 + 'px'});
	switch(mode){
		case "parallel":
			for (var i=0; i<t.length; i++) {
				Effect.Appear(t[i], {duration: defaultDuration});
			}
			break;
		case "serial":
			for (var i=0; i<t.length; i++) {
				Effect.Appear(t[i], {duration: tileDuration, queue: {position:'end', scope: 'tileScope', limit:20}});
			}
			break;
	}
	updateGalleryNumber();
}

function updateGalleryNumber(){
	// Change the number displayed in gallery
	var totalPortfolioItems = $('portfolio_number');
	if (currentTiles.length == 1) totalPortfolioItems.update('<span class="label">Below:</span> <span class="number">' + currentTiles.length + '</span> item displayed.');
	else totalPortfolioItems.update('<span class="label">Below:</span> <span class="number">' + currentTiles.length + '</span> items displayed.');
	Effect.Appear(totalPortfolioItems, {duration: defaultDuration});
}

function hideTiles(t){
	switch(mode){
		case "parallel":
			for (var i=0; i<t.length; i++) {
				Effect.Fade(t[i], {duration: defaultDuration});
			}
			break;
		case "serial":
			for (var i=t.length-1; i>-1; i--) {
				Effect.Fade(t[i], {duration: tileDuration, queue: {position:'end', scope: 'tileScope', limit:20}});	
			}
			break;
	}
	
	var totalPortfolioItems = $('portfolio_number');
	Effect.Fade(totalPortfolioItems, {duration: defaultDuration});
	
}

function hideThenShow(h, s){
	switch(mode){
		case "parallel":
			hideTiles(h);
			// The following 2 lines are part of a stupid hack to
			// a) get an event to fire afterFinish (doesn't seem to work), and
			// b) to pass an argument to a function called via setTimeout (we're using a global var here)
			currentTiles = s;
			window.setTimeout(function(){showTiles(currentTiles);}, defaultDuration*2*1000);
			break;
		case "serial":
			hideTiles(h);
			currentTiles = s;
			window.setTimeout(function(){showTiles(currentTiles);}, tileDuration*(h.length + 1)*1000);
			break;
	}
}

function getTilesByCategory(c){
	if (c == 'all') return getAllTiles();
	else return $$('div#portfolio_tiles div.' + c);
}

function showCategory(category){
	if (lastCategory != category){  // do nothing if the current category was clicked again
		// check if the overlay is visible, and close it if it is
		if ($('overlay_background').visible) hideOverlay();
	
		// Update the nav selection
		setActiveStatus(category);
	
		// Resort the tiles to reflect the current selection
		var tilesToShow = getTilesByCategory(category);
		var tilesToHide = getTilesByCategory(lastCategory);
		hideThenShow(tilesToHide, tilesToShow);

		// Just so we know what happened here
		lastCategory = category;
	}
}

function getTileNumberByName(name){
	var tileNumber = -1;
	for (var i=0; i<tileNames.length; i++){
		if (name == tileNames[i]) tileNumber = i;
	}
	if (tileNumber >= 0) {
		return tileNumber;
//	} else {
//		alert("There is no project with that name in the portfolio.");
//		return 0;
	}
}

// 2008 03 18 - RY - Query String stuff

function PageQuery(q) {
	if(q.length > 1) 
		this.q = q.substring(1, q.length);
	else 
		this.q = null;
	
	this.keyValuePairs = new Array();
	
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}

	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}

	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	
	this.getLength = function() { 
		return this.keyValuePairs.length; 
	}
	
}

function queryString(key){
	var page = new PageQuery(window.location.search);
	//alert(unescape(page.getValue(key));
	return unescape(page.getValue(key));
}

/*function queryString(parameter) { 
  var loc = location.search.substring(1, location.search.length);
  var param_value = false;

  var params = loc.split("&");
  for (i=0; i<params.length;i++) {
      param_name = params[i].substring(0,params[i].indexOf('='));
      if (param_name == parameter) {
          param_value = params[i].substring(params[i].indexOf('=')+1)
      }
  }
  if (param_value) {
      return param_value;
  }
  else {
      return false; //Here determine return if no parameter is found
  }
}*/

function displayItem(key){
	if(queryString(key)=='false') {
		document.write("you didn't enter a ?name=value querystring item.");
	}else{
		document.write(queryString(key));
	}
}