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

        var preInput = ''; // for communicating between event handlersx
        var paletteHTML = generateHTML(); //cached array of fully printed html for the palettes
        var selection = 0; //default palette selected
        displayDefaultSwatches();

        function fetchPalette() {

            var palettes = [];

            palettes[0] = [
                ["ffffff","000000",],
                ["e2e8f0","fdb3b3","fad38e","f8ee71","9be5b4","82e5d8","91cdf3","a4bff9","d6bdf9","fab7ce",],
                ["909fb2","f26868","eb8938","e8c453","4ab978","3bb0aa","4499df","687fe8","9f7be9","eb66a6",],
                ["1a202c","732b2b","7a351f","734211","23533d","244d51","2c4363","3d3869","453578","6e2658",],
            ];

            palettes[1] = [
                ["ffffff","000000",],
                ["f7fafc","fff5f5","fffaf0","fffff0","f0fff4","e6fffa","ebf8ff","ebf4ff","faf5ff","fff5f7",],
                ["edf2f7","fed7d7","fdebc9","fdfbc0","c7f5d5","b3f4e9","bfe3f7","c4dafd","e9d8fd","fed7e2",],
                ["e2e8f0","fdb3b3","fad38e","f8ee71","9be5b4","82e5d8","91cdf3","a4bff9","d6bdf9","fab7ce",],
                ["ccd5df","fa8383","f4ad57","ffd944","6ad191","51cfc4","65b3eb","809df4","b795f3","f588b3",],
                ["909fb2","f26868","eb8938","e8c453","4ab978","3bb0aa","4499df","687fe8","9f7be9","eb66a6",],
                ["70798a","e34040","db6b22","c69c2c","3b9e69","339593","3382cc","5c68d6","815dd2","d3418c",],
                ["4c5566","c33232","be5723","bc8932","31835a","2e7879","2d6cae","4f54bc","6c48bf","b53580",],
                ["2e3747","992e2e","9a4323","965a17","286649","295d60","2e5280","45438e","563e98","95286d",],
                ["1a202c","732b2b","7a351f","734211","23533d","244d51","2c4363","3d3869","453578","6e2658",],
            ];

            return palettes;
        }

        function displayDefaultSwatches() {
            $('.kolorPicker').each(function(){
                var self = $(this),
                swatchHTML = generateSwatches();



                if(self.data('swatches')) {
                    // only draw default swatches if data-swatches is enabled
                    $(self).addClass('js-kolor-target', 'true');
                    self.after(swatchHTML)
                }
                if(self.data('helper')) {
                    self.addClass('kp-has-helper');
                    self.after('<label for="' + self.attr('id') + '" class="kp-helper"><ion-icon class="align-text-top icon-sm mr-1" name="color-fill"></ion-icon>' + (lmsg('common.color_picker.pick_colour') != undefined ? lmsg('common.color_picker.pick_colour') : 'Pick a colour') + '</label>')
                }
                pickColour(self, self.val())
            });
        }

        function generateSwatches() {
            var swatches = [
                "fdb3b3","fad38e","f8ee71","9be5b4","82e5d8","91cdf3","a4bff9","d6bdf9","fab7ce",
                "f26868","eb8938","e8c453","4ab978","3bb0aa","4499df","687fe8","9f7be9","eb66a6",
                "732b2b","7a351f","734211","23533d","244d51","2c4363","3d3869","453578","6e2658",

            ];
            var wrapper = document.createElement('div');
            wrapper.className = 'swatches clear clearfix open-swatches';

            for(var i = 0; i < swatches.length; i++) {
                wrapper.innerHTML += '<a class="swatch" id="' + swatches[i] + '" style="background-color:#' + swatches[i] + '"></a>';
            }
            return wrapper;
        }

        function pickColour(input, colour) {
            $(input).val(colour)
            .css({'background-color': colour})
            .css({'color': cla.colours.getColourContrast(colour)})
            .change()
            .next()
            .css({'color': cla.colours.getColourContrast(colour)});

        }

        function generateHTML() {
            var palettes = fetchPalette(),
            html = [];

            for(var i = 0; i < palettes.length; i++) {
                html[i] = '<div class="color-picker-header">\
                <h5>Color Picker</h5>\
                <div class="color-picker-close-button x-close-box"><ion-icon name="close-outline"></ion-icon></div>\
                </div>\
                <div class="color-picker-nav-wrapper">\
                <ul class="color-picker-nav">\
                <li class="color-picker-nav-item" id="0">' + (lmsg('common.color_picker.simple') != undefined ? lmsg('common.color_picker.simple') : 'Simple') + '</li>\
                <li class="color-picker-nav-item" id="1">' + (lmsg('common.color_picker.full') != undefined ? lmsg('common.color_picker.full') : 'Full') + '</li>\
                </ul>\
                </div>\
                <div class="clearfix"></div>';
                if (typeof palettes[i][0] !== 'object') {
                    for (var k = 0; k < palettes[i].length; k++) {
                        html[i] += "<a class='swatch' style='background-color:#" + palettes[i][k] + "' id='" + palettes[i][k] + "'></a>";
                    }
                } else
                {
                    for (var row = 0; row < palettes[i].length; row++) {
                        for (var column = 0; column < palettes[i][row].length; column++) {
                            html[i] += "<a class='swatch' style='background-color:#" + palettes[i][row][column] + "' id='" + palettes[i][row][column] + "'></a>";
                        }
                        html[i] += "<div class='clear swatch-row-" + row + "'></div>";
                    }
                }
            }

            return html;
        }

        function displayPicker(input) {
            var parent = $(input).parent();


            $('input.js-kolor-target').removeClass('js-kolor-target', 'false');
            $(input).addClass('js-kolor-target', 'true');

            if ($(parent).find('div').filter('#kolorPicker').size() === 0) {
                var target = $(input);
                var targetOffset = target.offset();

                $('body').append('<div class="color-picker-wrapper"/>');
                $('.color-picker-wrapper').append('<div id="kolorPicker" currentcolor="' + target.val() +  '" class="color-picker-container"></div>');

                //if the picker would appear out of the right of the current window the left offset is adjusted.
                var offsetAdjustment = targetOffset.left + $('.color-picker-container').outerWidth() - window.innerWidth + 20;
                var horizontalOffset = offsetAdjustment > 0 ? targetOffset.left - offsetAdjustment : targetOffset.left;
                if(horizontalOffset < 0) horizontalOffset = 0;

                $('.color-picker-wrapper').css({
                    'z-index' : '1100',
                    'position' : 'absolute',
                    'left': horizontalOffset + 'px',
                    'top': (target.outerHeight() + targetOffset.top) + 'px'
                });

                $('#kolorPicker').html(paletteHTML[selection]);

                if (target.hasClass('js-no-white')) {
                    $('.color-picker-wrapper').addClass('js-no-white');
                } else {
                    $('.color-picker-wrapper').removeClass('js-no-white');
                }

                $('li[id=' + selection + ']').addClass('color-picker-nav-item-active');

                $('.color-picker-wrapper .kolorPicker').focus();
            }
        }

        function cleanPicker() {
            $('.color-picker-wrapper').remove();
            $('#kolorPicker').remove();
            $('.kolorPicker').parent().removeAttr('style');
            $('body').off('click.kp');
            $('body').off('keydown');
        }

        $(document).off("click", ".kolorPicker");
        $(document).on("click", ".kolorPicker", function () {
            var elem = $(this);
            var elemId = elem.val();
            elem.css('background-color', elem.val()).addClass(elemId);
            elem.trigger('kolorPickerOpen');

            $('body').off('click.kp');
            $('body').on('click.kp', function (ev) {
                if (!($(ev.target).parents().is(".color-picker-wrapper") || $(ev.target).is(".color-picker-wrapper"))) {
                    elem.trigger('colorPickerClose');
                    cleanPicker();
                }
            });
            $('body').off('keydown');
            $('body').on('keydown', function(e) {
                // Close on escape key
                if(e.keyCode === 27) {
                    elem.trigger('kolorPickerClose');
                    cleanPicker();
                }
            });

            displayPicker(this);
            currentColor = $('#kolorPicker').attr('currentcolor');
            if (currentColor !== "") {
                $('.color-picker-container .swatch' + currentColor).addClass('current-swatch');
            }

        });

        $(document).on("keyup", ".kolorPicker", function () {

            if ($(this).val().charAt(0) != '#') {
                $(this).val('#' + $(this).val());
            }

            var check = /^#[0-9A-Fa-f]*$/;

            if (!check.test($(this).val())) {
                $(this).val(preInput); // if this value is invalid, restore it to what was valid
            }

            pickColour($(this), $(this).val());

            // call the change event on $(this) if you may have an assumed valid hex code
            if ( ($(this).val().length != preInput.length) && ($(this).val().length ==  7) ) {
                $(this).change();
            }
        });

        $(document).off("keypress", ".kolorPicker");
        $(document).on("keypress", ".kolorPicker", function (e) {

            preInput = $(this).val(); //catch this value for comparison in keyup

            return true;
        });

        $(document).off("click", '.swatch');
        $(document).on("click", '.swatch', function(evt){

            //get handle to input field to propagate update event
            var input = $('input.js-kolor-target');


            //grab from the tile's id
            var color = '#' + $(this).attr('id');

            //unhook ourselves from the page
            cleanPicker();
            pickColour(input, color);
        });

        $(document).off("click", '.color-picker-nav-item');
        $(document).on("click", '.color-picker-nav-item', function(){
            selection = $(this).attr('id'); //note which palette we selected
            currentColor = $('#kolorPicker').attr('currentcolor');

            $('#kolorPicker').html(paletteHTML[selection]);
            $('li[id=' + selection + ']').addClass('color-picker-nav-item-active');

            if (currentColor !== "") {
                $('.color-picker-container .swatch' + currentColor).addClass('current-swatch');
            }

        });

        $(document).off("click", '.x-close-box');
        $(document).on("click", '.x-close-box', function(){
            cleanPicker();
        });

        $(document).on("init", ".kolorPicker", function () {
            pickColour($(this), $(this).val());
        });
    });



    $('.js-no-white').on('change keyup blur',function(){
        // FIND CONTENT OF INPUT BOX

        var pickedColor  = $(this).val();

        // CHECK HOW MANY CHARACTERS ARE IN INPUT - IF 3 CHARACTER ARE ADDED IT TAKE EACH LETTER AND DUPLICATE IT IN ORDER
        // e.g. #f1f converts to #ff11ff

        if ($(this).val().length === 7) {
            var color = pickedColor;
        } else if ($(this).val().length === 4) {

            var hex1 = pickedColor.substr(1,1);
            var hex2 = pickedColor.substr(2,1);
            var hex3 = pickedColor.substr(3,4);

            pickedColor = '#' + hex1 + hex1 + hex2 + hex2 + hex3 + hex3;
            color = pickedColor;

        } else {
            var color = pickedColor;
            $( ".toolbar" ).remove();
        }

        // CONVERTS HEX TO HSL

        var r = parseInt(color.substr(1,2), 16);
        var g = parseInt(color.substr(3,2), 16);
        var b = parseInt(color.substr(5,2), 16);


        function rgbToHsl(r, g, b){
            r /= 255, g /= 255, b /= 255;
            var max = Math.max(r, g, b), min = Math.min(r, g, b);
            var h, s, l = (max + min) / 2;

            if(max == min){
                h = s = 0; // achromatic
            }else{
                var d = max - min;
                s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                switch(max){
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }

            return [h, s, l];
        }


        // FINDS LIGHTNESS OF HSL

        var lightness = rgbToHsl(r, g, b)[2] * 100;
        lightness = parseInt(lightness);


        // CHECKS WHETHER HSL LIGHTNESS WITHIN INPUT IS LOWER THAN 70 & ADD MESSAGE IF SO
        if (lightness >= 70) {
            $( ".choose-darker-color-message" ).remove();
            $(this).parent().append("<span class='choose-darker-color-message'>" + (lmsg('common.color_picker.choose_another_color') != undefined ? lmsg('common.color_picker.choose_another_color') : 'Please choose a darker colour') + "</span>");
        } else {
            $( ".choose-darker-color-message" ).remove();
        }
    });



})(jQuery);
