var hradioState = 0;  
function genreRadio(){
  //check if radio is on
  if (hradioState == 1) {
    //get current playing song
    var hthis = $("#playlistSortable li .jp-playlist-current");
    var hid = $(hthis).attr("songId");
    //check if a song is playing
    if (hthis.length > 0) {
      //check if this is last song in playlist, if so add song automatically 
      var hnext = $(hthis).parent().next().children("a");
      if (hnext.length == 0) {
        $.get("./addNextRadioSong.php?id="+hid, function(data) {
          $("#playlistSortable").append(data);
        });  
      } 
    } 
  }
}
  
function playSong(hthis){
  var hmp3 = $(hthis).attr("mp3");
  
  if (hmp3!=undefined) {
    $("#jquery_jplayer_1").jPlayer("setMedia", {mp3: hmp3});
    $("#jquery_jplayer_1").jPlayer("play");
  
    $("#playlistSortable li a").removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
    $(hthis).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
    
    $(".jp-progress-title").empty().append($(hthis).html());
    $("title").empty().append($(hthis).html());
    
    //Change now playing cover
    var hid = $(hthis).attr("songId");
    var hcover = '<div class="top-spacer"></div><img id="coverNowPlaying'+hid+'" class="cover-now-playing" src="./getCover.php?id='+hid+'&resize=0">';
    $("#api4").empty().append(hcover);
    //resize cover art
    resizeImage("coverNowPlaying"+hid);   

    //radio
		setTimeout(function(){genreRadio()}, 5000);    
  }
}

function playPrev(){
  var hthis = $("#playlistSortable li .jp-playlist-current");
  var hprev = $(hthis).parent().prev().children("a");

  playSong(hprev);
}

function playNext(){
  var hthis = $("#playlistSortable li .jp-playlist-current");
  var hnext = $(hthis).parent().next().children("a");

  playSong(hnext);
}

function autoStart(){
  //start auto playing first in playlist if no song is playing
  //
  //get current playing song
  var hthis = $("#playlistSortable li .jp-playlist-current");
  //check if no song is playing
  if (hthis.length == 0) {   
    //get first song in playlist
    var hthis = $("#playlistSortable li a").first();
    //start playing
    playSong(hthis);
  } 
}
  
function addSong(hmp3, hname, hid){
  var hSong = '<li><div onClick="deleteSong(this)" class="jp-playlist-delete"></div><div title="move up-down" class="jp-playlist-move"></div><a href="#" onClick="playSong(this)" songId="'+hid+'" mp3="'+hmp3+'" title="'+hname+'">'+hname+'</a></li>';
  $("#playlistSortable").append(hSong); 
  autoStart();
}

function addDirectories(hdir) {
  $.get("./addDirectories.php?id="+hdir, function(data) {
    $("#playlistSortable").append(data);
    autoStart();
  });
  //.complete(function() { autoStart(); });
}

function deleteSong(hthis){
  $(hthis).parent().remove();

  //radio
  genreRadio();
}

function radioPlaylist(){
  if (hradioState == 0){
    //set radio on
    hradioState = 1;
    $("#drag5 .handler .radio-playlist").addClass("radio-on");
    var hthis = $("#playlistSortable li .jp-playlist-current");
    var hid = $(hthis).attr("songId");
    //check radio
    genreRadio(hthis, hid);
  }
  else {
    //set radio off
    hradioState = 0;
    $("#drag5 .handler .radio-playlist").removeClass("radio-on");
  }
}  

function clearPlaylist(){
  $("#playlistSortable").empty();
}  

function resizeImage(pid) {
  //get width and (height minus spacer) of api4
  //smallest size wins
  pwidth = $("#api4").css('width').replace('px','');
  pheight = $("#api4").css('height').replace('px','') - $("#api4 .top-spacer").css('height').replace('px','') - 3;

  psquare = Math.min(pwidth, pheight) + 'px';
  
  $("#"+pid).css({'width' : psquare, 'height' : psquare});
}  

