// ---- Slideshow -----------------------------------------

// Slideshow script coded by Scott Upton & Jason Nelson of nterface
// http://www.uptonic.com | http://www.couloir.org | http://www.nterface.com
//
// This work is licensed under a Creative Commons License
// Attribution-ShareAlike 2.0
// http://creativecommons.org/licenses/by-sa/2.0/

// --- version date: 2008-09-12 --------------------------------------------------------

var gallery;

// get current photo id from URL
var hashId = document.location.href.split("#")[1];

// if no imageId supplied then set default
var imageId = (!hashId)? 0 : hashId - 1;

// CSS border size x 2
var borderSize = 20;

var imagePath = "http://media.nterface.com/images/";

var recentHash = "";
var thumbnailSetting = "Off";
var maxWidth = 800;

// Set Info
var imagesPerSet = 9;

// A container to preload the images
var images = new Array();

/*--------------------------------------------------------------------------*/

var Gallery = Class.create({
	initialize: function(items, thumbSetting) {
		this.items = items;
		this.thumbSetting = thumbSetting;
		this.set = 1;
		this.imagesPerSet = 9;
		
		this.captionEl = $('caption');
		this.loadingEl = $('loading');
		this.photoEl = $('artwork');
		this.photoBoxEl = $('inner');
		this.counterEl = $('counter');
		this.prevLinkEl = $('prevLink');
		this.nextLinkEl = $('nextLink');
		
		this.loadImages(thumbSetting);
		
		setInterval(pollHash, 1200);
	},
	viewImage: function(imageIdToLoad) {
		imageId = imageIdToLoad -1;

		this.initSwap();
	},
	showImage: function(){
		var base = this;
			
		new Effect.Fade(this.loadingEl, {duration: 0.2});

		new Effect.Appear(this.photoEl, {
			duration: 0.3,
			queue: 'end', 
			afterFinish: function() {	
				if(base.items.length > 1) {
					[base.prevLinkEl, base.nextLinkEl].each(Element.show);
				}
			}
		});
	},
	nextImage: function(){
		(imageId == (this.items.length - 1)) ? imageId = 0 : imageId++;

		this.initSwap();
	},
	previousImage: function(){
		(imageId == 0) ? imageId = this.items.length - 1 : imageId--;

		this.initSwap();
	},
	initSwap: function() {
		var base = this;
			
		// Show the loading image
		this.loadingEl.show();

		// Hide the caption
		this.captionEl.hide();

		// Hide the previous and back buttons
		[this.prevLinkEl, this.nextLinkEl].each(Element.hide);
		
		//Hide the photo	
		this.photoEl.hide();
		
		// Get the current image
		var image = this.items[imageId];

		// Get the dimensions to resize the image box to
		var dimensions = new getDimensions(image.width, image.height, maxWidth, 660);
		
		// Set anchor for bookmarking
		this.prevLinkEl.href = "#" + (imageId+1);
		this.nextLinkEl.href = "#" + (imageId+1);
	
		// Load the photo into a temporary image
		var photoUrl = imagePath + image.id + "/" + dimensions.width + "x" + dimensions.height + ".jpeg";

		var tmpImage = new Image();
		
		
		tmpImage.onload = function() {
			// Set the src
			base.photoEl.src = tmpImage.src
			
			// Set the height and width
			base.photoEl.width = dimensions.width; 
			base.photoEl.height = dimensions.height;

			base.showImage();
		}

		tmpImage.src = photoUrl;		
			
		// Resize the photo box
		this.photoBoxEl.style.height = dimensions.height + "px";
		
		// Set the caption
		if(image.description.length > 0) {
			this.captionEl.show(); 
		}

		this.captionEl.innerHTML = image.description;
		this.counterEl.innerHTML = (imageId+1)+ ' of ' + this.items.length;
		
		// Do the thumbnail stuff
		if(thumbnailSetting != "Off") {
			var imageSet = Math.floor((imageId / imagesPerSet) + 1);

			if(imageSet > this.set) {
				this.nextSet();
			}
			else if (imageSet < this.set) {
				this.previousSet();
			}
			
			// Remove the current thumbnail class
			$$("li.cur").each(function(li) {
				li.removeClassName('cur');
			});  
	
			thumbnail = $('image_' + (imageId + 1));
	
			if(thumbnail) {
				thumbnail.addClassName('cur');
			}
		}
	},
	previousSet : function() {
		if(this.set != 1) {
			this.set--;
		}

		this.endImage = this.set * imagesPerSet;
		this.startImage = this.endImage - (imagesPerSet - 1);

		if(this.set == 1) {
			$("prev_set").addClassName("dis");
		}

		if(this.endImage > this.items.length) {
			this.endImage = this.items.length;
		}

		// Hide all the thumbs
		for(var i=1; this.items.length >= i; i++) {
			$('image_' + i).hide();
		}

		// Show the ones we want
		for(var i=this.startImage; this.endImage >= i; i++) {
			$('image_' + i).show();
		}

		$("next_set").removeClassName("dis");
	},
	nextSet : function() {
		if(this.set * imagesPerSet < this.items.length) {
			this.set++;
		};

		this.endImage = this.set * imagesPerSet;
		this.startImage = this.endImage - (imagesPerSet - 1);

		if(this.endImage >= this.items.length) {
			this.endImage = this.items.length;
			$("next_set").addClassName("dis");
		}

		// Hide all the photos
		for(var i=1; this.items.length >= i; i++) {
			$('image_' + i).hide();
		}

		// Show the thumbs in this batch
		for(var i=this.startImage; this.endImage >= i; i++) {
			$('image_' + i).show();
		}

		this.loadThumbs(this.startImage, this.endImage);

		$("prev_set").removeClassName("dis");
		
	},
	loadThumbs: function(startImage, endImage) {
		this.endImage = endImage;
		this.startImage = startImage;

		if(this.endImage >= this.items.length) {
			this.endImage = this.items.length;
		}

		// Show the thumbs in this batch
		for(var i=this.startImage; this.endImage >= i; i++) {
			var thumb = this.items[i-1];
			var path = "/110x10-c.jpeg";

			var imageArt = $('imageArt_' + i);
			
			if(this.thumbSetting == "Horizontal") {
				var dimensions = new getDimensions(thumb.width, thumb.height, 76, 57);
				
				path = "/" + dimensions.width + "x" + dimensions.height + ".jpeg";
		
				imageArt.height = dimensions.height;
				imageArt.width = dimensions.width; 
			}

			imageArt.src = imagePath + thumb.id + path;

			if(this.thumbSetting == "Vertical") {
				path = "/100x75-c.jpeg";
				
				$('imageArt2_' + i).src = imagePath + thumb.id + path;
			}
		}
	},
	loadImages: function() {
		if(this.thumbSetting == "Vertical") { 
			maxWidth = 640;
			imagesPerSet = 28;
		}
	
		this.initSwap();
	
		if(this.thumbSetting != "Off")
		{
			this.loadThumbs(1, imagesPerSet);
		}
		
		// Preload the images
		for(i = 0; i < this.items.length; i++) {
			var mediaImage = this.items[i];
			
			var dimensions = new getDimensions(mediaImage.width, mediaImage.height, maxWidth, 660);
	
			var imageUrl = imagePath + mediaImage.id + "/" + dimensions.width + "x" + dimensions.height + ".jpeg";
			
			images[i] = new Image();
			
			images[i].src = imageUrl;
		}
	}
});

