/*
 * Please see weepie-framework.php for more details.
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 * @version $Id: wpie-settings.js 170 2018-02-28 22:56:29Z Vincent Weber <weepie-plugins@outlook.com> $
 * @since 1.2
 */
var WPIESETT = (function($) {
	""; // fix for yuicompressor
	"use strict";
	var settings = {
		// declare public params
		currNsData					: {},
		currNsDatal10n				: {},
		settingsform 				: {},
		settingGrp					: '',
		resetBtn 					: {},
		showOnRequestEl 			: {},
		inActiveEl 					: {},
		loadingImg 					: {},
		togglethis					: {},
		descrIcons					: {},
		done						: false
	};

	// declare private params
	var valSetCookies = '1',
		valPopup 	  = '0',
		valBar 		  = '1',
		cssClassBody = 'wpie-settings-page',
		cssIdEiTextarea = 'wpie-ei-textarea',
		cssIdBtnExport = 'wpie-btn-export',
		cssIdBtnImport = 'wpie-btn-import',
		cssIdEiMessage = 'wpie-ei-message',
		cssIdExportDownloadLink = 'wpie-export-file-link',
		ajaxActionExport = 'wpie-settings-export',
		ajaxActionImport = 'wpie-settings-import';

	// extend
	var extend = {
		wpieTablerows: function() {
			$('tbody tr:even', this).addClass('alternate');
			$('tbody tr:last', this).addClass('last');
		},
		showRow: function () {
			var field = $(this);

	  		field.parents('td').css({'padding':'', 'min-height':'', 'height':''});
		  	field.parents('td').siblings('th').show();
		},
		hideRow: function () {
			var field = $(this);

		  	field.parents('td:first').css({'padding-top':'0','padding-bottom':'0', 'min-height':'0', 'height':'0'});
		  	field.parents('tr:first').addClass('noborder');
		  	// hide title
		  	field.parents('td:first').siblings('th').hide();
		},
		showField: function () {
			var field = $(this);

			if(field.is(':disabled')) {
				field.removeAttr('disabled');
			}

		  	field.data('active', 'yes');
		  	field.attr('data-active', 'yes');
		},
		hideField: function () {
			var field = $(this);

		  	field.data('active', 'no');
		  	field.attr('data-active', 'no');
		},
		isCheckbox: function() {
			var el = $(this);

			if(!el.length) {
				return false;
			} else if('checkbox' !== el[0].type) {
				return false;
			} else {
				return true;
			}
		},
		isChecked: function() {
			var el = $(this);

			if(!el.isCheckbox()) {
				return;
			}

			return (el.is(':checked'));
		},
		cbCheck: function(status) {
			if('undefined' === typeof status) {
				status = true;
			}
			if('boolean' !== typeof status) {
				if(0 === parseInt(status)) {
					status = false;
				} else if(1 === parseInt(status)) {
					status = true;
				}
			}
			$(this).prop('checked', status);

			if(status) {
				$(this).addClass('checked');
			} else {
				$(this).removeClass('checked');
			}

			// allow chaining
			return $(this);
		}
	}

	/** private methods **/
	var showRows = function () {
		$(this).showRow();
	}

	var hideRows = function () {
		$(this).hideRow();
	}

	/**
	 * Success handler for the export process
	 *
	 * @param {Object} r
	 */
	var exportSuccess = function(r) {
		try {
			if(null == r) {
				WPIESETT.errorResponseMsg(r);
			} else {
				switch(r.state) {
					case '0':
					  settings.errorResponseMsg(r);
						break;
					case '1':
						if(r.out.exported) {
							if(r.out.msg) {
							  $('#' + cssIdEiMessage)
								  .html(r.out.msg)
								  .addClass('wpie-green')
								  .show();
							}
							$('#' + cssIdEiTextarea).val(r.out.exported).trigger('focus').trigger('select');
							$('#' + cssIdExportDownloadLink).attr('href', 'data:application/octet-stream,' + r.out.exported);
						}
				  break;
				}
			}
		} catch(exc) {
			WPIE.log(exc.message, exc);
		}
	}

	/**
	 * Success handler for the import process
	 *
	 * @param {Object} r
	 */
	var importSuccess = function(r) {
		try {
			if(null == r) {
				WPIESETT.errorResponseMsg(r);
			} else {
				switch(r.state) {
				case '0':
					settings.errorResponseMsg(r);
					break;
		  		case '1':
		  			if(r.out.imported) {
						if(r.out.msg) {
							$('#' + cssIdEiMessage)
								.html(r.out.msg)
								.addClass('wpie-green')
								.show();
						  }
						  setTimeout(function() {
							location.reload(true);
						  }, 3000);
		  			}
			    break;
			  }
			}
		} catch(exc) {
			WPIE.log(exc.message, exc);
		}
	}

	/** public methods	**/
	settings.errorResponseMsg = function(r) {
		if(null == r || !r.errors || !r.errors.length) {
			WPIE.alert(this.currNsDatal10n.unknown_error);
		} else if(r.errors && r.errors.length) {
			WPIE.log(r.errors);
			WPIE.alert(this.currNsDatal10n.error_occured);
		}
	}

	settings.showRow = function(el) {
		if('undefined' === typeof el || (el && 0 === el.length)) {
			return;
		}

		var row = el.parents('tr'),
			rowDescr;

		if(0 === row.length) {
			return;
		}

		rowDescr = row.next('.description');

		row.show().find('input, select').prop('disabled', false);
		rowDescr.show();
	}

	settings.hideRow = function(el) {
		if('undefined' === typeof el || (el && 0 === el.length)) {
			return;
		}

		var row = el.parents('tr'),
			rowDescr;

		if(0 === row.length) {
			return;
		}

		rowDescr = row.next('.description');

		row.hide().find('input, select')
		//.prop('disabled', true)
		;
		rowDescr.hide();
	}

	settings.showHideRowForCheckbox = function($this, el) {
		if(0 === $this.length || 0 === el.length) {
			return;
		}

		if($this.isChecked()) {
			this.showRow(el);
		} else {
			this.hideRow(el);
		}
	}

	settings.showGroup = function(show) {
		if(0 === show.length) {
			return;
		}
		show.prev('h3').show();
		show.show().find('input, select').prop('disabled', false);
	}

	settings.hideGroup = function(hide) {
		if(0 === hide.length) {
			return;
		}
		hide.prev('h3').hide();
		hide.hide().find('input, select')
		//.prop('disabled', true)
		;
	}

	settings.showHideGroup = function(show, hide) {
		if(0 === show.length || 0 === hide.length) {
			return;
		}

		this.showGroup(show);
		this.hideGroup(hide);
	}

	settings.getAjaxArgs = function(action, data, ns) {
		return WPIE.getAjaxArgs(action, data, ns);
	}


	settings.handlerCheckboxClick = function (e) {
		if( !$(this).hasClass('checked') || $(this).hasClass('unchecked') ) {
			$(this).removeClass('unchecked');
			$(this).addClass('checked');
		} else {
			$(this).removeClass('checked');
			$(this).addClass('unchecked');
		}
	}

	settings.handlerResetSettings = function (e) {
		var thiz = e.data.thiz;

		if (confirm(thiz.currNsDatal10n.reset_confirm)) {
			thiz.settingsform.submit(function(d) {
				$('input[wpie_do_reset]"]').val('1');

				return true;
			});
		} else {
			e.preventDefault();
			return false;
		}
	}

	/**
	 * Handler for toggling an element
	 *
	 * @param object e
	 *
	 * @returns void
	 */
	settings.handlerToggle = function(e) {
		var thiz = e.data.thiz, toggler = $(this);

		toggler.next('.togglethis').slideToggle('fast', function() {
			var togglethis = $(this);

			if(togglethis.is(':visible')) {
				$(this).data('toggle-status', 'show');
				$(this).attr('data-toggle-status', 'show');
			} else {
				 $(this).data('toggle-status', 'hide');
				 $(this).attr('data-toggle-status', 'hide');
			}
		});
	}

	settings.handlerEachToggleThis = function(e) {
		var status = $(this).data('toggle-status');

		if('hide' === status) {
			$(this).hide();
		} else {
			$(this).show();
		}
	}

	settings.handlerToggleDescr = function(e) {
		var thiz = e.data.thiz, toggler = $(this);

		toggler.parents('tr').next('tr').find('.togglethis').slideToggle(75, function() {
			var togglethis = $(this);

			if(togglethis.is(':visible')) {
				$(this).data('toggle-status', 'show');
				$(this).attr('data-toggle-status', 'show');
			} else {
				 $(this).data('toggle-status', 'hide');
				 $(this).attr('data-toggle-status', 'hide');
			}
		});
	}

	/**
	 * Handler for click event on export button
	 *
	 * @param {Object} e
	 */
	settings.handlerExport = function(e) {
		var thiz = e.data.thiz,
			btn = $(this);

		if($('#' + cssIdEiTextarea).val() !== '') {
			alert('Settings already exported...');
			return;
		}

		// disable the button while exporting
		btn.prop('disabled', true);

		// setup ajax arguments
		var args = thiz.getAjaxArgs(ajaxActionExport, {});
		args['wpie_do_export'] = '1';
		args['ns'] = wpieData['curr_sett_ns'];

		// do ajax request
		$.post(ajaxurl, args, exportSuccess, 'json')
		// if fails, log the error
		.fail(function(XMLHttpRequest, textStatus, errorThrown) {
			WPIE.log(XMLHttpRequest.statusText);
			// enable the button after refreshing
			btn.prop('disabled', false);
			})
		.always(function() {

		});
	}

	/**
	 * Handler for click event on import button
	 *
	 * @param {Object} e
	 */
	settings.handlerImport = function(e) {
		var thiz = e.data.thiz,
			btn = $(this),
			content = $('#' + cssIdEiTextarea).val().trim();

		if(content === '') {
			alert('No content for import found...');
			return;
		}

		// disable the button while importing
		btn.prop('disabled', true);

		// setup ajax arguments
		var args = thiz.getAjaxArgs(ajaxActionImport, { content: content });
		args['wpie_do_import'] = '1';
		args['ns'] = wpieData['curr_sett_ns'];

		// do ajax request
		$.post(ajaxurl, args, importSuccess, 'json')
		// if fails, log the error
		.fail(function(XMLHttpRequest, textStatus, errorThrown) {
			WPIE.log(XMLHttpRequest.statusText);
			// enable the button after refreshing
			btn.prop('disabled', false);
			})
		.always(function() {

		});
	}

	/**
	 * Init all events
	 *
	 * @returns void
	 */
	settings.events = function() {
		// reset settings button
		this.resetBtn.on('click', {thiz:this}, this.handlerResetSettings);
		$('body.' + cssClassBody).on('click', '.toggler', {thiz:this}, this.handlerToggle);
		$('body.' + cssClassBody).on('click', '.descr-i', {thiz:this}, this.handlerToggleDescr);
		// export / import
		$('body.' + cssClassBody).on('click', '#' + cssIdBtnExport, {thiz:this}, this.handlerExport);
		$('body.' + cssClassBody).on('click', '#' + cssIdBtnImport, {thiz:this}, this.handlerImport);
		$('body.' + cssClassBody).on('click', '#' + cssIdEiTextarea, function(e) { $(this).trigger('focus').trigger('select') });
		$('#' + cssIdEiTextarea).on('change paste keyup', function(e) {
			var pasted = '';
			if(e.type === 'paste') {
				pasted = e.originalEvent.clipboardData.getData('text');
			}

			if($(e.currentTarget).val().length > 0 || pasted.length > 0) {
				$('#' + cssIdBtnExport).prop('disabled', true);
				$('#' + cssIdBtnImport).prop('disabled', false);
			} else {
				$('#' + cssIdBtnExport).prop('disabled', false);
				$('#' + cssIdBtnImport).prop('disabled', true);
			}
		 }).trigger('change');

	}

	/**
	 * Init the settings logic when the DOM is ready
	 *
	 * Tasks:
	 * 		- settings params
	 * 		- extending jQuery with methods
	 * 		- callings methods: this.events()
	 * 		- do CSS logic
	 *
	 */
	settings.init = function() {
		try {
			if(!window.wpieData) {
				throw new Error('Missing global param: wpieData');
			}

			var requiredGlobals = ['curr_sett_ns'];

			for(var i in requiredGlobals) {
				var param = requiredGlobals[i];
				if(null == wpieData[param]) {
					throw new Error('Missing global param: '+param);
				}
			}

			// namespace dependent global plugin data
			var data = WPIE.getNameSpaceData();
			this.currNsData = data.currNsData;
			this.currNsDatal10n = data.currNsDatal10n;

			// init DOM elements
			this.settingsform 				= $('form.wpie-settings-form');
			this.resetBtn 					= $('.wpie-btn-reset');
			this.showOnRequestEl 			= $('.showonrequest');
			this.inActiveEl 				= $('.in-active');
			this.loadingImg 				= $('img.ajax-loading');
			this.togglethis					= $('.togglethis');
			this.descrIcons					= $('.descr-i');

			// setting name
			this.settingGrp = this.settingsform.data('setting-group');

			// extend the jQuery with methods stored in param "extend"
			$.fn.extend(extend);

			// init all events
			this.events();

			// hide rows that we will show later on request
			$.each(this.showOnRequestEl, hideRows);
			$.each(this.inActiveEl, hideRows);

			// init toggle elements
			this.togglethis.each(this.handlerEachToggleThis);

			// set textarea CSS max-width to not exceed the table
			$('textarea').css( 'max-width', $('textarea').parent('td').innerWidth()+'px' );

			this.done = true;

		} catch (exc) {
			this.done = false;
			WPIE.log(exc.message);
		}
	}

	return settings;

})(jQuery || {}, WPIESETT || {});

jQuery(function($) {
	// call init method when DOM is ready
	WPIESETT.init();
});