// JavaScript Document

function MyMain(){
	
	$.backstretch("images/background.jpg");
	
	var blogURL = "/wordpress/?";
	
	/*var pathname = window.location.toString();
	if(pathname.indexOf("www") >= 0){
		blogURL = "http://www.keerilmakan.com/wordpress/?";
	}*/
	
	var mainData;
	var pageData;
	
	var addressArray = []; //this is the array we build from the address bar
	var jqueryAddressArray = []; // these are all the possible jquery addresses, retrieved from the main nav
	var mainNavObj = $("body").find("#mainnav li");
	var currentPage="notset";
	var fadeTime = 500;
	var isSwapping = false;
	var justLoaded = true;
	
	var quoteObj;
	var currentQuoteIndex;
	
	var genres = [];
	var recordings = [];
	var pieces = [];
	
	var audContainer = $("#audContainer");
	var audio;// = audContainer.children('#myAudio');
	var actualAudio;// = audio.get(0);
	
	var playerIsOpen = false;
	
	function scrollToTarget(tgt){
		//console.log("SCROLL TO "+tgt);
		$(window).scrollTo(tgt, 800);	
	}
	
	
	function resetNav(){
		mainNavObj.each(function(index) {
			var theBtn = $(this);
			var theID = theBtn.attr("ref");
			
			if(theID == addressArray[0]){
				if (!(theBtn.is('.selected'))) {
					theBtn.addClass("selected");
				}
			} else {
				if ((theBtn.is('.selected'))) {
					theBtn.removeClass("selected");
				}
			}
		});
	};
	
	function fadeInQuote(){
		$("#main-content .content-animated h3").eq(currentQuoteIndex).css( {left: 0});
		$("#main-content .content-animated h3").eq(currentQuoteIndex).animate({
			opacity: 1
		}, fadeTime, function() {
    		startQuoteTimer();			
		});
	}
	
	function fadeOutQuote(){
		$("#main-content .content-animated h3").eq(currentQuoteIndex).animate({
			left: '-10px',
			opacity: 0
		}, fadeTime, function() {
    		if(currentQuoteIndex < quoteObj.length - 1){
				currentQuoteIndex ++;
			} else {
				currentQuoteIndex = 0;
			}
			fadeInQuote();
		});
	}
	
	function startQuoteTimer(){
		$("#main-content").doTimeout( 'quoteTimer', 5000, function(){
			if(addressArray[0] == "home" || addressArray[0] == "bio"){
				fadeOutQuote();
			}
		});	
	}
	
	function loadVideo(theLink){
		//console.log("load video: "+theLink);
		var vidID = theLink.substring(theLink.lastIndexOf('/') + 1);
		//console.log(vidID);
		
		var str = '<iframe width="640" height="480" src="http://www.youtube.com/embed/'+vidID+'" frameborder="0" allowfullscreen></iframe>'
		
		$('#main-content #vidsIFrame').html(str);
	}
		
	function showNewContent(){
		var contentIWant;
		if(addressArray[0] == "home" || addressArray[0] == "bio" || addressArray[0] == "photos"){
			contentIWant = $('#main-content').find('div .entry-content').html();
			$('#main-content').html("<div class='content-animated'>"+contentIWant+"</div>");
		}
		if(addressArray[0] == "videos"){
			contentIWant = $('#main-content').find('div .entry-content').html();
			$('#main-content').html("<div class='content-animated'></div>");
			
			str = "<div class='vids'><h1>Videos</h1>";
			
			str += '<div id="vidsIFrame"></iframe></div>';
			
			str += "</div><div id='vidLinks'><p>Videos:</p></div>";
			$('#main-content .content-animated').append(str);
			
			$('#main-content #vidLinks').append(contentIWant);
			
			$('#vidLinks').click(function(e){
				if( $(e.target).is('a') ){
					
					if (e.preventDefault) {
						e.preventDefault();
					} else {
						e.returnValue = false;
					}
					e.stopImmediatePropagation();
					loadVideo(e.target.href);
					return false;
					
				}
				
				/*
				// even out the event models
				e = ( e ) ? e : event;
				var el = e.target || e.srcElement;
				
				if ( el.nodeName.toLowerCase() == 'a') {
					alert("link clicked");
					// cancel the default action
					if (e.preventDefault) {
						e.preventDefault();
					} else {
						e.returnValue = false;
					}
				}
				*/
				
			});
			
			var linkObj = $("#vidLinks").find("a");
			linkObj.each(function(index) {
				var theLink = $(this);
				loadVideo(theLink.attr('href'));
				return false;
			});
			
		}
		
		if(addressArray[0] == "home" || addressArray[0] == "bio"){
			currentQuoteIndex = 0;
			quoteObj = $("#main-content").find("h3");
			quoteObj.each(function(index) {
				var theQuote = $(this);
				theQuote.addClass("quote-animated");
				if(index > 0){
					theQuote.css({ opacity: 0 });
				}
			});
			if(quoteObj.length > 0){
				startQuoteTimer();
			}
		} 
		
		$('#main-content .content-animated').animate({
			left: '0px'
		}, fadeTime*1.5, function() {
			if(addressArray.length > 1){
				scrollToTarget("#"+addressArray[addressArray.length-1]);	
			}
		});
		$('#main-content').fadeTo(fadeTime, 1);
		isSwapping = false;
		if($('#subnav')){
			$('#subnav').fadeTo(fadeTime, 0.8);
		}
		
		if(addressArray[0] == "videos"){
			$('#events').fadeTo(fadeTime, 0, function() {
			$('#events').css({ visibility: 'hidden' });
		});
		} else {
			$('#events').css({ visibility: 'visible' });
			$('#events').fadeTo(fadeTime, 1);
		}
	}
	
	function loadNewMainContent(){
		if(addressArray[0] == undefined){
			return false;	
		}
		
		if($('#subnav')){
			$('#subnav').remove();
		}
		
		var myURL;
		
		var itm;
		var str;
		var piece;
		var childIWant;
		var childNum;
		var linkTxt;
		var anchorTxt;
		
		if(addressArray[0] == "home"){
			myURL = blogURL+"page_id=476 #content";
			$('#main-content').load(myURL, showNewContent);
		} else if(addressArray[0] == "bio"){
			myURL = blogURL+"page_id=2 #content";
			$('#main-content').load(myURL, showNewContent);
		} else if(addressArray[0] == "photos"){
			myURL = blogURL+"page_id=579 #content";
			$('#main-content').load(myURL, showNewContent);
		} else if(addressArray[0] == "videos"){
			myURL = blogURL+"page_id=748 #content";
			$('#main-content').load(myURL, showNewContent);
		} else if(addressArray[0] == "music"){
			$('#nav').append("<ul id='subnav'></ul>");
			
			$('#main-content').empty();
			$('#main-content').html("<div class='content-animated'></div>");
			
			var cats;
			var cat;
			var pieceCats;
			
			for( var i=0; i<genres.length; i++){
				itm = genres[i];
				linkTxt = itm.find('title').text();
				anchorTxt = linkTxt.toLowerCase().replace(/ /g, '-');
				anchorTxt = anchorTxt.replace(/[(, )]/g, '');
				//console.log("anchor text is "+anchorTxt);
				
				$('#subnav').append("<li ref='subnav'><a href='#/music/"+anchorTxt+"'>"+linkTxt+"</a>");
				str = "<h1 id='"+anchorTxt+"'>"+linkTxt+"</h1>";
				cats = itm.find('category');
				cats.each(function(index) {
					if($(this).text() != "Genres"){
						cat = $(this).text();
						return false;
					}
				});
				
				for(var n=0; n<pieces.length; n++){
					piece = pieces[n];
					
					var myTitle = piece.find('title').text();
					
					anchorTxt = myTitle.toLowerCase().replace(/ /g, '-');
					anchorTxt = anchorTxt.replace(/[(, ), \:, \', \’, \", \?, \&]/g, '');
					//console.log("anchor text is "+anchorTxt);
					
					pieceCats = piece.find('category');
					pieceCats.each(function(index) {
						//console.log("testing "+ $(this).text() + " against category "+ cat);
						if($(this).text() == cat){
							//console.log("found the category "+cat);
							//console.log("title is "+myTitle);
							/*var myContent = piece.find('content:encoded').nodeValue; //comes up undefined
							var myContent = piece.find('content:encoded').text(); //causes error
							console.log(myContent);
							console.log("-----------------");*/
							//str += piece.find('content:encoded').text(); - not working, can't figure out why not.
							
							for(var t=0; t<piece.children().length; t++){
								//console.log("NODE NAME: "+piece.children()[t].nodeName); //I CAN GET THE NODE NAMES...
								//console.log("NODE VALUE: "+piece.children()[t].nodeValue);  //BUT I CAN'T GET THE NODE VALUE (null)...
								//console.log(piece.children()[t].text()); //AND I CAN'T GET THE TEXT (ERROR)
								//console.log("-----------------");
								if(piece.children()[t].nodeName == "content:encoded"){
									childIWant = t;
									//console.log("child i want is "+childIWant);
									break;
								}
							}
							childNum = 0;
							piece.children().each(function(index) {
								//console.log(childNum+", "+childIWant);
								if(childNum == childIWant){
									//console.log($(this).text());
									/*console.log("new attempt");
									if($.browser.msie){
										console.log($(this)[0].childNodes[0].nodeValue);
									} else {
										console.log($(this)[0].childNodes[1].nodeValue);
									}*/
									
									str += "<div class='piece' id='"+anchorTxt+"'><h2><b>"+myTitle+"</b></h2><p>"+$(this).text()+"</p></div>"; //this is giving me the text
									return false;
								}
								childNum ++;
								
								//console.log($(this).nodeName); //HERE I CAN'T GET THE NODE NAME (COMES UP UNDEFINED)...
								//console.log($(this).nodeValue); //AND I CAN'T GET THE NODE VALUE (COMES UP UNDEFINED)...
								//console.log($(this).text()); // BUT I CAN GET THE TEXT (WTF!?!)
								//console.log("-----------------");
							});
							return false;
						}
					});
				}
				
				$('#main-content .content-animated').append(str);
				
				//need to find all the content for each of these really
			}
				
			$('#subnav').append("<li ref='subnav' class='topOfPageLink'><a href='#/"+addressArray[0]+"/topOfPage'>Top of page</a>");
			
			showNewContent();
		} else if(addressArray[0] == "recordings") {
			$('#nav').append("<ul id='subnav'></ul>");
			
			$('#main-content').empty();
			$('#main-content').html("<div class='content-animated'></div>");
			
			var rec;
			var pieceRecs;
			//console.log("recordings length is "+recordings.length);
			for( var i=0; i<recordings.length; i++){
				itm = recordings[i];
				
				linkTxt = itm.find('title').text();
				anchorTxt = linkTxt.toLowerCase().replace(/ /g, '-');
				anchorTxt = anchorTxt.replace(/[(, )]/g, '');
				//console.log("anchor text is "+anchorTxt);
				
				$('#subnav').append("<li ref='subnav'><a href='#/recordings/"+anchorTxt+"'>"+linkTxt+"</a>");
				
				str = "<div class='recording'><h1 id='"+anchorTxt+"'>"+linkTxt+"</h1>";
				
				for(var t=0; t<itm.children().length; t++){
					//console.log(itm.children()[t].nodeName);
					if(itm.children()[t].nodeName == "content:encoded"){
						childIWant = t;
						break;
					}
				}
				childNum = 0;
				itm.children().each(function(index) {
					if(childNum == childIWant){
						//console.log("This is the child I want");
						//console.log($(this).text());
						//console.log("-----------");
						str += "<div class='recordingBody'>"+$(this).text()+"</div>";
						return false;
					}
					childNum ++;
				});
				
				cats = itm.find('category');
				cats.each(function(index) {
					if($(this).text() != "Recordings"){
						rec = $(this).text();
						return false;
					}
				});
				
				for(var n=0; n<pieces.length; n++){
					piece = pieces[n];
					
					var myTitle = piece.find('title').text();
					
					pieceRecs = piece.find('category');
					pieceRecs.each(function(index) {
						//console.log("testing "+ $(this).text() + " against category "+ rec);
						if($(this).text() == rec){
							
							for(var t=0; t<piece.children().length; t++){
								if(piece.children()[t].nodeName == "content:encoded"){
									childIWant = t;
									break;
								}
							}
							childNum = 0;
							piece.children().each(function(index) {
								if(childNum == childIWant){
									//console.log("this is the child I seek");
									//console.log($(this).text());
									//console.log("------------");
									str += "<div class='piece'><h2><b>"+myTitle+"</b></h2><p>"+$(this).text()+"</p></div>"; 
									return false;
								}
								childNum ++;
							});
							return false;
						}
					});
				}
				
				str += "</div>";
				
				str = str.replace("find","replace")
				$('#main-content .content-animated').append(str);
			}
				
			$('#subnav').append("<li ref='subnav' class='topOfPageLink'><a href='#/"+addressArray[0]+"/topOfPage'>Top of page</a>");
			
			showNewContent();
		} 
		else 
		{
			alert("need to load "+addressArray[0]);
			return false;	
		}	
	}
	
	function fadeMainContent(){
		//$('html, body').animate({ scrollTop: 0 }, 0);
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		
		$('#main-content .content-animated').animate({
			left: '-20px'
		}, fadeTime);
		$('#main-content').fadeTo(fadeTime, 0, function() {
    		loadNewMainContent();
   		 });
		 if($('#subnav')){
			$('#subnav').fadeTo(fadeTime, 0);
		}
	}
	
	function loadSongInPlayer(songID, playIt){
		
		var theLinks = $('#musicMenu').find("h2 a");
		var theLink;
		var i;
		
		for(var i = 0; i<theLinks.length; i++){
			theLink = theLinks[i].href;
			//console.log("the link "+theLink);
			theLink = theLink.substring(theLink.lastIndexOf("/")+1, theLink.lastIndexOf("."));
			//console.log("the link "+theLink);
			if(theLink == songID){
				//console.log("found it "+i);
				var myName = $('#musicMenu h2').eq(i).text();
				$("#nowPlaying").html("Playing: <span class='ital'>"+myName+"</span>");
				break;
			}
		}
		
		var audPath = "music-samples/"+songID;
		
		audContainer.html('<audio id="myAudio" controls><source id="mp3" type="audio/mpeg"><source id="ogg" type="audio/ogg"></audio>');
		audio = audContainer.children('#myAudio');
		//console.log("AUDIO");
		actualAudio = audio.get(0);
		//console.log(audio);
		//console.log("AUDIO ELEMENT");
		//console.log(audio.get(0));
		
		//set mp3 and ogg source nodes
		audio.children().each(
			function(){
				//console.log("src was "+$(this).attr("src"));
				//console.log("network state "+actualAudio.networkState);
				$(this).attr("src", (audPath+"."+$(this).attr("id")));
			}
		);
		
		//start audio player (need to call load when changing source)
		audio.load();
		if(playIt == true){
			actualAudio.play();
		}
		var theOffset = document.getElementById(songID).offsetTop;
		theOffset -= 30;
		document.getElementById("musicMenu").scrollTop = theOffset;
		//$("#musicMenu").scrollTo(songID, 800);
	}
	
	function openMusicPlayer(){
		if(playerIsOpen == false){
			$("#musicPlayer").animate({
				top: "0"
			}, 300, function() {
				$(".openClose").text("close audio");			
			});
		} else {
			$("#musicPlayer").animate({
				top: "-270px"
			}, 300, function() {
				$(".openClose").text("open audio");			
			});
		}
		playerIsOpen = !playerIsOpen;
	}
	
	function showMusicPlayer(){
		var contentIWant = $('#musicMenu').find('div .entry-content').html();
		$('#musicMenu').html(contentIWant);
		
		$('#main-container').click(function(e){
			if( $(e.target).is('a') ){
				
				var myURL = e.target.href;
				
				if(myURL.search("music-samples") != -1){
				
					if (e.preventDefault) {
						e.preventDefault();
					} else {
						e.returnValue = false;
					}
					e.stopImmediatePropagation();
					var songID = e.target.href;
					songID = songID.substring(songID.lastIndexOf("/")+1, songID.lastIndexOf("."));
					loadSongInPlayer(songID, true);
					return false;
					
				}
				
			}
			
			/*
			// even out the event models
			e = ( e ) ? e : event;
			var el = e.target || e.srcElement;
			
			if ( el.nodeName.toLowerCase() == 'a') {
				alert("link clicked");
				// cancel the default action
				if (e.preventDefault) {
					e.preventDefault();
				} else {
					e.returnValue = false;
				}
			}*/
			
		});
		
		var theLinks = $('#musicMenu').find("h2");
		var theLink;
		var theH;
		var i;
		
		var linksArray = [];
		
		for(var i = 0; i<theLinks.length; i++){
			theLink = $('#musicMenu').find("h2 a")[i].href;
			theLink = theLink.substring(theLink.lastIndexOf("/")+1, theLink.lastIndexOf("."));
			linksArray.push(theLink);
		}
		
		i = 0;
		theLinks.each(
			function(){
				$(this).attr("id", linksArray[i]);
				i ++;				
			}
		);
		
		var firstID = $('#musicMenu').find("h2 a")[0].href;
		firstID = firstID.substring(firstID.lastIndexOf("/")+1, firstID.lastIndexOf("."));
		loadSongInPlayer(linksArray[0], false);
		
		$('.openClose').click(function() {
			openMusicPlayer();
		});
	}
	
	function loadMusicPlayer(){
		var audioURL = blogURL+"page_id=754";
		$('#musicMenu').load(audioURL+" #content", showMusicPlayer);	
	}
		
	function showEvents(){
		var contentIWant = $('#events').find('div .entry-content');
		$('#events').html("<div id='events-title'><h1>EVENTS</h1></div>");
		$('#events').append(contentIWant);
		$("#events-title").css({ opacity: 0.2 });
		$('#events').fadeTo(fadeTime, 1);
		justLoaded = false;
		loadMusicPlayer();
		loadNewMainContent();
	}
	
	function loadEvents(){
		var eventsURL = blogURL+"page_id=29";
		$('#events').load(eventsURL+" #content", showEvents);
	}
	
	function mainDataLoaded(){
		alert("Data Loaded: " + mainData.text());
		//var items = mainData.find("item");
		//alert(items);
		loadEvents();
	}
	
	function loadMainData(){
		var mainDataURL = blogURL+"feed=rss2";
		//alert("getting "+mainDataURL);
		
		$.ajax({
			url: blogURL+"feed=rss2",
			dataType: "xml",
			success: function(data){
				mainData = data;
				/*console.log("MAIN DATA");
				console.log(mainData);
				console.log("-------------");*/
				$(data).find('item').each(function() {
					var $item = $(this);
					// grab the post title
					var title = $item.find('title').text();
					var categories = $item.find('category');
					//alert(title+": "+categories.length);
					categories.each(function(index) {
						if($(this).text() == "Genres"){
							//alert($(this).text());
							genres.push($item);
						}
						if($(this).text() == "Recordings"){
							//alert($(this).text());
							recordings.push($item);
						}
						if($(this).text() == "Pieces"){
							//alert($(this).text());
							pieces.push($item);
						}
					});
				});
				//alert("Genres: "+genres.length);
				//alert("Recordings: "+recordings.length);
				loadEvents();
			}
		 });
		
		/*$.get(mainDataURL, function(data) {
			mainData = data;
			//alert(mainData);
			$(data).find('item').each(function() {
				var $item = $(this);
				// grab the post title
				var title = $item.find('title').text();
				var categories = $item.find('category');
				//alert(title+": "+categories.length);
				categories.each(function(index) {
					if($(this).text() == "Genres"){
						//alert($(this).text());
						genres.push($item);
					}
					if($(this).text() == "Recordings"){
						//alert($(this).text());
						recordings.push($item);
					}
					if($(this).text() == "Pieces"){
						//alert($(this).text());
						pieces.push($item);
					}
				});
			});
			//alert("Genres: "+genres.length);
			//alert("Recordings: "+recordings.length);
			loadEvents();
		}).error(function() { alert("Sorry - there was an error loading the site data. Please refresh your browser."); });*/
		
	}
	
	/*$('#vidLinks').click(function(e){
		if( $(e.target).is('a') ){
			
			if (e.preventDefault) {
				e.preventDefault();
			} else {
				e.returnValue = false;
			}
			e.stopImmediatePropagation();
			alert("need to change video");
			return false;
			
		}*/
		
		/*
		// even out the event models
		e = ( e ) ? e : event;
		var el = e.target || e.srcElement;
		
		if ( el.nodeName.toLowerCase() == 'a') {
			alert("link clicked");
			// cancel the default action
			if (e.preventDefault) {
				e.preventDefault();
			} else {
				e.returnValue = false;
			}
		}
		*/
		
	//});
	
	
	//get all jquery addresses
	mainNavObj.each(function(index) {
		var theBtn = $(this);
		var theID = theBtn.attr("ref");
		jqueryAddressArray.push(theID);
	});
	
	//set up jquery address
	$.address.change(function(event) {
	//	console.log("address change "+event.value +", "+ addressArray[0] +", "+ currentPage);
		if(isSwapping){
			//console.log("is swapping");
			if(addressArray[0] != undefined){
				$.address.path(addressArray[0]);
			}
			//console.log("--------------");
			return false;	
		}
		var lastArray = [];
		for(var i=0; i<addressArray.length; i++){
			lastArray.push(addressArray[i]);	
		}
		addressArray.length = 0;
		if(event.value == "/"){
			addressArray.push("home");
			if(currentPage == "notset"){
				currentPage = "home";
			}
		} else {
			var str = event.value;
			if(str.substring(0, 1) == "/"){
				str = str.substring(1, str.length);
			}
			if(str.substring(str.length-1) == "/"){
				str = str.substring(0, str.length-1);
			}
			addressArray = str.split("/");
		}
		
		//if justLoaded == true, then the site is just loading.
		//load events first, which will then call loadNewMainContent();
		if(justLoaded == true){
			currentPage = addressArray[0];
			isSwapping = true;
			loadMainData();
			resetNav();
			/*loadEvents();*/
			//console.log("--------------");
			return false;
		}
		//console.log("address change: "+addressArray[0]+", "+currentPage);
		if(addressArray[0] == currentPage){
			//console.log("already on that page");
			//console.log("named anchor is #"+addressArray[1]);
			if(addressArray.length == 1 || addressArray[addressArray.length-1] == "topOfPage"){
				$('html, body').animate({ scrollTop: 0 }, 'slow');	
			} else {
				scrollToTarget("#"+addressArray[addressArray.length-1]);
			}
			//console.log("--------------");
			return false;	
		} else {
			if(currentPage == "home"){
				//stop the quote timer on the home page
				$.doTimeout( 'quoteTimer' );	
			}
			currentPage = addressArray[0];	
			//alert("set current page to "+currentPage);
		}
		
		resetNav();
		
		fadeMainContent();
		//console.log("--------------");
	});
	
	$("header").css({ opacity: 0.15 });
	
	$("#events").css({ opacity: 0 });
	$('#main-content').css({ opacity: 0 });
}



$(document).ready(function() {
	MyMain();
});

      
