/**
 * dyne.js -- because it's time we delegate some work to your client.
 *
 * This code is copyleft 2010 Hellekin O. Wolf. This is free software.
 * Licence: GPL v3 or later. Check http://gnu.org/license/
 *
 * It requires jQuery 1.4+ and loaded to work.
**/

// Extend jQuery with an exists(element) function
// in jQuery, an element with length 0 doesn't exist in the DOM
$.extend({ exists: function(element) { return ($(element).length > 0); } });

if ($.exists("#selected_site"))  $("#selected_site").data("index", 1);
if ($.exists("#jquery_jplayer")) var JP = $("#jquery_jplayer");

var Dyne = {
  init: function()
  {  
    if ($.exists("#selected_site")) {
      Dyne.init_rotate_sites();
      setInterval(Dyne.rotate_sites, 2000);
    }
    if ($.exists("div.tab_container")) Dyne.init_tabs();
    if ($.exists("#jquery_jplayer"))   $.getScript("/javascripts/jquery.jplayer.js", Dyne.init_jplayer);
    // make this happen last, as it's remote
    if ($.exists("#clustrMaps"))       setTimeout(Dyne.clustrMaps, 2500);
  },
  init_jplayer: function(){
    if ($("#jquery_jplayer").length == 0) return;

    // Stores the value of percentage of track loaded
    var global_lp = 0;

    var methods = {
      displayPlayList: function() {
        for (i=0; i < JP.data("jPlayer.config").playList.length; i++) {
          $("#playlist_list ul").append("<li id='playlist_item_"+i+"'>"+ $(this).data("jPlayer.config").playList[i].name+"</li>");
	  $("#playlist_item_"+i).data( "index", i ).hover(
            function() {
              if (JP.data("jPlayer.config").playItem != $(this).data("index"))
                $(this).addClass("playlist_hover");
            },
            function() {
              $(this).removeClass("playlist_hover");
            }
          ).click( function() {
              var index = $(this).data("index");	    
            if (JP.data("jPlayer.config").playItem != index) $(this).playListChange( index );
            else                   $(this).play();
          });
        }
	return JP;
      },
      playListInit: function(autoplay) {
        if (autoplay) JP.playListChange( JP.data("jPlayer.config").playItem );
	else          JP.playListConfig( JP.data("jPlayer.config").playItem );
        return JP;
      },
      playListConfig: function(index) {
        JP.playListHiliteNone();
        $("#playlist_item_"+index).addClass("playlist_current");

	var playItem = index;
        $(this).setFile(JP.data("jPlayer.config").playList[playItem].mp3, JP.data("jPlayer.config").playList[playItem].ogg);
	return JP;
      },
      playListChange: function(index) {
        JP.playListConfig( index );
	JP.play();
	return JP;
      },
      playListNext: function() {
	var playItem = JP.data("jPlayer.config").playItem;
        var index    = (playItem+1 < JP.data("jPlayer.config").playList.length) ? playItem+1 : 0;
	$(this).trigger("jPlayer.playListChange", index);
	return $(this);
      },
      playListPrev: function() {
	var playItem = JP.data("jPlayer.config").playItem;
        var index = (playItem-1 >= 0) ? playItem-1 : JP.data("jPlayer.config").playList.length-1;
	$(this).trigger("jPlayer.playListChange", index);
	return $(this);
      },
      volumeMore: function() {
        var v = $(this).data("jPlayer.config").volume;
	if (v > 90) v = 100
	else        v = v + 10
	$(this).trigger("jPlayer.volume", v);
	return $(this);
      },
      volumeLess: function() {
        var v = $(this).data("jPlayer.config").volume;
	if (v < 10) v = 0
	else        v = v - 10;
	$(this).trigger("jPlayer.volume", v);
	return $(this);
      },
      playListHiliteNone: function() {
        $("#playlist_list ul li").removeClass("playlist_current");
      }
    };
    $.each(methods, function(i) {
      $.fn[i] = this;
    });

    $("#jquery_jplayer").jPlayer({
      swfPath: "swf",
      playItem: 5,
      playList: [
        {name:"[radio] ROR 87.9FM (ondarossa.info)", mp3:"http://radio.dyne.org:8000/ondarossa.mp3", ogg:"http://radio.dyne.org:8000/ondarossa.ogg"},
        {name:"[radio] Auroville (aurovilleradio.org)", mp3:"http://radio.dyne.org:8000/auroville", ogg:""},
        {name:"[radio] M2M (m2m.streamtime.org)", mp3:"http://radio.dyne.org:8000/radioM2M.mp3", ogg:""},
        {name:"[radio] RRC (antisecradio.fm)", mp3:"http://radio.dyne.org:8000/rrc.mp3", ogg:""},
        {name:"[Yue] Things Just Happen", mp3:"http://esaurito.yue.it/yue__few_words/yue-05-things_just_happen.mp3", ogg:"http://esaurito.yue.it/yue__few_words/yue-05-things_just_happen.ogg"},
      ],
      ready: function () {
        // Draw the control bar
        var ctrlBar = "";
        for (i=0; i < 100; i++){
          ctrlBar = ctrlBar + "<a href='#' id='lb-"+i+"'>|</a>";
        }
        $('#player_progress_ctrl_bar').html(ctrlBar);
        // Playlist
        $(this).displayPlayList().playListInit(false); // boolean for autoplay
      }
    })
    .jPlayerId("play",  "player_play")
    .jPlayerId("pause", "player_pause")
    .jPlayerId("stop",  "player_stop")
    .jPlayerId("loadBar", "player_progress_load_bar")
    .jPlayerId("playBar", "player_progress_play_bar")
    .jPlayerId("volumeMin", "player_volume_min")
    .jPlayerId("volumeLess", "player_volume_less")
    .jPlayerId("volumeMore", "player_volume_more")
    .jPlayerId("volumeMax", "player_volume_max")
    .jPlayerId("volumeBar", "player_volume_bar")
    .jPlayerId("volumeBarValue", "player_volume_bar_value")
    .jPlayerId("playListPrev", "player_list_prev")
    .jPlayerId("playListNext", "player_list_next")
    .onProgressChange(function(lp,ppr,ppa,pt,tt) {
      var lpInt = parseInt(lp);
      var ppaInt = parseInt(ppa);

      global_lp = lpInt;

      var loadBar = "";
      for (l=0; l < lpInt; l++){
        loadBar = loadBar + "|";
      }

      var playBar = "";
      for (i=0;i < ppaInt; i++){
        playBar = playBar + "|";
      }
      $('#player_progress_play_bar').text(playBar);
    })
    .onSoundComplete( function() {
      $(this).play();
    });

  },
  init_tabs: function()
  {
    // When page loads...
    // Make all sections under .tab_container .tab_content
    $(".tab_container > section").addClass("tab_content");
    $(".tab_content").hide();                        // Hide all content
    $("ul.tabs li:eq(1)").addClass("active").show(); // Activate first tab
    $(".tab_content:eq(1)").show();                  // Show first tab content

    // On Click Event
    $("ul.tabs li").click(function() {
      $("ul.tabs li").removeClass("active"); // Remove any "active" class
      $(this).addClass("active");            // Add "active" class to selected tab
      $(".tab_content").hide();              // Hide all tab content

      // Find the href attribute value to identify the active tab + content
      var activeTab = $(this).find("a").attr("href");
      $(activeTab).fadeIn(); //Fade in the active ID content
      return false;
    });
  },
  clustrMaps: function()
  {  
    var img = document.createElement("IMG");
    img.src = "http://clustrmaps.com/counter/index2.php?url=http://dyne.org";
    img.alt = "Locations of visitors to this page";
    img.onError = function() {
      $(this).onError           = null;
      $(this).src               = "http://www.meetomatic.com/images/clustrmaps-back-soon.jpg";
      $("#clustrMapsLink").href = "http://clustrmaps.com";
    };

    var lnk  = document.createElement("A");
    lnk.href = "http://clustrmaps.com/counter/maps.php?url=http://dyne.org";
    lnk.id   = "clustrMapsLink";
    lnk.appendChild(img);

    $("#clustrMaps").html(lnk);

  },
  init_rotate_sites: function()
  {
    // Add default selected_site to the loop
    // From:
    //   <article id="selected_site">
    //     <a href="http://code.dyne.org/">
    //       <img id="selected_site_icon" src="images/sites/code_dyne_org.png" alt="Free Software"></a>
    //     <h1><a href="http://code.dyne.org/">code.dyne.org</a></h1>
    //     <h2>free and open source software</h2>
    //   </article>
    //
    // To:
    //   <dt><a href="http://code.dyne.org/" title="Free Software">code.dyne.org</a></dt>
    //   <dd>free and open source software</dd>
    var link    = $("#selected_site h1 a");
    var sslink  = '<a href="'+link.attr("href")+'" title="'+$("#selected_site h2").text()+'">'+link.text()+'</a>';
    var ssitedt = $("<dt/>").append(sslink);
    var ssitedd = $("<dd/>").append($("#selected_site img").attr("alt"));
    $("#sites dl.data").append(ssitedt).append(ssitedd);
    // Remind the size of items to rotate
    $("#sites").data("size", $("#sites dl.data dt").length);
    $("#sites").data("selected_site", 1); // start with the first item
    $("#sites dl.data").css("display", "none"); // hide dl.data, as it's only for... data :)
  },
  rotate_sites: function(delay)
  {
    var idx = $("#sites").data("selected_site");
    var max = $("#sites").data("size") - 1;
    if (max == null) return;

    var dt   = $("#sites dl.data dt:eq("+idx+")");
    var a    = dt.find("a");
    var item = new Array;
    item["name"]  = a.text();
    item["url"]   = a.attr("href");
    item["alt"]   = a.attr("title");
    item["title"] = $(dt).next().text();

    var html = '<a href="'+ item.url +'">';
    html += "\n"+'<img id="selected_site_icon" src="/images/sites/'+ item.name +'.gif" alt="'+ item.alt +'" /></a>';
    html += "\n"+'<h1><a href="'+ item.url +'">'+ item.name +'</a></h1>';
    html += "\n"+'<h2>'+ item.title +'</h2>';
    $("#selected_site").hide().html(html).fadeIn(500);

    if (idx >= max) idx = 0;
    else            idx++;
    $("#sites").data("selected_site", idx);
  }
};

$(document).ready(Dyne.init);