function showImage(hthis) {
  //show image div and ajax loader
  $("#largeAlbumCover").html('<img src="./app/img/ajax-loader.gif">')
    .fadeIn("fast")
    .css("position","absolute")
    .css("top", ( ($(window).height() - $("#largeAlbumCover").height()) / 2) +$(window).scrollTop() + "px")
    .css("left", ( ($(window).width() - $("#largeAlbumCover").width()) / 2) +$(window).scrollLeft() + "px")
    .css('z-index',maxZ("#largeAlbumCover"))
    .click(function(){ $("#largeAlbumCover").fadeOut("fast"); });   

  //preload the image
  var himage = $(hthis).parent().attr("href");
  imgPreload = new Image();
  //when preloading is done, display it
  imgPreload.onload = function() {
    //show popup with full size image
    $("#largeAlbumCover").html("<img id='largeAlbumCoverImage' src='"+himage+"' title='close' />");

    //recalculate height and width of image if image is bigger than window
    hheight = imgPreload.height;
    hwidth = imgPreload.width;

    hratio = hwidth / hheight;
    if (hwidth > $(window).width()) {
      hwidth = $(window).width();
      hheight = hwidth / hratio;
      $("#largeAlbumCoverImage").css("height",hheight);
      $("#largeAlbumCoverImage").css("width",hwidth);
    }
    if (hheight > $(window).height()) {
      hheight = $(window).height();
      hwidth = hheight * hratio;
      $("#largeAlbumCoverImage").css("height",hheight);
      $("#largeAlbumCoverImage").css("width",hwidth);
    }
    
    $("#largeAlbumCover")
      .css("top", ( ($(window).height() - hheight) / 2) + $(window).scrollTop() + "px")
      .css("left", ( ($(window).width() - hwidth) / 2) + $(window).scrollLeft() + "px");   
  }
  imgPreload.src = himage;
}  
 
function getDirectory(pid) {
  $("#api2").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $("#api2").load("./selectDirectories.php?id="+pid);
}
  
function getTree() {
  $("#api3").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $("#api3").load("./getTree.php");
}

function showTree() {
  $("#api3-link").addClass("tree-albums-current");
  $("#api7-link").removeClass("tree-albums-current");
  $("#api14-link").removeClass("tree-albums-current");
  $("#api3").css({'visibility' : 'visible'});
  $("#api7").css({'visibility' : 'hidden'});
  $("#api14").css({'visibility' : 'hidden'});
}

function getAlbums(pgenre,psort) {
  $("#api7").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $("#api7").load("./getAlbums.php?genre="+encodeURIComponent(pgenre)
                                +'&sort='+encodeURIComponent(psort));
}

function showAlbums() {
  $("#api3-link").removeClass("tree-albums-current");
  $("#api7-link").addClass("tree-albums-current");
  $("#api14-link").removeClass("tree-albums-current");
  $("#api3").css({'visibility' : 'hidden'});
  $("#api7").css({'visibility' : 'visible'});
  $("#api14").css({'visibility' : 'hidden'});
}

function getSearch(pgenre,partist,palbum,psong,ppath) {
  $("#api14").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $("#api14").load("./search.php?genre="+encodeURIComponent(pgenre)
                                +'&artist='+encodeURIComponent(partist)
                                +'&album='+encodeURIComponent(palbum)
                                +'&song='+encodeURIComponent(psong)
                                +'&path='+encodeURIComponent(ppath));
}

function search() {
  $("#api3-link").removeClass("tree-albums-current");
  $("#api7-link").removeClass("tree-albums-current");
  $("#api14-link").addClass("tree-albums-current");
  $("#api3").css({'visibility' : 'hidden'});
  $("#api7").css({'visibility' : 'hidden'});
  $("#api14").css({'visibility' : 'visible'});
}
  
function maxZ(helem){
  //calculate highest z-index
  //and add one
  var hmaxZ = Math.max.apply(null,$.map($('.drag'), function(e,n){
    return parseInt($(e).css('z-index'))||1 ;
    }) 
  );
  return hmaxZ+1;
}  
  
