/*
 * AJAX loader for Last.fm recent tracks XML feed.
 *
 * Copyright (c) 2007, silverorange Inc.
 *
 * Michael Gauthier <mike@silverorange.com>
 * http://labs.silverorange.com/
 *
 * 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 silverorange Inc. 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.
 *
 * Function documentation:
 *
 * @param DOMElement element the element to load recent tracks into.
 * @param String username the Last.fm username to get recent tracks for.
 * @param String throbber_image a URI indicating the location of the loading
 *                               throbber image.
 */





// last.fm vars
//var months = ["January", "February", "March","April", "May", "June","July","August","September","October","November", "December"];
var months = ["Jan", "Feb", "Mar","Apr", "May", "Jun","Jul","Aug","Sep","Oct","Nov", "Dec"];


// create xmlhttprequest
var request = null;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = null;
    }
  }
}
if (request == null)
  alert("Error creating request object!");



if(undefined!==document.getElementById('delicious_list')){
  var ul = document.createElement('ul')
  if(Delicious.posts){
     for (var i=0, post; post = Delicious.posts[i]; i++) {
	 var li = document.createElement('li')
	 var a = document.createElement('a')
	     var br = document.createElement('br')
	 a.setAttribute('href', post.u)
	 a.appendChild(document.createTextNode(post.d))
	 li.appendChild(a)
	     li.appendChild(br)
	     if (undefined!=post.n) {
	       li.appendChild(document.createTextNode(post.n))
	     }
	 ul.appendChild(li)
     }
   }else{
   ul.setText("test");
  } 
  document.getElementById('delicious_list').appendChild(ul)
}


// last.fm
function so_clearInnerHTML(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) obj.removeChild(obj.firstChild);
}

//
function last_fm_chart(chart_type,element,username)
{
  if (request) {
    document.getElementById('lastfm_ul').style.display = "block";
    element.innerHTML = "<p>loading last.fm chart...</p>";

      var proxy = "/includes/last-fm.php?username=" + escape(username) + "&chart_type=" + chart_type + "&dummy=" + new Date().getTime();
    request.open("GET", proxy, true);
    request.onreadystatechange = callback;
    request.send(null);
  }
}

function callback() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      var last_fm_xml = request.responseXML;
      if (last_fm_xml.getElementsByTagName("recenttracks").length == 1) {
        element.innerHTML = format_recent_tracks_chart(last_fm_xml);
      } else if (last_fm_xml.getElementsByTagName("weeklyartistchart").length == 1) {
        element.innerHTML = format_weekly_artist_chart(last_fm_xml);
      } else if (last_fm_xml.getElementsByTagName("weeklytrackchart").length == 1) {
        element.innerHTML = format_weekly_track_chart(last_fm_xml);
      } else if (last_fm_xml.getElementsByTagName("topartists").length == 1) {
        element.innerHTML = format_top_artists_chart(last_fm_xml);
      } else if (last_fm_xml.getElementsByTagName("toptracks").length == 1) {
        element.innerHTML = format_top_tracks_chart(last_fm_xml);
      }
    }
  delete request;
  }
}

function format_recent_tracks_chart(last_fm_document) {
      prepareLinks();
      document.getElementById("last_fm_rt").className = "selected";
      var tracks = last_fm_document.getElementsByTagName("track");
        if (tracks.length == 0) {
          return "&lt;none recently&gt;";
        } else {
          var chart = "<table id=\"last_fm_artists\">\n";
          for (var i = 0; i < tracks.length; i++) {
            chart += "<tr>";
            var artists = tracks[i].getElementsByTagName('artist');
            var names = tracks[i].getElementsByTagName('name');
            var url = tracks[i].getElementsByTagName('url');
            var dates = tracks[i].getElementsByTagName('date');
            var a_url = url[0].firstChild.nodeValue.split('_/')[0];
            
            var date = new Date();
            date.setTime(parseInt(dates[0].getAttribute('uts')) * 1000);
      
            var hours = date.getHours();    
            if (hours > 12) {
              hours -= 12;
              var ampm = "pm";
            } else {
              var ampm = "am";
            }
            if (hours == 0)
              hours = 12;
      
            var minutes = date.getMinutes();
            if (minutes < 10)
              minutes = "0" + minutes;
      
            // display a single track
            chart += "<td " +
              "class=\"lastfm_artist_track\"><a href=\"" +
              a_url + "\" title=\"Visit the Last.fm page for this track.\">" +
              artists[0].firstChild.nodeValue + "</a> &ndash; <a href=\"" +
              url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this track.\">" +
              names[0].firstChild.nodeValue + "</a></td><td class=\"lastfm_time\">" +
              hours + ':' + minutes + ' ' + ampm + ', ' +
              months[date.getMonth()] + ' ' + date.getDate() +
              "</td></tr>\n";
          }
          chart += "</table>";
        }
        return chart;
}

