// JavaScript Document

// Tour Dates in Sidebar

$(window).load(function(){
	$('.fb_iframe_widget').animate({ 'opacity' : '0.7' },0);
	
	$('#sidebar').hover(function(){
		$('.fb_iframe_widget').stop().animate({ 'opacity' : '1' }, 200);
	}, function(){
		$('.fb_iframe_widget').stop().animate({ 'opacity' : '0.7' }, 200);
	});
	
	$('img.email_download').click(function(e){
		e.preventDefault();
		$(this).fadeOut(function(){
			$('.addressForm').fadeIn();
		});
	});
	
	$('input#submit').click(function(){
		submitEmail();
	});
	
	$('#emailAddress').bind( 'focus', function(){
		if($(this).val() == "email address"){
			$(this).val("");	
		}
	});
	
	$('#emailAddress').bind('blur', function(){
		if($(this).val() == ""){
			$(this).val("email address");	
		}
	});
	
	$.getJSON("http://api.bandsintown.com/artists/the%20civil%20wars/events.json?api_version=2.0&app_id=mike&callback=?",
		function(data){
			for(var i = 0; i < 5; i++){ // loops through next 6 dates
				//var date = data[i].formatted_datetime.split(',')[1].replace(/^\s+/, '');
				//var month = date.split(' ')[0].substring(0,3);
				//var day = date.split(' ')[1];
				var date = data[i].datetime.split('T')[0];
				var month = date.split('-')[1];
				var day = date.split('-')[2];
				var ticketLink = data[i].ticket_url; // stores ticket link
				var location = data[i].formatted_location;
				var city = location.split(',')[0];
				var region = location.split(',')[1];
				
				switch(month){
					case '01':
						month = "Jan";
					break;
					case '02':
						month = "Feb";
					break;
					case '03':
						month = "Mar";
					break;
					case '04':
						month = "Apr";
					break;
					case '05':
						month = "May";
					break
					case '06':
						month = "Jun";
					break
					case '07':
						month = "Jul";
					break
					case '08':
						month = "Aug";
					break
					case '09':
						month = "Sep";
					break
					case '10':
						month = "Oct";
					break
					case '11':
						month = "Nov";
					break
					case '12':
						month = "Dec";
					break
				}
				
				if(region == ' United Kingdom'){
					region = ' UK';
				}
			
				var tourInfo = "<a href='" + ticketLink + "' target='_blank'> " + city + ", " + region + "</a>";
			
				$('#tourDates').append("<ul><li class='date'>" + month + ' ' + day + "</li><li class='venue'>" + tourInfo + "</li></ul>"); // append final product to sidebar
			}
		});
	
});

	
// Home Page

function Main(){
	
	this.imageArray = []; // starting image array
	this.imageIndex = 0; // starting image index
	this.rotationSpeed = 5000; // speed that each slide stays visible (in ms)
	this.transitionSpeed = 400; // speed that each slide fades in/out
	this.firstTime = true;
	this.slideShowIsActive = false;
	this.buttonLock = false;
	
	this.populateArray(this.imageArray, this.imageIndex);
}

