/*  Copyright (C) 2009, 2010 Josiah Barber

    The JavaScript code in this page is free software: you can
    redistribute it and/or modify it under the terms of the GNU
    General Public License (GNU GPL) as published by the Free Software
    Foundation, either version 3 of the License, or (at your option)
    any later version.  The code is distributed WITHOUT ANY WARRANTY;
    without even the implied warranty of MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
*/

var flags = ['drums', 'keyboard', 'vocals', 'guitar', 'violin'];

var songs = [
//    {name: "Ann", date: "20090916", flags: ['vocals', 'guitar', 'violin'],
//     description: "I periodically get crushes.  It's a little embarrassing.</p>" +
//"<p><i>Your name is Ann;<br />My name is Darshan.</i> [x2]</p>" +
//"<p><i>I like the way you talk;<br />I like your Czech accent.</i></p>" +
//"<p><i>I love the shape of your lips,<br />and I love your beautiful eyes.</i> [x2]</p>" +
//"<p><i>I like your skin.<br />Oh, it's beautiful,<br />Skin, oh, it's so soft,<br />Skin, oh it's beautiful and soft.</i> [x2]</p>" +
//"<p><i>I like the way you walk;<br />I like your Czech assets.</i></p>" +
//"<p><i>I love the shape of your hips,<br />and I love that you're pretty and wise.</i> [x2]"},

//    {name: "Ann - Part 1", date: "20090911", flags: ['vocals', 'guitar'],
//     description: "The first version."},

//    {name: "Ann - Part 2", date: "20090911", flags: ['vocals', 'guitar', 'violin'],
//     description: "First draft of the updated version."},

    {name: "Too Much For One Heart", date: "20091106", flags: ['guitar', 'vocals'],
     description: "Self expression is satisfying.</p>" +

"<p><i>It feels like my heart is going to explode.<br />" +
"It feels like my heart is going to explode.</i></p>" +

"<p><i>Sometimes my heart grows so fast.<br />" +
"Sometimes my heart grows so fast,<br />" +
"that I cry my eyes. I cry my eyes out.<br />" +
"I write cheesy songs, and I cry my eyes out.</i></p>" +

"<p><i>All that I feel is too much for my heart to bear alone.<br />" +
"All this love is too much for one heart.<br />" +
"The only way to survive is friends and lovers.<br />" +
"We can put our hearts together, and feel, feel, feel, feel<br />" +
"love. Love. Love, love, love, love.</i></p>" +

"<p><i>Sometimes my heart feels so much.<br />" +
"Sometimes my heart feels so much,<br />" +
"that I cry my eyes. I cry my eyes out.<br />" +
"I write cheesy songs, and I cry my eyes out.</i>"},

    {name: "I Endure", date: "20091004", flags: ['guitar', 'vocals'],
     description: "I wrote this in the winter of 2000.  It's been one of my favorite songs ever since, but for some reason I never got around to recording it until today.</p>" +
"<p><i>Every morning, I get real tired, and I lie down in my soft, warm bed.</i><br/>" +
"<i>Images pass before my eyes.</i><br/>" +
"<i>Scenes are granted my mind to view.</i><br/>" +
"<i>Other worlds I enter at random.</i></p>" +

"<p><i>The story makes no sense, but it's cool as hell.</i><br/>" +
"<i>Sam says that it's cool as ice, nevertheless it's cool as hell.</i></p>" +

"<p><i>Every afternoon, I wake up in a soft, warm place.</i><br/>" +
"<i>Images are granted me of what can only be described as a room.</i><br/>" +
"<i>And I can only be described as Josiah.</i><br/>" +
"<i>And this can only be described as life.</i></p>" +

"<p><i>I endure.</i><br/>" +
"<i>Do you der?</i><br/>" +
"<i>To der is to be cool.</i><br/>" +
"<i>To be cool is to live right.</i><br/>" +
"<i>To live right is to enter paradise.</i></p>" +

"<p><i>Yeah, I'm going to heaven.</i><br/>" +
"<i>Are you gonna see/meet me there?</i></p>" +

"<p><i>If you want to see me in heaven,</i><br/>" +
"<i>Then you will der, and you will der.</i><br/>" +
"<i>Just like I do.</i><br/>" +
"<i>Just like me.</i>"},

    {name: "Things Have Changed", date: "20091004", flags: ['guitar', 'vocals'],
     description: "I used to be part of a spirtual community that was just a bit cult-like.  The head teacher had way too much control over us, and this somewhat angry, self-empowering song was written right after I left the group in spring 2007.</p>" +
"<p><i>Things have chaged.</i><br/>" +
"<i>You cannot take advantage of me or my friends anymore.</i></p>" +

"<p><i>I have connections.</i><br/>" +
"<i>I have power.</i><br/>" +
"<i>I have money — Oh, yeah, that's power.</i><br/>" +
"<i>I have the means to repay what you did to me.</i><br/>" +
"<i>I have the means to put you out of your misery.</i><br/>" +
"<i>Don't tempt me. Oh no, don't try me.</i></p>" +

"<p><i>You've been warned.</i><br/>" +
"<i>You better watch out.</i><br/>" +
"<i>You've been warned.</i>"},

    {name: "Ann", date: "20091004", flags: ['guitar', 'vocals'],
     description: "I had a crush on my friend, Ann, in September 2009.</p>" +
"<p><i>I like your skin.</i><br/>" +
"<i>Skin, oh it's beautiful.</i><br/>" +
"<i>Skin, oh it's so soft.</i><br/>" +
"<i>Skin, oh it's beautiful and soft.</i></p>" +

"<p><i>I like your voice.</i><br/>" +
"<i>Voice, oh it's beautiful.</i><br/>" +
"<i>Voice, oh it's so sweet.</i><br/>" +
"<i>Voice, oh it's beautiful and sweet.</i></p>" +

"<p><i>Your name is Ann.</i><br/>" +
"<i>My name is Darshan.</i><br/>" +
"<i>I like the way you talk; I like your Czech accent.</i><br/>" +
"<i>I love the shape of your lips, and I love your beautiful eyes.</i>"},

    {name: "Ellen", date: "20091004", flags: ['guitar', 'vocals'],
     description: "I had a crush on my friend, Ellen, in January 2008.</p>" +
"<p><i>Ellen, I like you.</i></p>" +

"<p><i>While it is certainly true that I don't know you very well,</i><br/>" +
"<i>It is also true that I really like what I know.</i></p>" +

"<p><i>I'd like to dance with you.</i><br/>" +
"<i>How'd you like to dance with me?</i><br/>" +
"<i>Well, I could dance the whole night through, If I could dance with you.</i>"},

    {name: "Invitation to Love", date: "20091004", flags: ['guitar', 'vocals'],
     description: "I wrote this in the summer of 2004. I was getting really into meditation and experiencing a lot of lovey feelings inside, but I was also feeling very critcal of the world and felt that it was severely broken and lacking in love.</p>" +
"<p><i>What has happened to the world we live in?</i><br/>" +
"<i>Love is talked/sung about, but practically forgotten.</i></p>" +

"<p><i>Well, I invite you to know love.</i></p>" +

"<p><i>Love is offered for us to just rest/dance/sing/play/laugh in.</i><br/>" +
     "<i>So just sing and dance and play and laugh in it.</i>"},

    {name: "Miraculous", date: "20091004", flags: ['guitar', 'vocals'],
     description: "A funny little song written in the summer of 2007.</p>" +
"<p><i>It's so miraculous just to be alive.</i></p>" +

"<p><i>Let's go for a walk,</i><br/>" +
"<i>Let's take a walk through life,</i><br/>" +
"<i>Let's go out together,</i><br/>" +
"<i>Let's go out tonight.</i></p>" +

"<p><i>Just that we exist I feel is a miracle.</i><br/>" +
"<i>It's so miraculous just to be around.</i>"},

    {name: "Strawberry-Rhubarb Jam", date: "20090502", flags: ['drums', 'keyboard'],
     description: "As in: jam session with myself. 'Record' was pressed four times, with 'rewind' pressed in between. I often do that and then cut-and-paste the pieces until I'm happy with the arrangement. Other times, like here and with Jet Set, I'm so intrigued by the result that I can't bring myself to ruin the organic flow, so I leave them as they are."},

    {name: "Nigirizushi", date: "20090430", flags: ['drums', 'keyboard'],
     description: "Arranged, but not much."},

    {name: "Taco Salad", date: "20090506",
     description: "For some reason I felt like I was wrestling with this one; the basic idea came together easily, but then little things kept going wrong and it just wouldn't quite come together. But I'm happy with where it's at now."},

    {name: "Deprimido sin Café", date: "20090504", flags: ['drums', 'keyboard'],
     description: "Every five days or so, I skip my daily cup of coffee. I usually feel a bit down on those days."},

    {name: "Blue Caramel Corn", date: "20090424", flags: ['drums', 'keyboard'],
     description: "The beginning of the roll. I took the time to arrange this one pretty carefully."},

    {name: "Licorice", date: "20090428", flags: ['drums', 'keyboard'],
     description: "Left alone, but planned out before recording."},

    {name: "Jet Set", date: "20090313", flags: ['drums', 'keyboard'],
     description: "A jam session with myself."},

    {name: "'fore I", "basename" : "Fore I", date: "200912", flags: ['vocals', 'guitar'],
     description: "One of the only songs up here right now in which I actually sing.  I love singing, but most of my songwriting lately has been done in the wee hours of the morning, when Asha's sleeping, so my only option is electronic music and headphones.</p>" +

"<p>When I write songs, I usually just sing whatever random words come out of my mouth. Sometimes I keep them; other times I go back and write real lyrics.  In the case of <i>'fore I</i>, I felt embarrassed by the initial \"word soup,\" so when I played it for Asha for the first time, I warned her that the lyrics were stupid and that I was planning on writing real lyrics soon.</p>" +

"<p>When she heard it, however, she said that she loved the lyrics and that I had to keep them. She explained that they meant:</p>" +

"<p><i>'fore I get out of town</i> = before I die</p>" +

"<p><i>I better watch/jump with ladies on the trampoline; watch/swim with women in the submarine</i> = have fun connecting with pretty ladies</p>" +

"<p><i>I'm gonna knock your socks off / rock your world 'til you're in love with me</i> = make music that rocks / have fun connecting with pretty ladies</p>" +

"<p>I figured that was probably about right."},
    {name: "Nine Times", date: "200806", flags: ['vocals', 'guitar'],
     description: "Remember the Instrumental Improvisational Thingy?  It started as a guitar riff that I liked and decided to record.  This song is what happened when I took the riff and decided to try singing over it instead of doing instrumental things over it.  The lyrics are pretty ridiculous and aren't actually about anyone; they just happened to fit the rhythm I wanted to sing."},

    {name: "20090624", date: "20090624", flags: ['drums', 'keyboard'],
     description: "Another one that was only meant as a bunch of ideas that might go well together if cut and pasted a lot.  Unlike with <i>Strawberry-Rhubarb Jam</i>, however, this one was left unarranged out of laziness rather than out of admiration of its current state.  It's been long enough that I don't think I'll ever get around to chopping it up, but I think it's good enough to share as it is."},

    {name: "Girls Are Very Pretty", date: "2008Summer", flags: ['drums', 'violin', 'guitar'],
     description: "An idea I always meant to elaborate on, but probably never will, at this point."},

    {name: "Cells", date: "200804", flags: ['drums', 'keyboard', 'vocals', 'guitar'],
     description: "Written for my Anatomy and Physiology class.  I find this recording kind of hard to listen to now. My generally slightly-out-of-tune vocals are more so, the whole thing feels really loose, and something with the levels just hurts my ears.  Sorry.  At least this proves I'm improving. Anyway, I spent a lot of time on it and was pretty proud of it at the time, so here it is."},

    {name: "Heart", date: "200805", flags: ['drums', 'keyboard', 'vocals'],
     description: "Here's another song written for Anatomy and Physiology class."},

    {name: "Six Point Seven", date: "200805", flags: ['drums', 'keyboard', 'vocals'],
     description: "One of the songs I've spent the most time on. When I do it \"live\" with my sampler, it has a super-cool intro and outro that I really should record at some point."},

//    {name: "", date: "",
//     description: ""},

]