function format_weekly_artist_chart(last_fm_document) {
      prepareLinks();
      document.getElementById("last_fm_wa").className = "selected";
      var weeklyArtistChart = last_fm_document.getElementsByTagName("weeklyartistchart");
      if (weeklyArtistChart ==''){
        alert("There is a problem with the Last.fm xml feed");
      }
      var from = new Date();
      from.setTime(parseInt(weeklyArtistChart[0].getAttribute("from")) * 1000);
      var to = new Date();
      to.setTime(parseInt(weeklyArtistChart[0].getAttribute("to")) * 1000);
      var artists = last_fm_document.getElementsByTagName("artist");
      
      if (artists.length == 0) {
        // there are no recently listened tracks
        element.appendChild(document.createElement("&lt;none recently&gt;"));
      } else {
        // display weekly artists        
        var chart = "<table id=\"last_fm_artists\">\n";
        for (var i = 0; i < 10; i++) {
          chart += "<tr>";
          //var artists = tracks[i].getElementsByTagName('artist');
          var names = artists[i].getElementsByTagName("name");
          var playCount = artists[i].getElementsByTagName("playcount");
          var url = artists[i].getElementsByTagName("url");
    
          // display each artist
          chart += "<td><a href=\"" +
            url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this track.\">" +
            names[0].firstChild.nodeValue + "</a></td><td class=\"lastfm_play_count\">" + 
            playCount[0].firstChild.nodeValue + 
            " plays </td></tr>\n";
        }
        chart += "</table>" +
             "<div id=\"dates\">" + from.getDate() + " " + months[from.getMonth()] + " " + from.getFullYear() + " - " + 
             to.getDate() + " " + months[to.getMonth()] + " " + to.getFullYear() + "</div>";
        // call your function to remove all the children from your element
      return chart;
    }
}

function format_weekly_track_chart(last_fm_document) {
      prepareLinks();
      document.getElementById("last_fm_wt").className = "selected";
      var weeklyTrackChart = last_fm_document.getElementsByTagName("weeklytrackchart");
      if (weeklyTrackChart ==''){
        alert("There is a problem with the Last.fm xml feed");
      }
      var from = new Date();
      from.setTime(parseInt(weeklyTrackChart[0].getAttribute("from")) * 1000);
      var to = new Date();
      to.setTime(parseInt(weeklyTrackChart[0].getAttribute("to")) * 1000);
      var tracks = last_fm_document.getElementsByTagName("track");

      if (tracks.length == 0) {
        // there are no recently listened tracks
        element.appendChild(document.createElement("&lt;none recently&gt;"));
      } else {
        // display weekly artists        
        var chart = "<table id=\"last_fm_artists\">\n";
        for (var i = 0; i < 10; i++) {
          chart += "<tr>";
          var artists = tracks[i].getElementsByTagName("artist");
          var names = tracks[i].getElementsByTagName("name");
          var playCount = tracks[i].getElementsByTagName("playcount");
          var url = tracks[i].getElementsByTagName("url");
          var a_url = url[0].firstChild.nodeValue.split('_/')[0];
    
          // display each artist
          chart += "<td><a href=\"" +
              a_url + "\" title=\"Visit the Last.fm page for this track.\">" +
              artists[0].firstChild.nodeValue + "</a> &ndash; <a href=\"" +
              url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this track.\">" +
              names[0].firstChild.nodeValue + "</a></td><td class=\"lastfm_play_count\">" + 
            playCount[0].firstChild.nodeValue + 
            " plays </td></tr>\n";
        }
        chart += "</table>" +
             "<div id=\"dates\">" + from.getDate() + " " + months[from.getMonth()] + " " + from.getFullYear() + " &#151; " + 
             to.getDate() + " " + months[to.getMonth()] + " " + to.getFullYear() + "</div>";
        // call your function to remove all the children from your element
      return chart;
    }
}

