//evito en formularios acciones por pulsar enter
document.addEventListener("keydown", function(event) {
if (event.keyCode === 13) event.preventDefault();
})
document.addEventListener('contextmenu', event => event.preventDefault());
setTimeout(function () {
let viewheight = $(window).height();
let viewwidth = $(window).width();
let viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute("content", "height=" + viewheight + "px, width=" + viewwidth + "px, initial-scale=1.0");
}, 300);
//variables generales
const ALLOWED_UPLOAD_FILE_FORMATS = ['mp3','mpeg'],
APIWEB_URL="https://apiweb.admira.com/v1/";
var idTrack,
isLoadigContent = false,
accordionCanPush = true;
var idAlbum = localStorage.getItem('idAlbum');
var nameAlbum = localStorage.getItem('nameAlbum');
var idPlayer = localStorage.getItem('idPlayer');
var namePlayer = localStorage.getItem('namePlayer');
var idSchedule = localStorage.getItem('idSchedule');
var nameSchedule = localStorage.getItem('nameSchedule');
////variables para la subida de archivos
var file,
title,
numFiles,
liNum,
fileInput, //asignaremos a esta variable el input cuando carguemos albumPage()
fileList = [];
var jsmediatags = window.jsmediatags; // jsmediatags <- Librería obtención metadatos
////////////////
// variables para el uso del apartado Schedule: Debemos sacar la semana actual en la que estamos,
// para añidirla a los datos que recibimos y que apereza en fullcalendar
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var daysOfWeek = {};
var day = startOfWeek;
var i = 0;
var $trigger;
while (day <= endOfWeek) {
daysOfWeek[day.format("dddd")] = day.format("YYYY-MM-DD");
day = day.clone().add(1, 'd');
i++;
}
///////////
$(function(){
checkPrivacyCookieAndtutorial();
$.contextMenu({
selector: '#help',
position: function(opt, x, y){
opt.$menu.css({bottom: "0px", left: "70px"});
},
callback: function(key, options) {
if(key==="guide"){
showTutorial();
}
if(key==="manual"){
//enlace a guia
}
},
trigger: 'left',
items: {
"guide": {name: "Quick Guide"},
"manual": {name: "Read Manual"},
// "tips": {name: "Show Help Tips"},
}
});
});
function checkPrivacyCookieAndtutorial(){
if(!$.cookie('cookie_privacy')){
var bodyHtml = '
'+
'
This website uses cookies to ensure the best user experience. If you continue browsing you are giving your consent for the acceptance of the aforementioned cookies and acceptance of our cookies policy, click on the link for more information.
Vamos a echar un vistazo a las principales funcionalidades de la plataforma
'+
'
';
swal({
title: titleHtml,
html: bodyHtml,
showLoaderOnConfirm: true,
reverseButtons: true,
showConfirmButton: false,
showCloseButton: true,
showCancelButton: true,
cancelButtonText: 'Omitir introducción',
focusConfirm: true,
animation: false,
customClass: 'modal animation tutorial',
buttonsStyling: false,
onBeforeOpen: () => {
$("body").on("click", ".controller ul button", function() {
var slide = $(this).attr('id');
$('#vidContainer').removeClass();
$('#vidContainer').addClass(slide);
$(".controller ul button").each(function(index){
$('#vidContainer video:eq('+index+')')[0].pause();
if($(this).hasClass('active')){
$(this).removeClass();
}
});
$(this).addClass('active');
switch (slide) {
case 'slideOne':
$('#vidContainer video:eq(0)')[0].play();
$(".titleTutorial h2").text("Bienvenido a Admira music");
$(".titleTutorial h3").text("Vamos a echar un vistazo a las principales funcionalidades de la plataforma");
break;
case 'slideTwo':
$('#vidContainer video:eq(1)')[0].play();
$(".titleTutorial h2").text("El espacio de trabajo");
$(".titleTutorial h3").text("Admira music esta diseñado para que siempre tengas a mano justo lo que necesitas en cada momento");
break;
case 'slideThree':
$('#vidContainer video:eq(2)')[0].play();
$(".titleTutorial h2").text("Elementos básicos");
$(".titleTutorial h3").text("Estos son los elementos que debes conocer para trabajar con Admira music");
break;
}
});
}
}).then(function(){
if(!$.cookie('cookie_tutorial')) $.cookie('cookie_tutorial',true, { expires: 365, path: '/' });
});
setTimeout(function(){
$('#vidContainer video:eq(0)')[0].play();
},100);
}
////Funciones y eventos varios /////
/**
* Cerrar menú de proyectos Y cerrar launcher pulsando fuera del menú launcher
*/
$(document).on("click", function(event){
if($trigger !== event.target.className){
$("#projects ul").css("display","none");
}
if($('#app-selector').hasClass('visible')){
setTimeout(function(){
if($trigger !== event.target.className){
$( "#launcher" ).trigger('click');
}
},250);
};
});
/**
* Función para añadir a cada inputs con clase typpyInput el tooltip tippy para ver caracteres disponibles.
*/
function chargeTyppyInput() {
$('.typpyInput').each(function(index){
var iD = $(this).attr('id');
var elem = $(this);
var count = "countLeft"+[index];
var $div = $("
", {class: count});
elem.parent().append($div);
limiter($(this), elem.attr('maxLength'), $(".countLeft"+[index]));
tippy('#'+iD, {
html: document.querySelector('.countLeft'+[index]),
hideOnClick: false,
trigger: 'keyup focus',
placement: 'bottom right',
arrow: false,
theme: 'crystal',
size:'small',
duration: 200,
animation: 'fade',
})
});
};
function tipLeft() {
tippy('.tip',{
delay: 600,
arrow: true,
arrowType: 'round',
placement: 'left',
size: 'medium',
duration: 200,
animation: 'fade',
theme: 'graphite'
})
}
function tipRight() {
tippy('.tip',{
delay: 600,
arrow: true,
arrowType: 'round',
placement: 'right',
size: 'medium',
duration: 200,
animation: 'fade',
theme: 'graphite'
})
}
/**
* Función que cuenta y resta los caracteres disponibles.
*/
function limiter (inputTxt, limit, elem) {
$(inputTxt).on("keyup focus", function() {
setCount(this, elem);
});
function setCount(src, elem) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html( limit - chars + ' Characters left');
}
setCount($(inputTxt)[0], elem);
}
/**
* Cambiar la vista en main, por lista o cuadrícula
*/
$("body").on("click", ".showList", function(){
var cat = $(this).parent().parent().data('filter');
if (cat==='players'){
$( "#player" ).removeClass( "grid" );
$( "#player" ).addClass( "list" );
}else if (cat==='albums'){
$( "#album" ).removeClass( "grid" );
$( "#album" ).addClass( "list" );
}else if (cat==='schedules'){
$( "#schedule" ).removeClass( "grid" );
$( "#schedule" ).addClass( "list" );
}
$(this).addClass('active');
$( ".showGrid" ).removeClass('active');
$( ".index" ).addClass( "active" );
});
$("body").on("click", ".showGrid", function(){
var cat = $(this).parent().parent().data('filter');
if (cat==='players'){
$( "#player" ).removeClass( "list" );
$( "#player" ).addClass( "grid" );
}else if (cat==='albums'){
$( "#album" ).removeClass( "list" );
$( "#album" ).addClass( "grid" );
}else if (cat==='schedules'){
$( "#schedule" ).removeClass( "list" );
$( "#schedule" ).addClass( "grid" );
}
$(this).addClass('active');
$( ".showList" ).removeClass('active');
$( ".index" ).removeClass( "active" );
});
/**
* Cambiar el orden de las vistas en main (players, albums...)
*/
//$("body").on("click", "li.index", function(){ //generico para V2 poder ordenar por más parámetros
//$("body").on("click", "li.name", function(){
$("body").on("click", "li.index", function(){
$(this).toggleClass('ordinal');
var typeOrder = $(this).parent().parent().data('filter'),
contentOrder = $(this)[0].classList[1] ;
if ($(this).hasClass('ordinal')){
orderView(typeOrder,contentOrder,'desc');
}else{
orderView(typeOrder,contentOrder,'asc');
}
});
/**
* Función para ordenar las vistas.
*/
var orderObj = {
'players': [],
'albums': [],
'schedules': [],
}
function orderView(typeToOrder, contentOrder, order) {
var data = orderObj[typeToOrder];
if (data.length !== 0){
switch (typeToOrder){
case "albums":
$("#album").html("");
data.sort(function(a, b) {
var nameA = a[contentOrder].toString().toUpperCase()
var nameB = b[contentOrder].toString().toUpperCase();
if (order==='asc'){
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}else{
if (nameA > nameB) {
return -1;
}
if (nameA < nameB) {
return 1;
}
// names must be equal
return 0;
}
});
$.each(data, function( index, album ) {
var strList='
' ;
swal({
title: 'Create player',
position: 'top-end',
html: bodyHtml,
reverseButtons: true,
preConfirm: function(){
if (document.getElementById('nameNewPlayer').checkValidity() && document.getElementById('descrNewPlayer').checkValidity()) {
return [
,document.getElementById('nameNewPlayer').value
,document.getElementById('locationPlayer').value
,document.getElementById('descrNewPlayer').value
];
} else {
swal.showValidationMessage(
'The name and description field are required.'
)
}
},
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
customClass: 'modal animation',
buttonsStyling: false
}).then( function (result) {
//console.log(result.value)
if (Array.isArray(result.value)) {
createPlayer( result.value[1], result.value[2], result.value[3]);
}
});
$('#nameNewPlayer').focus();
chargeTyppyInput(); //llamamos a la funcion para que los inpunts tengan tooltip que muestre contador de caracteres restantes.
});
function modifyPlayer(id, namePlayer, locationPlayer, descrPlayer, volume, crossfade){
$('#spinner').css("display", "flex");
var name = $.trim(namePlayer);
var location = $.trim(locationPlayer);
var description = $.trim(descrPlayer);
localStorage.setItem('nameSchedule', name);
$.when( putPlayer(id, name, location, description, volume, crossfade) ).done(function() {
switch (window.location.hash){
case "#player-page":
setTimeout(function(){
sourceArea();
playerPage();
}, 500);
break;
case "#player-list":
setTimeout(function(){
sourceArea();
playerList();
}, 500);
break;
}
swal({
position: 'top-end',
type: 'success',
html: 'The player '+namePlayer+' has been modified',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
});
$('#spinner').css("display", "");
});
}
$("body").on("click", "#player a", function(){
idPlayer = $(this).parent().data("id");
namePlayer = $(this).parent().data("name");
localStorage.setItem('idPlayer', idPlayer);
localStorage.setItem('namePlayer', namePlayer);
// console.log(idPlayer);
// console.log(namePlayer);
});
$("body").on("click", "#player ul.toolsRow .edit", function(){
idPlayer = $(this).parent().parent().data("id");
namePlayer = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idPlayer);
localStorage.setItem('namePlayer', namePlayer);
playerInfoAreaPage();
});
$("body").on("click", "#player ul.toolsRow .delete", function(){
idPlayer = $(this).parent().parent().data("id");
namePlayer = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idPlayer);
localStorage.setItem('namePlayer', namePlayer);
deletePlayer();
});
/////////////////////////////////////////////////////
//////////////CONTENT FUNCTIONS//////////////////
$("body").on( "change", "#selectall", function(){
if(this.checked)
$("#listAlbumsAssign :checkbox").each(function() {
this.checked = true;
});
else
$("#listAlbumsAssign :checkbox").each(function() {
this.checked = false;
});
});
$("body").on( "change", "#listAlbumsAssign :checkbox", function(){
if(!this.checked && $('#selectall').is(':checked') ) {
$('#selectall').prop( "checked", false );
}
})
function modifyContent(id, titleContent){
$('#spinner').css("display", "flex");
var title = $.trim(titleContent);
// localStorage.setItem('nameTrack', name);
$.when( putContent(title) ).done(function() {
switch (window.location.hash){
case "#album-page":
setTimeout(function(){
sourceArea();
albumPage();
}, 500);
break;
case "#schedule-list":
setTimeout(function(){
sourceArea();
scheduleList();
}, 500);
break;
case "#schedule-page":
setTimeout(function(){
sourceArea();
schedulePage();
}, 500);
break;
}
swal({
position: 'top-end',
type: 'success',
html: 'The content '+title+' has been modified',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
});
$('#spinner').css("display", "");
});
}
function putTracktToAlbum(arrIdAlbums){
var ajaxReqs = [];
arrIdAlbums.forEach(function(id) {
ajaxReqs.push(
$.ajax({
type:'POST',
crossDomain: true,
dataType: 'json',
url: APIWEB_URL+"block/"+id+"/content?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
data: 'content_id=' + idTrack,
})
);
});
$.when.apply($, ajaxReqs).then(function() {
swal({
type: 'success',
title: 'Added!',
html: `The track ${nameTrack} has been added`,
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
})
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("Fail putPlaylistToPlayer: "+ jqXHR, textStatus, errorThrown);
});
}
function assingTrack(){
$.when( getAlbumsBlock() ).done(function( albums ) {
var strList = "";
var bodyHtml = '
'+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
'+
'
@liAlmbums
'+
'
'+
'
'+
'
'+
'
';
if (albums.data.length>0){
$.each(albums.data, function( index, album ) {
if (album.id === idAlbum) { return; } //saltamos cuando el id del álbum, es el mismo que donde está asignado el track.
strList += '
'+
'
';
});
bodyHtml = bodyHtml.replace("@liAlmbums",strList);
swal({
title: 'Assign Track',
html: bodyHtml,
reverseButtons: true,
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
preConfirm: ( function () {
return $("#listAlbumsAssign input:checked");
}),
customClass: 'modal animation lite',
buttonsStyling: false
}).then( function (result) {
if (result.value) {
var arrIdAlbums = [];
$(result.value).each(function(index,data) {
//console.log(index,data);
arrIdAlbums.push($(data).attr("id"));
});
putTracktToAlbum(arrIdAlbums);
}
});
}else{
//SI NO HAY DATOS
}
});
}
function deleteTrack(block_content_id){
var bodyHtml = '
'+
'
Are you sure you want to delete the track '+nameTrack+'?
';
if (players.data.length>0){
$.each(players.data, function( index, player ) {
if (player.id === idPlayer) { return; } //saltamos cuando el id del player, es el mismo que donde está asignado el schedule.
if (player.playlistMode === 1){
strList += '
'+
'
';
}
});
bodyHtml = bodyHtml.replace("@liPlayers",strList);
swal({
title: 'Assign Schedule',
html: bodyHtml,
reverseButtons: true,
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
preConfirm: ( function () {
return $("#listPlayersAssign input:checked");
}),
customClass: 'modal animation lite',
buttonsStyling: false
}).then( function (result) {
if (result.value) {
var arrIdAlbums = [];
$(result.value).each(function(index,data) {
//console.log(index,data);
arrIdAlbums.push($(data).attr("id"));
});
putScheduleToPlayers(arrIdAlbums);
//putTracktToAlbum(arrIdAlbums);
}
});
}else{
//SI NO HAY DATOS
}
});
}
function deleteSchedulePlaylists(playListSchedulesId){
$.each(playListSchedulesId, function( index, playlistId ) {
$.ajax({
type: 'DELETE',
dataType: 'json',
crossDomain: true,
url: APIWEB_URL+"playlist/"+playlistId+"?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
});
})
}
function deleteSchedule(){
var playListSchedulesId = [];
$.when(getSchedulePlaylist()).done(function(schedulePlaylist){
$.each(schedulePlaylist.data, function( index, playlist ) {
playListSchedulesId.push(playlist.playlist.id);
})
// console.log(playListSchedulesId)
});
var bodyHtml = '
'+
'
Are you sure you want to delete the schedule '+nameSchedule+'?
'
'
';
swal({
title: 'Delete schedule',
html: bodyHtml,
showLoaderOnConfirm: true,
reverseButtons: true,
preConfirm: ( function () {
return fetch(APIWEB_URL+"schedule/"+idSchedule+"?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
{
method: 'DELETE',
crossDomain: true
}).then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
swal.showValidationMessage(
`Request failed: ${error}`
)
})
}),
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
customClass: 'modal animation',
buttonsStyling: false
}).then( function (result) {
if (result.value) {
deleteSchedulePlaylists(playListSchedulesId);
swal({
position: 'top-end',
type: 'success',
html: 'The schedule '+nameSchedule+' has been deleted',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
})
//vacíamos la varible que tiene id del álbum que acabamos de eliminar
idSchedule = "";
localStorage.setItem('idSchedule', "");
nameSchedule = "",
localStorage.setItem('nameSchedule', "");
//después de eliminar el bloque, volvemos a cargar la página para listar sin el álbum eliminado
switch (window.location.hash){
case "#schedule-page":
//Cambiamos vista a albumList, por si eliminamos el mismo álbum de sourceArea, que el de la vista de albumpage.
setTimeout(function(){
window.location.hash = '#schedule-list';
}, 2000);
break;
case "#schedule-list":
setTimeout(function(){
sourceArea();
scheduleList();
}, 2000);
break;
case "#player-list":
case "":
setTimeout(function(){
sourceArea();
playerList();
}, 2000);
break;
case "#player-page":
setTimeout(function(){
sourceArea();
playerPage();
}, 2000);
break;
}
}
});
}
$("body").on("click", "#openerSchedule" , function() {
var bodyHtml = '
'+
'
'+
''+
'
'+
'
'+
'
'+
''+
''+
''+
''+
'
'+
'
'+
'
';
swal({
title: 'Create schedule',
position: 'top-end',
html: bodyHtml,
reverseButtons: true,
preConfirm: function(){
if (document.getElementById('nameNewSchedule').checkValidity()) {
return [
,document.getElementById('nameNewSchedule').value
,document.getElementById('descrNewSchedule').value
];
} else {
swal.showValidationMessage(
'The name field is required.'
)
}
},
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
customClass: 'modal animation',
buttonsStyling: false
}).then( function (result) {
// console.log(result.value)
if (Array.isArray(result.value)) {
createSchedule( result.value[1], result.value[2]);
}
});
$('#nameNewSchedule').focus();
chargeTyppyInput(); //llamamos a la funcion para que los inpunts tengan tooltip que muestre contador de caracteres restantes.
});
function createSchedule(nameSchedule, descrSchedule){
$('#spinner').css("display", "flex");
var name = $.trim(nameSchedule);
var description = $.trim(descrSchedule);
$.when( postSchedule(name, description) ).done(function(schedule) {
swal({
position: 'top-end',
type: 'success',
title: 'Added!',
html: 'New Schedule Added!',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
})
scheduleList();
sourceArea();
$('#spinner').css("display", "");
// // console.log('schedule',schedule);
// var newScheduleId = schedule.data.id;
// var ajaxReqsPlayList = [];
// var ajaxReqsPlayListAssign = [];
// var daysWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
// for(var i=0; i<7; i++){
// ajaxReqsPlayList.push(
// $.ajax({
// type:'POST',
// dataType: 'json',
// crossDomain: true,
// url: APIWEB_URL+"playlist?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
// data: 'name=music_'+schedule.data.name+'_'+daysWeek[i]+'&description=Playlist created to use for ADmira Music.'
// })
// );
// }
// $.when.apply($, ajaxReqsPlayList).then(function(Mon,Tue,Wed,Thu,Fri,Sat,Sun) {
// var date = new Date();
// var date2 = new Date();
// var dateFinish = new Date( date2.setFullYear(date2.getFullYear() + 30) );
// var datestart = Date.parse(date)/1000;
// var dateend = Date.parse(dateFinish)/1000;
// var weekBinary = ["0","0","0","0","0","0","0"];
// for(var i=0; i < arguments.length; i++){
// weekBinary[i] = "1";
// var week = weekBinary.join("");
// ajaxReqsPlayListAssign.push(
// $.ajax({
// type:'POST',
// dataType: 'json',
// crossDomain: true,
// url: APIWEB_URL+"schedule/"+newScheduleId+"/playlist?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
// data: 'playlist_id='+arguments[i][0].data.id+'&datestart='+datestart+'&dateend='+dateend+'&week='+week+'&hourstart=0&hourend=1440'
// })
// );
// // console.log( 'playlist_id='+arguments[i][0].data.id+'&datestart='+datestart+'&dateend='+dateend+'&week='+week+'&hourstart=2&hourend=1440' )
// // console.log(daysWeek[i]," ", arguments[i][0].data.name);
// weekBinary = ["0","0","0","0","0","0","0"];
// }
// $.when.apply($, ajaxReqsPlayListAssign).then(function() {
// scheduleList();
// sourceArea();
// $('#spinner').css("display", "");
// swal({
// position: 'top-end',
// type: 'success',
// title: 'Added!',
// html: 'New Schedule Added!',
// showConfirmButton: false,
// customClass: 'notify',
// timer: 3000,
// toast: true,
// })
// }).fail(function(jqXHR, textStatus, errorThrown){
// console.log("Fail createSchedule assign playlist: "+ jqXHR, textStatus, errorThrown);
// });
// }).fail(function(jqXHR, textStatus, errorThrown){
// console.log("Fail createSchedule: "+ jqXHR, textStatus, errorThrown);
// });
}).fail(function(){
$('#spinner').css("display", "");
swal({
position: 'top-end',
type: 'error',
title: 'Error',
html: 'Error creating a chedule',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
})
});
}
function modifySchedule(id, nameSchedule, descrSchedule){
$('#spinner').css("display", "flex");
var name = $.trim(nameSchedule);
var description = $.trim(descrSchedule);
if(description === "") description=" ";
localStorage.setItem('nameSchedule', name);
$.when( putSchedule(id, name, description) ).done(function() {
switch (window.location.hash){
case "#player-page":
setTimeout(function(){
sourceArea();
playerPage();
}, 500);
break;
case "#player-list":
setTimeout(function(){
sourceArea();
playerList();
}, 500);
break;
case "#schedule-list":
setTimeout(function(){
sourceArea();
scheduleList();
}, 500);
break;
case "#schedule-page":
setTimeout(function(){
sourceArea();
schedulePage();
}, 500);
break;
}
swal({
position: 'top-end',
type: 'success',
html: 'The schedule '+nameSchedule+' has been modified',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
});
$('#spinner').css("display", "");
});
}
$("body").on("click", "#schedule a", function(){
idSchedule = $(this).parent().data("id");
nameSchedule = $(this).parent().data("name");
localStorage.setItem('idSchedule', idSchedule);
localStorage.setItem('nameSchedule', nameSchedule);
});
$("body").on("click", "#schedule ul.toolsRow .edit", function(){
idSchedule = $(this).parent().parent().data("id");
nameSchedule = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idSchedule);
localStorage.setItem('namePlayer', nameSchedule);
scheduleInfoAreaPage();
});
$("body").on("click", "#schedule ul.toolsRow .delete", function(){
idSchedule = $(this).parent().parent().data("id");
nameSchedule = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idSchedule);
localStorage.setItem('namePlayer', nameSchedule);
deleteSchedule();
});
/////////////////////////////////////////////////
//////////////ALBUMS FUNCTIONS//////////////////
function deleteAlbum(){
var bodyHtml = '
'+
'
Are you sure you want to delete the album '+nameAlbum+'?
'
'
';
swal({
title: 'Delete album',
html: bodyHtml,
showLoaderOnConfirm: true,
reverseButtons: true,
preConfirm: ( function () {
return fetch(APIWEB_URL+"block/"+idAlbum+"?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
{
method: 'DELETE',
crossDomain: true
}).then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
swal.showValidationMessage(
`Request failed: ${error}`
)
})
}),
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
customClass: 'modal animation',
buttonsStyling: false
}).then( function (result) {
if (result.value) {
swal({
position: 'top-end',
type: 'success',
html: 'The album '+nameAlbum+' has been deleted',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
})
//vacíamos la varible que tiene id del álbum que acabamos de eliminar
idAlbum = "";
localStorage.setItem('idAlbum', "");
nameAlbum = "",
localStorage.setItem('nameAlbum', "");
//después de eliminar el bloque, volvemos a cargar la página para listar sin el álbum eliminado
switch (window.location.hash){
case "#album-page":
//Cambiamos vista a albumList, por si eliminamos el mismo álbum de sourceArea, que el de la vista de albumpage.
setTimeout(function(){
window.location.hash = '#album-list';
}, 2000);
break;
case "#album-list":
setTimeout(function(){
sourceArea();
albumList();
}, 2000);
break;
case "#schedule-list":
setTimeout(function(){
sourceArea();
scheduleList();
}, 2000);
break;
case "#schedule-page":
setTimeout(function(){
sourceArea();
schedulePage();
}, 2000);
break;
}
}
});
}
$("body").on("click", "#openerAlbum" , function() {
var bodyHtml = '
'+
'
'+
''+
'
'+
'
'+
'
'+
''+
''+
''+
''+
''+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
'
'+
'
'+
'
'+
'
';
swal({
title: 'Create album',
html: bodyHtml,
reverseButtons: true,
preConfirm: function(){
if (document.getElementById('nameNewAlbum').checkValidity()) {
return [
,document.getElementById('nameNewAlbum').value
,document.getElementById('descrNewAlbum').value
,document.querySelector('input[name="playMode"]:checked').value
];
} else {
swal.showValidationMessage(
'The name field is required.'
)
}
},
showCloseButton: true,
showCancelButton: true,
focusConfirm: true,
animation: false,
customClass: 'modal animation',
buttonsStyling: false
}).then( function (result) {
// console.log(result)
if (Array.isArray(result.value)) {
createAlbum( result.value[1], result.value[2], result.value[3] );
}
});
$('#nameNewAlbum').focus();
chargeTyppyInput(); //llamamos a la funcion para que los inpunts tengan tooltip que muestre contador de caracteres restantes.
});
$("body").on("click", "#album a", function(){
idAlbum = $(this).parent().data("id");
nameAlbum = $(this).parent().data("name");
localStorage.setItem('idAlbum', idAlbum);
localStorage.setItem('nameAlbum', nameAlbum);
});
$("body").on("click", "#album ul.toolsRow .edit", function(){
idAlbum = $(this).parent().parent().data("id");
nameAlbum = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idAlbum);
localStorage.setItem('namePlayer', nameAlbum);
albumInfoAreaPage();
});
$("body").on("click", "#album ul.toolsRow .delete", function(){
idAlbum = $(this).parent().parent().data("id");
nameAlbum = $(this).parent().parent().data("name");
localStorage.setItem('idPlayer', idAlbum);
localStorage.setItem('namePlayer', nameAlbum);
deleteAlbum();
});
function modifyAlbum(id, nameAlbum, descrAlbum, playMode){
$('#spinner').css("display", "flex");
var name = $.trim(nameAlbum);
var description = $.trim(descrAlbum);
localStorage.setItem('nameAlbum', name);
if(description === "") description=" ";
$.when( putAlbum(id, name, description, playMode) ).done(function() {
//después de elimodificar el bloque, volvemos a cargar la página para listar sin el álbum eliminado
switch (window.location.hash){
case "#album-page":
setTimeout(function(){
sourceArea();
albumPage();
}, 500);
break;
case "#album-list":
setTimeout(function(){
sourceArea();
albumList();
}, 500);
break;
case "#schedule-list":
setTimeout(function(){
sourceArea();
scheduleList();
}, 500);
break;
}
swal({
position: 'top-end',
type: 'success',
html: 'The album '+nameAlbum+' has been modified',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
});
$('#spinner').css("display", "");
});
}
function createAlbum(nameAlbum, descrAlbum, playMode){
$('#spinner').css("display", "flex");
var name = $.trim(nameAlbum);
var description = $.trim(descrAlbum);
$.when( postAlbumBlock(name, description, playMode) ).done(function() {
albumList();
sourceArea();
$('#spinner').css("display", "");
swal({
position: 'top-end',
type: 'success',
html: 'New album added!',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
});
});
}
//////////////////////////////////////////////////////
///////////////////DOWNLOAD PLAYERS//////////////////////
$("body").on("click", ".player li", function(){
var $OS = $(this).attr("id");
switch ($OS) {
case "windows":
location.href = "https://new.admira.mobi/Downloads/ADmiraMobi.exe"
break;
case "apple":
location.href = "https://new.admira.mobi/Downloads/ADmiraHTML5xOSX.dmg"
break;
case "ubuntu":
location.href = "https://new.admira.mobi/download/download_ubuntu"
break;
case "android":
location.href = "https://new.admira.mobi/Downloads/ADmiraMobi.apk"
break;
case "android_html5":
window.open ("https://new.admira.mobi/download/" + $OS);
break;
case "ios":
window.open ("https://new.admira.mobi/download/" + $OS);
break;
}
});
//////////////////////////////////////////////////////
///////////////////UPLOAD FILES//////////////////////
function uploadProcess (title, file, loop){
var form_data = new FormData();
form_data.append('type',1);
form_data.append('title',title);
form_data.append('file', file);
var promise = $.ajax({
type: 'POST',
url: APIWEB_URL+"content?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
data: form_data,
cache: false,
contentType: false,
processData: false,
crossDomain: true,
dataType: 'json'
});
promise.done(function(response){
$.ajax({
type:'POST',
crossDomain: true,
dataType: 'json',
url: APIWEB_URL+"block/"+idAlbum+"/content?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
data: 'content_id=' + response.data.id,
});
}).done(function(){
console.log("Añadida canción: ",title ," al album id ",idAlbum);
$("#files_to_upload ul li:nth-child(" + liNum + ")").find("div").removeClass('state1').addClass('state2');
loopUloadadContent(loop+1);
})
promise.fail(function(error){
swal({ position: 'top-end',
type: 'error',
html: 'Error in the upload process',
showConfirmButton: false,
customClass: 'notify',
timer: 2500,
toast: true
});
console.log("Error: ",error.responseJSON.message);
$('#spinner').css("display", "");
});
}
function loopUloadadContent(i){
var loop = i || 0;
if(loop < numFiles) {
$('#btn_empty_list').prop("disabled",true);
liNum = (loop+1).toString();
// alert(liNum);
$("#files_to_upload ul li:nth-child(" + liNum + ")").find("div").removeClass('state0').addClass('state1');
// var form_data = new FormData();
file = fileList[loop];
var titleFromFile = file.name.substr(0, file.name.lastIndexOf('.'));
jsmediatags.read (file, {
onSuccess: function(tag) {
var tags = tag.tags;
if (tags.title === undefined) {
uploadProcess(titleFromFile,file,loop)
}else{
uploadProcess(tags.title,file,loop);
}
},
onError: function(error) {
uploadProcess(titleFromFile,file,loop)
console.log('jsmediatags :(', error.type, error.info);
}
});
// form_data.append('type',1);
// form_data.append('title',title);
// form_data.append('file', fileList[loop]);
// var promise = $.ajax({
// type: 'POST',
// url: APIWEB_URL+"content?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
// data: form_data,
// cache: false,
// contentType: false,
// processData: false,
// crossDomain: true,
// dataType: 'json'
// });
// promise.done(function(response){
// $.ajax({
// type:'POST',
// crossDomain: true,
// dataType: 'json',
// url: APIWEB_URL+"block/"+idAlbum+"/content?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
// data: 'content_id=' + response.data.id,
// });
// }).done(function(){
// console.log("Añadida canción: ",title ," al album id ",idAlbum);
// $("#files_to_upload ul li:nth-child(" + liNum + ")").find("i").removeClass('state1').addClass('state2');
// loopUloadadContent(loop+1);
// })
// promise.fail(function(error){
// swal({ position: 'top-end',
// type: 'error',
// html: 'Error in the upload process',
// showConfirmButton: false,
// customClass: 'notify',
// timer: 2500,
// toast: true
// });
// console.log("Error: ",error.responseJSON.message);
// $('#spinner').css("display", "");
// });
}else{
console.log("terminé de subir");
swal({ position: 'top-end',
type: 'success',
html: 'The file(s) has been uploaded.',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true,
});
$('#spinner').css("display", "");
$('.main-uploader').css({'z-index':'', 'background':''});
$("#upload-input").val("");
fileList = [];
setTimeout(function(){
sourceArea();
albumPage();
}, 2000);
}
}
$("body").on("click", "#btn_upload", function (evt) {
evt.preventDefault();
checkToken(function(done){
if(done){
if ($("#upload-input").val() !== "") {
$("#files_to_upload ul").sortable("disable");
$('#btn_upload').prop("disabled",true);
numFiles = $('input#upload-input')[0].files.length;
loopUloadadContent();
$('#spinner').css("display", "flex");
$('.main-uploader').css({'z-index':960, 'background':'white'});
}
}
});
});
$("body").on("click", "#btn_empty_list", function (evt) {
evt.preventDefault();
if ($("#upload-input").val() !== "") {
$("#files_to_upload ul").html("");
$("#upload-input").val("");
fileList = [];
$('#btn_upload').prop("disabled",false);
$("#files_to_upload ul").sortable("enable");
}
});
function dragToUpload(){
var drop = $("input#upload-input");
drop.on('dragenter', function (e) {
$('.dragarea').addClass('drag-active');
}).on('dragleave dragend mouseout drop', function (e) {
$('.dragarea').removeClass('drag-active');
});
// $('#upload-input').click(function(){
// console.log('pulse')
// // $(this).val("");
// })
$('#upload-input').change(function(evnt){
//Al haber un change, el ipunt elimina el contenido que había por el nuevo que se añade, por lo tanto debemos de limpiar el array fileList, para que sea igual al del input
fileList = [];
for (var i = 0; i < fileInput.files.length; i++) {
if( $.inArray(fileInput.files[i].type.substr(fileInput.files[i].type.lastIndexOf('/')+1,fileInput.files[i].type.length), ALLOWED_UPLOAD_FILE_FORMATS) < 0) {
swal({ position: 'top-end',
type: 'error',
html: 'Extension not allowed',
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
});
//Se podrá incluir archivos antes de subir, PERO cuando entre aquí por ser una extensión no permitida, para asegurar, limpiaremos todo y se vuelve a empezar.
fileList = [];
$("#upload-input").val("");
$("#files_to_upload ul").html("");
return false;
}
fileList.push(fileInput.files[i]);
}
renderFileList();
// console.log("fileList: ", fileList);
});
}
function renderFileList() {
$("#files_to_upload ul").html("");
fileList.forEach(function (file, index) {
$("#files_to_upload ul").append("
"+file.name+"
");
});
$("#files_to_upload ul").sortable({
containment: '#files_to_upload',
cursor: 'ns-resize',
axis: 'y',
start: function( event, ui ){
$(ui.item).parent().find('.ui-sortable-placeholder').hide();
},
update: function(event, ui) {
$("#files_to_upload li").each(function(i) {
fileList[i] = fileInput.files[parseInt($(this).attr('data-pos'))];
});
// console.log('After fileList ',fileList);
}
});
$("#files_to_upload ul").disableSelection();
};
////////////////////////////////////////////////////////
/**
* Funcion control tabs en Source Area
*/
function tabs(evt, list) {
var i, x, tablinks;
var x = document.getElementsByClassName("source");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
$('.tablink').each(function(){
$(this).removeClass('active');
});
document.getElementById(list).style.display = "block";
evt.addClass('active');
}
$("body").on("click", ".tablink" , function() {
var optLink = $(this).text();
tabs($(this), optLink);
});
// function goBack() {
// window.history.back();
// }
function hideInfo(){
// document.getElementById('info_area').style.transform='translateX(15.625vw)';
$('#info_area').removeClass('showInfo');
$('.container').removeClass('opacity1');
$('#info_area').addClass('hideInfo');
$('.container').addClass('opacity0');
$('main').removeClass('minMain');
$('main').addClass('maxMain');
$('#audio').removeClass('minMain');
$('#audio').addClass('maxMain');
$('.main_head').removeClass('minMain');
$('.main_head').addClass('maxMain');
if (window.location.hash.split('-')[1]==='page')
$('.edit')[0].disabled = false;
}
function showInfo(){
// document.getElementById('info_area').style.transform='translateX(15.625vw)';
$('#info_area').removeClass('hideInfo');
$('.container').removeClass('opacity0');
$('main').removeClass('maxMain');
$('main').addClass('minMain');
$('#info_area').addClass('showInfo');
$('.container').addClass('opacity1');
$('#audio').addClass('minMain');
$('#audio').removeClass('maxMain');
$('.main_head').addClass('minMain');
$('.main_head').removeClass('maxMain');
if (window.location.hash.split('-')[1]==='page')
$('.edit')[0].disabled = true;
}
/**
* Funcion para pintar en la listas de ítems, según texto introduccido en el input
*/
function searchItems (input, el){
var $btnClose = $(input).closest('#searchbar').find('.close');
$(input).on("keyup", function () {
var searchText = $(this).val();
searchText = searchText.toLowerCase();
searchText = searchText.replace(/\s+/g, '');
$(el +' > li').each(function(){
var currentLiText = $(this).attr('data-name');
if (((currentLiText.toLowerCase()).replace(/\s+/g, '')).indexOf(searchText) !== -1) {
$(this).css('display','');
}else{
$(this).css('display','none');
}
});
if ( $(this).val().length > 0 ) {
$btnClose.css('display', 'flex');
}else{
$btnClose.css('display', 'none');
}
});
$btnClose.on("click", function () {
$(input).val("");
$(this).css('display','none');
$(el +' > li').each(function(){
$(this).css('display','block');
});
});
}
function searchItemsPagination (arrSearch, input, container){
function template(data) {
var html = "";
$.each(data, function(index, item){
html += item;
});
return html;
}
// console.log(arrSearch)
var $btnClose = $(input).closest('#searchbar').find('.close');
var initSearch;
$(input).on("keyup", function () {
var arrDataPlv = [];
var searchText = $(this).val();
searchText = searchText.toLowerCase();
searchText = searchText.replace(/\s+/g, '');
if (searchText.length >= 3) {
initSearch = true;
$(container).html("");
$('#spinner').css("display", "flex");
$.each(arrSearch, function( index, player ) {
var currentLiText = player[1];
if (((currentLiText.toLowerCase()).replace(/\s+/g, '')).indexOf(searchText) !== -1) {
arrDataPlv.push(player[0]);
// $("#player").append(player[0]);
}
});
$('#pagination-container-players').pagination({
dataSource: arrDataPlv,
prevText: '',
nextText: '',
pageSize: 15,
pageRange: 1,
callback: function(data, pagination) {
orderObj.players = [];
// template method of yourself
var html = template(data);
$(container).html(html);
setTimeout(function(){
$('#player > li').each(function(){
orderObj.players.push({
id: $(this).data("id"),
name: $(this).data("name"),
status: $(this).find('.img span')[0].classList[1],
download: $(this).find('ul.infoRow li:eq(0)').html(),
description: $(this).find('ul.infoRow li:eq(1)').html()
})
});
$('#spinner').css("display", "");
},50);
}
})
}else if (initSearch && searchText.length <= 3){
initSearch = false;
var arrDataPlv = [];
$(container).html("");
$('#spinner').css("display", "flex");
$.each(arrSearch, function( index, player ) {
arrDataPlv.push(player[0]);
});
$('#pagination-container-players').pagination({
dataSource: arrDataPlv,
prevText: '',
nextText: '',
pageSize: 15,
pageRange: 1,
callback: function(data, pagination) {
orderObj.players = [];
// template method of yourself
var html = template(data);
$(container).html(html);
setTimeout(function(){
$('#player > li').each(function(){
orderObj.players.push({
id: $(this).data("id"),
name: $(this).data("name"),
status: $(this).find('.img span')[0].classList[1],
download: $(this).find('ul.infoRow li:eq(0)').html(),
description: $(this).find('ul.infoRow li:eq(1)').html()
})
});
$('#spinner').css("display", "");
},50);
}
});
}
if (searchText.length > 0) {
$btnClose.css('display', 'flex');
} else {
$btnClose.css('display', 'none');
}
$btnClose.on("click", function () {
$(this).css('display','none');
if (searchText.length >= 3){
$.each(arrSearch, function( index, player ) {
arrDataPlv.push(player[0]);
});
$('#pagination-container-players').pagination({
dataSource: arrDataPlv,
prevText: '',
nextText: '',
pageSize: 15,
pageRange: 1,
callback: function(data, pagination) {
orderObj.players = [];
// template method of yourself
var html = template(data);
$(container).html(html);
setTimeout(function(){
$('#player > li').each(function(){
orderObj.players.push({
id: $(this).data("id"),
name: $(this).data("name"),
status: $(this).find('.img span')[0].classList[1],
download: $(this).find('ul.infoRow li:eq(0)').html(),
description: $(this).find('ul.infoRow li:eq(1)').html()
})
});
$('#spinner').css("display", "");
},50);
}
})
}
$(input).val("");
});
});
// $(input).on("keydown", function (event) {
// var searchText = $(this).val();
// var backspace = event.keyCode ? event.keyCode : event.which;
// if (searchText.length === 3){
// console.log(event)
// alert(9)
// var arrDataPlv = [];
// $(container).html("");
// $('#spinner').css("display", "flex");
// $.each(arrSearch, function( index, player ) {
// arrDataPlv.push(player[0]);
// });
// $('#pagination-container-players').pagination({
// dataSource: arrDataPlv,
// prevText: '',
// nextText: '',
// pageSize: 15,
// pageRange: 1,
// callback: function(data, pagination) {
// orderObj.players = [];
// // template method of yourself
// var html = template(data);
// $(container).html(html);
// setTimeout(function(){
// $('#player > li').each(function(){
// orderObj.players.push({
// id: $(this).data("id"),
// name: $(this).data("name"),
// status: $(this).find('.img span')[0].classList[1],
// download: $(this).find('ul.infoRow li:eq(0)').html(),
// description: $(this).find('ul.infoRow li:eq(1)').html()
// })
// });
// $('#spinner').css("display", "");
// },50);
// }
// });
// }
// });
}
//////////////////////////////////////////////* */
// Schedule
//////////////////////////////////////////////* */
function loadSchedule(parametersEvents, idsPlaylistSchedule) {
var whatDayDrag;
var daysCalendar = {};
$.each(idsPlaylistSchedule, function(i,idPlaylist){
daysCalendar[i] = { [idPlaylist]:{
deleted:[],
added:[],
modified:[]
}
};
});
eventsAfterRender = parametersEvents;
$('#spinner').css("display", "flex");
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
minTime: '00:00:00',
maxTime: '24:00:00', // 24h + 6 de minTime
slotLabelFormat: 'HH:mm',
timeFormat: 'HH:mm',
firstDay: 1, //Para que empiece en lunes
allDaySlot: false,
eventOverlap: false,
editable: true,
// eventStartEditable: true,
// eventDurationEditable: true,
droppable: true,
//navLinks: true,
slotDuration: "00:30:00",
snapDuration: '00:30:00',
defaultTimedEventDuration: '01:00:00',
forceEventDuration: true,
nowIndicator: true,
// customButtons: {
// CustomButton: {
// text: 'Upload Changes',
// click: function() {
// eventsAfterButton = $('#calendar').fullCalendar('clientEvents');
// $.each($('#calendar').fullCalendar('clientEvents'),function(index,event){
// console.log(moment(event.end).format());
// console.log(moment(event.end).format('dddd'));
// });
// }
// }
// },
header: {
left: '',
right: 'CustomButton'
},
columnFormat: 'dddd',
//==================Añadir pulsando un envent
// selectable: true,
// selectHelper: true,
// select: function(start, end, allDay) {
// var title = prompt('Event Title:');
// if (title) {
// $('#calendar').fullCalendar('renderEvent',
// {
// title: title,
// start: start,
// end: end,
// allDay: allDay
// },
// true);
// }
// $('#calendar').fullCalendar('unselect');
// },
// hiddenDays: [0],
// defaultDate: '2018-10-15',
// views: {
// month: {
// droppable: false,
// editable: false
// }
// },
// drop: function(date, jsEvent, ui, resourceId ) {
// var title = $(jsEvent.target).data('event').title;
// var idAD = $(jsEvent.target).data('event').idAD;
// alert('Added from source Area');
// // $('#calendar').fullCalendar('renderEvent', {
// // title: title,
// // idAD: idAD,
// // // start: jsEvent.target.dataset.start,
// // // end: jsEvent.target.dataset.end
// // });
// },
eventReceive: function(event){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added.push(
{
content_id: event.idBlock,
content_type: 1,
startHour: moment.duration(event.start.format('HH:mm:ss')).asMinutes(),
endHour: moment.duration(event.end.format('HH:mm:ss')).asMinutes(),
internalId: event._id
}
);
// console.log(window[ moment(event.end).format('dddd') ])
},
eventRender: function(event, element){
element.find(".fc-content").prepend("");
element.find(".closeon").on('click', function() {
if ( !event.dragged ){ //Si el bloque ya lo contenía el schedule de la carga de APIweb
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].deleted.push(
{
playlist_content_id: event.idContent,
}
);
} else { // Si es dragged true, es que lo hemos añadido desde source area
$.each(daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added, function(i, evt){
if(event.idBlock === evt.content_id && moment.duration(event.start.format('HH:mm:ss')).asMinutes() === evt.startHour && moment.duration(event.end.format('HH:mm:ss')).asMinutes() === evt.endHour){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added.splice(i,1);
console.log('Álbum eliminado que se había añadido anteriormente al array added, lo sacamos del array');
return false;
}
})
}
//elimanos el album del grid
$('#calendar').fullCalendar('removeEvents',event._id);
console.log(daysCalendar[ moment(event.start).format('dddd') ])
});
},
eventConstraint: {
start: '00:00:00',
end: '24:00:00'
},
events: parametersEvents,
eventDragStart: function(event){
whatDayDrag = moment(event.start).format('dddd');
},
eventDrop: function(event, delta, revertFunc) {
var coincidence = false;
if (whatDayDrag != moment(event.start).format('dddd')) {
revertFunc();
}else{
if ( !event.dragged ){//Si el bloque ya lo contenía el schedule de la carga de APIweb
$.each(daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified, function(i, evt){
if(event.idContent === evt.playlist_content_id){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified[i].startHour = moment.duration(event.start.format('HH:mm:ss')).asMinutes();
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified[i].endHour = moment.duration(event.end.format('HH:mm:ss')).asMinutes();
console.log('Álbum que viene de la carga del Schedule. Previamente se había modificado el horario y añadido a modified. Modificamos solamente el horario');
coincidence = true;
return false;
}
})
if (!coincidence){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified.push(
{
playlist_content_id: event.idContent,
startHour: moment.duration(event.start.format('HH:mm:ss')).asMinutes(),
endHour: moment.duration(event.end.format('HH:mm:ss')).asMinutes()
}
);
}
} else { // Si es dragged true, es que lo hemos añadido desde source area
$.each(daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added, function(i, evt){
if(event._id === evt.internalId){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added[i].startHour = moment.duration(event.start.format('HH:mm:ss')).asMinutes();
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added[i].endHour = moment.duration(event.end.format('HH:mm:ss')).asMinutes();
console.log('Álbum que previamente habíamos añadido desde source area y ahora hemos modificado el horario. Modificamos solamente el horario dentro de added');
coincidenceDrageed = true;
return false;
}
})
}
}
// console.log(daysCalendar[ moment(event.end).format('dddd') ]);
},
eventResize: function(event, delta, revertFunc) {
var coincidence = false;
if ( !event.dragged ){//Si el bloque ya lo contenía el schedule de la carga de APIweb
$.each(daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified, function(i, evt){
if(event.idContent === evt.playlist_content_id){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified[i].startHour = moment.duration(event.start.format('HH:mm:ss')).asMinutes();
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified[i].endHour = moment.duration(event.end.format('HH:mm:ss')).asMinutes();
console.log('Álbum que viene de la carga del Schedule. Previamente se había modificado el horario y añadido a modified. Modificamos solamente el horario');
coincidence = true;
return false;
}
})
if (!coincidence){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].modified.push(
{
playlist_content_id: event.idContent,
startHour: moment.duration(event.start.format('HH:mm:ss')).asMinutes(),
endHour: moment.duration(event.end.format('HH:mm:ss')).asMinutes()
}
);
}
} else { // Si es dragged true, es que lo hemos añadido desde source area
$.each(daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added, function(i, evt){
if(event._id === evt.internalId){
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added[i].startHour = moment.duration(event.start.format('HH:mm:ss')).asMinutes();
daysCalendar[moment(event.start).format('dddd')][idsPlaylistSchedule[moment(event.start).format('dddd')]].added[i].endHour = moment.duration(event.end.format('HH:mm:ss')).asMinutes();
console.log('Álbum que previamente habíamos añadido desde source area y ahora hemos modificado el horario. Modificamos solamente el horario dentro de added');
coincidenceDrageed = true;
return false;
}
})
}
// console.log(daysCalendar[ moment(event.end).format('dddd') ]);
},
eventClick: function(calEvent, jsEvent, view) {
// console.log(moment(calEvent.start).format('dddd'));
// console.log(calEvent)
// console.log('Album: ' + calEvent.title);
// console.log('Album idContent: ' + calEvent.idContent);
// console.log('Album idBlock: ' + calEvent.idBlock);
// console.log('Album internalId: ' + calEvent._id);
// console.log('Album start: ' + moment(calEvent.start).format());
// console.log('Album end: ' + moment(calEvent.end).format());
// console.log('Album dragged: ' + calEvent.dragged);
// console.log('Day of week: ' + moment(calEvent.end).format('dddd'));
},
eventAfterAllRender: function(){
//eventsAfterRender = $('#calendar').fullCalendar('clientEvents');
// console.log($('#calendar').fullCalendar('clientEvents'));
$('#spinner').css("display", "");
}
})
$('#schedule-page button.save').click(function(){
// console.log('pipas');
$(this).prop("disabled",true);
//Eliminamos de los objetos dentro del array added 'internalId. Valor que no necesita la APIweb.
$.each(idsPlaylistSchedule, function(i,idPlaylist){
$.each(daysCalendar[i][idPlaylist], function(arr,obj){
$.each(obj, function(l, objarr){
if(objarr.endHour === 0 && objarr.endHour < objarr.startHour ){
objarr.endHour=1440;
}
})
if(arr !== 'added'){
return;
}
$.each(obj, function(l, objAdded){
// console.log(objAdded);
delete objAdded['internalId'];
})
// console.log(daysCalendar[i][idPlaylist]);
})
});
//Envío ajax
var ajaxReqsPlayList = [];
$.each(idsPlaylistSchedule, function(i,idPlaylist){
// console.log(JSON.stringify(daysCalendar[i]));
ajaxReqsPlayList.push(
$.ajax({
type:'POST',
dataType: 'json',
crossDomain: true,
// contentType: 'application/json',
url: APIWEB_URL+"playlist/"+idPlaylist+"/contentMultiple?access_token="+localStorage.getItem('access_token')+"&project_id="+localStorage.getItem('project_id'),
data:'data=' +JSON.stringify(daysCalendar[i])
})
);
})
$.when.apply($, ajaxReqsPlayList).then(function() {
swal({
type: 'success',
position: 'top-end',
title: 'Saved!',
html: `The Schedule ${nameSchedule} has been saved`,
showConfirmButton: false,
customClass: 'notify',
timer: 3000,
toast: true
})
setTimeout(function(){
window.location.hash = '#schedule-list';
}, 2000);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log("Fail postSchedules: "+ jqXHR, textStatus, errorThrown);
});
});
}
//////////////////////////////////////////////////
$(function() {
// indexPage();
});
// function loadAlbumsSearch (){
// var arr = [];
// $.when( getAlbumsBlock() ).done(function(albums) {
// $.each(albums.data, function( index, album ) {
// arr.push({value: album.id, label:album.name})
// });
// });
// $("#autocomplete_album").autocomplete({
// //source: data
// position: {
// my : "left+0 top+15"
// },
// delay: 500,
// minLength: 0,
// source : arr,
// focus: function(event, ui) {
// // prevent autocomplete from updating the textbox
// event.preventDefault();
// $(this).val(ui.item.label);
// },
// select: function(event, ui) {
// // prevent autocomplete from updating the textbox
// event.preventDefault();
// idAlbum = ui.item.value;
// nameAlbum = ui.item.label;
// window.location.hash = "#album-page";
// }
// }).focus( function () {
// $(this).autocomplete("search", '');
// }).autocomplete("widget").attr('style', 'max-height: 400px; overflow-y: auto; overflow-x: hidden;');
// }
//////////////////////////////////////////////* */
// launcher //
//////////////////////////////////////////////* */
$( "#launcher" ).click(function() {
$trigger = $(this).attr('class');
$( "#app-selector" ).toggleClass( "visible" );
$( ".triangle" ).toggleClass( "visible" );
}
);
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
$svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
}
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
//////////////////////////////////////////////* */
// AudioPlayer
//////////////////////////////////////////////* */
var music = document.getElementById('music'),
onplayhead = false,
percent,
playBtn = document.getElementById('pButton'),
closeButton = document.getElementById('closeButton'),
progressbar = document.getElementById('seekObj');
music.addEventListener('timeupdate', timeUpdate, false);
playBtn.addEventListener('click', togglePlay, false);
closeButton.addEventListener("click", closeAudioPlayer, false);
music.addEventListener('ended', endSong, false);
progressbar.addEventListener('click', seekclick, false);
// progressbar.addEventListener('mousedown', function(){
// onplayhead = true;
// this.addEventListener('mousemove', seek, false);
// }, false);
// window.addEventListener("mouseup", function() {
// if (onplayhead) {
// this.removeEventListener('mousemove', seek, true);
// progressbar.value = percent / 100;
// }
// onplayhead = false;
// }, false);
function timeUpdate() {
var value = (music.currentTime / music.duration);
if (value >= 0 || value <= 1) {
progressbar.value = (music.currentTime / music.duration);
}
if (music.currentTime === music.duration) {
closeAudioPlayer();
}
};
function seekclick(evt) {
percent = evt.offsetX / this.offsetWidth;
progressbar.value = percent / 100;
music.currentTime = percent * music.duration;
}
function seek(evt) {
if (onplayhead) {
percent = evt.offsetX / this.offsetWidth;
music.currentTime = percent * music.duration;
}
}
function togglePlay() {
if (music.paused === false) {
music.pause();
$('#pButton').removeClass('pause');
$('#pButton').addClass('play');
} else {
music.play();
$('#pButton').removeClass('play');
$('#pButton').addClass('pause');
}
}
function endSong() {
$('#pButton').removeClass('pause');
$('#pButton').addClass('play');
music.currentTime = 0;
progressbar.value = 0;
music.pause();
}
function closeAudioPlayer() {
var audioArea = document.getElementById('audio');
audioArea.classList.remove('visible');
endSong();
setTimeout(function(){
music.src = "";
}, 3000);
//music.src = "";
}
var wViewport = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var hViewport = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);