/**
 * @author Zach
 */
var RockBox = Class.create({
initialize: function(element) {
	this.galleries = new Array();
	this.galleryImages = new Array();
	this.endObserver = Array();
	this.formatFrames();
	this.current = 0;
	this.duration = .5;
},
/*
 * Gets frames and iterates through
 */
formatFrames: function() {
	var frames = $$(".rockBox");
	
	for (var i = 0; i < frames.length; i++) {
		this.detectType(frames[i]);
	}
},

detectType: function(frame)
{
	if(frame.getAttribute('rel') == 'gallery')
		this.setupGalleryImage(frame);
	else if(frame.getAttribute('rel') == 'thumbnails')
		this.setupThumbLink(frame);
	else if(frame.getAttribute('rel') == 'form')
		this.setupFormLink(frame);
},

setupThumbLink: function(frame)
{
	var galleryName = frame.getAttribute('rev');
	var galleryTitle = frame.getAttribute('title');
	
	var galleryIndex = this.galleries.indexOf(galleryName);
	
	if(galleryIndex == -1)
	{
		this.galleries.push(galleryName);
		galleryIndex = this.galleries.indexOf(galleryName);
		this.galleryImages[galleryIndex] = new Array();
	}
	var thumbObserve = this.startBox.bindAsEventListener(this , {type: 'thumbnails' ,gallery : galleryIndex , title : galleryTitle});
	Event.observe(frame , 'click' , thumbObserve);
	this.endObserver.push(Event.stopObserving.curry(frame , 'click' , thumbObserve));
},

setupFormLink: function(frame)
{
	var id = frame.getAttribute("href").split("#");
	if($(id[1])) {
		var element = $(id[1]).remove().show();
		var formObserve = this.startBox.bindAsEventListener(this , {type: 'form' , element:element});
		Event.observe(frame , 'click' , formObserve);
		this.endObserver.push(Event.stopObserving.curry(frame , 'click' , formObserve));
	}
},

setupGalleryImage: function(frame)
{
	var galleryName = frame.getAttribute('rev');
	var galleryIndex = this.galleries.indexOf(galleryName);
	/**
	 * @todo encapsulate this into a getGalleryIndex function
	 */
	if(galleryIndex == -1)
	{
		this.galleries.push(galleryName);
		galleryIndex = this.galleries.indexOf(galleryName);
		this.galleryImages[galleryIndex] = new Array();
	}	
	var imageIndex = this.galleryImages[galleryIndex].length;
	
	this.galleryImages[galleryIndex][imageIndex] = {
		url: frame.getAttribute("href"),
		image: new Element('img'),
		loaded: false,
		link: frame,
		thumb: frame.select('.thumb')[0],
		title: frame.getAttribute("title"),
		gallery: galleryIndex,
		index: imageIndex,
		type: 'gallery' 
	};

	var thumbObserve = this.startBox.bindAsEventListener(this , this.galleryImages[galleryIndex][imageIndex]);
	Event.observe(frame , 'click' , thumbObserve);
	this.endObserver.push(Event.stopObserving.curry(frame , 'click' , thumbObserve));
},

/**
 * 
 */
resizeBackground: function()
{
	this.background.setStyle({width : document.viewport.getWidth() + 'px' , height: document.viewport.getHeight() + 'px'});
},


/**
 * 
 * @todo check for is running state
 * @param {Object} e
 * @param {Object} type
 * @param {Object} id
 */
startBox: function(event , frame)
{
	Event.stop(event);
	if (!this.background)
		this.initContent();
	else 
	{
		this.content.update();
		this.background.show();
	}
	if(event)
	{
		var x = event.pointerX();
		var y = event.pointerY();
	
		this.container.setStyle({left:x + "px" , top:y + "px"});
	}
	
	if (frame.type == 'gallery') {
		this.loadImage(frame);
	}
	else if (frame.type == 'thumbnails') {
		this.showThumbs(frame);
	}
	else if (frame.type == 'form') {
		pageTracker._trackPageview(frame.element.id);
		this.showForm(frame);
	}
	
},


/**
 * @todo simplify this, and add extra elements as an extension
 */
initContent: function()
{
		var dimensions = document.viewport.getDimensions();
		
		this.background = new Element('div', {
			"id" : "SpockBox" , 
			'style': 'width:' + dimensions.width + "px; height:" + dimensions.height + "px;"
		}).hide();
		
		this.content = new Element('div', {
			'class': 'content'
		});
		
		this.loadingBar = new Element('div', {
			'class': 'loading'
		}).hide();
		this.content.appendChild(this.loadingBar);
		
		this.controls = new Element('div', {
			'id': 'controls'
		});
		
		
		/**
		 * Create the close button, watch for clicks, and register the stopObserving function for uninitialization 
		 */
		this.closeButton = new Element('div' , {'id' :'close'}).update('Close');
		var closeObserve = this.close.bindAsEventListener(this);
		Event.observe(this.closeButton , 'click' , closeObserve);
		this.endObserver.push(Event.stopObserving.curry(this.closeButton , 'click' , closeObserve));
		this.controls.appendChild(this.closeButton);
		
		this.container = new Element('div' , {'id' : "container"});
		
		this.container.appendChild(this.content);
		this.container.appendChild(this.controls);
		
		this.background.appendChild(this.container);
		document.body.appendChild(this.background);
		
		var resizeObserve = this.resizeBackground.bindAsEventListener(this);
		Event.observe(window , 'resize' , resizeObserve)
		this.endObserver.push(Event.stopObserving.curry(window , 'resize' , resizeObserve));

		
		this.autoCenter = new AutoCenter(this.container, {});
		this.autoCenter.center();
		new Effect.Appear(this.background, { duration:this.duration });
	
},

swapContent: function(content)
{	

	if (this.running != true) 
	{
		this.running = true;
		this.newContent = content;

			new Effect.Opacity(this.content, {
				from: 1,
				to: 0,
				duration: this.duration,
				afterFinish: function(){
					
					this.content.update();
					document.body.appendChild(this.newContent);
					
					var newDim = this.newContent.getDimensions();
					this.newContent.remove();
					var oldDim = this.container.getDimensions();
	
					var viewportDim = document.viewport.getDimensions();
					
					var scaleX = (newDim.width) / (oldDim.width) * 100;
					var scaleY = (newDim.height) / (oldDim.height) * 100;
					
					var shiftX = Math.floor((viewportDim.width - (newDim.width + 36)) / 2);
					var shiftY = Math.floor((viewportDim.height - (newDim.height + 36)) / 2);
					
					new Effect.Parallel([new Effect.Move(this.container, {
						x: shiftX,
						y: shiftY,
						duration: this.duration,
						mode: 'absolute',
						sync: true,
						transition: Effect.Transitions.spring
					}), new Effect.Scale(this.container, scaleY, {
						scaleX: false,
						duration: this.duration,
						sync: true,
						scaleContent: false,
						transition: Effect.Transitions.spring
					}), new Effect.Scale(this.container, scaleX, {
						scaleY: false,
						duration: this.duration,
						sync: true,
						scaleContent: false,
						transition: Effect.Transitions.spring
					})], {
						afterFinish: function(){
							
							this.content.update(this.newContent);
							new Effect.Opacity(this.content, {
								from: 0,
								to: 1,
								duration: this.duration,
								delay: .1,
								afterFinish:function() {
									this.running = false;
								}.bind(this)
							});
						
						}.bind(this),
						delay: .1,
						duration: this.duration
					});
				}.bind(this)
			});
	}
		
},
loadImage: function(frame)
{

	this.content.setOpacity(.1);
	if (frame.loaded == false) 
	{	
		this.current = frame.imageIndex;
		this.loadingBar.show();
		Event.observe(frame.image, 'load', this.showImage.bind(this, frame));
		frame.image.setAttribute("src", frame.url);
	}
	else 
		this.showImage(frame);
},

/**
 * Generate Next/Prev Dynamically per image
 * 
 * @param {Object} frame
 */
showImage: function(frame)
{
	if (frame.loaded == false) {
		this.loadingBar.hide();
		this.content.setOpacity(1);
	}
	frame.loaded = true;
	
	document.body.appendChild(frame.image.hide());
	imgDim = frame.image.getDimensions();
	frame.image.remove();
	
	var content = new Element('div');
	content.appendChild(frame.image.show());
	
	var index = this.galleryImages[frame.gallery].indexOf(frame);
	
	if(this.prevStop != null && $("SpockPrev"))
	{
		this.prevStop();
		this.preStop = null;
	}
	if (this.galleryImages[frame.gallery][index-1])
	{		
		var prev = new Element('div', {'id': "SpockPrev"}).update("< prev");
		content.appendChild(prev);
		
		var prevObserve = this.loadImage.bind(this, this.galleryImages[frame.gallery][index-1]);
		
		Event.observe(prev , "click" , prevObserve);
		this.prevStop = Event.stopObserving.curry(prev , "click" , prevObserve);
	}
	
	if(this.nextStop != null && $("SpockNext"))
	{
		this.nextStop();
		this.nextStop = null;
	}
	if (this.galleryImages[frame.gallery][index+1]) 
	{	
		var next = new Element('div', {'id': "SpockNext"}).update("next >");
		content.appendChild(next);
		
		var nextObserve = this.loadImage.bind(this, this.galleryImages[frame.gallery][index+1]);
		
		Event.observe(next , "click" , nextObserve);
		this.nextStop = Event.stopObserving.curry(next , "click" , nextObserve);
	}
	
		if(this.backThumbStop != null  && $("backThumbs"))
		{
			this.backThumbStop();
			this.backThumbStop = null;
		}
		
		var backThumb = new Element('div', {'id': "backThumbs"}).update("Back to thumbs!");
		content.appendChild(backThumb);
		var backThumbObserve = this.showThumbs.bind(this, frame);
		
		Event.observe(backThumb , "click" , backThumbObserve);
		this.backThumbStop = Event.stopObserving.curry(next , "click" , backThumbObserve);
	
	
	var viewport = document.viewport.getDimensions();
	var proportions = imgDim.width / imgDim.height;
	
	if(imgDim.width + 36 > viewport.width - 120)
	{
		imgDim.width = viewport.width - 120;
		imgDim.height = Math.floor((imgDim.width) / proportions)
	}
	
	if(imgDim.height + 88 > viewport.height - 120)
	{
		imgDim.height = viewport.height - 120;
		imgDim.width = Math.ceil((imgDim.height) * proportions);
	}
	content.setStyle({width:imgDim.width + 'px' , height:Math.floor(imgDim.height)+ 35 + 'px'});
	frame.image.setStyle({width:Math.floor(imgDim.width) + 'px' , height:Math.floor(imgDim.height) + 'px'});

	this.swapContent(content);
},

showThumbs: function(frame)
{	
	if(this.galleryImages[frame.gallery].length > 9)
		var thumbnails = new Element('div' , {'class' : 'thumbnails' , 'style' : 'width: 600px; height:510px;'});
	else
		var thumbnails = new Element('div' , {'class' : 'thumbnails' , 'style' : 'width: 450px; height:380px;'});
	
	var thumb;
	for(var i = 0; i < this.galleryImages[frame.gallery].length; i++)
	{
		thumb = new Element('img', { src: this.galleryImages[frame.gallery][i].thumb.getAttribute('src') , 'class':'rockThumb'});
		thumbnails.appendChild(thumb);
		
		var thumbObserve = this.loadImage.bind(this, this.galleryImages[frame.gallery][i]);
		Event.observe(thumb, 'click' , thumbObserve);
		this.endObserver.push(Event.stopObserving.curry(thumb, 'click' , thumbObserve));
	}
	thumbnails.appendChild(new Element('h2').update(frame.title));
	this.swapContent(thumbnails);
},

showForm: function(frame)
{
	this.swapContent(frame.element);
},

submitForm: function(e)
{
	e.stop();
	new Ajax.Request('wahoo.html' , { postBody : Form.serialize(this.emailForm) , onSuccess : this.submitSuccess.bindAsEventListener(this)});

},

showAjaxPage: function(url)
{
	if(this.running == true)
		return false;
	
	this.clearBackBuffer();
	this.appendToBackBuffer(new Element('div' , {'id' : 'ajaxContent'}));
	
	new Ajax.Updater($('ajaxContent') , url , {onComplete: function(){this.swapBuffer();}.bind(this)});
},

submitSuccess: function(response)
{
	if(response.headerJSON.success == true)
		this.hideForm();
	else
		this.hideForm();
},

close: function()
{
	if(this.running != true)
	{
		/*if(this.nextStop && $('SpockNext'))
			this.nextStop();
		if(this.prevStop && $('SpockPrev'))
			this.prevStop();
		if(this.backThumbStop && $('backThumbs'))
			this.backThumbStop();*/
			
		if(Prototype.Browser.IE == true)
			new Effect.Fade(this.background , { duration:this.duration , delay:0 });
		else
		{
			new Effect.Fade(this.background , { duration:this.duration , delay:1 });
		
			this.swapContent(new Element('div', {
				style: "width:100px; height:100px;"
			}));
		}
	}
},

uninitialize: function()
{
	for( var i = 0 ; i < this.endObserver.length ; i++)
		this.endObserver[i]();
}



});