function format_top_artists_chart(last_fm_document) {
      prepareLinks();
      document.getElementById("last_fm_ta").className = "selected";
      var topArtists = last_fm_document.getElementsByTagName("topartists");
      if (topArtists ==''){
        alert("There is a problem with the Last.fm xml feed");
      }
      var from = new Date();
      from.setTime(parseInt(topArtists[0].getAttribute("from")) * 1000);
      var to = new Date();
      to.setTime(parseInt(topArtists[0].getAttribute("to")) * 1000);
      var artists = last_fm_document.getElementsByTagName("artist");
      
      if (artists.length == 0) {
        // there are no recently listened tracks
        element.appendChild(document.createElement("&lt;none recently&gt;"));
      } else {
        // display weekly artists        
        var chart = "<div>\n";
        chart += "</div><table id=\"last_fm_artists\"><tr><td style=\"width:110px;\" rowspan=\"11\">";
        for (var i = 0; i < 10; i++) {
          var url = artists[i].getElementsByTagName("url");
          var thumbs = artists[i].getElementsByTagName("thumbnail");
    
          // display each artist image
          chart += "<a href=\"" +
            url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this artist.\">" +
            "<img src=\"" + thumbs[0].firstChild.nodeValue + "\"></a>\n";
        }
        chart += "</td></tr>";
        for (var i = 0; i < 10; i++) {
          chart += "<tr>";
          //var artists = tracks[i].getElementsByTagName('artist');
          var names = artists[i].getElementsByTagName("name");
          var playCount = artists[i].getElementsByTagName("playcount");
          var url = artists[i].getElementsByTagName("url");
    
          // display each artist
          chart += "<td><a href=\"" +
            url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this track.\">" +
            names[0].firstChild.nodeValue + "</a></td><td class=\"lastfm_play_count\">" + 
            playCount[0].firstChild.nodeValue + 
            " plays </td></tr>\n";
        }
        chart += "</table>";// +
             //"<div id=\"dates\">" + from.getDate() + " " + months[from.getMonth()] + " " + from.getFullYear() + " - " + 
             //to.getDate() + " " + months[to.getMonth()] + " " + to.getFullYear() + "</div>";
        // call your function to remove all the children from your element
      return chart;
    }
}

function format_top_tracks_chart(last_fm_document) {
      prepareLinks();
      document.getElementById("last_fm_tt").className = "selected";
      var topTracks = last_fm_document.getElementsByTagName("toptracks");
      if (topTracks ==''){
        alert("There is a problem with the Last.fm xml feed");
      }
      var from = new Date();
      from.setTime(parseInt(topTracks[0].getAttribute("from")) * 1000);
      var to = new Date();
      to.setTime(parseInt(topTracks[0].getAttribute("to")) * 1000);
      var tracks = last_fm_document.getElementsByTagName("track");
      
      if (tracks.length == 0) {
        // there are no recently listened tracks
        element.appendChild(document.createElement("&lt;none recently&gt;"));
      } else {
        // display weekly artists
        var chart = "<table id=\"last_fm_artists\">\n";
        for (var i = 0; i < 10; i++) {
          chart += "<tr>";
          var artists = tracks[i].getElementsByTagName("artist");
          var names = tracks[i].getElementsByTagName("name");
          var playCount = tracks[i].getElementsByTagName("playcount");
          var url = tracks[i].getElementsByTagName("url");
          var thumbs = tracks[i].getElementsByTagName("thumbnail");
          var a_url = url[0].firstChild.nodeValue.split('_/')[0];
    
          // display each artist
          chart += "<td class=\"lastfm_artist_track\"><a href=\"" +
              a_url + "\" title=\"Visit the Last.fm page for this track.\">" +
              artists[0].firstChild.nodeValue + "</a> &ndash; <a href=\"" +
              url[0].firstChild.nodeValue + "\" title=\"Visit the Last.fm page for this track.\">" +
              names[0].firstChild.nodeValue + "</a></td><td class=\"lastfm_play_count\">" + 
            playCount[0].firstChild.nodeValue + 
            " plays </td></tr>\n";
        }
        chart += "</table>";// +
             //"<div id=\"dates\">" + from.getDate() + " " + months[from.getMonth()] + " " + from.getFullYear() + " - " + 
             //to.getDate() + " " + months[to.getMonth()] + " " + to.getFullYear() + "</div>";
        // call your function to remove all the children from your element
      return chart;
    }
}


