/*
  Copyright (c) 2007, POTI Inc. All Rights Reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  * Neither the name of POTI Inc. or Songbird nor the names of its contributors
  may be used to endorse or promote products derived from this software without
  specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Create the MusicPortal global object if it isn't already here
if (typeof MusicPortal == "undefined") {
  var MusicPortal={};
}

MusicPortal.init = function() {
  if (typeof(songbird) != "undefined") {

    // set an internal variable so we know we're in Songbird
    this.isSongbird = true;
    // used to alternate the stripes of the song history
    this.curHistNum = 0;
    // used to determine if the current song and previous are the same
    this.curSongTitle = 'unknown';
    this.prevSongTitle = 'unknown';
    // set the permission scope at the full domain and
    // smallest path setting so ALL pages in my site can access the same
    // site library.
    songbird.setSiteScope("", "/");

    // Add our specific properties to the Songbird player
    this.addProperties();

    // setup our listeners
    this.setupListeners();

  } else {
    this.isSongbird = false;
  }
}

/* MusicPortal.showNowListening = function() {
  if (this.isSongbird) {
    document.getElementById('now-listening').style.display = 'block';
  } else {
    document.getElementById('download-songbird').style.display = 'block';
  }
} */

/* MusicPortal.getVersion = function() {
  var version = navigator.userAgent.match(/Songbird\/([\d\.]+)(\S+)/);
  if (version != null) {
    return version[1];
  } else {
    return null;
  }
} */

MusicPortal.setupListeners = function() {
  var obs = {
    mp: MusicPortal,
    observe: function ( aSubject, aTopic, aData) {
      this.mp.setData(aTopic, aData);
    }
  }

  if (this.isSongbird) {
    // listen to songbird state changes
    songbird.addListener("metadata.artist", obs);
    songbird.addListener("metadata.album", obs);
    songbird.addListener("metadata.title", obs);
    songbird.addListener("metadata.genre", obs);

  }
}

// These just look up a specific element in the document and then set
// the innerHTML to the new value passed in.
MusicPortal.onArtistChanged = function(value) {
  document.getElementById("curArtist").innerHTML = value;
}
MusicPortal.onAlbumChanged = function(value) {
  document.getElementById("curAlbum").innerHTML = value;
}
MusicPortal.onTitleChanged = function(value) {
  document.getElementById("curTitle").innerHTML = value;
  document.getElementById("curTitle").href = "http://skreemr.com/results.jsp?q=" + value +"&search=SkreemR+Search";
  document.getElementById("curTitle").title = "Search SkreemR for " + value;

  if (value != 'unknown') {
    this.curSongTitle = value;
    if (this.curSongTitle != this.prevSongTitle) {
      this.curHistNum++;
      var histRootElement = document.getElementById("songHistList");
      var newSongHistItem = document.createElement("li");
      // array for the SkreemR metadata links.
      var newSongHistLink = new Array();
          newSongHistLink['title']  = new Array(2);
          newSongHistLink['artist'] = new Array(2);
          newSongHistLink['album']  = new Array(2);
          newSongHistLink['genre']  = document.createElement("a");
      // array for the metadata separators
      var newSongHistSeparator      = new Array(6);
      var newSongHistTime = document.createElement("span");
      var curTimeStamp    = new Date();

      // Create SkreemR Link for the Title of the Song
      for(var i = 0; i < newSongHistLink['title'].length; i++) {
        newSongHistLink['title'][i] = document.createElement("a");
        newSongHistLink['title'][i].setAttribute("href", "http://skreemr.com/results.jsp?q="+value+"&search=SkreemR+Search");
        newSongHistLink['title'][i].setAttribute("title", "Search SkreemR for "+value);
        newSongHistLink['title'][i].innerHTML = value;
      }

      // Create SkreemR Link for the Artist of the Song
      for(var i = 0; i < newSongHistLink['artist'].length; i++) {
        newSongHistLink['artist'][i] = document.createElement("a");
        newSongHistLink['artist'][i].setAttribute("href", "http://skreemr.com/advanced_results.jsp?advanced=true&artist="+songbird.currentArtist+"&button=SkreemR+Search");
        newSongHistLink['artist'][i].setAttribute("title", "Search SkreemR for songs by "+songbird.currentArtist);
        newSongHistLink['artist'][i].innerHTML = songbird.currentArtist;
      }

      // Create SkreemR Link for the Album of the Song
      for(var i = 0; i < newSongHistLink['album'].length; i++) {
        newSongHistLink['album'][i] = document.createElement("a");
        newSongHistLink['album'][i].setAttribute("href", "http://skreemr.com/advanced_results.jsp?advanced=true&album="+songbird.currentAlbum+"&button=SkreemR+Search");
        newSongHistLink['album'][i].setAttribute("title", "Search SkreemR for other songs in the album, "+songbird.currentAlbum);
        newSongHistLink['album'][i].innerHTML = songbird.currentAlbum;
      }

      // Create separators for the different metadata fields
      for(var i = 0; i < newSongHistSeparator.length; i++) {
        newSongHistSeparator[i] = document.createElement("span");
        newSongHistSeparator[i].setAttribute("class", "separator");
        newSongHistSeparator[i].innerHTML = " &bull; ";
      }

      // For the song history list add the time the song was played
      newSongHistTime.setAttribute("class", "playedWhen");
      newSongHistTime.innerHTML = this.getCurDate(curTimeStamp);

      // Add a class attribute to allow the history list to be zebra striped.
      //newSongHistItem.setAttribute("class", (this.curHistNum % 2) ? "odd" : "even");

      newSongHistItem.appendChild(newSongHistLink['title'][1]);

      // If the song played has artist metadata get it here
      if(songbird.currentArtist != "") {
        newSongHistItem.appendChild(newSongHistSeparator[0]);
        newSongHistItem.appendChild(newSongHistLink['artist'][1]);
      }
      // If the song played has album metadata get it here
      if(songbird.currentAlbum != "") {
        newSongHistItem.appendChild(newSongHistSeparator[1]);
        newSongHistItem.appendChild(newSongHistLink['album'][1]);
      }
      newSongHistItem.appendChild(newSongHistTime);
      //histRootElement.appendChild(newSongHistItem);
      histRootElement.insertBefore(newSongHistItem, histRootElement.getElementsByTagName("li")[1]);
      this.stripeList("songHistList");
      this.prevSongTitle = this.curSongTitle;
    }
  }
}
MusicPortal.stripeList = function(value) {
  var parentElement = document.getElementById(value);
  var lis           = parentElement.getElementsByTagName("li");
  for (var i = 1; i < lis.length; i++) {
    var myli = lis[i];
    myli.className = (i%2) ? "odd" : "even";
  }
}

