function doNarrowCSS() {
    if ($(document).width() < 1050 && $("body").attr("class") != "min") {
	$("body").attr("class","min");
    } else if ($("body").attr("class") == "min") {
	$("body").attr("class","");
    }
    var height = $("#rail").height() + parseInt($("#rail").css("padding-bottom")) - ($(".content").height() + $("#sub_middle").height());
    /*$("#sub1").css("height",height);
    $("#sub2").css("height",height);*/
    $(".content:first").css("margin-bottom",height);
}

function delicious() {
    if (undefined !== $('#delicious_list')){
	var ul = $('<ul></ul>');
	if(Delicious.posts){
	    for (var i=0, post; post = Delicious.posts[i]; i++) {
		var li = $('<li></li>')
		    .append($('<a></a>').attr('href',post.u)
		    .append(post.d));
		if (undefined != post.n) {
		    li.append(post.n);
		}
		ul.append(li);
	    }
	} else {
	    ul.append('test');
	} 
	$('#delicious_list').append(ul)
    }
    doNarrowCSS();
}

/*
 * 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 lastFm = {
    months : ["Jan", "Feb", "Mar","Apr", "May", "Jun","Jul","Aug","Sep","Oct","Nov", "Dec"],


    // last.fm

    //
    last_fm_chart: function(chart_type,username)
    {
	$('#lastfm_ul').css('display','block');
	lastFm.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();
	$.ajax({
	    type: 'GET',
	    url: proxy,
	    success: lastFm.callback
	});
    },

    callback: function(msg) {
      var last_fm_xml = msg;
      if (last_fm_xml.getElementsByTagName('recenttracks').length == 1) {
	lastFm.element.append(lastFm.format_recent_tracks_chart(last_fm_xml));
      } else if (last_fm_xml.getElementsByTagName("weeklyartistchart").length == 1) {
	lastFm.element.append(lastFm.format_weekly_artist_chart(last_fm_xml));
      } else if (last_fm_xml.getElementsByTagName("weeklytrackchart").length == 1) {
	lastFm.element.append(lastFm.format_weekly_track_chart(last_fm_xml));
      } else if (last_fm_xml.getElementsByTagName("topartists").length == 1) {
	lastFm.element.append(lastFm.format_top_artists_chart(last_fm_xml));
      } else if (last_fm_xml.getElementsByTagName("toptracks").length == 1) {
	lastFm.element.append(lastFm.format_top_tracks_chart(last_fm_xml));
      }
	doNarrowCSS();
    },

    format_recent_tracks_chart: function(last_fm_document) {
	  lastFm.prepareLinks();
	  $('#last_fm_rt').attr('class','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 + ', ' +
		  lastFm.months[date.getMonth()] + ' ' + date.getDate() +
		  '</td></tr>\n';
	      }
	      chart += '</table>';
	    }
	    return chart;
    },

    format_weekly_artist_chart: function(last_fm_document) {
	  lastFm.prepareLinks();
	  $('#last_fm_wa').attr('class','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
	    lastFm.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>';
	  return chart;
	}
    },

    format_weekly_track_chart: function(last_fm_document) {
	  lastFm.prepareLinks();
	  $('#last_fm_wt').attr('class','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
	    lastFm.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>';
	  return chart;
	}
    },

    format_top_artists_chart: function(last_fm_document) {
	  lastFm.prepareLinks();
	  $('#last_fm_ta').attr('class','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
	    lastFm.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>";// +
	  return chart;
	}
    },

    format_top_tracks_chart: function(last_fm_document) {
	  lastFm.prepareLinks();
	  $('#last_fm_tt').attr('class','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
	    lastFm.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>";
	  return chart;
	}
    },

    // last.fm nav initialization
    prepareLinks: function() {
      var linksarray = $('a');
      for (var i=0; i<linksarray.length; i++) {
	var linkAnchor = $('#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', 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', 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', 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', 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', username);
	    linkAnchor.firstChild.nodeValue = 'Top Tracks';
	    return false;
	  }
	  linksarray[i].className = "";
	}
      }
    }
};

// twitter
function twitter() {
    /*if(undefined !== $('#twitter_update_list')) {
	//var url = 'http://api.twitter.com/1/statuses/user_timeline/williumbillium.json?count=5';
	//$.getJSON({
	$.ajax({
	    type: 'GET',
	    //url: '/includes/ba-simple-proxy.php?url=' + url + '&mode=native',
	    //url: '/includes/ba-simple-proxy.php?url=' + url,
	    dataType: 'jsonp',
	    //url: 'http://twitter.com/status/user_timeline/williumbillium.json?count=10&callback=twitterParse',
	    url: 'http://twitter.com/status/user_timeline/williumbillium.json?count=5',
	    //jsonpCallback: twitterParse
	    success: twitterParse
	});
    }*/
	$('#twitter').hide();
}

function twitterParse(tweets) {
    if (undefined == tweets) {
	
    } else {
	var statusHTML = 'loading twitter stream...';
	var username = '';
	for (var i=0; i<tweets.length; i++) {
	    username = tweets[i].user.screen_name
	    if (i==0){
		statusHTML='';
	    }
	    var tweet = makeUrlAnchors(tweets[i].text);
	    var tweet = makeUsernameAnchors(tweet);
	    statusHTML += ('<li><span>' + tweet + 
		'</span> <a class="postTime" href="http://twitter.com/' + 
		username + '/statuses/' + tweets[i].id + '">' + 
		relative_time(tweets[i].created_at) + '</a></li>');
	}
	$('#twitter_update_list').html(statusHTML);
	doNarrowCSS();
    }
}

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) {
	   return makeUsernameAnchors(tweet,index+1);
     } else {
	subTweet = tweet.substr(index+1);
	var subIndexEnd = subTweet.search(/[~`!@#\$%\^&\*\(\)-\+=\{\}\[\]:;"'<>,\.\?/\s]+/);
	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;
	}
	if (index != tweet.lastIndexOf('@')) {
	   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';}
}

function jsonFlickrFeed(o){
    var i=0;
    var f = $('#flickr');
    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/,'_b.jpg');

	var f_a = $('<a></a>').attr({
	    class: 'thickbox',
	    title: o.items[i].title,
	    rel: 'flickr',
	    href: src_l
	});
	f_a.insertBefore(f);
	var f_img = $('<img></img>').attr({
	    class: 'flickrBadge',
	    src: src_t,
	    title: o.items[i].title,
	    alt: 'A photo on flickr'
	});
	f_a.append(f_img);

    }
    doNarrowCSS();
}


function letsGo(){
    lastFm.element = $('#lastfm_chart');
    var username = 'bloodthrstylust';
    var chart_type = 'recent_tracks';
    lastFm.last_fm_chart(chart_type, username);

    //lastFm.prepareLinks();
    delicious();
    twitter();
}

