$(document).ready(function() {

    // set focus to first text form field
    if( $("input:text:visible:first").val().length === 0 ) {
      $("input:text:visible:first").focus();
    }

    var selCount = 0;
    var totalCount = 0;
    var txtVal = '';
    var selToggle = false;

    displaySelectionCount(); // initial display

    // select/deselect image
    $("div[id^=image_]")
      .bind('mouseover mouseout', function() { // highlight on hover
        $(this).toggleClass('imgThumb_hover');
      })
      .click(function () {
        $(this).toggleClass('imgThumb_selected');

        if ($(this).hasClass("imgThumb_selected")) {
            selectImage(this);
        } else {
            deselectImage(this);
        }
        displaySelectionCount();
      });

    // select all
    $("input[id^=selectAll]").click(function() {
        $("div[id^=image_]").addClass("imgThumb_selected");
        selectImage("div[id^=image_]");
        displaySelectionCount();
      });

    // deselect all
    $("input[id^=deselectAll]").click(function() {
        $("div[id^=image_]").removeClass("imgThumb_selected");
        deselectImage("div[id^=image_]");
        displaySelectionCount();
      });

    function displaySelectionCount() {
        totalCount = $(".imgThumb:visible").length;
        if (totalCount==0) {
            $("#topOptionsBar").hide();
            $("#noImages").show();
            $("#bottomOptionsBar").hide();
        } else {
            selCount = $(".imgThumb_selected:visible").length;
            txtVal = 'Selected ' + selCount + ' of ' + totalCount;
            $(".selectedImageCount").text(txtVal);
        }
    }

    function selectImage(image) {
        $(image).css('opacity', .3);
        $(image).parent().css('background-color', '#DF7401');
    }

    function deselectImage(image) {
        $(image).css('opacity', 1);
        $(image).parent().css('background-color', 'black');
    }

    $("input[id^=unhideSelected]").click(function() {

        // prompt to verify action
        selCount = $(".imgThumb_selected:visible").length;

        if (selCount==0) {
            alert ("No images have been selected.");
        } else {
            confirmMsg = "Remove the hidden flag from the " + selCount + " selected images?"
            var unhideConfirmed = confirm(confirmMsg);
            if (unhideConfirmed) {
                $("#dialogBoxHdr").text("Removing Hidden Flag from Selected Images");
                txtVal = processSmugJSON('unhide');
                displaySelectionCount();
            }
        }

    }); // unhideSelected click

    $("input[id^=deleteSelected]").click(function() {

        // prompt to verify action
        selCount = $(".imgThumb_selected:visible").length;

        if (selCount==0) {
            alert ("No images have been selected.");
        } else {
            disclaimerMsg = "This will permanently remove the selected images from your SmugMug account.";
            confirmMsg = disclaimerMsg + "\n\n" + "Delete the " + selCount + " selected images?"
            var deleteConfirmed = confirm(confirmMsg);
            if (deleteConfirmed) {
                $("#dialogBoxHdr").text("Deleting Images...");
                txtVal = processSmugJSON('delete');
                displaySelectionCount();
            }
        }

    }); // deleteSelected click


    function processSmugJSON(smugMethod) {

        var txtVal = '';
        var selCount = $(".imgThumb_selected:visible").length;
		
        openModal("#dialogBox"); // display progress dialog
        nextImage(smugMethod, selCount);

        return txtVal;

    } // processSmugJSON

    function nextImage(smugMethod, count) {

        // get next image
        $(".imgThumb_selected:visible").slice(count-1, count).each(function(index) {

            var curImg = this;

            var fullImgID = $(curImg).attr('id');

            var imgID = fullImgID.substring(6,15);
            var imgKy = fullImgID.substring(16);

            $("#dialogBoxMsg").text('Processing image ' + imgID + '_' + imgKy);

            var apiCmd = '';
            var apiArg = '';
            switch(smugMethod) {
                case 'unhide':
                    apiCmd = 'smugmug.images.changeSettings';
                    apiArg = 'ImageID=' + imgID + ',ImageKey=' + imgKy + ',Hidden=0';
                    break;
                case 'delete':
                    apiCmd = 'smugmug.images.delete';
                    apiArg = 'ImageID=' + imgID + ',ImageKey=' + imgKy;
                    break;
            }

            $.getJSON('/api/smugJSON.php?c=' + apiCmd + '&a=' + apiArg, function(data) {
                $(curImg).hide(); // image div
                $(curImg).parent().hide(); // background highlight div
                $(curImg).addClass(smugMethod + "Processed");

                // Check gallery container, hide if empty
                galleryID = $(curImg).parent().parent().attr('id');
                numChildren = $("#"+galleryID).children(":visible").length;
                if (numChildren==0) {
                    $("#"+galleryID).hide();
                    $("#"+galleryID+"_msg").hide();
                }

                displaySelectionCount();

                count--;
                if (count>0) {
                    nextImage(smugMethod, count); // recurse to process next image
                } else {
                    $("#dialogBoxMsg").text('Processing Complete');
                    $.getJSON('/api/smugJSON.php?s=.2', function(data) { closeModal("#dialogBox"); });
                }

            }); // JSON callback

        }); // .each

    } // nextImage()


    function processSmugJSONsave(smugMethod) {

        var txtVal = '';

        openModal("#dialogBox"); // display progress dialog
//$("#dBoxBtnCancel").focus();

        $(".imgThumb_selected:visible").each(function(index) {
            fullImgID = $(this).attr('id');
            imgID = fullImgID.substring(6,15);
            imgKy = fullImgID.substring(16);

//            txtVal += (index+1) + ': ' + imgID;
// $(something).text(txtVal); // update progress bar???

            var apiCmd = '';
            switch(smugMethod) {
                case 'unhide':
                    apiCmd = 'smugmug.images.changeSettings';
                    apiArg = 'ImageID=' + imgID + ',ImageKey=' + imgKy + ',Hidden=0';
                    break;
                case 'delete':
                    apiCmd = 'smugmug.images.delete';
                    apiArg = 'ImageID=' + imgID + ',ImageKey=' + imgKy;
                    break;
            }

            $.getJSON('/api/smugJSON.php?c=' + apiCmd + '&a=' + apiArg, function(data) {
//                alert ("Method: " + data.method + "\n" + "Status: " + data.status);
//                $("#dialogBoxMsg").text(txtVal + " (" + data.status + ")");
            });

            $(this).hide(); // image div
            $(this).parent().hide(); // background highlight div
            $(this).addClass(smugMethod + "Processed");

            // Check gallery container, hide if empty
            galleryID = $(this).parent().parent().attr('id');
            numChildren = $("#"+galleryID).children(":visible").length;
            if (numChildren==0) {
                $("#"+galleryID).hide();
                $("#"+galleryID+"_msg").hide();
            }

        });

//        $("#dBoxBtnOk").show();
//        $("#dBoxBtnCancel").show();
//        $("#dBoxBtnClose").show();

        closeModal("#dialogBox");

        return txtVal;

    } // processSmugJSON

    // close dialog box
    $("#dBoxBtnClose").click(function(){
        $("#dBoxBtnClose").hide();
        closeModal("#dialogBox");
    });

    function showMsgDialog() {
        $("#overlay").css('opacity', .8);
        $("#overlay").show();
        $("#dialogBox").show();
    }

    function hideMsgDialog() {
        $("#overlay").hide();
        $("#dialogBox").hide();
        $("#dialogBoxClose").hide();
    }

    function openModal(thisID) {
        $("#overlay").css('opacity', .8);
        $("#overlay").show();
        $(thisID).css('z-index', 1001);
        $(thisID).show();
    }

    function closeModal(thisID) {
        $(thisID).hide();
        $("#overlay").hide();
        $(thisID).css('z-index', 99);
    }

});