MusicPortal.getCurDate = function(value) {
  var curTime = value;
  var date = "";
  {
    var yyyy = curTime.getUTCFullYear();
    var MM   = curTime.getUTCMonth()+1;
        MM   = ((MM < 10)? "0":"") +MM;
    var dd   = curTime.getUTCDate();
        dd   = ((dd < 10)? "0":"") +dd;
    var hh   = curTime.getUTCHours(); /*
    var hh   = ((hh > 12)? -12:0) +hh;
        hh   = (hh == 0)? 12:hh; */
        hh   = ((hh < 10)? "0":"") +hh;
    var mm   = curTime.getUTCMinutes();
        mm   = ((mm < 10)? "0":"") +mm;
    var ss   = curTime.getUTCSeconds();
        ss   = ((ss < 10)? "0":"") +ss;
    var ms   = curTime.getUTCMilliseconds();
        ms   = ((ms < 10)? "0":"") +ms;
        ms   = ((ms < 100)? "0":"") +ms;
    var tz   = curTime.getTimezoneOffset();
    var sign = "";
    if (tz != 0) {
      (tz > 0)?(sign = "-"):(sign = "+");
      tz /= 60;
      tz = Math.abs(tz);
      tz =((tz < 10)?"0":"") +tz;
      tz = sign+tz;
    } else {
      tz = "Z";
    }
    var tt   = ((curTime.getHours() >= 12)? "PM":"AM");
        date = yyyy+"-"+MM+"-"+dd+"T"+hh+":"+mm+":"+ss+tz;
  }
  return date;
}

// Called by the observer of the state changes this code figures out
// which metadata changed and calls the appropriate function
MusicPortal.setData = function(metadata, value) {

  var emptyValue = 'unknown';

  if (value == '') {value = emptyValue;}
  if ( metadata == "metadata.artist" ) {
    this.onArtistChanged(value);
  } else if ( metadata == "metadata.album" ) {
    this.onAlbumChanged(value);
  } else if ( metadata == "metadata.title" ) {
    this.onTitleChanged(value);
  }

  if ((document.getElementById("curArtist").innerHTML == emptyValue) && (document.getElementById("curAlbum").innerHTML == emptyValue) && (document.getElementById("curTitle").innerHTML == emptyValue)) {
    document.getElementById("now-listening-metadata").style.display = "none";
    document.getElementById("now-listening-nothing").style.display = "block";
  }
  else {
    document.getElementById("now-listening-metadata").style.display = "block";
    document.getElementById("now-listening-nothing").style.display = "none";
  }
}

MusicPortal.addProperties = function() {
  // create 2 new property types that we can set values for when we
  // create mediaItems. Be sure to use a specific unique name for the
  // first arg so it doesn't overlap with any other property. Some args are
  // optional, check the docs for the full usage.
  songbird.createImageProperty("http://example.com/ccImage", "CC", true);
  songbird.createTextProperty("http://example.com/userTags", "Tags");

  // create a hidden property on items to store the link to the amazon affiate program
  songbird.createTextProperty("http://example.com/purchaseLink", "Link", true, true);
}
//    file:///builds/songbird/examples/musicblog/index.html

