Subversion Repositories cheapmusic

Rev

Rev 149 | 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();
        }

        flexdatalistSetup();

        dataTableSetup();

        tooltipSetup();

        inputClearerSetup();
        
    discogsSwipeSetup();
});


function tableFilterButtons() {
        $(".filterButton").click(function() {
                $.post("filterTable.php", {
                                submitBtn: $(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();
                                        dataTableSetup();
                                        discogsSwipeSetup();
                                }
                        }
                );
        });
}

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

        $("#detailTab").click(function(e) {
                e.preventDefault();
                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";
                }
        });

        $(".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") {
                                        x = document.getElementById("productTable");
                                        x.innerHTML = data;
                                        detailTableFilterButtons();
                                        tableFilterButtons();
                        dataTableSetup();
                                        x.scrollIntoView();
                                }
                        }
                );
        });
}

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() {
                    searchTitle = "Searching for:<br><br><strong>" + document.getElementById("barcodeSearchTerm").value + "</strong>";
                    if (window.google_tag_manager && window.ga && ga.create) {
                        window.dataLayer.push({ "event" : "search", "search_term" : document.getElementById("barcodeSearchTerm").value, "eventCallback": function () {progressBar(searchTitle);}});
                    } else {
                        progressBar(searchTitle);
                    }
                });
            }
        }).observe(document.getElementById("barcodeResult"), { childList: true, subtree: true });
        });
}

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 + "&nonce=" + document.getElementById("nonce").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 + "&nonce=" + document.getElementById("nonce").value);
}

function addWishlist(id, field, cnt, wl) {
        $(field).tooltip('hide');
        $(field).children('i').first().html('library_add_check');
        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 + "&nonce=" + document.getElementById("nonce").value);
}

function deleteWishlist(id, field, title, artist) {
        $(field).tooltip('hide');
        if (confirm('Remove ' + title + ' by ' + artist + ' from wishlist?')) {
                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 + "&nonce=" + document.getElementById("nonce").value);
                row = field.closest("tr");
                if ($(row).hasClass("child")) {
                    row.previousElementSibling.remove();
                }
                row.remove();
        }
}

function editWishlist(id, field) {
        if (field !== null) {
                $(field).tooltip('hide');
                var row = field.closest("tr");
                if ($(row).hasClass("child")) {
                    row = row.previousElementSibling;
                }

                var artist = mysqliHtmlDecode(row.getElementsByTagName("td")[1].innerHTML);
                var title = mysqliHtmlDecode(row.getElementsByTagName("td")[2].innerHTML);
                var barcode = row.getElementsByTagName("td")[3].getAttribute("data-order");
                var cond = row.getElementsByTagName("td")[4].innerHTML;
                var format = row.getElementsByTagName("td")[5].innerHTML;
                var price = row.getElementsByTagName("td")[6].getAttribute("data-order");

                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 row = document.getElementById("wlIdRow" + id);
        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 table = row.closest("table");

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
                if (this.readyState == 4) {
                        json = JSON.parse(this.responseText);
                        switch (json.retval) {
                                case 0:
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[1]).data(artist);
                                        row.setAttribute("data-artist", artist);
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[2]).data(title);
                                        row.setAttribute("data-title", title);
                                        row.getElementsByTagName("td")[3].setAttribute("data-order", barcode);
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[3]).data(barcode); // bugbug Format
                                        row.setAttribute("data-barcode", barcode);
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[4]).data(cond);
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[5]).data(format);
                                        row.getElementsByTagName("td")[6].setAttribute("data-order", price);
                                        $(table).DataTable().cell(row.getElementsByTagName("td")[6]).data('$' + Number(price).toFixed(2));
                    $(table).DataTable().draw();
                                        $("#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 + "&nonce=" + document.getElementById("nonce").value);
}

// Flex Data List
function flexdatalistSetup() {
        if ($.fn.flexdatalist) {
                $('.flexdatalist').flexdatalist({
            valueProperty: "value",
                        minLength: 0,
                        searchContain: true,
            searchByWord: true,
                        noResultsText: ""
                });
                $("input[id='searchTerm-flexdatalist']").val($("input[id='searchTerm']").val());
        $("input.flexdatalist").on("select:flexdatalist", function (event) { handleFlexdataSelect(); });
        } else {
                setTimeout(function () { flexdatalistSetup(); }, 100);
        }
}