function getSongDetails(pid) {
  $.get("./getSongDetails.php?id="+pid, function(data) {
    $("#drag8").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag8") });
    $("#api8").empty();
    $("#api8").append(data);
  });  
}

function createDirectories(pind_append) {
  if (pind_append == 1) {
	  htrue = true;
	}
  else if (confirm("Are you sure you want to (re)create the music database?\nThis could take several minutes or hours (depending on the size of the library).")) {
    htrue = true;
  }
  if (htrue === true) {
  	$("#drag9").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag9")});
    $("#api9").empty();
    $("#api9").html('<iframe class="iframe-style" src="./createDirectories.php?ind_append='+pind_append+'"></iframe>');
  }
}

function getID3(pid) {
  $("#getID3").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $.get("./getID3.php?id="+pid, function(data) {
    $("#getID3").empty().append(data);
  });  
}
  
function manageDesktops(hind_all_users, hvisible) {
  $("#api12").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $.get("./desktopCRUD.php?pmode=R&ind_all_users="+hind_all_users, function(data) {
    if (hvisible != 0) {
			$("#drag12").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag12")});
		}
    $("#api12").empty();
    $("#api12").append(data);
  });  
}

function manageUsers(hvisible) {
  $("#api11").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $.get("./userCRUD.php?pmode=R", function(data) {
    if (hvisible != 0) {
			$("#drag11").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag11")});
		}
    $("#api11").empty();
    $("#api11").append(data);
  });  
}

function manageSettings(hvisible) {
  $("#api13").empty().append('<div class="top-spacer"></div><img src="./app/img/ajax-loader.gif">');
  $.get("./settingCRUD.php?pmode=R", function(data) {
    if (hvisible != 0) {
			$("#drag13").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag13")});
		}
    $("#api13").empty();
    //$("#api13").append(data);
		$.get("./themeCRUD.php?pmode=R", function(data2) {
			$("#api13").append(data+data2);
		});  
  });  
}
  
function logout() {
  window.location.href="./login.php";
}
  
function aboutAudioStreamer(hvisible) {
  $.get("./aboutAudioStreamer.php", function(data) {
    if (hvisible != 0) {
			$("#drag10").css({'visibility' : 'visible' , 'z-index' : maxZ("#drag10")});
		}
    $("#api10").empty();
    $("#api10").append(data);
  });  
}

function getParams(hthis) {
  hparams="";
  $(hthis).parent().find("[updId]").each(function(){
    var hdetail = $(this);
//    if (hparams != ""){
//      hparams += "&"
//    }
    if (hdetail.attr("type")=='checkbox'){
      if (hdetail.is(":checked")){
        hparams += "&"+hdetail.attr("updId")+"=1";
      }
      else {
        hparams += "&"+hdetail.attr("updId")+"=0";
      }
    }
    else {
      hparams += "&"+hdetail.attr("updId")+"="+hdetail.val();
    }
   });
   return hparams;
 }
   
function desktopUpdate(hthis,hind_all_users) {
  hurl = "./desktopCRUD.php?pmode=U"+getParams(hthis)+"&ind_all_users="+hind_all_users; 
  $.get(hurl, function(data) {
    xmlDoc = $.parseXML( data );
    $xml = $( xmlDoc );    
    haction = '<script type="text/javascript">' + $xml.find("action").text() + '<\/script>';
    
    $("#api12").append(haction);
    if ($xml.find("status").text() == "SUCCESS") {
      $(hthis).parent().find(".changed").removeClass("changed");
    }
  });  
  //requery
  //manageDesktops(hind_all_users);  
}
                         
function desktopCopy(hthis,hind_all_users) {
  hurl = "./desktopCRUD.php?pmode=C"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageDesktops(hind_all_users);  
  });  
}

function desktopDelete(hthis,hind_all_users) {
  hurl = "./desktopCRUD.php?pmode=D"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageDesktops(hind_all_users);  
  });  
}