var cur = 0;
var audioSupported = false;

function propagateDescriptions() {
  var s = "";
  for (var i = 0; i < songs.length; i++){
      s += '<p><span title="Play this track" class="songname" onClick="setSong(' +
          i + '); playCur()"><b>' +
          songs[i]['name'] + '</b></span> - ' +
          '<i>' + prettyDate(songs[i]['date']) + '</i> - ' +
          songs[i]['description'] +
          '</p>';
  }

  document.getElementById("descriptions").innerHTML = s;
}

// Must have an audio element in the page first
function checkAudioSupport() {
  var au = document.getElementsByTagName("audio")[0];
  if (! au.canPlayType) return;
  var oggSupport = au.canPlayType("audio/ogg");
  var mpegSupport = au.canPlayType("audio/mpeg");
  if (oggSupport == "probably" ||
      oggSupport == "maybe" ||
      mpegSupport == "probably" ||
      mpegSupport == "maybe")
    audioSupported = true;
}

function setSong(index) {
  if (index >= songs.length) index = 0;
  if (index < 0) index = songs.length - 1;

  cur = index;

  var prevIndex = index - 1;
  if (prevIndex < 0) prevIndex = songs.length - 1;

  var nextIndex = index + 1;
  if (nextIndex >= songs.length) nextIndex = 0;

  var name = songs[index]['name'];
  var basename = songs[index]['basename'] || name;
  var prevName = songs[prevIndex]['name'];
  var nextName = songs[nextIndex]['name'];

  document.getElementById("playerarea").innerHTML = '\
    <div id="curtrackname"></div>\
    <div id="curtracktime"></div>\
    <audio>\
      <source src="' + basename + '.ogg" type="audio/ogg" />\
      <source src="' + basename + '.mp3" type="audio/mpeg" />\
        <i>This page uses the </i><code>audio</code><i> element,\
        which your browser does not appear to support.</i><br />\
    </audio>\
    <div id="controls"></div>';

  if (! audioSupported) checkAudioSupport(); //starts as false; if it's true already, we're good
  if (! audioSupported) return;

  var au = document.getElementsByTagName("audio")[0];

  document.getElementById("curtrackname").innerHTML = name;
  document.getElementById("curtracktime").innerHTML = '' +
    '<span id="curtime">0:00</span> / <span id="duration">0:00</span>';

  document.getElementById("controls").innerHTML = '\
    <img title="Previous: ' + prevName + '" onClick="prevSong()" src="previous.png" />\
    <img title="Backward 10 seconds" onClick="seekBackward()" src="backward.png" />\
    <img title="Play" onClick="togglePause()" src="play-disabled.png" id="playpause_b" />\
    <img title="Forward 10 seconds" onClick="seekForward()" src="forward.png" />\
    <img title="Next: ' + nextName + '" onClick="nextSong()" src="next.png" />';

  au.addEventListener("ended", nextSong, true);
  au.addEventListener("durationchange", dispDuration, true);
  au.addEventListener("timeupdate", dispCurrentTime, true);
  au.addEventListener("canplay", updatePlayPauseButton, true);

  updatePlayPauseButton(); //Might have been ready before listener was set

  while (cur > 0) {
      songs.push(songs[0]);
      songs.shift();
      cur--;
  }

  propagateDescriptions();
  window.scroll(0,0);
}

