/*
 * main.js
 *  January 2010
 *  
 *  Javascript enhancements for Rory Gallagher site
 * 
 * by kchevalier@suntouchdesign.com
 * 
 */

$(document).ready(function() {
	Preloader.init();
	Addresser.init();
	SearchBar.init();
	HeaderVideo.init();
	FeaturedItems.init();
	InstrumentZoom.init();
	InstrumentSlider.init();
	InstrumentPicker.init();
	Timeline.init();
	Songs.init();
	MailingList.init();
	PremiumPopup.init();
	CSSHacks.init();
});

var Preloader = {
	
	cache: [],
	
	init: function() {},
	
	load: function( image ) {
		image = 'http://' + document.domain + image;
		var doLoad = true;
		var cacheLength = Preloader.cache.length;
		for ( var i=0; i<cacheLength; i++ ) {
			if ( Preloader.cache[i].src == image ) {
				doLoad = false;
				i = cacheLength;
				break;
			}
		}
		if ( doLoad ) {
			var cacheImage = document.createElement('img');
			cacheImage.src = image;
			Preloader.cache.push( cacheImage );
		}
	},
	
	auto: function() {
		$('[cache]').each(function(i) {
			Preloader.load( $(this).attr( 'cache' ) );
		});
	}
};

var Addresser = {
	
	home: true,
	reIEhack: new RegExp( "^/?" + $.address.baseURL() ),
	
	init: function() {
		
		var landingClass = $('#content').attr('class');
		
		if ( landingClass == 'home' ) {
			
			$.address.strict( true );
			
			$.address.change(function(evt) {
				var href = evt.value.replace( Addresser.reIEhack, '' );
				
				$.ajax({
					type: 'GET',
					url: href,
					dataType: 'html',
					success: function( page, textStatus ){
						var newContent = $(page).find('#content');
						var contentClass = newContent.attr('class');
						$('#content').attr( 'class', contentClass );
						$('#content').html( newContent.html() );
						$.address.title( $(page).find('#content').attr('pageTitle') );
						HeaderVideo.page = contentClass;
						switch( contentClass ) {
							case 'home':
								FeaturedItems.init();
								HeaderVideo.resize( 'mid' );
								MailingList.init();
								break;
							case 'guitars':
								InstrumentZoom.init();
								InstrumentSlider.init();
								InstrumentPicker.init();
								HeaderVideo.resize( 'small' );
								break;
							case 'amps':
								InstrumentZoom.init();
								InstrumentSlider.init();
								InstrumentPicker.init();
								HeaderVideo.resize( 'small' );
								break;
							case 'page story':
								Timeline.init();
								HeaderVideo.resize( 'small' );
								break;
							default:
								HeaderVideo.resize( 'small' );
								break;
						}
						CSSHacks.init();
						Addresser.forms();
						Modals.init();
					}
				});
				
				return href;
			});
			
			$("a[rel!=outside]:not(.article a)").live( 'click', function() {
				$.address.value( $(this).attr('href').replace( Addresser.reIEhack, '' ) );
				return false;
			});
			
			Addresser.forms();
			
		}
		
	},
	
	forms: function() {
		$('form[rel!=outside]').unbind();
		$('form[rel!=outside]').bind( 'submit', Addresser.formEventHandler );
		$('#content.shop form').unbind( 'submit', Addresser.formEventHandler );
	}, 
	
	formEventHandler: function(evt){
		if ( evt.target.method == 'get' || 'GET' ) {
			var reFormPage = new RegExp( '(?:' + $.address.baseURL() + ')?/(?:#/)?(.*)$' );
			var actions = reFormPage.exec( evt.target.action );
			if ( actions && actions[1] ) {
				var action = $.address.baseURL() + '/#/' + actions[1];
				var params = '';
				var formLength = evt.target.elements.length;
				for ( var i=0; i<formLength; i++ ) {
					if ( evt.target.elements[i].value == '' ) continue;
					if ( params == '' ) params = '?' + evt.target.elements[i].name + '=' + evt.target.elements[i].value;
					else params += '&' + evt.target.elements[i].name + '=' + evt.target.elements[i].value;
				}
				window.location = action + params;
			}
			if ( $(this).parent().attr('id') == 'searchForm' ) SearchBar.toggleBar2();
			return false;
		}
	},
	
	isHome: function() {
		if ( $.address.path() != '/' ) {
			Addresser.home = false;
	//		alert( HeaderVideo.firstVideo );
		}
		return Addresser.home;
	}
	
};

