/**
 * Short Pixel WordPress Plugin javascript
 */
// init checks bulkProcess on each page. initSettings is when the settings View is being loaded.
jQuery(document).ready(function(){SPAATG.init(); });

function delayedInit() {
    if(typeof SPAATG !== 'undefined' && SPAATG.didInit == false) {

        console.error('SPAATG: Delayed Init. Check your installation for errors');
        SPAATG.init();
    } else {
        setTimeout(delayedInit, 10000);
    }
}
setTimeout(delayedInit, 10000);

var SPAATG = function() {

	 var updateTimer;

	// The InitSettings usually runs before these settings, making everything complicated (@todo)
    function init() {

        if (typeof SPAATG.API_IS_ACTIVE !== 'undefined') return; //was initialized by the 10 sec. setTimeout, rare but who knows, might happen on very slow connections...

        // Extracting the protected Array from within the 0 element of the parent array
        SPAATG.setOptions(SPAATGConstants[0]);

				/*if (jQuery('#shortpixel-form-request-key').length > 0)
				{
					  jQuery('#pluginemail').on('change, keyup', jQuery.proxy(this.updateSignupEmail, this));
						jQuery('#request_key').on('mouseenter', jQuery.proxy(this.updateSignupEmail, this));
						jQuery('#request_key').on('click', jQuery.proxy(this.newApiKey, this));
				} */

        if (window.SPAATGProcessor)
				{
          window.SPAATGProcessor.Load(SPAATG['HAS_QUOTA']);
				}
        this.didInit = true;

				// Move footer notices to the top, where it should be.
				$headerEnd = jQuery( '.wp-header-end' );

      	jQuery( 'div.shortpixel-notice' ).not( '.inline, .below-h2' ).insertAfter( $headerEnd );

				var settingsPage = document.querySelector('.is-spaatg-settings-page, .is-shortpixel-settings-page');
				if (settingsPage !== null)
				{
					  this.initSettings();
				}
    }
    function setOptions(options) {
        for(var opt in options) {
            SPAATG[opt] = options[opt];
        }
    }
/*
    function isEmailValid(email) {
				var regex = /^\S+@\S+\.\S+$/;
				return regex.test(email);
    }
*/
    function updateSignupEmail() {

				clearTimeout( SPAATG.updateTimer );

				SPAATG.updateTimer = setTimeout( function() {

        var email = jQuery('#pluginemail').val().trim();
				var $submit = jQuery('#request_key');
				var isValid = SPAATG.isEmailValid(email)
        if(isValid) {
            jQuery('#request_key').removeClass('disabled');
						$submit.removeClass('disabled');
						$submit.removeAttr('disabled');
        }
				else
				{
						$submit.attr('disabled', true);
					  $submit.addClass('disabled');
				}
        jQuery('#request_key').attr('href', jQuery('#request_key').attr('href').split('?')[0] + '?pluginemail=' + email);
			}, 1000);
    }

    // Settings part-general
    function validateKey(button){
        jQuery('#valid').val('validate');

        jQuery(button).parents('form').submit();
    }

    jQuery("#key").on('keypress', function(e) {
        if(e.which == 13) {
            jQuery('#valid').val('validate');
        }
    });


    // Settings part-general
    function enableResize(elm) {
        return;
        if(jQuery(elm).is(':checked')) {
            jQuery("#width,#height").prop("disabled", false);
            SpaatgResize.lastW = false; //to trigger the animation
            jQuery(".resize-type-wrap").show(800, window.SpaatgResize.run);
        } else {
            jQuery("#width,#height").prop("disabled", true);
            window.SpaatgResize.hide();
            jQuery(".resize-type-wrap").hide(800);
        }
    }


    function setupGeneralTab() {
        return;
				// @todo Make something workable out of this
        var rad = 0;

        /*if (typeof document.spaatg_options !== 'undefined')
          rad = document.spaatg_options.compressionType;
        */
				if (document.getElementById('compressionType-database') !== null)
					var savedCompression = document.getElementById('compressionType-database').value;
				else
					var savedCompression = null;

        for(var i = 0, prev = null; i < rad.length; i++) {
            rad[i].onclick = function() {

                if(this !== prev) {
                    prev = this;
                }

							 if (this.value == savedCompression)
  					 		jQuery('#compression-type warning').removeClass('display');
							else
							  jQuery('#compression-type warning').addClass('display');
            };
        }

        SPAATG.enableResize("#resize");

        jQuery("#resize").on('change', function(){ enableResize(this); });
        jQuery(".resize-sizes").on('blur', function(e){
            var elm = jQuery(e.target);

            if(SPAATG.resizeSizesAlert == elm.val())
              return; // returns if check in progress, presumed.

            SPAATG.resizeSizesAlert = elm.val();
            var minSize = jQuery("#min-" + elm.attr('name')).val();
            var niceName = jQuery("#min-" + elm.attr('name')).data('nicename');
            if(elm.val() < Math.min(minSize, 1024)) { // @todo is this correct? This will always be < 1024, and give first error
                if(minSize > 1024) {
                    alert( SPstringFormat(spaatgTr.pleaseDoNotSetLesser1024,niceName) );
                } else {
                    alert( SPstringFormat(spaatgTr.pleaseDoNotSetLesserSize, niceName, niceName, minSize) );
                }
                e.preventDefault();
                //elm.val(this.defaultValue);
                elm.focus();
            }
            else {
                this.defaultValue = elm.val();
            }
        });

        jQuery('.shortpixel-confirm').on('click', function(event){
            var choice = confirm(event.target.getAttribute('data-confirm'));
            if (!choice) {
                event.preventDefault();
                return false;
            }
            return true;
        });


    }

    /* function apiKeyChanged() {
        jQuery(".spaatg-options-legacy .shortpixel-key-valid").css("display", "none");
        jQuery(".spaatg-options-legacy button#validate").css("display", "inline-block");
    } */



    function checkThumbsUpdTotal(el) {
        var total = jQuery("#" +(el.checked ? "total" : "main")+ "ToProcess").val();
        jQuery("div.bulk-play span.total").text(total);
        jQuery("#displayTotal").text(total);
    }

    function initSettings() {
      //  SPAATG.adjustSettingsTabs();
        SPAATG.setupGeneralTab(); // certain alerts.



        jQuery("article.sp-tabs a.tab-link").on('click', function(e){
            var theID = jQuery(e.target).data("id");
            SPAATG.switchSettingsTab( theID );
        });

				// Init active tab
			/*	var activeTab = document.querySelector('section.sel-tab');
				if (activeTab !== null);
				SPAATG.switchSettingsTab(activeTab.getAttribute('id')); */
    }

    // Switch between settings tabs.
    /*function switchSettingsTab(target){

        var tab = target.replace("tab-",""),
            beacon = "",
            section = jQuery("section#" +target);

				if (section.length == 0)
				{
					 tab = 'settings'; // if tab does not exist.
				}
        jQuery('input[name="display_part"]').val(tab);
        var uri = window.location.href.toString();
        if (uri.indexOf("?") > 0) {
            var clean_uri = uri.substring(0, uri.indexOf("?"));
            clean_uri += '?' + jQuery.param({'page':'spaatg-settings', 'part': tab});
          //  window.history.replaceState({}, document.title, clean_uri);
        }

        if(section.length > 0){
            jQuery("section").removeClass("sel-tab");
            jQuery('section .wp-shortpixel-tab-content').fadeOut(50);
            jQuery(section).addClass("sel-tab");

            jQuery(section).find('.wp-shortpixel-tab-content').fadeIn(50, SPAATG.adjustSettingsTabs);

						var event = new CustomEvent('spaatg.ui.settingsTabLoad', { detail : {tabName: tab, section: section }});
						window.dispatchEvent(event);

        }
    } */

    // Fixes the height of the current active tab.
  /*  function adjustSettingsTabsHeight(){
        jQuery('.wso.banner').css('opacity', 1);
    } */

  /*  function closeHelpPane() {
        jQuery('#shortpixel-hs-button-blind').remove();
        jQuery('#shortpixel-hs-tools').remove();
        jQuery('#hs-beacon').remove();
        jQuery('#botbutton').remove();
        jQuery('#shortpixel-hs-blind').remove();
    } */

    function checkQuota() {
        var data = {
          action:'spaatg_check_quota',
          nonce: SPAATGConstants[0].nonce_ajaxrequest,
          return_json: true
        };

        jQuery.post(SPAATG.AJAX_URL, data, function(result) {
            window.location.href = result.redirect;
        });
    }

    function percentDial(query, size) {
        jQuery(query).knob({
            'readOnly': true,
            'width': size,
            'height': size,
            'fgColor': '#1CAECB',
            'format' : function (value) {
                 return value + '%';
            }
        });
    }

  /*function browseContent(browseData) {
        browseData.action = 'shortpixel_browse_content';

        var browseResponse = "";
        jQuery.ajax({
            type: "POST",
            url: SPAATG.AJAX_URL,
            data: browseData,
            success: function(response) {
                 browseResponse = response;
            },
            async: false
        });
        return browseResponse;
    } */


    function newApiKey(event) {
				event.preventDefault();
        SPAATG.updateSignupEmail();

        if(!jQuery("#tos").is( ":checked" )) {
            event.preventDefault();
            jQuery("#tos-robo").fadeIn(400,function(){jQuery("#tos-hand").fadeIn();});
            jQuery("#tos").click(function(){
                jQuery("#tos-robo").css("display", "none");
                jQuery("#tos-hand").css("display", "none");
            });
            return;
        }
				if (jQuery('#request_key').is(':disabled'))
				{
					return false;
				}
        jQuery('#request_key').addClass('disabled');
        jQuery('#pluginemail_spinner').addClass('is-active');

				jQuery('#shortpixel-form-request-key').submit();

    }

    // Used by confirmation fields in bulk/safety screens.
    function checkRandomAnswer(e)
    {
        var value = jQuery(e.target).val();
        var answer = jQuery('input[name="random_answer"]').val();
        var target = jQuery('input[name="random_answer"]').data('target');

        if (value == answer)
        {
          jQuery(target).removeClass('disabled').prop('disabled', false);
          jQuery(target).removeAttr('aria-disabled');

        }
        else
        {
            jQuery(target).addClass('disabled').prop('disabled', true);
        }

    }

    function openImageMenu(e) {
            e.preventDefault();
            //install (lazily) a window click event to close the menus
            if(!this.menuCloseEvent) {
                jQuery(window).on('click', function(e){
                    if (!e.target.matches('.sp-dropbtn')) {
                        jQuery('.sp-dropdown.sp-show').removeClass('sp-show');
                    }
                });
                this.menuCloseEvent = true;
            }
            var shown = e.target.parentElement.classList.contains("sp-show");
            jQuery('.sp-dropdown.sp-show').removeClass('sp-show');
            if(!shown) e.target.parentElement.classList.add("sp-show");
    }

    function convertPunycode(url) {
        var parser = document.createElement('a');
        parser.href = url;
        if(url.indexOf(parser.protocol + '//' + parser.hostname) < 0) {
            return parser.href;
        }
        return url.replace(parser.protocol + '//' + parser.hostname,  parser.protocol + '//' + parser.hostname.split('.').map(function(part) {return sp_punycode.toASCII(part)}).join('.'));
    }



    return {
        init                : init,
        didInit             : false,
        setOptions          : setOptions,
        //isEmailValid        : isEmailValid,
        updateSignupEmail   : updateSignupEmail,
        validateKey         : validateKey,
        enableResize        : enableResize,
        setupGeneralTab     : setupGeneralTab,
  //      apiKeyChanged       : apiKeyChanged,
        checkThumbsUpdTotal : checkThumbsUpdTotal,
        initSettings        : initSettings,
      //  switchSettingsTab   : switchSettingsTab,
      //  closeHelpPane       : closeHelpPane,
        checkQuota          : checkQuota,
        percentDial         : percentDial,
      //  initFolderSelector  : initFolderSelector,
    //    browseContent       : browseContent,
        newApiKey           : newApiKey,
  //      includeUnlisted     : includeUnlisted,
        checkRandomAnswer : checkRandomAnswer,
      //  recheckQuota        : recheckQuota,
        openImageMenu       : openImageMenu,
        menuCloseEvent      : false,
        convertPunycode     : convertPunycode,
      //  checkExifWarning    : checkExifWarning,
      //  checkBackUpWarning  : checkBackUpWarning,
			//	checkSmartCropWarning: checkSmartCropWarning,
        toRefresh       : false,
        resizeSizesAlert: false,
        returnedStatusSearching: 0, // How often this status has come back in a row from server.

    }
}(); // End of SPAATG

