/* soundcite - v0.4.1 - 2015-05-11
 * Copyright (c) 2015 Tyler J. Fisher and Northwestern University Knight Lab 
 */
/*
Modified by D. Denocq / Cite de la musique, Philharmonie de Paris October 2015
*/
$(document).ready(function(event) {
    if (document.getElementsByClassName('soundcite') != null) {
        var elements = document.getElementsByClassName('soundcite');
        // console.log(elements.length);

        // setup audio container
        audio_container = document.createElement('div');
        addClass(audio_container, 'soundcite-audio');
        document.getElementsByTagName('body')[0].appendChild(audio_container);

        for (var i = 0; i < elements.length; i++) {

            if (elements[i].getAttribute('data-url')) {
                new Clip(elements[i]);
            }

            // 11/07/2022 Christophe Leonardi Migration SYRACUSE : fix keyboards navigation focus on span

            elements[i].setAttribute("tabindex", "0")

            // END 11/07/2022 Christophe Leonardi Migration SYRACUSE : fix keyboards navigation focus on span
        }

    }


});

// Christophe Leonardi 11/07/2022 Migration SYRACUSE : Launch clip on enter key

$(document).keydown(function(touche) {
    var k = touche.which || touche.keyCode;
    if (k == 13) {
        if ($(document.activeElement).hasClass("soundcite")) {
            $(document.activeElement).click()
        }

    }
})

// END Christophe Leonardi 11/07/2022 Migration SYRACUSE : Launch clip on enter key


var bind = function(func, context) {
    var slice = Array.prototype.slice;
    var args = slice.call(arguments, 2);
    return function() {
        return func.apply(context, args.concat(slice.call(arguments)));
    };
};

function removeClass(el, name) {
    var cn = el.className;
    for (var i = 0, arr = name.match(/\S+/g); i < arr.length; i++) {
        cn = cn.replace(new RegExp('(?:^|\\s)' + arr[i] + '(?!\\S)'), '');
    }
    el.className = cn;
}

function addClass(el, name) {
    var cn = el.className;
    for (var i = 0, arr = name.match(/\S+/g); i < arr.length; i++) {
        if (!cn.match(new RegExp('(?:^|\\s)' + arr[i] + '(?!\\S)'))) {
            cn += " " + arr[i];
        }
    }
    el.className = cn;
}

function getClip(audio) {
    return $('span[data-url="' + audio.src + '"]');
}
var clips = [];

// setup audio container
var audio_container = document.createElement('div');
addClass(audio_container, 'soundcite-audio');
document.getElementsByTagName('body')[0].appendChild(audio_container);


// pause all playing clips. Optionally pass a clip as an argument which
// should not be paused, for the case that this is triggered from a 
// click handler.
function pause_all_clips(except_clip) {
    for (var i = 0; i < clips.length; i++) {
        if (clips[i].playing) {
            if (!except_clip || except_clip.el !== clips[i].el) {
                clips[i].pause();
            }
        }
    }
}

// Clip
function Clip(el) {
    this.el = el;
    //console.log(el);
    this.id = "clip" + clips.length;
    this.start = el.hasAttribute('data-start') ? el.getAttribute('data-start') : 0; // ms          
    this.end = el.hasAttribute('data-end') ? el.getAttribute('data-end') : null; // ms

    this.plays = el.hasAttribute('data-plays') ? parseInt(el.getAttribute('data-plays')) : 1;
    this.plays_left = this.plays;

    this.url = el.getAttribute('data-url');
    this.ct = 0;
    this.playing = false;
    this.sound = null;

    var audio = document.createElement("audio");
    audio.id = "audio" + this.id;
    audio.setAttribute("src", this.url);
    audio.setAttribute("preload", "none");

    audio_container.appendChild(audio);


    /*ajout du style "player"*/
    addClass(this.el, 'soundcite-loaded soundcite-play');
    /*ajout du click*/
    this.el.addEventListener('click', bind(this.click_handler, this));

    /*gestion des �v�nements */
    audio.addEventListener('ended', bind(this.ending, this));
    audio.addEventListener('timeupdate', bind(this.track_progress, this));

    clips[clips.length] = this;
}

Clip.prototype.ending = function() {
    console.log(this.el.id + ":end");
    removeClass(this.el, 'soundcite-pause');
    addClass(this.el, 'soundcite-play');
    this.playing = false;
}

Clip.prototype.canplay = function() {
    a = document.getElementById("audio" + this.id);
    this.duration = a.duration;

}

Clip.prototype.sound_loaded = function() {
    this.el.addEventListener('click', bind(this.click_handler, this));
    addClass(this.el, 'soundcite-loaded soundcite-play');
}

Clip.prototype.play = function() {
    removeClass(this.el, 'soundcite-play');
    addClass(this.el, 'soundcite-pause');

    a = document.getElementById("audio" + this.id);
    a.load();
    this.playing = true;

    /*Si l'extrait est en pause (lecture commenc�e)*/
    if (this.ct > 0) {
        a.currentTime = this.ct;
    }

    a.play();
}

Clip.prototype.pause = function() {
    removeClass(this.el, 'soundcite-pause');
    addClass(this.el, 'soundcite-play');

    a = document.getElementById("audio" + this.id);
    a.pause();

    console.log(a.currentTime);
    this.ct = a.currentTime;

    this.playing = false;
}

Clip.prototype.stop = function() {
    removeClass(this.el, 'soundcite-pause');
    addClass(this.el, 'soundcite-play');
    this.stop_sound(); // implement in subclass
    this.playing = false;
    this.plays_left = this.plays; // reset plays_left!
}

Clip.prototype.track_progress = function() {
    a = document.getElementById("audio" + this.id);
    var totalTime = a.duration;
    var position = a.currentTime; // implement in subclass
    var percentage = (position * 100) / totalTime;
    this.el.style.cssText = 'background: -webkit-linear-gradient(left, rgba(0,0,0,.15)' + percentage + '%, rgba(0,0,0,.05)' + (percentage + 1) + '%);' + 'background: linear-gradient(to right, rgba(0,0,0,.15)' + percentage + '%, rgba(0,0,0,.05)' + (percentage + 1) + '%);';
    //console.log(percentage);
}

Clip.prototype.click_handler = function(event) {
    event.preventDefault(); // if used on a tag, don't follow href
    pause_all_clips(this);
    console.log("playing:" + this.playing);
    if (this.playing) {
        this.pause();
    } else {
        this.play(); // implement in subclass
    }
}