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

	'use strict';

	$('.wpas-colorpicker').wpColorPicker();

	/*----------- Add Note -----------*/
	$('#wpadminbar .wpas-add-note > a').click(function (e) {
		e.preventDefault();

		// Get URL Parameters
		$.urlParam = function (name) {
			var results = new RegExp('[\\?&amp;]' + name + '=([^&amp;#]*)').exec(TB_url);
			return results[1] || 0;
		};

		// Retrieve variables
		var TB_url = $(this).attr('href');
		var TB_title = $(this).attr('title');
		var TB_width = $.urlParam('width');
		var TB_height = $.urlParam('height');

		// Show Thickbox & Resize it (only our modal)
		tb_show(TB_title, TB_url, false);
		$('.wpas-modal-inner').parents('#TB_window').css({
			width: TB_width + 'px',
			height: TB_height + 'px',
			marginLeft: '-' + parseInt((TB_width / 2), 10) + 'px'
		});
		$('.wpas-modal-inner').parents('#TB_ajaxContent').css({
			'padding': '0',
			'overflow': 'hidden'
		});

		return false;
	});

	/*----------- Edit / Delete Ticket TinyMCE -----------*/
	$('.wpas-edit').click(function (e) {
		e.preventDefault();
		var replyID = $(this).data('reply');
		var origin = $(this).data('origin');
		var originMsg = $('#' + origin).html();
		var wysiwygID = $(this).data('wysiwygid');

		// Handle Layout changes
		$('.' + origin).hide();
		$('#' + replyID).show();
		$('.' + replyID).show();

		// TinyMCE: Set original content
		tinyMCE.get(wysiwygID).setContent(originMsg);
	});
	$('.wpas-editcancel').click(function (e) {
		e.preventDefault();
		var replyID = $(this).data('reply');
		var origin = $(this).data('origin');
		var originMsg = $('#' + origin).html();
		var wysiwygID = $(this).data('wysiwygid');

		// Handle Layout changes
		$('.' + origin).show();
		$('#' + replyID).hide();
		$('.' + replyID).hide();

		// TinyMCE: empty content
		tinyMCE.get(wysiwygID).setContent('');
	});
	$('.wpas-delete').click(function (e) {
		if (confirm(wpasL10n.alertDelete)) {
			return true;
		} else {
			return false;
		}
	});

	/*----------- Style Settings Tab -----------*/
	if (document.location.href.indexOf('wpas-settings') > -1) {
		$('.form-table:not(:last)').after('<hr class="wpas_divider"/>');
	}

	/*----------- Add Predefined Messages to TinyMCE -----------*/
	$('.wpas-predefine').click(function (e) {
		e.preventDefault();
		var predefinedAnswer = $(this).attr('data-message');
		if (tinyMCE && tinyMCE.activeEditor && $('#wp-ticket_reply-wrap').hasClass('tmce-active')) {
			tinyMCE.execInstanceCommand('ticket_reply', "mceInsertContent", false, predefinedAnswer);
		} else {
			if (confirm(wpasL10n.alertQuickReplies)) {
				$('#ticket_reply-tmce').click();
			}
		}
	});

	/*----------- Button Color -----------*/
	$('#btn-color > button').click(function (e) {
		var btnColor = $(this).attr('class');
		var btnLabel = $(this).text();
		$('#btn-color > button span').remove();
		$(this).html(btnLabel + '<span>&nbsp;&#10003;</span>');
		$('#wpas_ticket_buttons_class').val(btnColor);
	});
});