// twitter
if(undefined!==document.getElementById('twitter_update_list')){
  var twitters;
  function twitterCallback2(obj) {
    twitters = obj;
    var statusHTML="loading twitter stream...";
    var username="";
    for (var i=0; i<twitters.length; i++){
      username = twitters[i].user.screen_name
      if (i==0){statusHTML='';}
      var tweet = makeUrlAnchors(twitters[i].text);
      var tweet = makeUsernameAnchors(tweet);
      statusHTML+= ('<li><span>'+tweet+'</span> <a class="postTime" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>')
    }
    document.getElementById('twitter_update_list').innerHTML = statusHTML;
  }
  function makeUsernameAnchors(tweet,start) {
      var index = tweet.indexOf('@',start);
      if (index != -1 ) {
	 // ignore if the @ is not at the start of a word
	 if (tweet.substr(index-1,1) != ' ' && index != 0) {
//	    if (newStartIndex != tweet.lastIndexOf('@')) {
	       return makeUsernameAnchors(tweet,index+1);
/*	    } else {
	       return tweet;
	    }*/
	 } else {
	    //var indexEnd = tweet.indexOf(' ',index);
	    //var indexEnd = tweet.search(/[!@#\$%\^&\*\(\)\s]/,index);
	    subTweet = tweet.substr(index+1);
	    var subIndexEnd = subTweet.search(/[~`!@#\$%\^&\*\(\)-\+=\{\}\[\]:;"'<>,\.\?/\s]+/);
	    //var indexEnd = subTweet.search(/[~`!@#\$%\^&\*\(\)-\+=\{\}\[\]:;"'<>,\.\?/\s]+/) + index + 1;
	    if (subIndexEnd == -1) {
	       var indexEnd = 0 + tweet.length;
	       var atUsername = tweet.substring(index+1,indexEnd);
	    } else {
	       var indexEnd = subIndexEnd + index + 1;
	       var atUsername = tweet.substring(index+1,indexEnd);
	    }
	    if (atUsername != '') {
	       tweet = tweet.replace('@'+atUsername,'@<a class="username" href="http://www.twitter.com/'+atUsername+'">'+atUsername+'</a>');
	       newStartIndex = indexEnd+51+atUsername.length;
	    } else {
	       newStartIndex = indexEnd;
	    }
	    /*newStartIndex = index + atUsername.length;
	    if (newStartIndex != tweet.lastIndexOf('@')) {*/
	    if (index != tweet.lastIndexOf('@')) {
	       //return makeUsernameAnchors(tweet,indexEnd+51+atUsername.length);
	       return makeUsernameAnchors(tweet,newStartIndex);
	    }
	 }
      }
      return tweet;
  }
  function makeUrlAnchors(tweet,start) {
      var index = tweet.indexOf('http://',start);
      if (index != -1 ) {
	 var indexEnd = tweet.indexOf(' ',index);
	 if (indexEnd == -1) {
	    var url = tweet.substring(index,tweet.length);
	 } else {
	    var url = tweet.substring(index,indexEnd);
	 }
	 if (url != '') {
	    tweet = tweet.replace(url,'<a href="'+url+'">'+url+'</a>');
	 }
	 newStartIndex = index + 11 + url.length;
	 if (newStartIndex != tweet.lastIndexOf('http://')) {
	    return makeUrlAnchors(tweet,indexEnd+11+url.length);
	 }
      }
      return tweet;
  }

  function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);  
    if (delta < 60) {return 'less than a minute ago';} 
    else if(delta < 120) {return 'about a minute ago';}
    else if(delta < (45*60)) {return (parseInt(delta / 60)).toString() + ' minutes ago';}
    else if(delta < (90*60)) {return 'about an hour ago';}
    else if(delta < (24*60*60)) {return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';}
    else if(delta < (48*60*60)) {return '1 day ago';}
    else {return (parseInt(delta / 86400)).toString() + ' days ago';}
  }
}

// last.fm nav initialization
function prepareLinks() {
  var linksarray = document.getElementsByTagName("a");
  //var linksarray = linksarray.getElmentsBy
  for (var i=0; i<linksarray.length; i++) {
        var linkAnchor = document.getElementById('last_fm_menu_title');
    //perhaps we should use the value of the id attribute as the function parameter instead of all these ifs?
    if (linksarray[i].getAttribute("id") == "last_fm_rt") {
      linksarray[i].onclick = function() {
        last_fm_chart('recent_tracks', element, username);
        linkAnchor.firstChild.nodeValue = 'Recent Tracks';
        return false;
      }
      linksarray[i].className = "";
    } else if (linksarray[i].getAttribute("id") == "last_fm_wa") {
      linksarray[i].onclick = function() {
        last_fm_chart('weekly_artist', element, username);
        linkAnchor.firstChild.nodeValue = 'Weekly Artists';
        return false;
      }
      linksarray[i].className = "";
    } else if (linksarray[i].getAttribute("id") == "last_fm_wt") {
      linksarray[i].onclick = function() {
        last_fm_chart('weekly_tracks', element, username);
        linkAnchor.firstChild.nodeValue = 'Weekly Tracks';
        return false;
      }
      linksarray[i].className = "";
    } else if (linksarray[i].getAttribute("id") == "last_fm_ta") {
      linksarray[i].onclick = function() {
        last_fm_chart('top_artists', element, username);
        linkAnchor.firstChild.nodeValue = 'Top Artists';
        return false;
      }
      linksarray[i].className = "";
    } else if (linksarray[i].getAttribute("id") == "last_fm_tt") {
      linksarray[i].onclick = function() {
        last_fm_chart('top_tracks', element, username);
        linkAnchor.firstChild.nodeValue = 'Top Tracks';
        return false;
      }
      linksarray[i].className = "";
    }
  }
}

   function jsonFlickrFeed(o){
     var i=0;
     var f = document.getElementById("flickr");
     var r = document.getElementById("rail");
     //while(o.items[i]){
     for(i=0;i<8;i=i+1){
	 var src = o.items[i].media.m;  
	 src_t = src.replace(/_m.jpg/,"_s.jpg");
	 src_l = src.replace(/_m.jpg/,".jpg");

	 /*var f_div = document.createElement("div");
	 f_div.setAttribute("class","flickrBadge");
	 r.insertBefore(f_div,f);
	 var f_a = document.createElement("a");
	 f_a.setAttribute("class","thickbox");
	 f_a.setAttribute("title",o.items[i].title);
	 f_a.setAttribute("rel","flickr");
	 f_a.setAttribute("href",src_l);
	 f_div.appendChild(f_a);*/
	 var f_a = document.createElement("a");
	 f_a.setAttribute("class","thickbox");
	 f_a.setAttribute("title",o.items[i].title);
	 f_a.setAttribute("rel","flickr");
	 f_a.setAttribute("href",src_l);
	 r.insertBefore(f_a,f);
	 var f_img = document.createElement("img");
	 f_img.setAttribute("class","flickrBadge");
	 f_img.setAttribute("src",src_t);
	 f_img.setAttribute("title",o.items[i].title);
	 f_img.setAttribute("alt","A photo on flickr");
	 f_a.appendChild(f_img);

	 //document.write('<a href="' + o.items[i].link + '"<img src="' + src_t + '" alt="' + o.items[i].title +'"></a>')
	 //document.write('<a class="thickbox" rel="flickr" href="' + src_l + '"<img src="' + src_t + '" title="' + o.items[i].title +'" alt="A photo on flickr"></a>')
     }
   }


var element = document.getElementById("lastfm_chart");
var username = "bloodthrstylust";
var chart_type = "recent_tracks";
last_fm_chart(chart_type, element, username);

window.onload = prepareLinks;

