Subversion Repositories cheapmusic

Rev

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

var myTimer;

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

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

        if (document.getElementById("detailFilterForm")) {
                tableFilterButtons();
                detailTableFilterButtons();
        }

        if (document.getElementById("barcodeForm")) {
                barcodeFormButtons();
        }

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

        flexdatalistSetup();

        tooltipSetup();
        
        if (typeof addDiscogsEvents === "function") {
            addDiscogsEvents();
        }
});


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

function detailTableFilterButtons() {
        $("#detailFilterForm").on('submit', function(e) {
                e.preventDefault();
                return false;
        });

        $("#detailTab").click(function() {
                x = document.getElementById("detailFilter");
                if (x.style.display == "block") {
                        document.getElementById("detailTabArrow").innerHTML = '<i class="material-icons material-text">expand_more</i>';
                        x.style.display = "none";
                } else {
                        document.getElementById("detailTabArrow").innerHTML = '<i class="material-icons material-text">expand_less</i>';
                        x.style.display = "block";
                }
                return false;
        });

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

function barcodeFormButtons() {
        $("#barcodeForm").on('submit', function(e) {
                e.preventDefault();
                return false;
        });

        $(".barcodeButton").click(function() {
                var formData = $("#barcodeForm").serializeArray();
                formData.push({
                        name: this.name,
                        value: this.value
                });
                formData.push({
                name: "nonce",
                        value: document.getElementById("nonce").value
                });
                $.post("barcode.php",
                        formData,
                        function(data, status) {
                                if (status == "success") {
                                        document.getElementById("barcodeResult").innerHTML = data;
                                }
                        }
                );

        new MutationObserver(function() {
                $("#barcodeSearchForm").off("submit");
            if (document.getElementById("barcodeSearchTerm") && document.getElementById("barcodeSearchTerm").value !== "") {
                $("#barcodeSearchForm").submit(function() {
                    progressBar("Searching for:<br><br><strong>" + document.getElementById("barcodeSearchTerm").value + "</strong>");
                });
            }
        }).observe(document.getElementById("barcodeResult"), { childList: true, subtree: true });

                return false;
        });
}

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(myTimer);
                                myTimer = window.setInterval(function() { completeProgress(); }, 1000);
                        }
                }
        });
}

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

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

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.";
                                        alertTxt = "alert-success";
                                        break;
                                case 1:
                                        msg = "Already on the wishlist.";
                                        alertTxt = "alert-warning";
                                        break;
                                default:
                                        msg = "ERROR! Could not add to the wishlist.";
                                        alertTxt = "alert-danger";
                                        break;
                        }
                        document.getElementById("wishlistAdd" + cnt).innerHTML = "<div class=\"alert " + alertTxt + " 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({
                backdrop: 'static',
                keyboard: false
        });
}

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);
}

// Flex Data List
function flexdatalistSetup() {
        if ($.fn.flexdatalist && $.fn.clearer) {
                $('.flexdatalist').flexdatalist();
                $(function() {
                        $("input[id='searchTerm-flexdatalist']").clearer();
                });
                $('.flexdatalist').flexdatalist({
                        minLength: 0,
                        searchContain: true,
                        noResultsText: ""
                }); /* reset after running clearer */
        } else {
                setTimeout(function () { flexdatalistSetup(); }, 100);
        }
}

// Pagination
function paginationSetup() {
        if ($.fn.paginate && $.fn.modal && $.fn.tooltip && typeof Popper !== "undefined") {
                if (document.getElementById("discogsDeck") !== null) {
                        $("[id^=masterModal]").modal("hide");
                        $('#discogsDeck').paginate({
                                paginateElement: '.card',
                                elementsPerPage: paginationPerPage(),
                                effect: 'default',
                                firstButtonText: '<i class="material-icons material-text">first_page</i>',
                                lastButtonText: '<i class="material-icons material-text">last_page</i>',
                                prevButtonText: '<i class="material-icons material-text">navigate_before</i>',
                                nextButtonText: '<i class="material-icons material-text">navigate_next</i>',
                                extraButtonClasses: 'btn bg-primary px-2 shadow-sm',
                                functionOnNav: function () { tooltipSetup(); if (typeof addDiscogsEvents === "function") { addDiscogsEvents();}  }
                        });
            tooltipSetup();
            if (typeof addDiscogsEvents === "function") {
                addDiscogsEvents();
            }
                }
        } else {
        setTimeout(function () { paginationSetup(); }, 100);
        }
}

// Tooltip Setup
function tooltipSetup() {
        if ($.fn.tooltip && typeof Popper != 'undefined') {
                $('[data-toggle="tooltip"]').tooltip({
                        trigger: 'hover'
                });

                $('[data-toggle2="tooltip"]').tooltip({
                        trigger: 'hover'
                });
        } else {
        setTimeout(function () { tooltipSetup(); }, 100);
        }
}

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 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)) {
                                                // 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 whole 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;
}