//  
// Copyright 2008-2010 iLike Inc.
// version 1.0.f027  Thu, 02 Sep 2010 07:26:29 -0700

(function() {
  // Quit if we've already played this tune
  if (typeof(window["iLike"]) != "undefined")
    return;

  // don't do the same thing twice
  window["iLike"] = new Object();
  window["theApp"] = null;

  iLike.debug_write = function(txt) {
    try {
      p = document.createElement("p");
      p.innerHTML = txt;
      d = document.getElementById('debug_div');
      if(d) {
        d.appendChild(p);
      }
    } catch(e) { }
  }

  //document.write('<div id="debug_div" style="display:none;border: 1px solid #000000; width:600px;"><p>debug div</p></div>');

  
  iLike.urls = 
    { swf: "http://swfs.ilike.com/swfs/hiddenAudioPlayer.swf?v=dbc4",
      displaySongs: "http://www.ilike.com/api/html_render_songs",
      displayPlaylist: "http://www.ilike.com/api/html_display_playlist",
      displayConcerts: "http://www.ilike.com/api/html_display_concerts",
      playlistAdd: "http://www.ilike.com/api/html_playlist_add_song",
      playlistMove: "http://www.ilike.com/api/html_update_playlist_move_to_top",
      playlistRemove: "http://www.ilike.com/api/html_update_playlist_remove_song",
      playlistUpdate: "http://www.ilike.com/api/html_update_playlist",
      chooseSongs: "http://www.ilike.com/api/html_song_chooser",
      searchSongs: "http://www.ilike.com/api/html_song_chooser_search_async",
      getGenres: "http://www.ilike.com/api/html_get_genres",
      findArtistsByGenre: "http://www.ilike.com/api/html_find_artists_by_genre",
      findSongs: "http://www.ilike.com/api/html_find_songs",
      loadSongs: "http://www.ilike.com/api/html_load_songs",
      imageBase: "http://s0.ilike.com/images/",
      keywordUrl: "http://c.ilike.com/conv_click.php?u=http%3A%2F%2Fs0.ilike.com%2Fimages%2Fpixel.gif&h=0072ac51ee3ddc6b3c8951c640ebb916&i="
    };


  function _require(scr) {
    document.write('<script type="text/javascript" src="'+scr+'"></script>')
  };
  if(typeof Prototype == 'undefined') {
    _require("http://www.ilike.com/js/prototype.js?v=1_6_0_3b");
  }
  _require("http://www.ilike.com/js/playlist.js?v=2cba");
  
  var style = document.createElement("link");
  style.setAttribute("rel", "stylesheet")
  style.setAttribute("type", "text/css");
  style.setAttribute("href", "http://www.ilike.com/stylesheets/api.css?v=1f85");
  style.setAttribute("charset", "utf-8");
  document.getElementsByTagName("head")[0].appendChild(style);
  /* For Mozilla */
  if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, false);
  }

  /* For Internet Explorer */
  /*@cc_on @*/
  /*@if (@_win32)
    document.write("<script id='__ilike_ie_onload' defer src='javascript:void(0)'></script>");
    var script = document.getElementById("__ilike_ie_onload");
    script.onreadystatechange = function() {
      if (this.readyState == "complete") {
        //debugger;
        init(); // call the onload handler
      }
    };
  /*@end @*/

  /* For Safari */
  if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var init_timer = setInterval(function() {
      if (/loaded|complete/.test(document.readyState)) {
        if (init_timer)
        {
          clearInterval(init_timer);
          init_timer = null;
        }
        init(); // call the onload handler
      }
    }, 10);
  }

  //
  // Cross-browser solution for triggering init after the page loads but before
  // external resources (e.g. images) are loaded.  From http://dean.edwards.name/weblog/2006/06/again/.
  //
  function init() {
    // Quit if this function has already been called
    if (arguments.callee.done)
      return;

    // Flag this function so we do not do the same thing twice
    arguments.callee.done = true;

    iLike.App = Class.create();
    iLike.App.prototype = {

      initialize: function() {
        this.lastOpenSongExpando = null;
        this.data = (typeof(g_data) != "undefined") ? g_data : null;
        this.baseUrl = "http://www.ilike.com/";
        this.swfBaseUrl = this.baseUrl + 'swfs/';
        this.swfVersion = (typeof(g_swfVersion) != "undefined") ? g_swfVersion : Math.random();
      },

      createObjectsFromData: function(c, list, name) {
        // Create a simulated hash table of instances for fast lookups
        if (!c.hash)
          c.hash = new Array;

        if (!c.arr)
          c.arr = new Array;

        // Create instances of the specified class for each item in the list.  Items must have an id.
        for (var i = 0; i < list.length; i++)
        {
          var o = new c(list[i].id, list[i].tag);
          c.arr.push(o);
          c.hash[list[i].id] = o;
        }

        // Add a helper function "byId" for use when wiring up onclick event handlers
        if (!c.byId)
          c.byId = function(id) { return c.hash[id]; }
      },

      removeObjectsById: function(c, list) {
        // nothing to do if the target object does not have any data stored
        if(!c.hash || !c.arr) {
          return;
        }

        removed = {};
        for(var i = 0; i < list.length; ++i) {
          var o = c.byId(list[i]);
          if(o) {
            if(o.onRemove) {
              o.onRemove();
            }
            delete c.hash[list[i]];
            removed[list[i]] = 1;
          }
        }
        for(i = 0; i < c.arr.length; ++i) {
          if(removed[c.arr[i].id]) {
            c.arr[i] = null;
          }
        }
        c.arr = c.arr.compact();
      },
      
      adjustHeight: function() {
        //TODO: fill this in
      },

      trackEvent: function(evt) {
        //TODO: fill this in
      },
            
      urlForSwf: function(swf_name) {
        return "http://swfs.ilike.com/swfs/" + swf_name + "?v=dbc4";
      }
    };

    iLike.Ajax = new Object();
    iLike.Ajax.XmlHttpScriptTransport = Class.create();
    iLike.Ajax.XmlHttpScriptTransport.prototype = {
      initialize: function() {},

      open: function(method, url, options) {
        this.method = method;
        this.url = url;
        this.options = options;
      },
      send: function(body) {
        var outerComplete = "_c" + Math.floor(Math.random() * 1000000);
        var innerComplete = this.complete.bind(this);
        var timer = null;
        function _complete(data) {
          if(typeof data == "number") {
            iLike.Ajax[outerComplete] = function(){};
            data = null;
          } else {
            delete iLike.Ajax[outerComplete];
            $("_ilike_" + outerComplete).remove();
          }
          clearInterval(timer);
          innerComplete(data);
        };
        iLike.Ajax[outerComplete] = _complete;

        full_url = this.url + (-1 == this.url.indexOf('?') ? '?' : '&') + "script_target=" + encodeURIComponent("iLike.Ajax." + outerComplete);
        if(body) {
          full_url = full_url + "&" + body;
        }
        
        _includeScript(full_url, "_ilike_" + outerComplete);
        timer = setInterval(_complete, 10 * 1000);
      },
      setRequestHeader: function(name, value) {

      },
      getResponseHeader: function(name) {
       return (this.data && this.data.headers) ? this.data.headers[name] : "";
      },

      complete: function(data) {
        this.data = data;

        statusHeader = this.getResponseHeader("Status");
        this.status = (statusHeader && statusHeader.length > 0) ? statusHeader.match(/^[0-9]+/)[0] - 0 : 500;
        
        this.responseText = (data ? data.body : "");
        this.readyState = 4;
        this.onreadystatechange();
      },
      
      onreadystatechange : null,
      overrideMimeType : null,
      readyState: null,
      status: null,
      responseText: null,
      url: null,
      method: null,
      options: null
    };
    
    iLike.Ajax.Request = Class.create();
    Ajax.Request.prototype.__request = Ajax.Request.prototype.request;
    
    Object.extend(Object.extend(iLike.Ajax.Request.prototype, Ajax.Request.prototype), {
        request: function(url) {
          // override the transport to use our whizzy script tag transport
          this.transport = new iLike.Ajax.XmlHttpScriptTransport();
          this.__request(url);
        }
      });
   
    iLike.Ajax.Updater = Class.create();
    Ajax.Updater.prototype.__request = Ajax.Updater.prototype.request;
    
    Object.extend(Object.extend(iLike.Ajax.Updater.prototype, Ajax.Updater.prototype), {
        request: function(url) {
          // override the transport to use our whizzy script tag transport
          this.transport = new iLike.Ajax.XmlHttpScriptTransport();
          this.__request(url);
        }
      });
   
    // Create the app and get things rolling
    theApp = new iLike.App();

    if(typeof deconcept == "undefined") {
      _includeScript("http://www.ilike.com/js/swfobject.js?v=1_4_4");
    }
    if(typeof iLike.SongExpando == "undefined") {
      _includeScript("http://www.ilike.com/js/song.js?v=e709");
    }
    if(typeof iLike.Stepper == "undefined") {
      _includeScript("http://www.ilike.com/js/util.js?v=b035");
    }
  };
  
  function _ping(url) {
    var image = new Image();
    image.src = url;
    image.width = 0;
    image.height = 0;
    document.body.insertBefore(image, document.body.firstChild);
  }

  function _includeScript(scr, id) {
    var script = document.createElement("script");
    script.setAttribute("src", scr);
    script.setAttribute("type", "text/javascript");
    if(id) {
      script.setAttribute("id", id);
    }
    document.getElementsByTagName("head")[0].appendChild(script);
  };

  function _displaySongLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLikeDisplaySong = iLike.API.displaySong = function(options){return iLike.Embed.displaySong(options);};
        iLike.Embed.displaySong(options);
      }
    }, 10);
  };
  function _displayPlaylistLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLikeDisplayPlaylist = iLike.API.displayPlaylist = function(options){return iLike.Embed.displayPlaylist(options);};
        iLike.Embed.displayPlaylist(options);
      }
    }, 10);
  };
  function _songChooserLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLikeSongChooser = iLike.API.songChooser = function(options){return iLike.Embed.songChooser(options);};
        iLike.Embed.songChooser(options);
      }
    }, 10);
  };
  function _displayConcertsLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLikeDisplayConcerts = iLike.API.displayConcerts = function(options){return iLike.Embed.displayConcerts(options);};
        iLike.Embed.displayConcerts(options);
      }
    }, 10);
  };
  function _getGenresLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.getGenres = function(options){return iLike.Embed.getGenres(options);};
        iLike.Embed.getGenres(options);
      }
    }, 10);
  };
  function _findArtistsByGenreLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.findArtistsByGenre = function(options){return iLike.Embed.findArtistsByGenre(options);};
        iLike.Embed.findArtistsByGenre(options);
      }
    }, 10);
  };
  function _findSongsLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.findSongs = function(options){return iLike.Embed.findSongs(options);};
        iLike.Embed.findSongs(options);
      }
    }, 10);
  };
  function _loadSongsLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.loadSongs = function(options){return iLike.Embed.loadSongs(options);};
        iLike.Embed.loadSongs(options);
      }
    }, 10);
  };
  function _playSongLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.playSong = function(options){return iLike.Embed.playSong(options);};
        iLike.Embed.playSong(options);
      }
    }, 10);
  };
  function _stopSongLoading(options) { 
    var timer = setInterval(function() { 
      if(typeof(iLike.Embed) != 'undefined') {
        clearInterval(timer);
        iLike.API.stopSong = function(options){return iLike.Embed.stopSong(options);};
        iLike.Embed.stopSong(options);
      }
    }, 10);
  };

  iLike.API = {
    displaySong : _displaySongLoading,    displayPlaylist : _displayPlaylistLoading,    songChooser : _songChooserLoading,    displayConcerts : _displayConcertsLoading,    getGenres : _getGenresLoading,    findArtistsByGenre : _findArtistsByGenreLoading,    findSongs : _findSongsLoading,    loadSongs : _loadSongsLoading,    playSong : _playSongLoading,    stopSong : _stopSongLoading
  };
  iLike.ping = _ping;
  if(typeof(window["_iLikeDevKey"]) == "undefined")
    window["_iLikeDevKey"] = null;
  window["iLikeDisplaySong"] = iLike.API.displaySong;
  window["iLikeDisplayPlaylist"] = iLike.API.displayPlaylist;
  window["iLikeSongChooser"] = iLike.API.songChooser;
  window["iLikeDisplayConcerts"] = iLike.API.displayConcerts;
  window["_iLikePing"] = iLike.ping;

  if(location.search.match(/fb_sig_in_iframe/))
    iLike.in_fb = 1;
})();
