// ---- 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: 11/28/05 --------------------------------------------------------

// the media array
var media;

// 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 photo = 'artwork';
var photoBox = 'inner';
var prevLink = 'prevLink';
var nextLink = 'nextLink';
var caption = 'caption';
var counter = 'counter';
var loading = 'loading';

var recentHash = "";
var thumbnailSetting = "Off";
var maxWidth = 800;

// Set Info
var set = 1;
var imagesPerSet = 9;

// A container to preload the images
var images = new Array();

/*--------------------------------------------------------------------------*/

var Slideshow = Class.create();

Slideshow.prototype = {
	initialize: function() {},

	showImage: function(){	
		new Effect.Fade('loading', {duration: 0.2});

		new Effect.Appear(photo, {
			duration: 0.3,
			queue: 'end', 
			afterFinish: function() {	
				if(media.length > 1) {
					[prevLink, nextLink].each(Element.show);
				}
			}
		});
	},
	nextImage: function(){
		(imageId == (media.length - 1)) ? imageId = 0 : imageId++;

		this.initSwap();
	},
	previousImage: function(){
		(imageId == 0) ? imageId = media.length - 1 : imageId--;

		this.initSwap();
	},
	initSwap: function() {			
		// Show the loading image
		$(loading).show();

		// Hide the caption
		$(caption).hide();

		// Hide the previous and back buttons
		[prevLink, nextLink].each(Element.hide);
		
		//Hide the photo	
		$(photo).hide();
		
		// Get the current image
		var image = media[imageId];

		// Get the dimensions to resize the image box to
		var dimensions = new getDimensions(image.width, image.height, maxWidth, 660);
		
		// Set anchor for bookmarking
		$(prevLink).href = "#" + (imageId+1);
		$(nextLink).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
			$(photo).src = tmpImage.src
			
			// Set the height and width
			$(photo).width = dimensions.width; 
			$(photo).height = dimensions.height;

			new Slideshow().showImage();
		}

		tmpImage.src = photoUrl;		
			
		// Resize the photo box
		$(photoBox).style.height = dimensions.height + "px";
		
		// Set the caption
		if(image.description.length > 0) {
			$(caption).show(); 
		}

		$(caption).innerHTML = image.description;
		$(counter).innerHTML = (imageId+1)+ ' of ' + media.length;
		
		// Do the thumbnail stuff
		if(thumbnailSetting != "Off") {
			var imageSet = Math.floor((imageId / imagesPerSet) + 1);

			if(imageSet > set) {
				this.nextSet();
			}
			else if (imageSet < 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(set != 1) {
			set--;
		}

		this.endImage = set * imagesPerSet;
		this.startImage = this.endImage - (imagesPerSet - 1);

		if(set == 1) {
			$("prev_set").addClassName("dis");
		}

		if(this.endImage > media.length) {
			this.endImage = media.length;
		}

		// Hide all the thumbs
		for(var i=1; media.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(set * imagesPerSet < media.length) {
			set++;
		};

		this.endImage = set * imagesPerSet;
		this.startImage = this.endImage - (imagesPerSet - 1);

		if(this.endImage >= media.length) {
			this.endImage = media.length;
			$("next_set").addClassName("dis");
		}

		// Hide all the photos
		for(var i=1; media.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 >= media.length) {
			this.endImage = media.length;
		}

		// Show the thumbs in this batch
		for(var i=this.startImage; this.endImage >= i; i++) {
			var thumb = media[i-1];
			var path = "/100x75-c.jpeg";

			if(thumbnailSetting == "Horizontal") {
				var dimensions = new getDimensions(thumb.width, thumb.height, 76, 57);
	
				path = "/" + dimensions.width + "x" + dimensions.height + ".jpeg";
		
				$('imageArt_' + i).height = dimensions.height;
				$('imageArt_' + i).width = dimensions.width; 
			}

			$('imageArt_' + i).src = imagePath + thumb.id + path;
			

			if(thumbnailSetting == "Vertical") {
				$('imageArt2_' + i).src = imagePath + thumb.id + path;
			}
		}
	}
}

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 viewImage(imageIdToLoad) {
	imageId= imageIdToLoad -1;

	new Slideshow().initSwap();
}

function loadImages(thumbSetting) {
	if(thumbSetting) {
		thumbnailSetting = thumbSetting;

		if(thumbnailSetting == "Vertical") { 
			maxWidth = 640;
			imagesPerSet = 28;
		}
	}

	new Slideshow().initSwap();

	if(thumbnailSetting != "Off")
	{
		new Slideshow().loadThumbs(1, imagesPerSet);
	}
	
	// Preload the images
	for(i = 0; i < media.length; i++) {
		var mediaImage = media[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 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 ) {
		viewImage(imageIdHash);
	}
}

var SlideshowRules = {
	'#prevLink:click': function(element) {
		new Slideshow().previousImage();
	},
	'#nextLink:click': function(element) {
		new Slideshow().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();
	}
};
