// FIXME: move to utils
// From: https://stackoverflow.com/a/175787
function isNumeric (str) {  
    return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
           !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

function selectChanged() {
    const sortValue = document.getElementById('sort-select').value
    const $films = [...document.querySelectorAll('.film')]
    location.hash = sortValue
    $films.sort((a, b) => {
        let aVal = a.dataset[sortValue]
        let bVal = b.dataset[sortValue]
        if (isNumeric(aVal) && isNumeric(bVal)) {
            aVal = parseFloat(aVal)
            bVal = parseFloat(bVal)
        }
        return aVal < bVal ? -1 : 1
    })
    document.getElementById('films-list').innerHTML = ''
    $films.forEach($film => {
        document.getElementById('films-list').appendChild($film)
    })
}

//document.getElementById('sort-select').addEventListener('change', selectChanged)

const locationHash = location.hash.replace('#', '')
if (locationHash !== '') {
    document.getElementById('sort-select').value = locationHash
    selectChanged()
}

document.querySelectorAll('.films .film figure').forEach(figure => {
    var imgs = figure.querySelectorAll('img')
    if (imgs.length > 1) {
        setInterval(() => {
            var img = figure.querySelector('img')
            img.parentElement.appendChild(img)
        }, 5000 + Math.random() * 1000)
    }
})