/*!
 * Shortcodes Media Helper Functions
 * Copyright (c) 2014 Intense Visions, Inc.
 */

/* global wp */
/* exported loadFileFrame, loadImageFrame, loadVideoFrame, loadVideoFrame */
/* jshint -W061 */

var frame;

function loadFileFrame($button, callback) {
	if (typeof(frame) !== 'undefined') {
		frame.close();
	}

	// Create the media frame.
	frame = wp.media.frames.file_frame = wp.media({
		title: $button.data('uploader_title'),
		button: {
			text: $button.data('uploader_button_text')
		},
		multiple: false // Set to true to allow multiple files to be selected
	});

	// When an image is selected, run a callback.
	frame.on('select', function() {
		// We set multiple to false so only get one image from the uploader
		var attachment = frame.state().get('selection').first().toJSON();

		if (callback) {
			callback(attachment);
		}
	});

	// Finally, open the modal
	frame.open();
}

function loadImageFrame($button, callback) {
	if (typeof(frame) !== 'undefined') {
		frame.close();
	}

	// Create the media frame.
	frame = wp.media.frames.file_frame = wp.media({
		title: $button.data('uploader_title'),
		button: {
			text: $button.data('uploader_button_text')
		},
		library: {
		//	type: 'image'
		},
		multiple: false // Set to true to allow multiple files to be selected
	});

	// When an image is selected, run a callback.
	frame.on('select', function() {
		// We set multiple to false so only get one image from the uploader
		var attachment = frame.state().get('selection').first().toJSON();

		if (callback) {
			callback(attachment);
		}
	});

	// Finally, open the modal
	frame.open();
}

function loadVideoFrame($button, callback) {
	if (typeof(frame) !== 'undefined') {
		frame.close();
	}

	// Create the media frame.
	frame = wp.media.frames.file_frame = wp.media({
		title: $button.data('uploader_title'),
		button: {
			text: $button.data('uploader_button_text')
		},
		library: {
			type: 'video'
		},
		multiple: false // Set to true to allow multiple files to be selected
	});

	// When an image is selected, run a callback.
	frame.on('select', function() {
		// We set multiple to false so only get one image from the uploader
		var attachment = frame.state().get('selection').first().toJSON();

		if (callback) {
			callback(attachment);
		}
	});

	// Finally, open the modal
	frame.open();
}

// Loads the media upload tool with multiselect and executes
// the callback after images has been selected
function loadGalleryFrame($button, callback) {
	if (typeof(frame) !== 'undefined') {
		frame.close();
	}

	// Create the media frame.
	frame = wp.media.frames.file_frame = wp.media({
		title: $button.data('uploader_title'),
		button: {
			text: $button.data('uploader_button_text')
		},
		library: {
			type: 'image'
		},
		multiple: true // Set to true to allow multiple files to be selected
	});

	// When an image is selected, run a callback.
	frame.on('select', function() {
		// We set multiple to false so only get one image from the uploader
		var selection = frame.state().get('selection');
		var attachments = [];

		selection.map(function(attachment) {
			attachment = attachment.toJSON();
			attachments.push(attachment);
		});

		if (callback) {
			callback(attachments);
		}
	});

	// Finally, open the modal
	frame.open();
}

