
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Image functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

function AjaxFillImage(element, imagename, preferredpixelsize) {

    if (!element || element.length == 0)
        return;
    if (!imagename) {
        //console.log('AjaxFillImage: image name not supplied');
        return;
    }

    // Already a data URI — use it directly without a server round-trip
    if (imagename.indexOf('data:') === 0) {
        $(element).attr("src", imagename).fadeIn();
        return;
    }

    if (!preferredpixelsize)
        preferredpixelsize = 32;

    var data = {
        "sImageName": imagename,
        "nPreferredPixels": preferredpixelsize,
    };

    var CachedBase64ImageString = GetCachedImageByName(imagename, preferredpixelsize);
    if (CachedBase64ImageString) {
        CachedBase64ImageString = CachedBase64ImageString.replace("data:image;", "data:image/png;");
        $(element).attr("src", CachedBase64ImageString).fadeIn();
        //console.log("CachedBase64ImageString: " + $(element).attr("id") + ", " + imagename);
        return;
    }

    var sFetchKey = imagename + "--" + preferredpixelsize;
    if (ImageFetchInFlight.has(sFetchKey))
        return;
    ImageFetchInFlight.add(sFetchKey);

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetImageBase64Data",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            ImageFetchInFlight.delete(sFetchKey);
            if (response.Success) {
                $(element).attr("src", response.Base64UrlString).fadeIn();
                //console.log("AjaxFillImage: SetCachedImageByName: " + imagename + "--" + preferredpixelsize);
                SetCachedImageByName(imagename, preferredpixelsize, response.Base64UrlString);
            }
            else {
            }
        },
        error: function (xhr, status, error) {
            ImageFetchInFlight.delete(sFetchKey);
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxFillImage", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}

function FillImageFromAttributes(element) {
    if (!element || element.length == 0)
        return;
    var imagename = $(element).attr('data-image');
    var preferredpixelsize = $(element).attr('data-image-size');
    AjaxFillImage(element, imagename, preferredpixelsize);
}

function FillDisabledImageFromAttributes(element) {
    if (!element || element.length == 0)
        return;
    var imagename = $(element).attr('data-image-disabled');
    var preferredpixelsize = $(element).attr('data-image-size');
    AjaxFillImage(element, imagename, preferredpixelsize);
}


function SetButtonBackgroundImageFromAttributes(element) {

    if (!element || element.length == 0)
        return;
    var imagename = $(element).attr('data-image');
    var preferredpixelsize = $(element).attr('data-image-size');
    AjaxSetButtonBackgroundImage(element, imagename, preferredpixelsize);
}

function SetButtonBackgroundDisabledImageFromAttributes(element) {

    if (!element || element.length == 0)
        return;
    var imagename = $(element).attr('data-image-disabled');
    var preferredpixelsize = $(element).attr('data-image-size');
    AjaxSetButtonBackgroundImage(element, imagename, preferredpixelsize);
}

function AjaxSetButtonBackgroundImage(element, imagename, preferredpixelsize) {

    if (!imagename) {
        //console.log('AjaxSetButtonBackgroundImage: image name not supplied');
        return;
    }

    // Already a data URI — use it directly without a server round-trip
    if (imagename.indexOf('data:') === 0) {
        $(element).css('background', 'url("' + imagename + '") top center no-repeat');
        $(element).css('background-size', (preferredpixelsize || 32) + 'px');
        return;
    }

    if (!preferredpixelsize)
        preferredpixelsize = 32;

    //console.log("AjaxSetButtonBackgroundImage: " + $(element).attr("id") + ", " + imagename);

    var CachedBase64ImageString = GetCachedImageByName(imagename, preferredpixelsize);
    if (CachedBase64ImageString) {
        CachedBase64ImageString = CachedBase64ImageString.replace("data:image;", "data:image/png;");
        $(element).css('background', 'url("' + CachedBase64ImageString + '") top center no-repeat');
        //console.log("CachedBase64ImageString: " + $(element).attr("id") + ", " + imagename);
        return;
    }

    var sFetchKey = imagename + "--" + preferredpixelsize;
    if (ImageFetchInFlight.has(sFetchKey))
        return;
    ImageFetchInFlight.add(sFetchKey);

    var data = {
        "sImageName": imagename,
        "nPreferredPixels": preferredpixelsize,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetImageBase64Data",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            ImageFetchInFlight.delete(sFetchKey);
            if (response.Success) {
                $(element).css('background', 'url("' + response.Base64UrlString + '") top center no-repeat');
                SetCachedImageByName(imagename, preferredpixelsize, response.Base64UrlString);
            }
            else {
            }
        },
        error: function (xhr, status, error) {
            ImageFetchInFlight.delete(sFetchKey);
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxSetButtonBackgroundImage", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}





function CacheImageFromAjax(imagename, preferredpixelsize) {

    if (!preferredpixelsize)
        preferredpixelsize = 32;

    if (!imagename) {
        //console.log('CacheImageFromAjax: image name not supplied');
        return;
    }

    if (GetCachedImageByName(imagename, preferredpixelsize))
        return;

    var data = {
        "sImageName": imagename,
        "nPreferredPixels": preferredpixelsize,
    };

    var sFetchKey = imagename + "--" + preferredpixelsize;
    if (ImageFetchInFlight.has(sFetchKey))
        return;
    ImageFetchInFlight.add(sFetchKey);

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetImageBase64Data",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            ImageFetchInFlight.delete(sFetchKey);
            if (response.Success) {
                //console.log("CacheImageFromAjax: SetCachedImageByName: " + imagename + "--" + preferredpixelsize);
                SetCachedImageByName(imagename, preferredpixelsize, response.Base64UrlString);
            }
            else {
            }
        },
        error: function (xhr, status, errorthrown) {
            ImageFetchInFlight.delete(sFetchKey);
            var errormsg = "Error " + xhr.status + ", " + status + ", " + errorthrown + ", image: " + imagename + ", size: " + preferredpixelsize;
            ToastError("CacheImageFromAjax", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



// Get all the commonly used images from Ajax
// Cache these images on the client for quick display
function AjaxGetImageCacheList() {

    //console.log("AjaxGetImageCacheList");

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetImageCacheList",
        type: "POST",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                $.each(response.ImageCacheItems, function (index) {
                    //console.log("CacheEachImage: " + response.ImageCacheItems[index].ImageName + ", " + response.ImageCacheItems[index].ImageSize);
                    CacheImageFromAjax(response.ImageCacheItems[index].ImageName, response.ImageCacheItems[index].ImageSize)
                });
            }
            else {
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxGetImageCacheList", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




/**
 * Set up all buttons in the specified div
 * This includes onclick and images
 * @param {any} element
 */
function SetupElementImagesInDivByParent(element) {

    if (!element || !element.length)
        return;

    //console.log("SetupElementImagesInDiv:" + $(element).attr("id"));

    // Iterate children of div
    // Ajax function to set up images in buttons
    // Recurse into each div
    $(element).children().each(function () {
        var ChildId = this.id;
        var ChildElementType = this.nodeName;
        var ChildElement = $(this);
        var IsSetup = $(ChildElement).attr("data-issetup");
        if (ChildElementType) {

            if (ChildElementType.toLowerCase() == "button") {

                if (!IsSetup) {
                    //console.log("SetupElementImagesInDiv: button :" + $(ChildElement).attr("id"));
                    SetButtonClickEventHandler(ChildElement);
                    SetButtonBackgroundImageFromAttributes(ChildElement);

                    // Remember that it is set up
                    // Don't come back here again
                    $(ChildElement).attr("data-issetup", true);
                }
            }
            else if (ChildElementType.toLowerCase() == "img") {

                if (!IsSetup) {
                    //console.log("SetupElementImagesInDiv: img :" + $(ChildElement).attr("id"));
                    FillImageFromAttributes(ChildElement);

                    // Remember that it is set up
                    // Don't come back here again
                    $(ChildElement).attr("data-issetup", true);
                }
            }
            else if (ChildElementType.toLowerCase() == "div")
                SetupElementImagesInDivByParent(ChildElement);
            else if (ChildElementType.toLowerCase() == "a")
                SetupElementImagesInDivByParent(ChildElement);
        }
    });
}





/**
 * Set up all the button in a div (called from an <img> within that div)
 * @param {any} element
 */
function SetupElementImagesInDiv(element) {

    if (!element)
        return;

    // Convert a raw html element to jQuery
    element = $(element);
    if (!element)
        return;

    var ElementId = element.attr('id');
    var ParentDiv = $(element).parent();
    if (!ParentDiv)
        return;
    var ParentId = ParentDiv.attr('id');
    var ParentElementType = ParentDiv.prop("nodeName");

    SetupElementImagesInDivByParent(ParentDiv);
}





//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Cached images
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


var ImageCache = {
    "key": "empty"
};
var ImageFetchInFlight = new Set();


function GetCachedImageByName(imagename, preferredpixelsize) {

    if (!imagename)
        return "";

    var sCacheName = imagename + "--" + preferredpixelsize;
    var sImageData = ImageCache[sCacheName];

    if (!sImageData || sImageData == null || sImageData.length == 0)
        sImageData = localStorage.getItem(sCacheName);

    //console.log("GetCachedImageByName: " + sCacheName);

    return sImageData;
}

function SetCachedImageByName(imagename, preferredpixelsize, imagedata) {

    if (!imagename)
        return "";

    var sCacheName = imagename + "--" + preferredpixelsize;
    ImageCache[sCacheName] = imagedata;

    try { localStorage.setItem(sCacheName, imagedata); } catch (e) { }

    //console.log("SetCachedImageByName: " + sCacheName);
}



// OLD. Works fine
// Moved to startup.js so images can begin caching earlier in the startup process
//$(document).ready(function () {

//    // The most commonly used images should be cached first
//    // Get image data from Ajax, then store in ImageCache global dictionary
//    AjaxGetImageCacheList();
//})






//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the View Image dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bViewImageDialogIsOpen = false;
function OpenViewImageDialog(ImageName, ImageBase64String) {

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogViewImage").igDialog({ modal: false, headerText: ImageName, height: 400, width: 600, resizable: true, showCloseButton: true, showMaximizeButton: true, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogViewImage").igDialog("open");

    CenterDialog("igDialogViewImage");

    $("#igDialogViewImageImg").css('background', 'url(' + ImageBase64String + ')');
    $("#igDialogViewImageImg").css('background-size', 'contain');
    $("#igDialogViewImageImg").css('background-repeat', 'no-repeat');
    $("#igDialogViewImageImg").css('background-position', 'center');

    // Set up controls
    bViewImageDialogIsOpen = true;
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseViewImageDialog() {
    $("#igDialogViewImage").igDialog("close");
    bViewImageDialogIsOpen = false;
}

function IsViewImageDialogOpen() {
    return bViewImageDialogIsOpen;
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//



function FileOpenAndUploadImage(ContentType, ValueString, sDbTable, sRecordId) {

    $('#ImportFileControl').attr("accept", ".png,.jpg,.jpeg,.bmp,.gif");

    $('#ImportFileControl').on('change', function () {

        $('#ImportFileControl').off('change');

        // Upload FormData with Ajax
        var formdata = new FormData();
        var ImportFileControl = $('#ImportFileControl').get(0);
        var files = ImportFileControl.files;
        formdata.append('ContentType', ContentType);
        formdata.append('ValueString', ValueString);
        formdata.append('dbtable', sDbTable);
        formdata.append('recordid', sRecordId);
        formdata.append('binarydata', files[0]);
        AjaxUploadImageFile(formdata);

        // Clear this so the 'change' event is triggered again
        $('#ImportFileControl').val("");
    });

    // Open the File Open dialog
    $('#ImportFileControl').trigger('click');
}

/**
 * Upload FormData with Ajax
 * @param {any} formdata
 */
function AjaxUploadImageFile(formdata) {

    // Modeless dialog for lengthly operations
    OpenPleaseWaitDialog("Import");

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxUploadImageFile",
        type: "POST",
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {

            ClosePleaseWaitDialog();

            if (response.Success) {
                RefreshSelectedContent();
                ToastMessage("Upload", response.UploadResults);
            }
            else {
                ToastError("Upload", response.UploadResults);
            }
        },
        error: function (xhr, status, error) {

            ClosePleaseWaitDialog();

            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxUploadImageFile", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


function DeleteContentImage(ContentType, ValueString, sDbTable, sRecordId) {

    AjaxDeleteContentImage(ContentType, ValueString, sDbTable, sRecordId);
}


/**
 * Delete an image associated with content
 * Example: RptGraphicImage (delete base64 image data)
 * @param {any} ContentType
 * @param {any} ValueString
 * @param {any} sDbTable
 * @param {any} sRecordId
 */
function AjaxDeleteContentImage(ContentType, ValueString, sDbTable, sRecordId) {

    var params = {
        "ContentType": ContentType,
        "ValueString": ValueString,
        "DbTable": sDbTable,
        "RecordId": sRecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxDeleteContentImage",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {
                CloseLastDropdown();
                RefreshSelectedContent();
                RefreshPropertyEditorPartialView();
                ToastMessage("Delete", response.DeleteResults);
            }
            else {
                ToastError("Export", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxDeleteContentImage", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