function onPageLoad() {
  propagateDescriptions();
  setSong(cur);
}

function nextSong() {
  var shouldPlay = ! isPaused();
  setSong(cur + 1);
  if (shouldPlay) playCur();
}

function prevSong() {
  var shouldPlay = ! isPaused();
  setSong(cur - 1);
  if (shouldPlay) playCur();
}

function pauseCur() {
  document.getElementsByTagName("audio")[0].pause();
  updatePlayPauseButton();
}

function playCur() {
  document.getElementsByTagName("audio")[0].play();
  updatePlayPauseButton();
}

function seekForward() {
  document.getElementsByTagName("audio")[0].currentTime += 10;
}

function seekBackward() {
  document.getElementsByTagName("audio")[0].currentTime -= 10;
}

function updatePlayPauseButton() {
  var src;
  var title = "Play";

  if (! isPaused()) {
    src = "pause.png";
    title = "Pause";
  }
  else if (isPlayable()) src = "play.png";
  else src = "play-disabled.png";

  document.getElementById("playpause_b").src = src;
  document.getElementById("playpause_b").title = title;
}

function togglePause() {
  isPaused() ? playCur() : pauseCur();
}

function isPaused() {
  return document.getElementsByTagName("audio")[0].paused;
}

function isPlayable() {
  return (document.getElementsByTagName("audio")[0].readyState >= 3);
}

