Subversion Repositories cheapmusic

Rev

Rev 84 | Rev 110 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(document).ready(function() {
    var x;

    $('[data-toggle="tooltip"]').tooltip({
        trigger: 'hover'
    });

    $('[data-toggle2="tooltip"]').tooltip({
        trigger: 'hover'
    });

    $('[rel="tooltip"]').on('click', function() {
        $(this).tooltip('hide');
    });

    $('.flexdatalist').flexdatalist();
    $(function() {
        $("input[id='searchTerm-flexdatalist']").clearer();
    });
    $('.flexdatalist').flexdatalist({
        minLength: 0,
        searchContain: true,
        noResultsText: ""
    }); /* reset after running clearer */

    $(window).on('beforeunload', function() {
        $(":submit").attr('disabled', 'disabled');
        document.body.style.cursor = "progress";
    });

    $(window).bind('resize orientationchange', paginationSetup);

    tableFilterButtons();
    detailTableFilterButtons();
    paginationSetup();
    navTabs();

    x = document.getElementById("tableFilterButton")
    if (x) {
        x.style.display = "none";
    }

    // Floating Top Navigation Button:
    window.onscroll = function() {scrollFunction()};
});

function tableFilterButtons() {
    $(".filterButton,.filterButtonSmall").click(function() {
        $.post("filterTable.php",
            {
                submit: $(this).attr("value"),
                sessionTab: document.getElementById("sessionTab").value
            },
            function(data, status) {
                if (status == "success") {
                    document.getElementById("productTable").innerHTML = data;
                    tableFilterButtons();
                    detailTableFilterButtons();
                    navTabs();
                }
            }
        );
    });
}

function detailTableFilterButtons() {
    $("#detailFilterForm").on('submit',function(e){e.preventDefault();return false;});
    $(".detailFilterButton").click(function() {
        var formData = $("#detailFilterForm").serializeArray();
        formData.push({ name: this.name, value: this.value });
        $.post("filterTable.php",
            formData,
            function(data, status) {
                if (status == "success") {
                    document.getElementById("productTable").innerHTML = data;
                    detailTableFilterButtons();
                    tableFilterButtons();
                    navTabs();
                }
            }
        );
    });
}

function navTabs() {
    $('.nav-tabs a').click(function(e){
        e.preventDefault();
        $(this).tab('show');
        if ($(this).attr('id') == "quickTab") {
            $(this).attr('class', 'nav-link active bg-white');
            $('#detailTab').attr('class', 'nav-link bg-white invert');
        } else /* detailTab */ {
            $(this).attr('class', 'nav-link active bg-white');
            $('#quickTab').attr('class', 'nav-link bg-white invert');
        }
        navTabs();
    });
    
}

function alertAutoClose() {
    window.setTimeout(function() {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function() {
            $(this).remove();
        });
    }, 3000);
}

function initProgressBarModal(title) {
    var elem = document.getElementById("progressBar");
    elem.style.width = '0%';
    elem.innerHTML = '0%';

    elem = document.getElementById("progressBarHeader");
    elem.innerHTML = title;

    elem = document.getElementById("progressBarMessage");
    elem.innerHTML = "";

    $("#progressBarDiv").modal({
        backdrop: "static"
    });
}

function updateProgressBar(width, message) {
    var elem = document.getElementById("progressBar");
    if (elem && width) {
        elem.style.width = width + '%';
        elem.innerHTML = width.toFixed(0) + '%';
        // bugbug document.getElementById("progressBarMessage").innerHTML = message;
    }
}

function endProgressBarModal() {
    $("#progressBarDiv").modal("hide");
}

// Refresh the progress bar.
function refreshProgress() {
    $.ajax({
        url: "pbChecker.php?file=" + document.getElementById("sessionId").value + "_" + document.getElementById("sessionTab").value,
        success: function(data) {
            updateProgressBar(data.percent, data.message);
            if (data.percent >= 100) {
                window.clearInterval(timer);
                timer = window.setInterval(completeProgress, 1000);
            }
        }
    });
}

// End the progress bar.
function completeProgress() {
    updateProgressBar(100, "Completed");
    window.clearInterval(timer);
    endProgressBarModal();
}

// Start the progress bar.
function progressBar(title) {
    initProgressBarModal(title);
    timer = window.setInterval(refreshProgress, 1000);
}

