// https://github.com/szimek/signature_pad

// Register storage for signature pad.
let LimitlessSignaturePadContainer = {};
let LimitlessSignaturePadCounter = 0;

// Start and scan all elements.
$(document).ready(function(){

    init();

    // Refresh
    setTimeout(function(){ refreshLimitlessSignature() }, 1);
});

// Resize function
$(window).resize(function()
{
    // Refresh
    refreshLimitlessSignature();
});

// Register initial method for signature pad.
jQuery.fn.LimitlessSignaturePad = function()
{

    // Count up container
    LimitlessSignaturePadCounter++;

    // Flag current object and store it to container.
    let currentObject = $(this[0]);
    let canvas = currentObject.children('canvas')[0];

    let signaturePad = new SignaturePad(canvas, {penColor: 'rgb(60, 140, 67)', minWidth : 3, maxWidth : 4});

    currentObject.children('canvas').attr('LimitlessSignatureCanvas', LimitlessSignaturePadCounter);
    LimitlessSignaturePadContainer[LimitlessSignaturePadCounter] = signaturePad;

    // Add click listener to container.
    currentObject.on("click touchend",function(event)
    {
        // Get object of pad.
        let target = event.target || event.srcElement;
        let id = $(target).attr('LimitlessSignatureCanvas');
        let pad = LimitlessSignaturePadContainer[id];
        let vcanvas = $(canvas);
        let vimg = $(canvas).next('img');

        // Saving
        if($(target).attr('data') === "Save")
        {
            // Reset border color
            currentObject.css('border-color','#888888');

            // Switch to image mode
            if($(canvas).attr('data') !== undefined)
            {
                //Button
                $(target).hide();
                vimg.show();
                vimg.attr('src', vcanvas.attr('data') );
                vcanvas.hide();
                vimg.change();
            }
            else
            {
                // Red border
                currentObject.css('border-color','#f44336');
            }
        }

        // Clearing
        if($(target).attr('data') === "Reset")
        {
            $(vcanvas).show();
            $(vcanvas).attr('data', null);
            $(vcanvas).parent('div').find('button').show();
            $(vimg).attr('src', null);
            $(vimg).hide();

            let canvas = $(vcanvas)[0];
            let canvasContext = $(vcanvas)[0].getContext('2d');
            canvasContext.clearRect(0, 0, canvas.width, canvas.height);

            $(vimg).change();
        }

        // Save string to canvas.
        if(pad)
        {
            $(target).attr('data',pad.toDataURL());
        }
    });

    // This is needed so other functions can keep chaining off of this.
    return this;
};

function init() {

    let counter = 0;

    $('.LimitlessBetterSignature').each(function(){

        let element = $(this);

        // adds auto generated id if element has no id
        if(!element.attr('id')) {
            counter++;
            element.attr('id', 'LimitlessBetterSignature' + counter);
        }

        element.LimitlessSignaturePad();
    });

}

// Refresh and Resize
function refreshLimitlessSignature() {

    // Loop all signature pad containers.
    $('.LimitlessBetterSignature').each(function()
    {
        // Load signature pad.
        let container = $(this);
        let canvas = $(this).children('canvas')[0];

        // Resize and refresh canvas.
        canvas.width = container.outerWidth() - 13;
        canvas.height = '150';

        // Clear signature pad.
        let signaturePad = LimitlessSignaturePadContainer[$(canvas).attr('LimitlessSignatureCanvas')];

        if(signaturePad !== undefined) signaturePad.clear();

    });
}
