(function() {

// Localize jQuery variable
var jQuery;

/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main(); 
}

/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.6.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js");
    script_tag.onload = scriptLoadHandler;
    script_tag.onreadystatechange = function () { // Same thing but for IE
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            scriptLoadHandler();
        }
    };
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);

    } else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

function trackDataToHTML(data, isFirst) {
  var htmlArray = [];
  var first_track_class = '';

  if (isFirst) {
    htmlArray.push('<img class="pic" src="' + data.image + '">');
    first_track_class = 'first_track';
  }
  
  htmlArray.push('<ul class="title">');
  jQuery.each(data.title, function(i, value) {
    htmlArray.push('<li>' + value + '</li>');
  });
  htmlArray.push('</ul>');
    
  htmlArray.unshift('<div class="track ' +   first_track_class + '">');
  htmlArray.push('</ul>');
  htmlArray.push('</div>');  
  return htmlArray.join('');
  
}

/******** Our main function ********/
function main() { 
    jQuery(document).ready(function($) { 
      var d = new Date();
      var no_cache = d.valueOf();
      
      if (loudcasterNowplayingSettings.port == undefined) {
        loudcasterNowplayingSettings.address = loudcasterNowplayingSettings.domain + ':80';      
      } else {
        loudcasterNowplayingSettings.address = loudcasterNowplayingSettings.domain + ':' + loudcasterNowplayingSettings.port;            
      }
      
      /******* Load CSS *******/
      var css_url = "http://" + loudcasterNowplayingSettings.address + "/stylesheets/nowplaying.widget.css?" + no_cache;
      var css_link = jQuery("<link>", { 
          rel: "stylesheet", 
          type: "text/css", 
          href: css_url
      });
      css_link.appendTo('head');          
  
      /******* Load HTML *******/
      var jsonp_url = "http://" + loudcasterNowplayingSettings.address + "/widgets/now_playing/" + loudcasterNowplayingSettings.channelID + ".json?callback=?&color=" + loudcasterNowplayingSettings.color;
      jQuery.getJSON(jsonp_url, function(data) {
        var nowPlayingHTML = [];
        tracks = data.tracks.slice(0,(loudcasterNowplayingSettings.length));
        jQuery.each(tracks, function(i, value) {
          var isFirst = (i == 0 ? true : false);
          nowPlayingHTML.push(trackDataToHTML(value, isFirst));
        });

        nowPlayingHTML.push('<div class="widget_footer"><a href="http://' + loudcasterNowplayingSettings.address + '/channels/' + loudcasterNowplayingSettings.channelID + '">POWERED BY <img class="loudcaster_logo" src="' + 'http://' + loudcasterNowplayingSettings.address + '/images/logos/tiny.png?' + no_cache + '"></a></div>');
        
        wrapper_element = jQuery('#loudcaster_now_playing');
        wrapper_element.click(function(){
             window.open(jQuery('#loudcaster_now_playing .widget_footer a')[0].href);
             return false;
        });        
        wrapper_element.addClass('loudcaster_now_playing');
        wrapper_element.html('<img class="big_play" src="' + 'http://' + loudcasterNowplayingSettings.address + '/images/icons/256/play_white_transparent.png?' + no_cache + '" ><div class="track_list">' + nowPlayingHTML.join('') + '</div>');
        wrapper_element.css('border', '3px solid ' + data.colors.background[0]);        

        jQuery('#loudcaster_now_playing .track').each(function(i, value) {
          if (data.colors.background[i]) {
            jQuery(this).css('background', data.colors.background[i]);
          }
        });      
      });
      
    });
}

})(); // We call our anonymous function immediately