var SearchBar = {
	
	div: '',
	button: '',
	showing: false,
	
	init: function() {
		SearchBar.div = $('#searchForm');
		SearchBar.button = $('#nav li.search a');
		SearchBar.div.find('input.search').val('');
		SearchBar.button.bind( 'click', SearchBar.toggleBar );
		SearchBar.div.find('form').bind( 'submit', SearchBar.toggleBar2 );
	},
	
	toggleBar: function(evt) {
		if ( SearchBar.showing ) {
			SearchBar.div.find('form').animate({ top: '-36px' }, 500 );
		}
		else {
			SearchBar.div.find('form').animate({ top: '0px' }, 500 ).find('#queryInput').focus();
			
		}
		SearchBar.showing = !SearchBar.showing;
		return false;
	},
	
	toggleBar2: function(evt) {
		if ( SearchBar.showing ) {
			SearchBar.div.find('form').animate({ top: '-36px' }, 500 );
		}
		else {
			SearchBar.div.find('form').animate({ top: '0px' }, 500 ).find('#queryInput').focus();
			
		}
		SearchBar.showing = !SearchBar.showing;
	}
};

var HeaderVideo = {
	
	div: '',
	speed: 1000,
	currentSize: 'big',
	intro: true,
	page: 'home',
	firstVideo: 0,
		
	init: function() {
		HeaderVideo.div = $('#headerVideo');
	},
	
	resize: function( newSize ) {
		if ( HeaderVideo.currentSize != newSize && !HeaderVideo.intro ) {
			switch( newSize ) {
				case 'small':
					HeaderVideo.div.children('#headerVideoTop').animate( { height: '175px' }, HeaderVideo.speed ).parent().children('#flashVideo').animate( { height: '200px' }, HeaderVideo.speed );
					break;
				case 'mid':
					HeaderVideo.div.children('#headerVideoTop').animate( { height: '305px' }, HeaderVideo.speed ).parent().children('#flashVideo').animate( { height: '330px' }, HeaderVideo.speed );
					break;
				case 'big':
					HeaderVideo.div.children('#headerVideoTop').animate( { height: '435px' }, HeaderVideo.speed ).parent().children('#flashVideo').animate( { height: '460px' }, HeaderVideo.speed );
					break;
			}
			HeaderVideo.currentSize = newSize;
		}
	},
	
	introComplete: function(){
		HeaderVideo.intro = false;
		if ( HeaderVideo.page == 'home' ) {
			HeaderVideo.resize( 'mid' );
		}
		else {
			HeaderVideo.resize( 'small' );
		}
	},
	
	replayIntro: function() {
		HeaderVideo.resize( 'big' );
		HeaderVideo.intro = true;
	},
	
	getFirstVideo: function() {
	//	alert( HeaderVideo.firstVideo );
		if ( !Addresser.isHome() ) {
			HeaderVideo.firstVideo = 2;
		}
		return HeaderVideo.firstVideo;
	}
};

