var Slideshow = new Class({
	
	sources: [],
	previous: 0,
	
	initialize: function( s, a ) {
		this.el = $( s );
		this.sources = a;
		this.previous = a.indexOf( this.el.getFirst().get( 'src' ) );
		new Asset.images( a, {
			onComplete: function() {
				this.change.periodical(4000, this);
			}.bind( this )
		} );
	},
	
	change: function() {
		var i = ( this.previous + 2 <= this.sources.length) ? this.previous + 1 : 0;
		var e1 = this.el.getFirst();
		e1.setStyle( 'zIndex', 100 );
		
		var e2 = new Element( 'img', {
			src: this.sources[i],
			'class': 'pageImage',
			style: { zIndex: 1 }
		} ).inject( 'slideshow' );
		
		e1.set( 'tween', {
			duration: 800,
			onComplete: function() { this.element.destroy() }
		} ).tween( 'opacity', 0 );
		this.previous = i;
	}
	
});


var Page = new Class({
	Implements: Options,
	
	options: {
		magicLinks: '#navigation ul li',
		magicForms: ['#contactFormHolder', '#commentFormHolder', '#quoteFormHolder'],
		magicFields: [ 'input', 'textarea', 'select' ],
		galleryWindow: 'gallery',
		galleryNav: 'galleryNav',
		slideshow: 'slideshow',
		navOffset: 65,
		nextPage: '#galleryNav .next',
		previousPage: '#galleryNav .previous',
		nextImage: '#galleryBottomNav .next',
		previousImage: '#galleryBottomNav .previous',
		galleryThumbnails: '.thumbnail',
		galleryBottomNav: 'galleryBottomNav',
		thumbnailWindow: 'thumbnailWindow',
		thumbnailLinks: '#thumbnails a',
		menuMatic: '#page #navigation',
		lightbox: '.hentry',
		perPage: 5
	},
	
	currentImage: 0,
	galleryPage: 0,
	funPeriodical: $empty,
	
	initialize: function(objOptions) {
		this.magicLinks( this.options.magicLinks );
		if( $chk( $$( this.options.magicForms )[ 0 ] ) ) {
			this.magicForms( this.options.magicForms );
		}
		if( $chk( $( this.options.galleryWindow ) ) ) {
			this.galleryWindow( this.options.galleryWindow );
			this.galleryNav( this.options.galleryNav );
			this.nextPage( this.options.nextPage );
			this.previousPage( this.options.previousPage );
			this.thumbnailLinks( this.options.thumbnailLinks );
			this.galleryBottomNav( this.options.galleryBottomNav );
			this.scroll = new Fx.Scroll( $( this.options.thumbnailWindow ) );
			// argh scroll the thumbnail window to the left
			this.scroll.set( 0 );
		}
		if( $chk( $( document.body ).getElement( this.options.menuMatic ) ) ) {
			var objMenu = new MenuMatic( { id: 'navigation' } )
		}
		if( $chk( $( this.options.slideshow ) ) ) {
			this.magicSlides();
		}
		if( $( document.body ).getElements( this.options.lightbox ).length > 0 ) {
			this.magicLightbox();
		}
	},
	
	// not really reusable code... meh
	// this is a hack to make lightbox work for client editable blog posts
	magicLightbox: function() {
		// strip the domain with "base" filename and extension
		var r = /^(http:\/\/s3\.katielwright.com\/[\d]{14}.+-)?.+(\.[\d\w]+)$/
		$( document.body ).getElements( this.options.lightbox ).each( function( entry, i ) {
			entry.getElements( 'img' ).each( function( e ) {
				var src = e.src;
				if( r.test( src ) ) {
					var matches = r.exec( src );
					var link = new Element( 'a', {
						href: matches[1]+'large'+matches[2],
						rel: 'lightbox-blogEntry'+i
					} );
					link.adopt( e.clone() ).replaces( e );
				}
			} );
		} );
		Slimbox.scanPage();
	},
	
	magicSlides: function( strSelector ) {
		new Request.JSON( {
			url: '/slideshow',
			onSuccess: function( objJSON ) {
				new Slideshow( this.options.slideshow, objJSON.images );
			}.bind( this )
		} ).get();
	},
	
	magicLinks: function( strSelectors ) {
		$$( strSelectors ).addEvents( {
			'click': function() {
				var locationURL = this.getElement( 'a' ).href;
				window.location = locationURL;
			},
			'mouseenter': function() {
				this.addClass( 'hover' );
			},
			'mouseleave': function() {
				this.removeClass( 'hover' );
			}
		} );
	},
	
	magicFields: function( fields )
	{
		var arrFields = $$( fields );
		var eleForm = arrFields[ 0 ].getParent( 'ul' );
		var objFormPos = eleForm.getPosition();
		var objFormSize = eleForm.getSize();
		eleForm.setStyles({
			position: 'relative',
			height: objFormSize.y,
			width: objFormSize.x
		});
		
		arrFields.each( function( element ) {
			var eleParent = element.getParent( 'li.field' );
			var objFieldPos = eleParent.getPosition();
			eleParent.setStyles( {
				top: ( objFieldPos.y - objFormPos.y ),
				left: ( objFieldPos.x - objFormPos.x )
			} );
			( function() {
				this.setStyles( {
					position: 'absolute'
				} );
				this.fade( 0, 1 );
			} ).delay( 1000, eleParent )
			// set the parent to position relative
			var objColor = new Color( element.getStyle( 'backgroundColor' ) );
			
			element.addEvents( {
				focus: function( objColor )
				{
					this.addClass( 'focused' );
				}.bind( eleParent, [ objColor ] ),
				blur: function( objColor )
				{
					this.removeClass( 'focused' );
				}.bind( eleParent, [ objColor ] )
			} );
		}.bind( this ) );
	},
	
	magicForms: function( arrForms ) {
		// if there is a form builder function for this id then call the form
		// builder
		arrForms.each( function( id ) {
			var f = id.slice( 1 );
			if( this[f] && $( document.body ).getElement( id ) ) {
				this[f]();
			}
		}.bind(this));
		$$( arrForms ).addEvent( 'submit', function( objEvent ) {
			objEvent.preventDefault();
			objEvent.target.set( 'send', {
				onComplete: function( response ) {
					
					var objJSON = JSON.decode( response );
					if( objJSON.response == false )
					{
						alert( objJSON.errors.join( "\n" ) );
					}
					else
					{
						this.empty();
						// $( 'errors' ).destroy();
						var eleMessage = new Element( 'p' ).
								addClass( 'message' ).
								set( 'html', objJSON.message );
						eleMessage.inject( this, 'before' );
					}
				}.bind(this)
			})
			objEvent.target.send();
		});
		this.magicFields( this.options.magicFields );
	},
	
	galleryWindow: function() {
		$( this.options.galleryWindow ).addEvents({
			mouseenter: this.galleryNavToggle.bind( this, [ 'closed' ] ),
			mouseleave: this.galleryNavToggle.bind( this, [ 'hidden' ] )
		});
	},
	
	gallerySetTween: function() {
		var eleNav = $( this.options.galleryNav );
		eleNav.set( 'tween', {
			duration: 800,
			link: 'chain'
		} );
		return eleNav;
	},
	
	galleryNavToggle: function( strPosition ) {
		var eleNav = this.gallerySetTween();
		switch( strPosition ) {
			case 'open':
				var intBottom = 0;
				break;
			case 'closed':
				var intBottom = -( eleNav.getSize().y ) + this.options.navOffset;
				break;
			case 'hidden':
				var intBottom = -( eleNav.getSize().y );
				break;
		}
		if( strPosition == 'closed' ) {
			this.funPeriodical = function() {
				this.fade( 0.75 );
				this.fade( 1 );
			}.periodical( 1700, eleNav );
		}
		else {
			$clear( this.funPeriodical );
			eleNav.set( 'opacity', 1 );
		}
		eleNav.tween( 'bottom', intBottom );
		this.galleryMenuOpen = ( this.galleryMenuOpen ) ? false : true;
	},
	
	galleryNav: function( strName ) {
		$( strName ).addEvents({
			mouseenter: function() {
				this.galleryNavToggle.bind( this, [ 'open' ] )();
				return false;
			}.bind( this ),
			mouseleave: function() {
				this.galleryNavToggle.bind( this, [ 'closed' ] )();
			}.bind( this )
		});
	},
	
	previousPage: function( strName ) {
		var element = $$( strName );
		if( this.galleryPage > 0 ) {
			element.setStyle( 'display', 'block' );
			var funChange = this.changePage.bind( this, [ this.galleryPage - 1 ] );
			element.removeEvents().
					addEvent( 'click', funChange );
		}
		else {
			element.setStyle( 'display', 'none' );
		}
	},
	
	nextPage: function( strName ) {
		var element = $$( strName )[0];
		var intThumbnails = $$( this.options.galleryThumbnails ).length;
		if( this.galleryPage + 1 < intThumbnails / this.options.perPage ) {
			element.setStyle( 'display', 'block' );
			var funChange = this.changePage.bind( this, [ this.galleryPage + 1 ] );
			element.removeEvents()
					.addEvent( 'click', funChange );
		}
		else {
			element.setStyle( 'display', 'none' );
		}
	},
	
	previousImage: function( strName ) {
		var element = $$( strName );
		if( this.currentImage > 0 ) {
			element.setStyle( 'display', 'block' );
			var funChange = this.changeImage.bind( this, [ this.currentImage - 1 ] );
			element.removeEvents()
					.addEvent( 'click', funChange );
		}
		else {
			element.setStyle( 'display', 'none' );
		}
	},
	
	nextImage: function( strName ) {
		var element = $$( strName );
		var intThumbnails = $$( this.options.galleryThumbnails ).length;
		if( this.currentImage + 1 < intThumbnails ) {
			element.setStyle( 'display', 'block' );
			var funChange = this.changeImage.bind( this, [ this.currentImage + 1 ] );
			element.removeEvents()
					.addEvent( 'click', funChange );
		}
		else {
			element.setStyle( 'display', 'none' );
		}
	},
	
	changePage: function( intPage ) {
		var arrThumbnails = $$( this.options.galleryThumbnails );
		var intThumbnails = arrThumbnails.length;

		var intIndex = intPage * this.options.perPage;
		var eleIndex = arrThumbnails[ intIndex ];
		
		this.scroll.start( ( intIndex * 130 ), 0 );
		this.galleryPage = intPage;
		this.nextPage( this.options.nextPage );
		this.previousPage( this.options.previousPage );
	},
	
	thumbnailLinks: function( strName ) {
		$$( strName ).each( function( eleLink, intIndex ) {
			eleLink.getParent().addEvent( 'click', function( objEvent ) {
				// stops the normal link behavior from happening
				if( objEvent ) { objEvent.stop(); }
				var strHref = eleLink.get( 'href' );
				new Asset.image( strHref, {
					onload: function( eleImage ) {
						$( 'image' ).empty().adopt( eleImage );
						this.currentImage = intIndex;
						this.galleryBottomNav();
					}.bind( this )
				} );
			}.bind( this ) );
		}.bind( this ) );
	},
	
	changeImage: function( intImage ) {
		var arrLinks = $$( this.options.thumbnailLinks );
		arrLinks[ intImage ].getParent().fireEvent( 'click' );
		// change the page in the nav
		var intPage = Math.floor( intImage / this.options.perPage );
		if( this.galleryPage != intPage ) {
			this.changePage( intPage );
		}
	},
	
	galleryBottomNav: function() {
		if( ! $chk( $( this.options.galleryBottomNav ) ) ) {
			var eleNum = new Element( 'div', {
				id: 'galleryNum'
			} );
			funArrow = function( strClass ) {
				return new Element( 'div', {
					'class': strClass
				});
			}
			new Element( 'div', { id: 'galleryBottomNav' } )
				.adopt( funArrow( 'next' ) )
				.adopt( funArrow( 'previous' ) )
				.adopt( eleNum )
					.inject( $( 'copyright'), 'after' );
			
		}
		
		this.nextImage( this.options.nextImage );
		this.previousImage( this.options.previousImage );
		
		var arrLinks = $$( this.options.thumbnailLinks );
		// preload the next image
		if( this.currentImage + 1 < arrLinks.length ) {
			new Asset.image( arrLinks[ this.currentImage + 1 ].get( 'href' ) );
		}
		var eleNum = $( 'galleryNum' );
		eleNum.set( 'html', ( this.currentImage + 1 )+'/'+arrLinks.length );
	},
	
	contactFormHolder: function() {
		var form = new Form(
			{ action: '/contact/submit', method: 'post', id: 'contactForm' },
			[
				[ 'text', { name: 'name' } ],
				[ 'text', { name: 'email', label: 'E-Mail' } ],
				[ 'text', { name: 'phoneNumber' } ],
				[ 'text', { name: 'howHear', label: 'How did you hear about me?' } ],
				[ 'textarea', { name: 'comment' } ],
				[ 'submit', { name: 'submit', value: 'Send' } ]
			]
		);
		form.inject( 'contactFormHolder' );
	},

	commentFormHolder: function() {
		var form = new Form(
			{ action: window.location, method: 'post', id: 'commentForm' },
			[
				[ 'text', { name: 'name' } ],
				[ 'text', { name: 'email' } ],
				[ 'text', { name: 'website' } ],
				[ 'textarea', { name: 'comment' } ],
				[ 'submit', { name: 'postComment', value: 'Post Comment' } ]
			]
		);
		form.inject( 'commentFormHolder' );
	},
	
	quoteFormHolder: function() {
		var form = new Form(
			{ action: window.location, method: 'post', id: 'quoteForm' },
			[
				[ 'text', { name: 'name' } ],
				[ 'text', { name: 'email' } ],
				[ 'text', { name: 'phoneNumber' } ],
				[ 'text', { name: 'howHear', label: 'How did you hear about me?' } ],
				[ 'textarea', { name: 'jobDescription' } ]
			]
		);
		form.inject( 'quoteFormHolder' );
	}

});



window.addEvent( 'domready', function() {
	var objPage = new Page();
	
	// Google Analytics
	try{ 
		var pageTracker = _gat._getTracker("UA-11514971-1");
		pageTracker._trackPageview();
	} catch(err) {}
});