function saveTransfer(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "savetransfer.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("target=" + btoa(url) + "&sessionTab=" + document.getElementById("sessionTab").value);
}

function addWishlist(id, field, cnt, wl) {
    $(field).tooltip('hide');
    $(field).remove();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
            json = JSON.parse(this.responseText);
            switch (json.retval) {
                case 0:
                    msg = "Added to wishlist.";
                    alert = "alert-success";
                    break;
                case 1:
                    msg = "Already on the wishlist.";
                    alert = "alert-warning";
                    break;
                default:
                    msg = "ERROR! Could not add to the wishlist.";
                    alert = "alert-dangere";
                    break;
            }
            document.getElementById("wishlistAdd" + cnt).innerHTML = "<div class=\"alert " + alert + " alert-dismissible mt-2 mb-0\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" + msg + "</div>";;
            alertAutoClose();
        }
    };
    xhttp.open("POST", "wishlistDB.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("id=" + id + "&function=add&wl=" + wl + "&sessionTab=" + document.getElementById("sessionTab").value);
}

function deleteWishlist(id, field, title, artist) {
    $(field).tooltip('hide');
    if (confirm('Remove ' + title + ' by ' + artist + ' from wishlist?')) {
        var parent = field.parentNode.parentNode.parentNode;
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "wishlistDB.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("function=delete&id=" + id + "&sessionTab=" + document.getElementById("sessionTab").value);
        parent.parentNode.removeChild(parent);
    }
}

function editWishlist(id, field) {
    if (field !== null) {
        $(field).tooltip('hide');
        var parent = field.parentNode.parentNode.parentNode;

        var artist = mysqliHtmlDecode(parent.getElementsByTagName("td")[1].innerHTML);
        var title = mysqliHtmlDecode(parent.getElementsByTagName("td")[2].innerHTML);
        var barcode = parent.getElementsByTagName("td")[3].innerHTML.replace(/-/g, '');
        var cond = parent.getElementsByTagName("td")[5].innerHTML;
        var format = parent.getElementsByTagName("td")[6].innerHTML;
        var price = parent.getElementsByTagName("td")[7].innerHTML;

        document.getElementById("wlMsg").innerHTML = "";
        document.getElementById("wlId").value = id;
        document.getElementById("wlArtist").value = artist;
        document.getElementById("wlTitle").value = title;
        document.getElementById("wlBarcode").value = barcode;
        document.getElementById("wlCond").value = cond;
        document.getElementById("wlFormat").value = format;
        document.getElementById("wlPrice").value = price;
    }

    $("#editWishlistModal").modal();
}

function saveEditedWishlist() {
    var id = document.getElementById("wlId").value;
    var field = document.getElementById("wlIdRow" + id);
    var parent = field.parentNode;
    var artist = document.getElementById("wlArtist").value;
    var title = document.getElementById("wlTitle").value;
    var barcode = document.getElementById("wlBarcode").value;
    var cond = document.getElementById("wlCond").value;
    var format = document.getElementById("wlFormat").value;
    var price = document.getElementById("wlPrice").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
            json = JSON.parse(this.responseText);
            switch (json.retval) {
                case 0:
                    parent.getElementsByTagName("td")[1].innerHTML = artist;
                    parent.getElementsByTagName("td")[2].innerHTML = title;
                    parent.getElementsByTagName("td")[3].innerHTML = barcode;
                    parent.getElementsByTagName("td")[4].innerHTML = barcode; // bugbug Format
                    parent.getElementsByTagName("td")[5].innerHTML = cond;
                    parent.getElementsByTagName("td")[6].innerHTML = format;
                    parent.getElementsByTagName("td")[7].innerHTML = price;
                    parent.getElementsByTagName("td")[8].innerHTML = '$' + Number(price).toFixed(2); // bugbug Format
                    $("#editWishlistModal").modal('hide');
                    break;
                case 1:
                    document.getElementById("wlMsg").innerHTML = "<div class=\"alert alert-danger alert-dismissible mt-0 mb-0\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" + json.msg + "</div>";
                    editWishlist(id, null)
                    break;
                default:
                    document.getElementById("wlMsg").innerHTML = "<div class=\"alert alert-danger alert-dismissible mt-0 mb-0\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>Unknown Error. Please reload page.</div>";
                    break;
            }
        }
    };
    xhttp.open("POST", "wishlistDB.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("function=update&id=" + id + "&artist=" + encodeURIComponent(artist) + "&title=" + encodeURIComponent(title) + "&barcode=" + encodeURIComponent(barcode) + "&cond=" + encodeURIComponent(cond) + "&format=" + encodeURIComponent(format) + "&price=" + encodeURIComponent(price) + "&sessionTab=" + document.getElementById("sessionTab").value);
}