function getDimensions(width, height, maxWidth, maxHeight) {
	if (height <= maxHeight && width <= maxWidth) {

		this.width = width;
		this.height = height;
	}
	else {	
		mutiplier = (maxWidth / width);

    	if (height * mutiplier <= maxHeight) {
			newHeight = Math.round(height * mutiplier);

			this.width = maxWidth;
			this.height = newHeight;
      	}
		else {
        	mutiplier = (maxHeight / height);

            newWidth = Math.round(width * mutiplier);

			this.width = newWidth;
			this.height = maxHeight;
		}
	}
}
	
/*------------------------------------------------*/

function isFirefoxMac() {	
	if(Prototype.Browser.Gecko) {
		var OS = navigator.platform.toLowerCase();
  		
  		if (OS.indexOf("mac") != -1) {
			return true;
		}

	}

	return false;
}

function pollHash() {
	if(window.location.hash == recentHash) {
		return; 
	}

	recentHash = window.location.hash;

	splitURL = recentHash.split("#");
	imageIdHash = splitURL[1];

	if(imageId != imageIdHash -1 ) {
		gallery.viewImage(imageIdHash);
	}
}

var SlideshowRules = {
	'#prevLink:click': function(element) {
		gallery.previousImage();
	},
	'#nextLink:click': function(element) {
		gallery.nextImage();
	},
	'a:focus': function(element) {
		element.blur();
	}
};