var FeaturedItems = {
	
	div: '',
	currentDiv: '',
	listLinks: '',
	arrow: '',
	currentClass: '',
	
	init: function() {
		FeaturedItems.div = $('#featuredItems');
		FeaturedItems.currentDiv = $('#currentFeaturedNews');
		FeaturedItems.listLinks = $('ul.featuredList li a');
		FeaturedItems.arrow = $('#featuredArrow');
		FeaturedItems.currentClass = FeaturedItems.currentDiv.attr( 'class' );
		FeaturedItems.listLinks.bind( 'click', FeaturedItems.onClickFeaturedItem );
	},
	
	onClickFeaturedItem: function(evt) {
		var bubble = false;
		var clickedClass =evt.target.parentNode.parentNode.className; 
		if ( FeaturedItems.currentClass != clickedClass ) {
			FeaturedItems.currentClass = clickedClass;
			var clickedItem = $('.' + clickedClass );
			FeaturedItems.currentDiv.find('.image img').fadeOut( 300, function() {
				$(this).remove();
				FeaturedItems.currentDiv.find('.image').prepend( '<img src="' + clickedItem.find('ul li.image img').attr('src') + '" style="left:-455px;" />' );
				FeaturedItems.currentDiv.find('.image img').animate( { left: '0px' }, 500 );
			} );
			FeaturedItems.currentDiv.find('.copy').fadeOut( 300, function() {
				$(this).remove();
				FeaturedItems.currentDiv.append( "<div class='copy' style='right:-247px;'><h3>" + clickedItem.find('ul li.title').html() + "</h3><p class='date'>" + clickedItem.find('ul li.date').html() + "</p><p class='description'>" + clickedItem.find('ul li.description').html() + "</p></copy>" );
				FeaturedItems.currentDiv.find('.copy').animate( { right: '0px' }, 500 );
			} );
			if ( clickedItem.offsetParent().attr('class') == '' ) {
				FeaturedItems.arrow.animate( { top: '0px' }, 500, 'swing' );
			}
			else {
				FeaturedItems.arrow.animate( { top: ( clickedItem.position().top  ) + 'px' }, 300, 'swing' );
			}
		}
		else {
			bubble = true;
		}
		return bubble;
	}
};

var InstrumentZoom = {
	
	init: function() {
		
		var xOffset = 32;
		if ( $.browser.msie ) {
			xOffset += 4;
		}
		
		$('.instrumentZoom').jqzoom({
			zoomWidth: 192,
			zoomHeight: 192,
			title: false,
			xOffset: 0,
			yOffset: 0,
			position: 'parent',
			parent: 'zoomBox'
		});
		
	}
};

var InstrumentSlider = {
	
	box: '',
	slider: '',
	head: '',
	list: '',
	items: '',
	
	sliderOffest: 0,
	listOffset: 0,
	boxWidth: 0,
	
	init: function() {
	
		InstrumentSlider.box = $('#instrumentListBox');
		InstrumentSlider.slider = $('#instrumentSlider');
		InstrumentSlider.head = $('#instrumentSliderHead');
		InstrumentSlider.list = $('ul.instrumentList');
		InstrumentSlider.items = $('ul.instrumentList li');
		
		InstrumentSlider.list.width( ( InstrumentSlider.items.outerWidth() + parseInt( InstrumentSlider.items.css( 'margin-left' ) ) + parseInt( InstrumentSlider.items.css( 'margin-right' ) ) ) * InstrumentSlider.items.size() );
		InstrumentSlider.boxWidth = parseInt( InstrumentSlider.box.width() );
		InstrumentSlider.sliderOffest = parseInt( InstrumentSlider.slider.width() ) - parseInt( InstrumentSlider.head.width() );
		InstrumentSlider.listOffset = parseInt( InstrumentSlider.list.width() ) - InstrumentSlider.boxWidth;
		
		InstrumentSlider.head.draggable({ 
			axis: 'x',
			containment: 'parent',
			drag: InstrumentSlider.drag,
			stop: InstrumentSlider.stop
		});
		
		InstrumentSlider.preload();
	},
	
	drag: function( evt, ui ) {
		var newLeft = 0 - parseInt( ui.position.left * InstrumentSlider.listOffset / InstrumentSlider.sliderOffest ); 
		InstrumentSlider.list.css( 'left', newLeft );
	},
	
	stop: function( evt, ui ) {
		InstrumentSlider.preload();
	},
	
	preload: function() {
		InstrumentSlider.items.each( function(i) {
			var workingLeft = $(this).position().left + $(this).offsetParent().position().left;
			if ( workingLeft < InstrumentSlider.boxWidth && workingLeft > -50 ) {
				Preloader.load( $(this).children('a').attr('cache') );
			}
		} );
	}
};

