var soundwidget

jQuery(document).ready(function($) {

// start our sound data object
var data = {}

// soundcloud api key
var soundcloud_apikey = 'htuiRd1JP11Ww0X72T1C3g'

// set our sound channels
var channels = { 'phthalo' : '/albums/catalog/phthalo/json', 'halocyan' : '/albums/catalog/halocyan/json', 'podcast' : '/phthalo/sound/json' }

// loop through our channels
for(var key in channels){

    $.ajax({
        url: channels[key],
        dataType: "json",
        context: {key : key},
        success: function(d){

            // temp channel data
            var channel = {title : d['channel']['title'], items : {}}

            // loop through all the items
            var items = d['channel']['items']
            var l=items.length
            for(var i=0;i<l;i++){

                var title = items[i]['title']
                var sounds = []

                // extract uri and info for soundcloud tracks
                if(items[i]['tracks']){
                    var t = items[i]['tracks']
                    var nl = t.length
                    for(var n=0;n<nl;n++){
                        if(t[n]['stream-url']){
                            sounds.push({
                                url : t[n]['stream-url'] + "?secret_token=" + t[n]['secret-token'] + "&consumer_key=" + soundcloud_apikey,
                                title : t[n]['title'],
                                length : t[n]['duration']
                            })
                        }
                    }
                    var trackcount = items[i]['tracks'].length
                }

                // extract uri and info for our podcast like feed            
                if(items[i]['enclosure']){
                    sounds.push({
                        url : items[i]['enclosure']['url'],
                        title : null,
                        length : items[i]['enclosure']['length']
                    })
                    var trackcount = 1
                }

                if( items[i]['release_id'] == '' || !items[i].hasOwnProperty('release_id') ){
                    var release_id = null;
                } else {
                    var release_id = items[i]['release_id'];
                }

                if( items[i].hasOwnProperty('purchase_urls') ){
                    var purchase_urls = items[i]['purchase_urls']
                } else {
                    var purchase_urls = false
                }

                // add our processed item to the channel data
                channel['items'][items[i]['id']] = { 
                    title : title, 
		    id : items[i]['id'],
                    release_id : release_id,
                    artist : items[i]['author'],
                    artist_url : items[i]['author_permalink'],
                    images : items[i]['images'],
                    sounds : sounds,
                    pubdate : items[i]['pubdate'],
                    trackcount : trackcount,
                    purchase_urls : purchase_urls,
                    url : items[i]['link']
                }

            }

            // sort our items: step 1: associative array into array
            var _items = []
            for(var key in channel['items']){
                _items.push( [ key, channel['items'][key] ] )
            }
 
            // sort our items: step 2: sort by the release id
            _items.sort( function(a,b){ return b[1]['release_id'] - a[1]['release_id']} )

            // sort our items: step 3: back into an associative array
            items = {}
            var l = _items.length
            for(var i=0;i<l;i++){
                items[_items[i][0]] = _items[i][1]
            }

            // sort our items: step 4: replace our unsorted with our sorted one
            channel['items'] = items

            // add to our sound data object
            data[this.key] = channel

            // if all the channels have been loaded
            a = 0;
            for (var ak in data){ a++; }

            b = 0;
            for (var bk in channels){ b++; }

            if(a == b) {
                // generate our widget
                soundwidget = $('<div id="phlayer"></div>')
                soundwidget.phlayer(data)
                $('#sidebar').append(soundwidget)

                // activate our other play buttons
                soundwidget.phlayer('activate_eplay')
  
                featured_play = []

		$('.phlayer-eplay', $('#new')).each(function(){
		    featured_play.push($(this).attr('data'))
		})

		soundwidget.phlayer('eplay', 
				    featured_play[Math.floor(Math.random() * featured_play.length)], 
				    false)

            }
       }
   })
}

});