// Copyright (c) 2005-2006 Justin Palmer (http://encytemedia.com)
// Examples and documentation (http://encytemedia.com/event-selectors)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

var EventSelectors = {
  version: '1.0_pre',
  cache: [],

  addLoadEvent : function(func) {
     var oldonload = window.onload;
		
     if (typeof window.onload != 'function') {
	  window.onload = func;
     } 
     else {
         window.onload = function() {
	      oldonload();
		func();
		}
     }
  },

  start: function(rules) {
    this.rules = rules || {};
    this.timer = new Array();
    this._extendRules();
    this.assign(this.rules);
  },
  
  assign: function(rules) {
    var observer = null;
    this._unloadCache();
    rules._each(function(rule) {
      var selectors = $A(rule.key.split(','));
      selectors.each(function(selector) {        
        var pair = selector.split(':');
        var event = pair[1];
        $$(pair[0]).each(function(element) {
          if(pair[1] == '' || pair.length == 1) return rule.value(element);
          if(event.toLowerCase() == 'loaded') {
            this.timer[pair[0]] = setInterval(this._checkLoaded.bind(this, element, pair[0], rule), 15);
          } else {
            observer = function(event) {
              var element = Event.element(event);
              if (element.nodeType == 3) // Safari Bug (Fixed in Webkit)
            		element = element.parentNode;
              rule.value($(element), event);
            }
            this.cache.push([element, event, observer]);
            Event.observe(element, event, observer);
          }
        }.bind(this));
      }.bind(this));
    }.bind(this));
  },
  
  // Scoped caches would rock.
  _unloadCache: function() {
    if (!this.cache) return;
    for (var i = 0; i < this.cache.length; i++) {
      Event.stopObserving.apply(this, this.cache[i]);
      this.cache[i][0] = null;
    }
    this.cache = [];
  },
  
  _checkLoaded: function(element, timer, rule) {
    var node = $(element);
    if(element.tagName != 'undefined') {
      clearInterval(this.timer[timer]);
      rule.value(node);
    }
  },
  
  _extendRules: function() {
    Object.extend(this.rules, {
     _each: function(iterator) {
       for (key in this) {
         if(key == '_each') continue;         
         var value = this[key];
         var pair = [key, value];
         pair.key = key;
         pair.value = value;
         iterator(pair);
       }
     }  
    });
  }
}

// Project Rules 
var ProjectRules = {
	'#details:click' : function(element) {
		$('details').hide();
		
		//new Effect.Fade('details', {duration: 0.3});

		if($('projTitleMo')) {
			$('projTitleMo').show();
		}
	},
	'#details:mouseover' : function(element) {
		$('details').addClassName('projNotesHov');
	},
	'#details:mouseout' : function(element) {
		$('details').removeClassName('projNotesHov');
	},
	'#projTitle:click' : function(element) {
		//new Effect.Appear('details', {duration: 0.4});
		
		$('details').show();
		
		$('projNotePlus').hide();
		$('projNoteTxt').hide();
	},
	'#projTitle:mouseover' : function(element) {
		$('projTitle').addClassName('projNotesHov');
		$('projNotePlus').show();
		$('projNoteTxt').hide();
	},
	'#projTitle:mouseout' : function(element) {
		$('projTitle').removeClassName('projNotesHov');
		$('projNotePlus').hide();
		$('projNoteTxt').hide();
	},
	'#projTitleMo:click' : function(element) {
		$('details').show();
		$('projNotePlus').hide();
		$('projNoteTxt').hide();
		$('projTitleMo').hide();
	},
	'#projTitleMo:mouseover' : function(element) {
		$('projTitleMo').addClassName('projNotesHov');
		$('projNotePlus').show();
		$('projNoteTxt').show();
	},
	'#projTitleMo:mouseout' : function(element) {
		$('projTitleMo').removeClassName('projNotesHov');
		$('projNotePlus').hide();
		$('projNoteTxt').hide();
	}
};