var InstrumentPicker = {
	
	speed: 500,
	imgWidth: 300,
	imgHeight: 500,
		
	next: '',
	previous: '',
	listItems: '',
	box: '',
	specs: '',
	description: '',
	type: 'guitar',
	
	goodBrowser: false,
	
	init: function() {
		
		InstrumentPicker.next = $('#instrumentDetails a.nextInstrument');
		InstrumentPicker.previous = $('#instrumentDetails a.previousInstrument');
		InstrumentPicker.listItems = $('ul.instrumentList li a');
		InstrumentPicker.box = $('#instrumentDetails .imageBox');
		InstrumentPicker.specs = $('#instrumentDetails .specs dl');
		InstrumentPicker.description = $('.instrumentDescription');
		
		if ( $('#content').hasClass( 'amps' ) ) {
			InstrumentPicker.type = 'amp';
		}
		
		if ( !$.browser.msie ) {
			InstrumentPicker.goodBrowser = true;
		}
		
		InstrumentPicker.next.bind( 'click', function(evt){
			InstrumentPicker.choose( evt.target + '.xml', 'left' );
			return false;
		});
		InstrumentPicker.previous.bind( 'click', function(evt){
			InstrumentPicker.choose( evt.target + '.xml', 'right' );
			return false;
		});
		InstrumentPicker.listItems.bind( 'click', function(evt){
			var instrumentURL = evt.target.parentNode.href;
			if( !instrumentURL ) instrumentURL = evt.target.parentNode.parentNode.href;
			InstrumentPicker.choose( instrumentURL + '.xml', 'down' );
			return false;
		});
		
		Preloader.load( InstrumentPicker.next.attr( 'cache' ) );
		Preloader.load( InstrumentPicker.previous.attr( 'cache' ) );
	},
	
	choose: function( requestURL, direction ) {
		
		var specsContent = '';
		var imgContent = '';
		var descriptionContent = '';
		var startLeft = '0px';
		var startTop = '0px';
		
		$.ajax({
			type: 'GET',
			url: requestURL,
			dataType: 'xml',
			success: function(instrument){
				
				var animateOps = {};
				if ( InstrumentPicker.goodBrowser ) animateOps.opacity = 0;
				switch( direction ) {
					case 'left':
						startLeft = InstrumentPicker.imgWidth + 'px';
						animateOps.left = '-' + InstrumentPicker.imgWidth + 'px';
						break;
					case 'right':
						startLeft = '-' + InstrumentPicker.imgWidth + 'px';
						animateOps.left = InstrumentPicker.imgWidth + 'px';
						break;
					case 'down':
						startTop = '-' + InstrumentPicker.imgHeight + 'px';
						animateOps.top = InstrumentPicker.imgHeight + 'px';
						break;
				}
				
				var year = $(instrument).find('year').text();
				var make = $(instrument).find('manufacturer').text();
				var model = $(instrument).find('model').text();
				var description = $(instrument).find('description').text();
				
				specsContent = '<dt>Make:</dt><dd>' + make + '</dd>';
				specsContent += '<dt>Model:</dt><dd>' + model + '</dd>';
				if ( year != 0 ) specsContent += '<dt>Year:</dt><dd>' + year + '</dd>';
				if ( $(instrument).find('notes').text() ) specsContent += '<dt>Notes:</dt><dd>' + $(instrument).find('notes').text() + '</dd>';
				InstrumentPicker.specs.children().fadeOut( InstrumentPicker.speed, function() { $(this).parent().html( specsContent ).children().css({ display: 'none' }).fadeIn( InstrumentPicker.speed ); } );
				
				imgContent = '<a href="/images/' + $(instrument).find( InstrumentPicker.type + '>image' ).text() + '" class="instrumentZoom" title="' + year + ' ' + make + ' ' + model + '">';
				imgContent += '<img src="/images/' + $(instrument).find( InstrumentPicker.type + '>image2' ).text() + '" title="' + year + ' ' + make + ' ' + model + '" style="left:' + startLeft + '; top:' + startTop + ';';
				if ( InstrumentPicker.goodBrowser ) imgContent += ' opacity:0;';
				imgContent += '" />';
				imgContent += '</a>';
				
				if ( description ) descriptionContent = '<h4>Instrument Description</h4>' + description;
				InstrumentPicker.description.fadeOut( InstrumentPicker.speed, function() { $(this).html( descriptionContent ).css({ display: 'none' }).fadeIn( InstrumentPicker.speed ); } );
				
				InstrumentPicker.next.attr( 'href', '/archives/' + InstrumentPicker.type + 's/' + $(instrument).find('next>label').text() );
				InstrumentPicker.previous.attr( 'href', '/archives/' + InstrumentPicker.type + 's/' + $(instrument).find('previous>label').text() );
				InstrumentPicker.next.attr( 'cache', '/images/' + $(instrument).find('next>image2').text() );
				InstrumentPicker.previous.attr( 'cache', '/images/' + $(instrument).find('previous>image2').text() );
				
				InstrumentPicker.box.find('img').animate( animateOps, InstrumentPicker.speed, 'swing', function(){ InstrumentPicker.addImg( imgContent, direction ); } );
				
				Preloader.load( InstrumentPicker.next.attr( 'cache' ) );
				Preloader.load( InstrumentPicker.previous.attr( 'cache' ) );
			}
		});
	},
	
	addImg: function( content, direction ) {
		
		var animateOps = {};
		if ( InstrumentPicker.goodBrowser ) animateOps.opacity = 1;
		switch( direction ) {
			case 'left':
				animateOps.left = '0px';
				break;
			case 'right':
				animateOps.left = '0px';
				break;
			case 'down':
				animateOps.top = '0px';
				break;
		}
		
		InstrumentPicker.box.html( content );
		InstrumentPicker.box.find('img').animate( animateOps, InstrumentPicker.speed, 'swing', function(){ InstrumentZoom.init(); } );
	}
	
};

