/**
 * @package: EGPS - Easy Sell for Google Photo
 */

$ = jQuery; 

$('document').ready(function () {

    $('.egps_showhidebtn').on('click', function(){
        showHideLoadingImage(true);

        var btn_id = $(this).attr('id');
        var btn_val = $(this).val();
        var btn_item = $(this);
        
        $.ajax({
            url: "?page=easy-photo-sell_albums&change_show_hide=1&bt_id=" + btn_id + "&bt_val=" + btn_val,
            type: "POST",
            data: {},
            dataType: 'text',
            async: true,
            contentType: false,
            processData: false,
            success: function(data){

                showHideLoadingImage(false);

                if(btn_val == 'n'){
                    btn_item.attr("class", "btn btn-outline-danger egps_showhidebtn");
                    btn_item.val("y");
                    btn_item.text("Hidden");
                }else{
                    btn_item.attr("class", "btn btn-success egps_showhidebtn");
                    btn_item.val("n");
                    btn_item.text("Visible");
                }

                //to re-generate albums data table
                //location.reload();

                return true;
            },
            error: function(error) {
                showHideLoadingImage(false);

                alert('error');
                console.log(error);
            }
        });
        return false;
    });


    $('.egps_showhidebtn_photo').on('click', function(){
        showHideLoadingImage(true);

        var btn_id = $(this).attr('id');
        var btn_val = $(this).val();
        var btn_item = $(this);
        
        $.ajax({
            url: "?page=easy-photo-sell_albums&change_show_hide_photo=1&bt_id=" + btn_id + "&bt_val=" + btn_val,
            type: "POST",
            data: {},
            dataType: 'text',
            async: true,
            contentType: false,
            processData: false,
            success: function(data){

                showHideLoadingImage(false);

                if(btn_val == 'n'){
                    btn_item.attr("class", "btn btn-danger egps_showhidebtn_photo");
                    btn_item.val("y");
                    btn_item.text("Hidden");
                }else{
                    btn_item.attr("class", "btn btn-success egps_showhidebtn_photo");
                    btn_item.val("n");
                    btn_item.text("Visible");
                }

                return true;
            },
            error: function(error) {
                showHideLoadingImage(false);

                alert('error');
                console.log(error);
            }
        });
        return false;
    });


    $('#egps_admin_update_album_database').on('click', function(){
        showHideLoadingImage(true);
        activateSyncButtons(true);

        window.pollingPeriod = 100;
        window.progressInterval;

        $.getJSON('?page=easy-photo-sell_albums&list_albums=1', function(data){
            clearInterval(window.progressInterval);
        });

        function updateProgress(){
            $.getJSON('../wp-content/plugins/egps-easy-sell-for-google-photo/common/progress.json',function(data){

                $('#progressbar').css('width', (data.percentComplete)+'%').children('.sr-only').html(data.percentComplete+"% Complete");

                if(data.percentComplete == 100){
                    //zeroProgress();

                    showHideLoadingImage(false);
                    activateSyncButtons(false);
                    clearInterval(window.progressInterval);

                    location.reload();
                }
            });
        }
        window.progressInterval = setInterval(updateProgress, window.pollingPeriod);
        
    });
    
    
    $('#egps_admin_update_photo_database').on('click', function(){
        showHideLoadingImage(true);
        activateSyncButtons(true);

        window.pollingPeriod = 100;
        window.progressInterval;

        $.getJSON('?page=easy-photo-sell_albums&sync_photo_data=1', function(data){
            clearInterval(window.progressInterval);
        });

        function updateProgress(){
            $.getJSON('../wp-content/plugins/egps-easy-sell-for-google-photo/common/progress.json',function(data){

                $('#progressbar').css('width', (data.percentComplete)+'%').children('.sr-only').html(data.percentComplete+"% Complete");

                if(data.percentComplete == 100){
                    //zeroProgress();

                    showHideLoadingImage(false);
                    activateSyncButtons(false);
                    clearInterval(window.progressInterval);

                    location.reload();
                }
            });
        }
        window.progressInterval = setInterval(updateProgress, window.pollingPeriod);
    });


    $('#egps_admin_dwnld_images').on('click', function(){
        
        showHideLoadingImage(true);
        activateSyncButtons(true);
        
        window.pollingPeriod = 100;
        window.progressInterval;

        $.getJSON('?page=easy-photo-sell_albums&download_images=1', function(data){
            clearInterval(window.progressInterval);
        });
        
        function updateProgress(){
            $.getJSON('../wp-content/plugins/egps-easy-sell-for-google-photo/common/progress.json',function(data){
                
                $('#progressbar').css('width', (data.percentComplete)+'%').children('.sr-only').html(data.percentComplete+"% Complete");

                if(data.percentComplete == 100){
                    //zeroProgress();

                    showHideLoadingImage(false);
                    activateSyncButtons(false);
                    clearInterval(window.progressInterval);

                    location.reload();
                }
            });
        }
        window.progressInterval = setInterval(updateProgress, window.pollingPeriod);
        
    });

    $('#currencyList').change(function(){
        var newval = $(this).val();
        var newcode = $('#currencyList option:selected').text();

        console.log(newval + " " + newcode);

        $("#egps_currency_set").val(newval);
        $("#egps_currency_code").val(newcode);
    });

    var cur_val = $('#egps_currency_set').val();
    $('#currencyList').val(cur_val).change();


    $('.egps_remove_space').on('input',function(e){
        $(this).val($(this).val().trim());
    });

    $('.egps-modal-opener').on('click', function(e){

        var ajaxurl = e.target.href;
        e.preventDefault();
        $("#egpsModalBody").html("");

        showHideLoadingImage(true);

        $.ajax({
            url: ajaxurl,
            type: 'GET',
            dataType: 'json', // added data type
            success: function(res) {

                var list = "<ul>";

                $.each(res, recurse);

                function recurse(key, val) {
                    list += "<li>";
                    if (val instanceof Object) {
                        list += "<b style='text-transform: uppercase; text-decoration: underline;'>" + key + "</b><ul>";
                        $.each(val, recurse);
                        list += "</ul>";
                    } else {
                        list += "<b>" + key + ":</b> " +val;
                    }
                    list += "</li>";
                }
                list += "</ul>";

                $("#egpsModalBody").html( list );

                showHideLoadingImage(false);
            }
        });

        $("#egpsModalDialog").modal("show");

    });

    $('.myModalCloseBtn').on('click', function(){
        $("#egpsModalDialog").modal("hide");
        showHideLoadingImage(false);
    });

    $('.egps_edit_photo_meta').unbind('click').click( function(e){

        e.preventDefault();
        var save = true;

        var ajaxurl = e.target.href;
        $("#egpsModalBody").html("");

        showHideLoadingImage(true);

        $.ajax({
            url: ajaxurl,
            type: 'GET',
            async: false,
            dataType: 'json', // added data type
            success: function(res) {

                let tarea = '<div>Keywords <b>must</b> start with # and be separated by a space.</div>';
                tarea += '<div><textarea id="egps_metadata_tarea" name="" rows="4" cols="50">'+ res[0].egps_description +'</textarea></div>';

                $("#egpsModalDialogTitle").html("Photo meta:");
                $("#myModalCloseBtn").html("Save & Close");
                $("#egpsModalBody").html( tarea );

                $(".myModalCloseBtn").on("click", function(){
                    let desc = $("#egps_metadata_tarea").val();
                    
                    if(save){
                        save = false;

                        if(desc != res[0].egps_description && desc != "null"){

                            $.ajax({
                                type: "POST",
                                url: "../wp-json/egps_rest/update_egps_photometa",
                                dataType: 'json',
                                data: {
                                    'egps_desc': desc,
                                    'egps_id': res[0].id
                                },
                                success: function(ret){
                                    console.log("success");
                                    console.log(ret);
                                },
                                error: function (e){
                                    console.log("error");
                                    console.log(e);
                                } 
                            });

                        }

                    }
                      
                })

                showHideLoadingImage(false);
            }
        });

        $("#egpsModalDialog").modal("show");

    });

    $('input.float').on('input', function() {
        this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
    });

    $('input.integer').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*?)\..*/g, '$1');
    });

    
});



function zeroProgress() {
    // set progress value back to zero
    $.getJSON('?page=easy-photo-sell_albums&zero_progress=1', function(){});
}

function activateSyncButtons(act){
    if(act){
        $(".button").attr("disabled", true);
        $(".button").off('click');
    }else{
        $(".button").attr("disabled", false);
        $(".button").on('click');
    }
}

function showHideLoadingImage(show){
    if(show){
        $('.loading_gif').show();

        //mouse cursor change
        document.body.style.cursor = "wait"; //progress

    }else{
        $('.loading_gif').hide();

        //mouse cursor back to normal
        document.body.style.cursor = "";
    }
}

function resetActualPageNumber(){
    // reset pagination of sub pages
    sessionStorage.setItem("actualPageNumber", 1);
}