function handleFlexdataSelect() {
    var i, v, t, f;

    v = $("input.flexdatalist").val();
    if (v.substr(0, 5) != "*ADV*") {
        $('input.clearable').trigger("change");
        return;
    }

    t = v.substr(5).split("*|*");
    for (i = 0; i < t.length; i++) {
        f = t[i].split("*:*");
        if (f[0] == "a") {
            $("#advArtist").val(f[1]);
        } else if (f[0] == "t") {
            $("#advTitle").val(f[1]);
        } else if (f[0] == "tr") {
            $("#advTrack").val(f[1]);
        } else if (f[0] == "b") {
            $("#advBarcode").val(f[1]);
        } else if (f[0] == "c") {
            $("#advCatno").val(f[1]);
        } else if (f[0] == "l") {
            $("#advLabel").val(f[1]);
        } else if (f[0] == "co") {
            $("#advCountry").val(f[1]);
        } else if (f[0] == "y") {
            $("#advYear").val(f[1]);
        }
    }

    $("#simpleSearchDiv").addClass("d-none");
    $("#advSearchDiv").removeClass("d-none");
    $('input.clearable').trigger("change");
}

// Pagination
function paginationSetup() {
        if ($.fn.paginate && $.fn.modal && $.fn.tooltip && typeof Popper !== "undefined") {
                if (document.getElementById("discogsDeck") !== null) {
            closeDiscogsModals();
                        $('#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-info px-2 shadow-sm',
                                functionOnNav: function () { $("div[id^=tooltip]").remove(); tooltipSetup(); }
                        });
            tooltipSetup();
                }
        } else {
        setTimeout(function () { paginationSetup(); }, 100);
        }
}

function closeDiscogsModals() {
    $("[id^=masterModal]").modal("hide");
    $("[id^=videoModal]").modal("hide");
}

// left and right swipe / mouse move
function discogsSwipeSetup() {
        if ($.fn.swipe) {
        $("#discogsDeck").swipe( {
            swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
                if(direction == "left") {
                    closeDiscogsModals();
                    $("div.paginateNav .next").trigger("click");
                } else if (direction == "right") {
                    closeDiscogsModals();
                    $("div.paginateNav .prev").trigger("click");
                }
            },
        allowPageScroll: "vertical"});
        } else {
        setTimeout(function () { discogsSwipeSetup(); }, 100);
        }
}

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

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

                $(document).on('show.bs.modal', function () {
                        $("div[id^=tooltip]").remove();
                });
        } else {
        setTimeout(function () { tooltipSetup(); }, 100);
        }
}

// Tooltip Setup
function dataTableSetup() {
        if ($.fn.DataTable) {
            $('table.DataTable').DataTable({
            "infoCallback": function( settings, start, end, max, total, pre ) {return "Showing " + total +" of "+ max + " entries";}
        });
        $('div.dataTables_filter input').attr('type', 'text').addClass('clearable');
        } else {
        setTimeout(function () { dataTableSetup(); }, 100);
        }
}

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

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

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

/* clearable input fields, toggle class */
function tog(v){return v?'addClass':'removeClass';}

function inputClearerSetup() {
    $(document).on('input focus change select', '.clearable', function(){
        $(this)[tog(this.value)]('x');
    }).on('mousemove', '.x', function( e ){
        $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');
    }).on('touchstart click', '.onX', function( ev ){
        ev.preventDefault();
        $(this).removeClass('x onX').val('').change();
        if (ev.target.id == "searchTerm-flexdatalist") {
            $('#' + ev.target.id).trigger("focusin");
        } else {
            $(this).trigger("keyup");
        }
    }).on('shown.bs.modal', function(e){
        $('#' + e.target.id + ' input.clearable').trigger("input");
    });
    
    $('input.clearable').trigger("change");
}