Main.prototype = 
{
	populateArray: function(arr, index){
		var images = $('#imageSlider > div'); // grabs images
		var numberOfImages = $(images).length; // stores number of images
		for(var i = 0, ii = numberOfImages; i < ii; i++){ // loops through images and stores into imageArray
			arr[i] = images[i];
		}
		this.checkFirstTime(); // check to see if this is the first time through the slideshow
	},
	
	checkFirstTime: function(){
		if(this.firstTime == true){ // if is first time fade in first image
			this.fadeInImage();
		}
		this.firstTime = false; // no longer the first time
		this.slideShowIsActive = true; // slideshow is now active
	},
	
	fadeInImage: function(){
		$(this.imageArray[this.imageIndex]).fadeIn(this.transitionSpeed); // fade in image
		this.timeOut = setTimeout(this.nextImage, this.rotationSpeed); // begin automated rotation timer
	},
	
	nextImage: function(){
		if(Main.slideShowIsActive){ // checks to see if slideshow is active
			clearTimeout(Main.timeOut); // stop rotation timer
			Main.timeOut = null; // clear pointer to rotation timer
			$(Main.imageArray[Main.imageIndex]).fadeOut(Main.transitionSpeed, function(){ // fade out current image
				Main.imageIndex++; // select the next image
				if(Main.imageIndex > Main.imageArray.length - 1){ // if at the end, go to the beginning
					Main.imageIndex = 0;	
				}
				Main.fadeInImage(); // fade in new image
			});
		}
	},
	
	stopSlideShow: function(){
		clearTimeout(Main.timeOut); // stop rotation timer
		Main.timeOut = null; // clear pointer to rotation timer
		Main.slideShowIsActive = false // slideshow is no longer active
		Main.buttonLock = true; // cannot select different slide while slideshow is stopped
	},
	
	resumeSlideShow: function(){
		if(!Main.slideShowIsActive){ // make sure slideshow isn't already active
			Main.timeOut = setTimeout(Main.nextImage, Main.rotationSpeed);	// set rotation timer
		}
		Main.slideShowIsActive = true; // slideshow is now active
		Main.buttonLock = false; // release the lock
	},
	
	moveToImage: function(self, thumbIndex){
		if(Main.buttonLock == false){ // if lock is off
			Main.stopSlideShow(); // stop slideshow
			$(Main.imageArray[Main.imageIndex]).fadeOut(Main.transitionSpeed, function(){ // fade out image
				Main.imageIndex = thumbIndex; // select the image that corresponds with thumbnail
				$(Main.imageArray[Main.imageIndex]).fadeIn(); // fade in appropriate image
				Main.resumeSlideShow(); // resume slideshow
			});
		}
	}
	
}

// Video Page
	
function Video(){
	
	this.easingStyle = 'easeInOutQuint'; // The 'easing' method in which the albums "slide" (http://gsgd.co.uk/sandbox/jquery/easing/).
	this.sliderSpeed = 500; // slider speed
	this.socialDown = false; // social buttons not exposed
};

Video.prototype =
{
	changeVideo: function(newSrc, self){
		var videoFrame = document.getElementsByTagName('iframe')[0]; // Stores the target iframe in "videoFrame" variable.
		var currentSrc = $(videoFrame).attr('src'); // Stores the current iframe source in "currentSrc" variable.
		var newVideo = "<iframe width='634' height='415' src='"+ newSrc +"' frameborder='0' allowfullscreen></iframe>" // Sets up the new iframe with the new source.
		if(currentSrc == newSrc){ // If the current source is the same as the new source don't do anything.
			return false;
		}
		else{
			$(videoFrame).remove(); // If the current source is not the same as the new source, remove the old iframe.
			$('#video').prepend(newVideo); // Prepend the new iframe into #video.
		}
		$(self).parent('li').css({ 'border' : '3px solid #fff' }); // Sets the border of the selected thumbnail.
		$(self).parent('li').siblings('li').css({ 'border' : '3px solid #eaeaea' }); // Sets the border of the unselected thumbnails.
	},
	
	nextPage: function(self, pageIndex){
		$(self).css({ 'background-position' : '0px 14px' }); // Set the fill of the selected page selector.
		$(self).siblings('li').css({ 'background-position' : '0px 0px' }); // Unset the fill of the sibling page selectors.
		$('#videoThumbs').scrollTo(((pageIndex) * 668), Video.sliderSpeed, {easing: Video.easingStyle }); // Scroll to the apporopriate page.
	}
	
}

// Music Page

