/*
 * Please see weepie-framework.php for more details.
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 * @since 1.1.8
 */
jQuery(function($) {
	try {
		// possible message types
		// @since WP 5.3.0 updated is deprecated and mapped to "success"
		var msgTypes = ['error', 'success', 'warning', 'info', 'updated'],
			msgSelectors = [],
			classNotice = 'wpie-notice-msg',
			classUpdateNag = 'update-nag',
			idNoticeHolder = 'notice-holder',
			ajaxActionDismiss = 'wpie-dismiss-upgrade-notice',
			delayTime = 60000,
			animateTime = 333,
			i,
			type,
			notices,
			currNsData = '',
			nameSpace = '';

		// get the plugin namespace from the global wpieData object
		if(null != window['wpieData'] && null != wpieData['curr_sett_ns']) {
			currNsData = window[wpieData.curr_sett_ns + 'Data'];
			nameSpace = currNsData.ns;
		}

		// loop over possible types
		for(i in msgTypes) {
			type = msgTypes[i];

			// if on a setting page, add setting error css ID selector for type
			if('' !== nameSpace) {
				msgSelectors.push('#setting-error-'+nameSpace+'-'+type);
			}

			// add WordPress default selectors
			msgSelectors.push('.notice-'+type);
			// add WeePie selectors
			// TODO check if the wpie-* class is used
			msgSelectors.push('.wpie-'+type);
		}

		// add the 'update-nag' selector
		msgSelectors.push('.'+classUpdateNag);

		// add a WeePie specific notice class
		$.each(msgSelectors, function(k,v) {
			$(v).addClass(classNotice);

			// TODO check if the update-nag notice needs margin 0
			if('.'+classUpdateNag === v) {
				$(v).css({'margin':'0'});
			}
		});

		// append WP and non WP messages to the notice holder
		notices = $('.'+classNotice);
		notices
			.appendTo($('#'+idNoticeHolder))
			.css({'display':'block'});

		// hide the notice holder if its not an error
		if(0 < notices.length) {
			$('#'+idNoticeHolder+':not(:has(.error)):not(:has(.'+classUpdateNag+'))')
				.delay(delayTime)
				.animate({'height':'0px'}, animateTime, function(){ $(this).hide();});
		}

		// dissmiss notices
		$('.'+classNotice+'.is-dismissible').on('click', 'button' + '.notice-dismiss', function(e) {
			var btn = $(this),
				noticeWrapper = btn.parent('.'+classNotice),
				ns = noticeWrapper.data('ns');

			btn.prop('disabled', true);

			// setup ajax arguments
			var args = WPIE.getAjaxArgs(ajaxActionDismiss, {}, ns);
			args.data['ns'] = args.ns;

			// do ajax request
			$.post(ajaxurl, args)
			// if fails, log the error
			.fail(function(XMLHttpRequest, textStatus, errorThrown) {
				WPIE.log(XMLHttpRequest.statusText);
				})
			.always(function() {
				btn.prop('disabled', false);
			});
		});
	} catch(exc) {
		if(window['WPIE']) {
			WPIE.log(exc.message);
		} else {
			console.log(exc.message);
		}
	}
});