var Timeline = {
	
	div: '',
	nav: '',
	reUrlId: /(#[^#]*)$/,
	speed: 1000,
	increment: 20,
	width: 0,
	maskWidth: 0,
	eraWidth: 500,
	eraInfluence: '',
	showingEra: '',
	buttonTimer: '',
	moving: false,
	
	init: function() {
		
		Timeline.div = $('#timeline');
		Timeline.nav = $('#timelineNav');
		
		Timeline.width = Timeline.div.width();
		Timeline.maskWidth =  Timeline.div.parent().parent().width();
		
		Timeline.nav.append( '<div id="backward"></div><div id="forward"></div>' );
		Timeline.nav.children('#backward').bind( 'mousedown', function(evt){
			if ( !Timeline.moving ) {
				Timeline.moving = true;
				Timeline.moveBackward();
				$('*').bind( 'mouseup', Timeline.buttonMouseupHandler );
			}
		} );
		Timeline.nav.children('#forward').bind( 'mousedown', function(evt){
			if ( !Timeline.moving ) {
				Timeline.moving = true;
				Timeline.moveForward();
				$('*').bind( 'mouseup', Timeline.buttonMouseupHandler );
			}
		} );
		
		Timeline.eraInfluence = new Array();
		Timeline.div.children('ul[id!=legend]').each( function(i) {
			Timeline.eraInfluence.push( { id: $(this).attr('id'), offset: Timeline.width - Timeline.eraWidth - $(this).position().left + 1 } );
		});
		
		Timeline.div.draggable({ 
			axis: 'x',
			containment: 'parent',
			drag: Timeline.onDragHandler
		});
		
		Timeline.nav.find('a').bind( 'click', function(evt){
			var gotoId = Timeline.reUrlId.exec( evt.target );
			if ( gotoId[1] ) {
				var gotoLeft = Timeline.width - Timeline.maskWidth - $( gotoId[1] ).position().left;
				if ( gotoLeft < 0 ) gotoLeft = 0; 
				Timeline.div.animate( { left: gotoLeft + 'px' }, Timeline.speed, 'swing', function(){
					Timeline.updateNav( gotoLeft );
				});
			}
			return false;
		} );
		
	},
	
	updateNav: function( newLeft ) {
		var length = Timeline.eraInfluence.length;
		for ( var i=0; i<length; i++ ) {
			var nextLeft = 0;
			if ( i < length - 1 ) {
				nextLeft = Timeline.eraInfluence[i+1].offset;
			}
			
			if ( newLeft < Timeline.eraInfluence[i].offset && newLeft >= nextLeft ) {
				if ( Timeline.showingEra != Timeline.eraInfluence[i].id ) {
					Timeline.showingEra = Timeline.eraInfluence[i].id;
					Timeline.nav.find( 'a#' + Timeline.showingEra + 'nav' ).addClass( 'showing' );
					Timeline.nav.find( 'a:not(#' + Timeline.showingEra + 'nav)' ).removeClass( 'showing' );
				}	
				break;
			}
		}
	},
	
	moveForward: function() {
		if ( Timeline.moving ) {
			var newLeft = parseInt( Timeline.div.css( 'left' ) ) - Timeline.increment;
			if ( newLeft < Timeline.increment ) newLeft = 0;
			if ( newLeft >= 0 ) {
				Timeline.div.css( 'left', newLeft + 'px' );
				Timeline.updateNav( newLeft );
				if ( newLeft != 0 ) Timeline.buttonTimer = setTimeout( Timeline.moveForward, 20 );
			}
		}
	},
	
	moveBackward: function() {
		if ( Timeline.moving ) {
			var newLeft = parseInt( Timeline.div.css( 'left' ) ) + Timeline.increment;
			var edge = Timeline.width - Timeline.maskWidth;
			if ( newLeft > edge ) newLeft = edge; 
			if ( newLeft <= edge) {
				Timeline.div.css( 'left', newLeft + 'px' );
				Timeline.updateNav( newLeft );
				if ( newLeft!= edge ) Timeline.buttonTimer = setTimeout( Timeline.moveBackward, 20 );
			}
		}
	},
	
	buttonMouseupHandler: function( evt ) {
		Timeline.moving = false;
		clearTimeout( Timeline.buttonTimer );
		$('*').unbind( 'mouseup', Timeline.buttonMouseupHandler );
	},
	
	onDragHandler: function( evt, ui ) {
		Timeline.updateNav( ui.position.left );
	}
	
};

var Songs = {
	
	player: '',
	reIds: /^album(\d+)-song(\d+)$/,
	
	init: function() {
		Songs.player = $('#flashAudioPlayer');
		$('ul.songList li .addToPlaylist a').live( 'click', function(evt) {
			var matches = Songs.reIds.exec( $(this).parent().parent().attr('id') );
			if ( matches ) {
				Songs.sendSongToPlayer( matches[1], matches[2] );
				$(this).before( "<div class='addedMessage'>Song added to playlist</div>" );
				$(this).parent().children('.addedMessage').css( { display: 'block', opacity: 0 } );
				$(this).parent().children('.addedMessage').animate( { opacity: 1, top: '-20px' }, 500, 'swing', function() {
					$(this).animate( { opacity: 0, top: '-40px' }, 500, 'swing', function() { $(this).remove() } );
				});
			}
			return false;
		});
	},
	
	getFlashMovie: function(movieName) {
		var isIE = navigator.appName.indexOf("Microsoft") != -1;
		return (isIE) ? window[movieName] : document[movieName];  
	},
	
	sendSongToPlayer: function( albumId, songId ) {
		Songs.getFlashMovie("audioPlayer").sendSongToPlayer( albumId, songId ); 
	},
	
	showPlayer: function() {
		Songs.player.css({ height: '458px' });
	},
	
	hidePlayer: function() {
		Songs.player.css({ height: '24px' });
	}
};

var MailingList = {
	showingLabel: true,
	label: 'Your Email Address',
	init: function(){
		$('#ea').val( MailingList.label );
		$('#ea').focus(function(evt){
			if ( MailingList.showingLabel ) {
				$(this).val('');
				$(this).addClass('emailText');
				
			}
			MailingList.showingLabel = false;
		});
		$('#ea').blur(function(evt){
			if ( $(this).val() == '' ) {
				$(this).val(MailingList.label);
				$(this).removeClass('emailText');
				MailingList.showingLabel = true;
			}
		});
	}
};

var PremiumPopup = {
	init: function() {
		$('#blackout').css({ opacity: 0.8 });
		$('#premiumLink').live( 'click', function(e){
			$('#premiumMembership').fadeIn();
			$('#blackout').fadeIn();
			return false;
		} );
		$('#premiumMembership .close').live( 'click', function(e){
			$('#premiumMembership').fadeOut();
			$('#blackout').fadeOut();
		} );
	}
};

var CSSHacks = {
	init: function() {
		$('input.search').val('');
	}
};