function Music(){
	
	this.albumArray = [];
	this.sliderSpeed = 500; // Speed that the albums "slide".
	this.easingStyle = 'easeInOutQuint'; // The 'easing' method in which the albums "slide" (http://gsgd.co.uk/sandbox/jquery/easing/).
	this.lyricsVisible = false;
	
	this.populateArray(this.albumArray) // Aggregates all albums on the page and puts the in the "albumArray" array.
	
	// retrieve lyrics from xml file
	if (window.XMLHttpRequest)
	{
		this.xmlhttp = new XMLHttpRequest();
	}
	
	else
	{
		this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	  
	  
	this.xmlhttp.open("GET","lyrics.xml",false);
	this.xmlhttp.send();
	this.xmlDoc = this.xmlhttp.responseXML; 
	
};

Music.prototype = 
{
	populateArray: function(arr){ 
		var albums = $('#albumSlider').children('div'); // Collects the all direct children divs of #albumSlider, and stores them in "albums" variable.
		$('#albumSlider').css({ 'width' : 634 * albums.length }); // Sets the width of #albumSlider depending on the number of albums.
		for(var i= 0, ii = albums.length; i < ii; i++) // Loops through each album.
		{
			arr[i] = albums[i]; // Stores each album in Music.albumArray array.
		}
		
	},
	
	moveToAlbum: function(self, thumbIndex){
		var $has = {
			touch: "ontouchstart" in document	
		}	
		var newAlbumLocation = -(634 * thumbIndex);
		$(self).siblings('li').removeClass('selected'); // Sets the border of the unselected thumbnails.
		$(self).addClass('selected'); // Sets the border of the selected thumbnail.
		//if(!$has.touch){
			$('#albumSliderContainer').scrollTo(Music.albumArray[thumbIndex], Music.sliderSpeed, { easing: Music.easingStyle }); // Scrolls to the appropriate album.
		//}
		/*else if($has.touch){
			$('#albumSlider').css({ '-webkit-transform' : 'translateX('+newAlbumLocation+'px)' });
				console.log($('#albumSlider').width());

		}*/
	
	},
	
	checkKey: function(e){
		if(Music.lyricsVisible){ // only works if lyrics are visible
			var whichKey = (window.event) ? event.keyCode : e.keyCode;
			switch(whichKey)
			{
				case 37: // left arrow
					Music.previousLyrics();
					$('.leftArrow').animate({ 'opacity' : '1' }, 0 , function(){
						$(this).animate({ 'opacity': '0.3' });
					});
					break;
				case 39: // right arrow
					Music.nextLyrics();
					$('.rightArrow').animate({ 'opacity' : '1' }, 0, function(){
						$(this).animate({ 'opacity': '0.3' });
					});
					break;
			}
		}
		else{
			return false;	
		}
	},
	
	addLyrics: function(songIndex){
		this.songIndex = songIndex;
		var albumTitle = Music.extractAlbumName(); // retrieve album title
		var songTitle = Music.extractSongTitle(songIndex); // retrieve song title
		var songLyrics = Music.extractSongLyrics(songIndex); // retrieve lyrics
		var songCredits = Music.extractSongCredits(songIndex); // retrieve credits
		$('#songTitle').append("<img src='images/album_title.png' /><h3>" + songTitle + "</h3> <img src='images/album_title.png' />");
		$('#songCredit').prepend("<p>" + songCredits + "</p>");
		if(songLyrics.length == 1)
			$('#songLyrics').prepend("<p>" + songLyrics + "</p>");
		else
			$('#songLyrics').prepend("<div id='lyricsLeft'><p>" + songLyrics[0] + "</p></div><div id='lyricsRight'><p>" + songLyrics[1] + "</p></div>");
		
		$('#lyrics').fadeIn();
	},
	
	nextLyrics: function(){
		$('#songTitle, #songCredit, #songLyrics').html(""); // reset song info
		var albumTracks = $('.albumTracks');
		var numberOfSongs = $(albumTracks[Music.albumIndex]).children('ul').length;
		Music.songIndex++;
		if(Music.songIndex > numberOfSongs - 1)
			Music.songIndex = 0;
		Music.addLyrics(Music.songIndex, 0);
	},
	
	previousLyrics: function(){
		$('#songTitle').html("");
		$('#songCredit').html("");
		$('#songLyrics').html("");
		var albumTracks = $('.albumTracks');
		var numberOfSongs = $(albumTracks[Music.albumIndex]).children('ul').length;
		Music.songIndex--;
		if(Music.songIndex < 0)
			Music.songIndex = numberOfSongs - 1;
		Music.addLyrics(Music.songIndex, 0);
	},
	
	extractAlbumName: function(albumIndex){
		var album = Music.xmlDoc.getElementsByTagName("ALBUM");
		var albumTitle = album[Music.albumIndex].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
		return albumTitle;	
	},
	
	extractSongTitle: function(songIndex){
		var album = Music.xmlDoc.getElementsByTagName("ALBUM");
		var songTitle = album[Music.albumIndex].getElementsByTagName("SONG");
		var title = songTitle[songIndex].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
		return title;	
	},
	
	extractSongCredits: function(songIndex){
		var album = Music.xmlDoc.getElementsByTagName("ALBUM");
		var songTitle = album[Music.albumIndex].getElementsByTagName("SONG");
		var credits = songTitle[songIndex].getElementsByTagName("CREDITS")[0].childNodes[0].nodeValue;
		return credits;
	},
	
	extractSongLyrics: function(songIndex){
		var album = Music.xmlDoc.getElementsByTagName("ALBUM");
		var songTitle = album[Music.albumIndex].getElementsByTagName("SONG");
		var lyrics = songTitle[songIndex].getElementsByTagName("LYRICS")[0].childNodes[0].nodeValue;
		lyrics = lyrics.toString().replace(/0/g, "<br/>");
		lyrics = lyrics.split('_');
		
		return lyrics;
	} 

}

// Store Page

function Store(){
	
	this.sliderSpeed = 500;
	this.easingMethod = "easeInOutQuint";
	this.storePageArray = new Array("#storeMusic", "#storeApparel", "#storeOther");
	this.currentPage = "#storeMusic";
	this.thumbView = true;
	this.fullScreenView = false;
	this.maxScrollRight = false;
	this.pageIsActive = false;
	this.buttonLock = false;
	this.styleLock = false;
	this.firstTime = true;
}

Store.prototype = 
{
	loadAppropriateCss: function(buttonIndex){
		if(buttonIndex == 0){
			$('#storeSlider').removeClass('full');
		}
		if(buttonIndex == 1){
			$('#storeSlider').addClass('full');
		}
		setTimeout(Store.checkPageWidth, 300);
	},
	goToPage: function(thumbIndex, pageTitle){
		if(!Store.firstTime){
			if(Store.currentPage != Store.storePageArray[thumbIndex]){
				$(Store.currentPage).fadeOut('fast', function(){
					Store.currentPage = Store.storePageArray[thumbIndex];
					$('#storeTitle h2').html(pageTitle);
					Store.checkPageWidth();
					$(Store.currentPage).fadeIn();
				});	
			}
		}
		else if(Store.firstTime){
			$(Store.currentPage).fadeOut('fast', function(){
				Store.currentPage = Store.storePageArray[thumbIndex];
				$('#storeTitle h2').html(pageTitle);
				Store.checkPageWidth();
				$(Store.currentPage).fadeIn();
			});	
		}
	},
	checkPageWidth: function(){
		var pageWidth = $(Store.currentPage).width();
		var pageUl = $(Store.currentPage).children('ul');
		var liWidth = $(Store.currentPage).children('ul').children('li').width();
		var numberOfUl = $(pageUl).length;
		var widthOfUl = $(pageUl).width();
		$(Store.currentPage).css({ 'width' : widthOfUl * numberOfUl });
		var newPageWidth = $(Store.currentPage).width();
		Store.checkArrows(liWidth);
		$('#storeSlider').animate({ 'opacity' : '1' }, 'fast', function(){
			if(Store.firstTime){
				$('img.merchTable').fadeOut();
				Store.firstTime = false;
			}
			Store.styleLock = false;
		});
	},
	nextPage: function(){
		var currentPage = this.currentPage;
		var pagePosition = $(currentPage).position();
		var liWidth = $(this.currentPage).children('ul').children('li').width();
		if(this.maxScrollRight == false && Store.buttonLock == false){
			Store.buttonLock = true;
			$('#storeSlider').scrollTo("+=564px", Store.sliderSpeed, { 
				easing: Store.easingMethod,
				onAfter: function(){ 
					Store.checkArrows(liWidth); 
					Store.buttonLock = false;
				}
			});
		}
	},
	previousPage: function(){
		Store.maxScrollRight = false;
		$('#storeSlider').scrollTo("-=564px", Store.sliderSpeed, {
			easing: Store.easingMethod,
			onAfter: function(){ Store.checkArrows(); }
		});
	},
	checkArrows: function(liWidth){
		var pageWidth = $(this.currentPage).width();
		var currentPage = this.currentPage;
		var pagePosition = $(currentPage).position();
		var numberOfLi = $(currentPage).children('ul').children('li').length;
		var numberOfUl = $(currentPage).children('ul').length;
		
		
		if(pagePosition.left != 0){
			Store.pageIsActive = true;
			$('.arrowLeftActive').fadeIn();
		}
		else{
			Store.pageIsActive = false;
			Store.maxScrollRight = false;
			$('.arrowLeftActive').fadeOut('fast');
		}
		
		if(liWidth == 188){
			if(pagePosition.left == -(564 * numberOfUl) + 564){
				$('.arrowRightActive').fadeOut('fast');
				Store.maxScrollRight = true;
			}
		}
		if(liWidth == 282){
			if(pagePosition.left == -((numberOfLi * 282) - 282)){
				$('.arrowRightActive').fadeOut('fast');
				Store.maxScrollRight = true;
			}
			else{
				Store.maxScrollRight = false;
				$('.arrowRightActive').fadeIn('fast');	
			}
		}
		
		if(pageWidth > 564 && !Store.maxScrollRight)
			$('.arrowRightActive').fadeIn('fast');
		else
			$('.arrowRightActive').fadeOut('fast');
			
	}
}

// About Page

function About(){
	this.firstTime = true;	
}

function submitEmail(){
	var email_address = $('#emailAddress').val();
	$.ajax({
		url: "http://app.topspin.net/api/v1/fan/create_fan",
		type: "GET",
		dataType: 'jsonp',
		data:  ({ 'fan' : {
						   email: '' + email_address + '',
						   source_campaign: 'https://app.topspin.net/api/v1/artist/3260/campaign/10095703', 
						   referring_url: 'http://thecivilwars.com',
						   confirmation_target: 'http://www.topspindownloads.com/confirm/',
						   artist_id:  '3260'
						   }
				}),
		success: function(resp) {
			$('.addressForm').fadeOut(function(){
				$("<p>Thank you! Please check your email for confirmation.</p>").appendTo('#email');
			}); 
		}, 
		error: function(){
			$('#emailAddress').css({ 'border' : '1px solid #9E0000' });	
		}

	});	
}

function getDownload(){
	var email_address = $('#freeEmail').val();
	$.ajax({
		url: "http://app.topspin.net/api/v1/fan/create_fan",
		type: "GET",
		dataType: 'jsonp',
		data:  ({ 'fan' : {
						   email: '' + email_address + '',
						   source_campaign: 'https://app.topspin.net/api/v1/artist/3260/campaign/10095703', 
						   referring_url: 'http://thecivilwars.com',
						   confirmation_target: 'http://www.topspindownloads.com/confirm/',
						   artist_id:  '3260'
						   }
				}),
		success: function(resp) {
			$('.free_download_form').fadeOut(function(){
				$("<p>Thank you! Please check your email for confirmation.</p>").appendTo('#freeDownload');
			}); 
		}, 
		error: function(){
			$('#freeEmail').css({ 'border' : '1px solid #9E0000' });	
		}

	});	
}


