var video = document.getElementById('video');
var isMuted = false;
var btnInterval;
var currentVerse = -1;

var trackListID = 0;
var trackID = 0;
var langID = 0;
var speed = data[langID].speeds[0].speed;

$(function() {
    if(isNumeric(qs("l"))) { langID = qs("l"); }
    if(isNumeric(qs("tl"))) { trackListID = qs("tl");}
    if(isNumeric(qs("s"))) { trackID = qs("s"); }
    if(isNumeric(qs("v"))) { moveVidTo(data[langID].trackLists[trackList].btns[qs("v")].time,true); }
    if(isNumeric(qs("t"))) { moveVidTo(qs("t"),true); }
    if(isNumeric(qs("sp"))) { setSpeed(qs("sp")); }

    initVid();

    $('body').on('click','#verses a', function(e) {
        e.preventDefault();
        moveVidTo($(this).data('time'));
    })
    .on('click','#tracklists a', function(e) {
        e.preventDefault();
        trackListID = $(this).data('tracklist');
        trackID = 0;
        initVid();
    })
    .on('click','#langs a', function(e) {
        e.preventDefault();
        langID = $(this).data('lang');
        trackListID = 0;
        trackID = 0;
        initVid();
        $('#langs li').removeClass();
        $('[data-lang="'+langID+'"]').addClass('current');
    })
    .on('change','#tracks', function(e) {
        time = video.currentTime;
        setTrack(this.value);
        video.currentTime = time;
    })
    .on('change','#speeds', function(e) {
        setSpeed(this.value);
    })

    $(window).keypress(function(e) {
        if (e.keyCode === 0 || e.keyCode === 32) { // spacebar = play / pause
            e.preventDefault();
            if (video.paused) {
                video.play();
            } else {
                video.pause();
            }
        } else if (e.keyCpde === 77 || e.keyCode === 109) { // m = mute / unmute
            isMuted = !isMuted;
            $('video').prop("muted", isMuted);
        }
    })
    .resize(function() {
      resizeVid();
    });

    $('video').on('play', function (e) {
        btnInterval = setInterval(function() {checkCurrentVerse()}, 100);
    })
    .on('pause', function (e) {
        clearInterval(btnInterval);
    })
    .on("loadeddata", function() {
        resizeVid();
    });
})

function checkCurrentVerse() {
    for(i=0; i<data[langID].trackLists[trackListID].btns.length; i++) {
        if ((video.currentTime>data[langID].trackLists[trackListID].btns[i].time) && (i==data[langID].trackLists[trackListID].btns.length-1 || video.currentTime<data[langID].trackLists[trackListID].btns[i+1].time)) {
            if(i!=currentVerse) {
                setVerse(i);
            }
            break;
        }
    }
}

function initVid() {
    resizeVid();
    popBtns();
    popTracks();
    popSpeeds();
}

function resizeVid() {
    $('#video').css('height', '');
    var o = $('#controls').first().offset();
    if (o.top + $('#controls').height() > window.innerHeight) {
        $('#video').height(window.innerHeight - $('#controls').height() - 15);
    }
}

function setSpeed(s) {
    speed = parseFloat(s);
    popTracks();
    video.playbackRate = speed;
}

function setTrack(trackFile) {
    $('#video source').attr('src', 'videos/'+trackFile);
    $("#video")[0].load();
}

function setVerse(btnNumber) {
    currentVerse = btnNumber;
    $('#verses li').removeClass();
    $('[data-verse="'+btnNumber+'"]').addClass('current');
}

function popSpeeds() {
    if(data[langID].speeds.length>1) {
        $('#speeds').html('');
        for(i=0; i<data[langID].speeds.length; i++) {
            defaultStr = (data[langID].speeds[i].default==true) ? 'selected="selected"' : '';
            $('#speeds').append('<option value="'+data[langID].speeds[i].speed+'" ' + defaultStr + '>'+data[langID].speeds[i].text+'</option>')
        }
    } else {
        $('#speeds').remove();
    }
}

function popTracks() {
    // hide dropdown if only one option
    $('#tracks').toggle(!data[langID].trackLists[trackListID].tracks.length<2);
    if(data[langID].trackLists[trackListID].tracks.length<2) {
        $('#tracks').hide();
    }
    // populate the dropdown
    $('#tracks').html('');
    for(i=0; i<data[langID].trackLists[trackListID].tracks.length; i++) {
        var t = data[langID].trackLists[trackListID].tracks[i];
        if($.inArray(parseFloat(speed), t.excSpeeds)) {
            if($('#tracks').html() == '') {
                setTrack(t.track);
            }
            $('#tracks').append('<option value='+t.track+'>'+t.text+'</option>')
        }
    }
}

function popBtns() {
    $('#verses').html('');
    $('#tracklists').html('');
    $('#langs').html('');
    for(i=0; i<=data[langID].trackLists[trackListID].btns.length-1; i++) {
        $('#verses').append('<li data-verse="'+i+'"><a href="?t='+data[langID].trackLists[trackListID].btns[i].time+'" data-time="'+data[langID].trackLists[trackListID].btns[i].time+'">'+data[langID].trackLists[trackListID].btns[i].text+'</a></li>')
    }
    if(data[langID].trackLists.length>1) {
        for(i=0; i<=data[langID].trackLists.length-1; i++) {
            $('#tracklists').append('<li data-tracklist="'+i+'"><a href="?tl='+i+'" data-trackList="'+i+'">'+data[langID].trackLists[i].icon+'</a></li>')
        }
    } else {
        $('#tracklists').remove();
    }
    if (data.length>1) {
        for(i=data.length-1; i>=0; i--) {
            $('#langs').append('<li data-lang="'+i+'" '+(langID==i ? ' class="current"' : '')+'><a href="?l='+i+'" data-lang="'+i+'">'+data[i].lang+'</a></li>')
        }
    }
}

function moveVidTo(time,addPause) {
    video.currentTime = time;
    if(!addPause) {video.play()};
}

function qs(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
