function doNarrowCSS() {
    // TODO: delete
    /*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());
    $(".content:first").css("margin-bottom",height);*/
}

/*
 * 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 = {

    element: $('#lastfm_chart'),

    start: function() {
        var username = 'bloodthrstylust';
        var chart_type = 'recent_tracks';

        $('#lastfm_ul').css('display','block');
        lastFm.element.html('<p>loading last.fm chart...</p>');

        $.getJSON(
            'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=bloodthrstylust' +
            '&api_key=b6efa6398139fc41a0aabcc68faaa396&format=json&callback=?',
            function(data) {
                lastFm.parse(data);
            }
        );
    },

    parse: function(data) {
        if (typeof data == 'object') {
            lastFm.format(data);
        } else {
            lastFm.element.html('There was a problem loading the last.fm data.');
        }
    },

    format: function(data) {
        $('#last_fm_rt').attr('class','selected');
        var tracks = data.recenttracks.track;
        var previousImageSmall = '';
        if (tracks.length == 0) {
            return '&lt;none recently&gt;';
        } else {
            var chart = '<ul id="last_fm_artists">\n';
            for (var i = 0; i < tracks.length; i++) {
                var artist = tracks[i].artist['#text'];
                var name = tracks[i].name;
                var url = tracks[i].url;
                var date = parseInt(tracks[i].date.uts) * 1000; // unix time in miliseconds
                var a_url = url.split('_/')[0];
                var relative_time = lastFm.relative_time(date);
                var imageSmall = tracks[i].image[0]['#text'];
                var imageLarge = tracks[i].image[2]['#text'];

                // display a single track
                chart += '<li class="lastfm_artist_track">' + artist + ' &ndash; ' + name + 
                    ' <span class="lastfm_time"><a href="' + url + '" title="' + name + 
                    ' on Last.fm">' + relative_time + '</a></span></li>\n';
            }
            chart += '</ul>';
	    }
        lastFm.element.html(chart);
    },

    // parameter = unix time in miliseconds
    relative_time: function (time_value) {
        var relative_to = new Date();
        var delta = parseInt((relative_to.getTime() - time_value) / 1000);
        if (delta < 60) {return '< 1 minute ago';} 
        else if(delta < 120) {return '1 minute ago';}
        else if(delta < (45*60)) {return (parseInt(delta / 60)).toString() + ' minutes ago';}
        else if(delta < (120*60)) {return '1 hour ago';}
        else if(delta < (24*60*60)) {return (parseInt(delta / 3600)).toString() + ' hours ago';}
        else if(delta < (48*60*60)) {return '1 day ago';}
        else {return (parseInt(delta / 86400)).toString() + ' days ago';}
    }
};

// twitter
var twitter = {
    start: function () {
	if(undefined !== $('#twitter_update_list')) {
	    $.ajax({
            type: 'GET',
            dataType: 'jsonp',
            url: 'http://twitter.com/status/user_timeline/williumbillium.json?count=20',
            success: twitter.parse,
            error: twitter.error
	    });
	}
	    //$('#twitter').hide();

    },

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

    error: function(jqXHR, textStatus, errorThrown) {
        var test = '';
    },

    makeUsernameAnchors: function (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 twitter.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 twitter.makeUsernameAnchors(tweet,newStartIndex);
                }
            }
        }
        return tweet;
    },

    makeUrlAnchors: function (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 twitter.makeUrlAnchors(tweet,indexEnd+11+url.length);
            }
        }
        return tweet;
    },

    relative_time: function (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 flickr() {
    $.getJSON(
	'http://api.flickr.com/services/feeds/photos_public.gne?id=97827724@N00&lang=en-us&format=json&jsoncallback=?',
	    function(data) {
            flickrParse(data);
	    }
    );
}

function flickrParse(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({
            title: o.items[i].title,
            rel: 'flickr',
            href: src_l
        });
        f_a.colorbox({transition:'fade',height:'85%'});
        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(){
    twitter.start();
    lastFm.start();
    //delicious();
    flickr();
}

$(window).resize(function(){
    doNarrowCSS();
});