// Pagination
function paginationSetup() {
    $("[id^=masterModal]").modal("hide");
    $('#discogsDeck').paginate({
        paginateElement: '.card',
        elementsPerPage: paginationPerPage(),
        effect: 'default',
        firstButtonText: '<i class="fas fa-angle-double-left"></i>',
        lastButtonText: '<i class="fas fa-angle-double-right"></i>',
        prevButtonText: '<i class="fas fa-angle-left"></i>',
        nextButtonText: '<i class="fas fa-angle-right"></i>',
        extraButtonClasses: 'btn bg-primary px-2 shadow-sm'
    });
    $('[data-toggle="tooltip"]').tooltip({
        trigger: 'hover'
    });
    $('[data-toggle2="tooltip"]').tooltip({
        trigger: 'hover'
    });
}

function filterWishlist() {
    var input, filter, table, tr, td, i, j, txtValue, flag;
    input = document.getElementById("tableFilter");
    filter = input.value.toUpperCase();
    table = document.getElementById("wishlistTable");
    tr = table.getElementsByTagName("tr");
    document.getElementById("tableFilterButton").style.display = (filter.length > 0 ? "" : "none");

    // Loop through all table rows, excluding the header, and hide those who don't match the search query
    for (i = 1; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        flag = "none";

        for (j = 0; j < td.length; j++) {
            if (td[j]) {
                txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    flag = "";
                    break;
                }
            }
        }

        tr[i].style.display = flag;
    }
}

function mysqliHtmlDecode(str) {
    str = str.replace(/&amp;/g, '&');
    str = str.replace(/&lt;/g, '<');
    str = str.replace(/&gt;/g, '>');
    return str;
}

// number of discogs entries per page according to screen size
function paginationPerPage() {
    var width = $(window).width();
    var num = Math.floor(width / 210);
    if (num > 9) {
        num = 9;
    } else if (width < 576) {
        num = 1;
    }
    return num;
}

// sort table by column
function sortTable(table, col, colType) {
    var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById(table);
    switching = true;
    // Set the sorting direction to ascending:
    dir = "asc";
    /* Make a loop that will continue until no switching has been done: */
    while (switching) {
        // Start by saying: no switching is done:
        switching = false;
        rows = table.rows;
        /* Loop through all table rows (except the first, which contains table headers): */
        for (i = 1; i < (rows.length - 1); i++) {
            // Start by saying there should be no switching:
            shouldSwitch = false;
            /* Get the two elements you want to compare, one from current row and one from the next: */
            x = rows[i].getElementsByTagName("TD")[col];
            y = rows[i + 1].getElementsByTagName("TD")[col];
            /* Check if the two rows should switch place, based on the direction, asc or desc: */
            if (dir == "asc") {
                if (colType == 'numeric') {
                    if (Number(x.innerHTML) > Number(y.innerHTML.toLowerCase)) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                } else /* if (colType == 'text') */ {
                    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                }
            } else if (dir == "desc") {
                if (colType == 'numeric') {
                    if (Number(x.innerHTML) < Number(y.innerHTML)) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                } else /* if (colType == 'text') */ {
                    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                        // If so, mark as a switch and break the loop:
                        shouldSwitch = true;
                        break;
                    }
                }
            }
        }
        if (shouldSwitch) {
            /* If a switch has been marked, make the switch and mark that a switch has been done: */
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            // Each time a switch is done, increase this count by 1:
            switchcount++;
        } else {
            /* If no switching has been done AND the direction is "asc", set the direction to "desc" and run the while loop again. */
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}

function scrollFunction() {
    var topButton = document.getElementById("topBtn");

    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        topButton.style.display = "block";
    } else {
        topButton.style.display = "none";
    }
}

function topFunction() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}