function strip_tags(input, allowed) {
  //  discuss at: http://phpjs.org/functions/strip_tags/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Luke Godfrey
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Pul
  //    input by: Alex
  //    input by: Marc Palau
  //    input by: Brett Zamir (http://brett-zamir.me)
  //    input by: Bobby Drake
  //    input by: Evertjan Garretsen
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Onno Marsman
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Eric Nagel
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Tomasz Wesolowski
  //  revised by: Rafał Kukawski (http://blog.kukawski.pl/)
  //   example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
  //   returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
  //   example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
  //   returns 2: '<p>Kevin van Zonneveld</p>'
  //   example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
  //   returns 3: "<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>"
  //   example 4: strip_tags('1 < 5 5 > 1');
  //   returns 4: '1 < 5 5 > 1'
  //   example 5: strip_tags('1 <br/> 1');
  //   returns 5: '1  1'
  //   example 6: strip_tags('1 <br/> 1', '<br>');
  //   returns 6: '1 <br/> 1'
  //   example 7: strip_tags('1 <br/> 1', '<br><br/>');
  //   returns 7: '1 <br/> 1'

  allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
  return input.replace(commentsAndPhpTags, '')
    .replace(tags, function ($0, $1) {
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

function rawurlencode(str) {
  //       discuss at: http://phpjs.org/functions/rawurlencode/
  //      original by: Brett Zamir (http://brett-zamir.me)
  //         input by: travc
  //         input by: Brett Zamir (http://brett-zamir.me)
  //         input by: Michael Grier
  //         input by: Ratheous
  //      bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //      bugfixed by: Brett Zamir (http://brett-zamir.me)
  //      bugfixed by: Joris
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //             note: This reflects PHP 5.3/6.0+ behavior
  //             note: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
  //             note: pages served as UTF-8
  //        example 1: rawurlencode('Kevin van Zonneveld!');
  //        returns 1: 'Kevin%20van%20Zonneveld%21'
  //        example 2: rawurlencode('http://kevin.vanzonneveld.net/');
  //        returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
  //        example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
  //        returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

  str = (str + '')
    .toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .
  replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
}

function rawurldecode(str) {
  //       discuss at: http://phpjs.org/functions/rawurldecode/
  //      original by: Brett Zamir (http://brett-zamir.me)
  //         input by: travc
  //         input by: Brett Zamir (http://brett-zamir.me)
  //         input by: Ratheous
  //         input by: lovio
  //      bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: Please be aware that this function expects to decode from UTF-8 encoded strings, as found on
  //             note: pages served as UTF-8
  //        example 1: rawurldecode('Kevin+van+Zonneveld%21');
  //        returns 1: 'Kevin+van+Zonneveld!'
  //        example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
  //        returns 2: 'http://kevin.vanzonneveld.net/'
  //        example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
  //        returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'

  return decodeURIComponent((str + '')
    .replace(/%(?![\da-f]{2})/gi, function () {
      // PHP tolerates poorly formed escape sequences
      return '%25';
    }));
}

function base64_encode(data) {
  //  discuss at: http://phpjs.org/functions/base64_encode/
  // original by: Tyler Akins (http://rumkin.com)
  // improved by: Bayron Guevara
  // improved by: Thunder.m
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Rafał Kukawski (http://kukawski.pl)
  // bugfixed by: Pellentesque Malesuada
  //   example 1: base64_encode('Kevin van Zonneveld');
  //   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  //   example 2: base64_encode('a');
  //   returns 2: 'YQ=='
  //   example 3: base64_encode('✓ à la mode');
  //   returns 3: '4pyTIMOgIGxhIG1vZGU='

  var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = '',
    tmp_arr = [];

  if (!data) {
    return data;
  }

  data = unescape(encodeURIComponent(data));

  do {
    // pack three octets into four hexets
    o1 = data.charCodeAt(i++);
    o2 = data.charCodeAt(i++);
    o3 = data.charCodeAt(i++);

    bits = o1 << 16 | o2 << 8 | o3;

    h1 = bits >> 18 & 0x3f;
    h2 = bits >> 12 & 0x3f;
    h3 = bits >> 6 & 0x3f;
    h4 = bits & 0x3f;

    // use hexets to index into b64, and append result to encoded string
    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  } while (i < data.length);

  enc = tmp_arr.join('');

  var r = data.length % 3;

  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}

function base64_decode(data) {
  //  discuss at: http://phpjs.org/functions/base64_decode/
  // original by: Tyler Akins (http://rumkin.com)
  // improved by: Thunder.m
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Aman Gupta
  //    input by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Onno Marsman
  // bugfixed by: Pellentesque Malesuada
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //   example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  //   returns 1: 'Kevin van Zonneveld'
  //   example 2: base64_decode('YQ===');
  //   returns 2: 'a'
  //   example 3: base64_decode('4pyTIMOgIGxhIG1vZGU=');
  //   returns 3: '✓ à la mode'

  var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    dec = '',
    tmp_arr = [];

  if (!data) {
    return data;
  }

  data += '';

  do {
    // unpack four hexets into three octets using index points in b64
    h1 = b64.indexOf(data.charAt(i++));
    h2 = b64.indexOf(data.charAt(i++));
    h3 = b64.indexOf(data.charAt(i++));
    h4 = b64.indexOf(data.charAt(i++));

    bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

    o1 = bits >> 16 & 0xff;
    o2 = bits >> 8 & 0xff;
    o3 = bits & 0xff;

    if (h3 == 64) {
      tmp_arr[ac++] = String.fromCharCode(o1);
    } else if (h4 == 64) {
      tmp_arr[ac++] = String.fromCharCode(o1, o2);
    } else {
      tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
    }
  } while (i < data.length);

  dec = tmp_arr.join('');

  return decodeURIComponent(escape(dec.replace(/\0+$/, '')));
}

/*!
 * Shortcodes Dialogs Helper Functions
 */

function intenseRefreshPreview() {
	var $ = jQuery;

	if ($('#preview-content').length > 0) {
		$('#preview').click();
	}
}

function intenseRenderDialog(shortcode, preset) {
	var $ = jQuery;

	$('#intense-shortcode-selector').css('max-width', '1000px');
	$('.intense-shortcodes').hide();
	$('.intense-shortcode-input').show().html('<center><img src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="padding: 100px;"></center>');
	$('.intense-shortcode-filter').hide();

	var active_skin = $('#intense-active-skin').val();

	$.ajax({
		type: 'POST',
		url: ajaxurl + '?action=intense_shortcode_dialog_action&shortcode=' + shortcode + '&preset=' + preset + "&skin=" + active_skin,
		beforeSend: function() {

		},
		success: function(data) {
			$('#intense-shortcode-selector').css('max-width', '1000px');
			$('.intense-shortcode-input').html(data);

			var previewXHR = null;

			$('.intense-shortcodes-back, .intense-shortcodes-help').show();
			$('#preview').click(function() {
				var shortcodeContent = eval($(this).data('function'));
				var shortcodeClass = $(this).data('shortcode-class');
				var $previewcontent = $('<div id="preview-content"></div>');
				var activeTab = 0;

				if (previewXHR) {
					previewXHR.abort();
				}

				previewXHR = $.ajax({
					type: 'POST',
					url: ajaxurl + '?action=intense_shortcode_preview_action',
					cache: false,
					data: {
						security: $('#nonce').val(),
						shortcode: shortcodeContent,
						'shortcode-class': shortcodeClass
					},
					beforeSend: function() {
						if ($('#preview-content').length === 0) {
							$('#shortcode-form .form-actions').append($previewcontent);
						} else {
							var i = 0;

							$('#preview-content > .nav.nav-tabs > li').each(function() {
								if ($(this).hasClass('active')) {
									activeTab = i;
								}

								i++;
							});
						}

						$('#preview-content').parent().find('.intense-preview-loader').remove();
						$('#preview-content').parent().prepend('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right;" />');
					},
					success: function(data) {
						$('#preview-content').parent().find('.intense-preview-loader').remove();
						$('#preview-content').remove();
						$('#shortcode-form .form-actions').append($previewcontent);
						$previewcontent.html(data);
						// These were causing the editor not to insert shortcode. Probably 
						// re-initializing the editor and messing things up
						//$(document).trigger('ready');
						//$(window).trigger('load');
						$('#preview-content > .nav.nav-tabs > li').removeClass('active');
						$($('#preview-content > .nav.nav-tabs > li')[activeTab]).addClass("active");
						$('#preview-content > .tab-content > .tab-pane').removeClass('active');
						$($('#preview-content > .tab-content > .tab-pane')[activeTab]).addClass("active");
						
						if ( typeof(intenseLoadGalleries) == 'function') {
							intenseLoadGalleries();
						}
						
						previewXHR = null;
					}
				});
			});

			//intenseSetupPresets();
			intenseInitializeRepeater();
		},
		dataType: 'html'
	});
}

function intenseResetDialog() {
	var $ = jQuery;

	$('#intense-shortcode-selector').css('max-width', '1000px');
	$('.intense-shortcode-input').fadeOut().html('');
	$('.intense-shortcodes-back, .intense-shortcodes-help').hide();
	$('.shortcode-help').remove();
	$('.intense-shortcodes-help').find('.dashicons').remove();
	$('.intense-shortcodes').fadeIn();
	$('.intense-shortcode-filter').show();
	setTimeout(function() { $('.intense-shortcode-filter > input').val('').focus(); },50);
	$('.intense-shortcode-filter > input').keyup();
	$('.intense.shortcode-list > li').css("opacity", 1).css("background-color", "#fff");
}

/*!
 * Shortcodes Repeater Helper Functions
 */

function intenseInitializeRepeater() {
	var $ = jQuery;

	$('.of-color.minicolors-input', $('.repeater-item-model')).minicolors('destroy');

	$('.repeater-add').click(function() {
		var $repeaterItem = $('.repeater-item-model').clone();
		var html = $repeaterItem.html().replace(/_id/g, '_' + $('.repeater-item').length); //set up ids

		$('.of-color.minicolors-input', $('.repeater-item-model')).minicolors('destroy');

		$repeaterItem.html(html);
		$repeaterItem.removeClass('repeater-item-model').addClass('repeater-item');
		$repeaterItem.find(".repeater-number").html($('.repeater-item').length + 1);

		$('.repeater-add').before($repeaterItem);

		intenseInitShortcode();

		$repeaterItem.slideDown();

		$repeaterItem.find('[data-toggle="tab"]').each(function() {
			var originalID = $(this).attr('href');
			var newID = originalID + '_' + $('.repeater-item').length;

			$(this).attr('href', newID);
		});

		$repeaterItem.find('.tab-pane').each(function() {
			var originalID = $(this).attr('id');
			var newID = originalID + '_' + $('.repeater-item').length;

			$(this).attr('id', newID);
		});

		intenseRefreshPreview();
	});

	$(document).on('click', '.repeater-remove', function() {
		var $item = $(this).parents('.repeater-item');

		$item.fadeOut(400, function() {
			$item.remove();

			var items = $('.repeater-item');
			var count = $('.repeater-item').length;

			for (var i = 0; i < count; i++) {
				$(items[i]).find(".repeater-number").html(i + 1);
			}
		});
	});

	$(document).on('click', '.repeater-hide', function() {
		var $content = $('.repeater-content', $(this).parents('.repeater-item'));

		$content.toggle();

		if ($content.is(':visible')) {
			$(this).html('&minus;');
		} else {
			$(this).html('&plus;');
		}
	});
}

/*!
 * Shortcodes Presets Helper Functions
 */

function intenseRenderPresets(shortcode) {
	var $ = jQuery;

	$.ajax({
		type: 'POST',
		url: ajaxurl + '?action=intense_shortcode_presets_action',
		cache: false,
		data: {
			security: $('#nonce').val(),
			shortcode: shortcode
		},
		beforeSend: function() {
			$('#preset-list-footer').append('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right;" />');
		},
		success: function(data) {
			$('#preset-list-footer').find('.intense-preview-loader').remove();
			$('#preset-list-content').html(data);
			intenseSetupPresets();
		}
	});
}

function intenseSetupPresets() {
	var $ = jQuery;

	$('#save').click(function() {
		var shortcodeContent = eval($(this).data('function'));
		var shortcodeClass = $(this).data('shortcode-class');
		var key = $('#key').val();
		var activeTab = 0;

		$.ajax({
			type: 'POST',
			url: ajaxurl + '?action=intense_shortcode_save_action',
			cache: false,
			data: {
				security: $('#nonce').val(),
				shortcode: shortcodeContent,
				'shortcode-class': shortcodeClass,
				key: key
			},
			beforeSend: function() {
				$('#preset-list-footer').append('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right;" />');
			},
			success: function(data) {
				$('#preset-list-footer').find('.intense-preview-loader').remove();
				intenseRenderPresets(shortcodeClass);
			}
		});
	});

	$("#presets").click(function(e) {
		$('#preset-list').toggle();
		e.stopPropagation();
	});

	$('#preset-list').click(function(e) {
		e.stopPropagation();
	});

	$(document).click(function() {
		$('#preset-list').hide();
	});

	$(".preset-list-item").click(function() {
		var preset = $(this).parent().attr('id').replace('preset-list-item-', '');
		var shortcode = $('#shortcode-form').data('shortcode');

		intenseRenderDialog(shortcode, preset);
	});

	$(".preset-list-remove").click(function(e) {
		var preset = $(this).parent().attr('id').replace('preset-list-item-', '');
		var shortcode = $('#shortcode-form').data('shortcode');

		e.preventDefault();

		$.ajax({
			type: 'POST',
			url: ajaxurl + '?action=intense_shortcode_remove_action',
			cache: false,
			data: {
				security: $('#nonce').val(),
				shortcode: shortcode,
				key: preset
			},
			beforeSend: function() {
				$('#preset-list-footer').append('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right;" />');
			},
			success: function(data) {
				$('#preset-list-footer').find('.intense-preview-loader').remove();
				intenseRenderPresets(shortcode);
			}
		});
	});
}

/*!
 * Snippet Functions
 */

function intenseResetSnippetDialog() {
	var $ = jQuery;
	var $snippetSelect = $('#snippet-selection');
}

function intenseLoadSnippets() {
	var $ = jQuery;

	if (!$('#snippet-selection').data('initialized')) {
		$('#snippet-selection').data('initialized', true);

		$.ajax({
			type: 'POST',
			url: ajaxurl + '?action=intense_load_snippets_action',
			cache: false,
			dataType: 'json',
			data: {
				security: $('#nonce').val()
			},
			beforeSend: function() {
				$('#snippet-form .form-actions').append('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right; margin-top: -10px;" />');
			},
			success: function(data) {
				var $snippetSelect = $('#snippet-selection');

				$snippetSelect.data('snippets', data);

				$('#snippet-form .form-actions').find('.intense-preview-loader').remove();

				$snippetSelect.children().remove();

				$snippetSelect.append(
					$("<option></option>")
					.attr("value", '')
					.text('')
					.data("content", '')
				);

				$.each(data, function(i, location) {
					$option_group = $('<optgroup label="' + location.title + '">');

					$.each(location.snippets, function(s, snippet) {
						$option_group.append(
							$("<option></option>")
							.attr("value", snippet.id)
							.text(snippet.title)
						);
					});

					$snippetSelect.append($option_group);
				});

				$snippetSelect.selectize({
					create: false,
					sortField: 'text',
					render: {
						option: function(item, escape) {
							return '<div>' + item.text + '</div>';
						},
						item: function(item, escape) {
							return '<div><i class="dashicons dashicons-intense-scissors" style="font-size: 15px;" title="' + item.text + '"></i> ' + item.text + '</div>';
						}
					},
					onChange: function(value) {
						var snippetdata = $('#snippet-selection').data('snippets');
						var content = '';
						var id = '';
						var title = '';

						$.each(snippetdata, function(i, location) {
							$.each(location.snippets, function(s, snippet) {
								if (snippet.id == value) {
									content = snippet.content;									
									id = snippet.id;
									title = snippet.title;
									return;
								}
							});
						});

						$('#snippet-content').val(content);
						$('#snippet-shortcode').html('[intense_snippet snippet_id="' + id + '" snippet_title="' + title + '"]');

						if (content === '') {
							$('#snippet-content').addClass('disabled').attr("disabled", "disabled");
						} else {
							$('#snippet-content').removeClass('disabled').attr("disabled", null);
						}
					}
				});
			}
		});
	}
}

/*!
 * Live Preview
 */

var intensePreviewTimer = null;

function intenseInitLivePreview() {
	var $ = jQuery;

	$('#post-preview').after('<span id="intense-live-preview">Live <input type="checkbox" id="intense-live-preview-toggle" /></span>');

	$(document).on('keyup', '.wp-editor-area, #title', intenseLivePreview);
	$(document).on('change', '.wp-editor-area, #title, #intense-live-preview-toggle, #comment_status, #ping_status', intenseLivePreview);

	$.each(tinyMCE.editors, function(i, e) {
		e.onChange.add(function(ed, l) {
			intenseLivePreview();
		});
	});
}

function intenseLivePreview() {
	var $ = jQuery;

	if ($('#intense-live-preview-toggle').prop('checked')) {
		clearTimeout(intensePreviewTimer);

		intensePreviewTimer = setTimeout(function() {
			$('#post-preview').click();
		}, 700);
	}
}

/*!
 * Shortcode Help
 */
function intenseShortcodeHelp() {
	var $ = jQuery;
	var $form = $('#shortcode-form');
	var shortcode = $form.data('shortcode');

	if ( $('.shortcode-help').length > 0 ) {
		$form.find('.shortcode-help').remove();
		$('.intense-shortcodes-help').find('.dashicons').remove();
	} else {
		$('.intense-shortcodes-help').append('<i class="dashicons dashicons-no-alt" style="width: auto; height: auto; line-height: inherit;"></i>');

		$.ajax({
			type: 'POST',
			url: ajaxurl + '?action=intense_shortcode_help_action',
			cache: false,
			data: {
				security: $('#nonce').val(),
				shortcode: shortcode
			},
			beforeSend: function() {
				$form.append('<img class="intense-preview-loader" src="' + intense_vars.plugin_url + '/assets/img/ajax-loader.gif" style="float: right;" />');
				$form.find('.shortcode-help').remove();
			},
			success: function(data) {
				$form.find('.intense-preview-loader').remove();
				$form.prepend('<div class="shortcode-help">' + data + '</div>');
				$('.shortcode-help').fadeIn();
			}
		});
	}
}

/*!
 * Initialize
 */

var intense_dialog_initialized = false;

jQuery(function($) {
	if (!intense_dialog_initialized) {
		//intenseInitLivePreview();

		//get selection on mouseover so you don't lose focus when the
		//button is clicked
		$('body').on('mouseover', '.intense-shortcode', function(e) {
			mce_selection_start = 0;
			mce_selection_end = 0;

			if (typeof qtrans_save != 'undefined') {
				if ($('.mce-tinymce:visible').length > 0) {
					mce_selection_start = tinyMCE.activeEditor.selection.getRng().startOffset;
					mce_selection_end = tinyMCE.activeEditor.selection.getRng().endOffset;
				} else {
					var ctl = document.getElementById('qtrans_textarea_content');
					mce_selection_start = ctl.selectionStart;
					mce_selection_end = ctl.selectionEnd;
				}
			}
		});

		// show dialog
		$('body').on('click', '.intense-shortcode', function(e) {
			e.preventDefault();

			$(this).magnificPopup({
				type: 'inline',
				alignTop: true,
				callbacks: {
					open: function() {
						intenseResetDialog();
					},
					afterClose: function() {
						intenseResetDialog();
					}
				}
			}).magnificPopup('open');
			return false;
		});

		$('body').on('click', '.intense-snippet', function(e) {
			e.preventDefault();

			$(this).magnificPopup({
				type: 'inline',
				alignTop: true,
				callbacks: {
					beforeOpen: function() {
						intenseLoadSnippets();
					},
					open: function() {
						intenseResetSnippetDialog();
					},
					afterClose: function() {
						intenseResetSnippetDialog();
					}
				}
			}).magnificPopup('open');
		});

		$('body').on('click', '#insert-snippet', function(e) {
			e.preventDefault();

			window.wp.media.editor.insert($('#snippet-content').val());

			$('.intense-snippet').magnificPopup('close');
		});

		$('body').on('click', '#insert-snippet-shortcode', function(e) {
			e.preventDefault();

			window.wp.media.editor.insert($('#snippet-shortcode').html());

			$('.intense-snippet').magnificPopup('close');
		});

		// filter shortcodes
		$('.intense-shortcode-filter > input').keyup(function() {
			if ($(this).val().length === 0) {
				$('.intense.shortcode-list > li').css("opacity", 1).css("background-color", "#fff");
			} else {
				var r = new RegExp($(this).val(), 'i');
				$('.intense.shortcode-list > li').css("opacity", 0.2).css("background-color", "#fff");
				$('.intense.shortcode-list > li').filter(function() {
					return $(this).text().match(r);
				}).css("color", "#000").css("opacity", 1).css("background-color", "#DCE7F1");
			}
		});

		// load shortcode specific dialog
		$('.intense.shortcode-list > li').click(function() {
			var shortcode = $(this).data('shortcode');
			intenseResetDialog();
			intenseRenderDialog(shortcode, '');
		});

		// handle back button
		$('.intense-shortcodes-back').click(intenseResetDialog);

		// handle help button
		$('.intense-shortcodes-help').click(intenseShortcodeHelp);

		// insert shortcode
		$('#intense-shortcode-selector').on('click', "input[name='insert']", function(e) {
			var shortcode = eval($(this).data('function'))();
			var previewContent = $(this).data('preview-content');
			var previewContentRegex = new RegExp(previewContent, "g");
			var cleanShortcode = shortcode.replace(/<br +\/>/gi, "\n").replace(previewContent, '');

			if (typeof qtrans_save != 'undefined') {
				var currentLanguageValue = document.getElementById('qtrans_textarea_content').value;
				var currentAllLanguagesValue = document.getElementById('content').value;
				var front = currentLanguageValue.substring(0, mce_selection_start);
				var back = currentLanguageValue.substring(mce_selection_end, currentLanguageValue.length);
				var newText = front + cleanShortcode + back;

				if ($('.mce-tinymce:visible').length > 0) {
					window.wp.media.editor.insert(cleanShortcode);
				} else {
					$('#qtrans_textarea_content').val(newText);
					switchEditors.go('content', qtrans_get_active_language());
				}
			} else {
				window.wp.media.editor.insert(cleanShortcode);
			}

			$('.intense-shortcode').magnificPopup('close');

			intenseLivePreview();

			e.preventDefault();
		});

		$('#intense-active-skin').change(function() {
			if ( $('#shortcode-form').length > 0 ) {
				var shortcode = $('#shortcode-form').data('shortcode');

				intenseRenderDialog( shortcode, '' );
			}
		});

		intense_dialog_initialized = true;
	}
});