function getDuration() {
  return document.getElementsByTagName("audio")[0].duration;
}

function getCurrentTime() {
  return document.getElementsByTagName("audio")[0].currentTime;
}

function dispDuration() {
  var d = getDuration();
  if (d) document.getElementById("duration").innerHTML = prettyTime(d);
}

function dispCurrentTime() {
  var c = getCurrentTime();
  if (c) document.getElementById("curtime").innerHTML = prettyTime(c);
}

function prettyTime(t) {
  var m = Math.floor(t / 60);
  if (m < 0) m = "0";

  var s = Math.round(Math.floor(t) % 60).toString();
  if (s.length == 1) s = "0" + s;

  return m + ":" + s;
}

function compareSongsByDate(a, b) {
  if (a['date'] < b['date'])
    return -1;
  if (a['date'] > b['date'])
    return 1;
  return 0;
}

function prettyDate(s) {
  var months = {
    "01" : "January",
    "02" : "February",
    "03" : "March",
    "04" : "April",
    "05" : "May",
    "06" : "June",
    "07" : "July",
    "08" : "August",
    "09" : "September",
    "10" : "October",
    "11" : "November",
    "12" : "December"
  };

  var year = s.substr(0, 4);
  if (! /\d/.test(s[4])) return s.substr(4) + " " + year;

  var month = months[s.substr(4, 2)];
  var day = s.substr(6, 2);
  if (day[0] == "0") day = day[1];

  s = ""
  if (day) s += day + " ";
  s += month + " ";
  s += year;

  return s;
}