function saveDesktop() {
  hcmd = "";
  $('.drag').each(function() {
    hcmd += "INSERT"+$(this).attr("id")+"','"+$(this).attr("style")+"');";
  });  

  hurl = "./saveDesktopItems.php"; 
  $.post(hurl, {type:'save', cmd: hcmd} , function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
  });
}

function saveDesktopAs() {
  var hname=prompt("Save desktop as ...","");
  if (hname!=null && hname!="") {
    hcmd = "";

    $('.drag').each(function() {
      hcmd += "INSERT"+$(this).attr("id")+"','"+$(this).attr("style")+"');";
    });  

    hurl = "./saveDesktopItems.php"; 
    $.post(hurl, {type:'saveAs', cmd: hcmd, name: hname} , function(data) {
      //if (data != "SUCCESS") {
      //  alert(data);
      //}
    });
  }
}

function themeswitch(hcss) {
  $('#themeswitch').text('@import url("app/css/'+hcss+'");');
}

function recallDesktop(pmsg) {
  hurl = "./getDesktopItems.php"; 
  $.get(hurl, function(data) {
    xmlDoc = $.parseXML(data);
    $xml = $(xmlDoc);    

    if ($xml.find("status").text() == "SUCCESS") {
      //recall the theme
      themeswitch($xml.find("css").text());
      
      //recall styles of drag div's
      $xml.find("desktopitem").each(function() {
        $('#'+$(this).find("item").text()).attr("style", $(this).find("style").text());         
      });
      
      //resize the now playing image
      resizeImage($("#api4 img").attr("id"));
    }

    if (pmsg == 1) {
      alert($xml.find("message").text());  
    }
  });  
}

function userUpdate(hthis) {
  hurl = "./userCRUD.php?pmode=U"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    else {
      $(hthis).parent().find(".changed").removeClass("changed");
    }
  });  
  //requery
  //manageUsers();  
}
                         
function userCopy(hthis) {
  hurl = "./userCRUD.php?pmode=C"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageUsers();  
  });  
}

function userDelete(hthis) {
  hurl = "./userCRUD.php?pmode=D"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageUsers();  
  });  
}

function settingUpdate(hthis) {
  hurl = "./settingCRUD.php?pmode=U"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    else {
      $(hthis).parent().find(".changed").removeClass("changed");
    }
  });  
  //requery
  //manageSettings();  
}

function themeUpdate(hthis) {
  hurl = "./themeCRUD.php?pmode=U"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    else {
      $(hthis).parent().find(".changed").removeClass("changed");
    }
  });  
  //requery
  //manageSettings();  
}
                         
function themeCopy(hthis) {
  hurl = "./themeCRUD.php?pmode=C"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageSettings();  
  });  
}

function themeDelete(hthis) {
  hurl = "./themeCRUD.php?pmode=D"+getParams(hthis); 
  $.get(hurl, function(data) {
    if (data != "SUCCESS") {
      alert(data);
    }
    //requery
    manageSettings();  
  });  
}
  
//custom jquery filter: instead of finding all matched content only finds content that starts with a given string
$.expr[":"].startsWith = function(el, i, m) {
  var search = m[3];        
  if (!search) return false;
  return eval("/^[/]*" + search + "/i").test($(el).text());
};

function scrollFocus() {
  if ($("#api3").css('visibility')=='visible') {
    hapi = "#api3";
  }
  else if ($("#api14").css('visibility')=='visible') {
    hapi = "#api14";
  }
  else {
    hapi = "#api7"
  }
  
  if ($("#scrollfield").val() == "") {
    $(hapi).scrollTo($(hapi+" .top-spacer"));
    $(hapi+" #tree li").removeClass("highlighted");
  }
  $(hapi).scrollTo($(hapi+" #tree :startsWith("+$("#scrollfield").val()+")"),{offset: {top:-20}});
  $(hapi+" #tree li").removeClass("highlighted");
  $(hapi+" #tree li:startsWith("+$("#scrollfield").val()+")").addClass("highlighted");
}