// first is string to replace, rest are arguments.
function SPstringFormat() {
  var params = Array.prototype.slice.call(arguments);

  if (params.length === 0)
      return;

   var s = params.shift();

    // skip the first one.
    for (i=0; i< params.length; i++) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }
    return s;
};
/** This doesn't go well with REACT environments */
/*if (!(typeof String.prototype.format == 'function')) {
    String.prototype.format = stringFormat;
} */


( function( $, w, d ) {
    w.SpaatgResize = {
        image : {
            width  : 0,
            height : 0
        },
        lag: 2000,
        step1: false,
        step2: false,
        step3: false,
        sizeRule: null,
        initialized: false,
        lastW: false,
        lastH: false,
        lastType: false,
    };

    SpaatgResize.hide = function() {
        jQuery('.presentation-wrap').css('opacity', 0);
    }

    SpaatgResize.animate = function(img, step1, frame, step2, rule) {
        img.animate( step1, 1000, 'swing', function(){
            SpaatgResize.step3 = setTimeout(function(){
                document.styleSheets[0].deleteRule(SpaatgResize.sizeRule);
                frame.animate(step2, 1000, 'swing', function() {
                    SpaatgResize.sizeRule = document.styleSheets[0].insertRule(rule);
                })
            }, 600);
        });

    }

    SpaatgResize.run = function() {
        if(!SpaatgResize.initialized) {
            var $document = $( d );
            $document.on( 'input change', 'input[name="resizeWidth"], input[name="resizeHeight"]', function(e) {
                clearTimeout(SpaatgResize.change);
                SpaatgResize.changeDone = true;
                SpaatgResize.changeFired = false;
                SpaatgResize.change = setTimeout( function() {
                    SpaatgResize.changeFired = true;
                    SpaatgResize.run();
                }, 1500 );
            } );
            $document.on( 'blur', 'input[name="resizeWidth"], input[name="resizeHeight"]', function(e) {
                if(SpaatgResize.changeFired) {
                    return;
                }
                clearTimeout(SpaatgResize.change);
                SpaatgResize.change = setTimeout( function() {
                    SpaatgResize.run();
                }, 1500 );
            } );
            $document.on( 'change', 'input[name="resizeType"]', function(e) {
                SpaatgResize.run();
            });
            SpaatgResize.initialized = true;
        }

        var w = $('#width').val();
        var h = $('#height').val();
        if(!w || !h) return;
        var type = ($('#resize_type_outer').is(':checked') ? 'outer' : 'inner');
        if(w === SpaatgResize.lastW && h === SpaatgResize.lastH && type === SpaatgResize.lastType) {
            return;
        }
        SpaatgResize.hide();
        SpaatgResize.lastW = w;
        SpaatgResize.lastH = h;
        SpaatgResize.lastType = type;

        var frame1W = Math.round(120 * Math.sqrt(w / h));
        var frame1H = Math.round(120 * Math.sqrt(h / w));
        var frameAR = frame1W / frame1H;
        if(frame1W > 280) {
            frame1W = 280; frame1H = Math.round(280 / frameAR);
        }
        if(frame1H > 150) {
            frame1H = 150; frame1W = Math.round(150 * frameAR);
        }
        var imgAR = 15 / 8;
        var img = $('img.spai-resize-img');
        img.css('width', '');
        img.css('height', '');
        img.css('margin', '0px');
        var frame = $('div.spai-resize-frame');
        frame.css('display', 'none');
        frame.css('width', frame1W + 'px');
        frame.css('height', frame1H + 'px');
        frame.css('margin', Math.round((156 - frame1H ) / 2) + 'px auto 0');

        clearTimeout(SpaatgResize.step1); clearTimeout(SpaatgResize.step2); clearTimeout(SpaatgResize.step3);
        img.stop(); frame.stop();

        if(SpaatgResize.sizeRule !== null) {
            document.styleSheets[0].deleteRule(SpaatgResize.sizeRule);
            SpaatgResize.sizeRule = null;
        }
        SpaatgResize.sizeRule = document.styleSheets[0].insertRule('.spai-resize-frame:after { content: "' + w + ' × ' + h + '"; }');
        frame.addClass('spai-resize-frame');

        $('.presentation-wrap').animate( {opacity: 1}, 500, 'swing', function(){
            //because damn chrome is not repainting the frame after we change the sizes otherwise... :(
            frame.css('display', 'block');

            SpaatgResize.step2 = setTimeout(function(){
                if(type == 'outer') {
                    if(imgAR > frameAR) {
                        var step1 = {
                            height: frame1H + 'px',
                            margin: Math.round((160 - frame1H) / 2) + 'px 0px'
                        };
                        var frameNewW = frame1H * imgAR;
                        var step2 = { width: Math.round(frameNewW) + 'px' };
                        var rule = '.spai-resize-frame:after { content: "' + Math.round(frameNewW * w / frame1W) + ' × ' + h + '"; }';
                    } else {
                        var step1 = {
                            width: frame1W + 'px',
                            margin: Math.round((160 - frame1W / imgAR) / 2) + 'px 0px'
                        };
                        var frameNewH = frame1W / imgAR;
                        var step2 = {
                            height: Math.round(frameNewH) + 'px',
                            margin: Math.round((156 - frameNewH) / 2) + 'px auto 0'
                        };
                        var rule = '.spai-resize-frame:after { content: "' + w + ' × ' + Math.round(frameNewH * w / frame1W) + '"; }';

                    }
                } else {
                    if(imgAR > frameAR) {
                        var step1 = {
                            width: frame1W,
                            margin: Math.round((160 - frame1W / imgAR) / 2) + 'px 0px'
                        };
                        var frameNewH = frame1W / imgAR;
                        var step2 = {
                            height: Math.round(frameNewH) + 'px',
                            margin: Math.round((156 - frameNewH) / 2) + 'px auto 0'
                        };
                        var rule = '.spai-resize-frame:after { content: "' + w + ' × ' + Math.round(frameNewH * w / frame1W) + '"; }';
                    } else {
                        var step1 = {
                            height: frame1H,
                            margin: Math.round((160 - frame1H) / 2) + 'px 0px'
                        };
                        var frameNewW = frame1H * imgAR;
                        var step2 = {
                            width: Math.round(frameNewW) + 'px'
                        };
                        var rule = '.spai-resize-frame:after { content: "' + Math.round(frameNewW * w / frame1W) + ' × ' + h + '"; }';
                    }
                }
                SpaatgResize.animate(img, step1, frame, step2, rule);
            }, 1000);
        });
    }

    $( function() {
        if($('#resize').is('checked')) {
            SpaatgResize.run();
        }
    } );
} )( jQuery, window, document );
