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

	'use strict';

	// Reading WordPress Options
	var wpas_json_str = wpas.replace(/&quot;/g, '"');
	var wpas_obj = $.parseJSON(wpas_json_str);

	// Convert size in bytes to human readable format
	function bytesToSize(bytes, precision) {
		var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
		var posttxt = 0;
		if (bytes === 0) return 'n/a';
		while (bytes >= 1024) {
			posttxt++;
			bytes = bytes / 1024;
		}
		return parseInt(bytes, 10).toFixed(precision) + " " + sizes[posttxt];
	}

	// Password repeat
	$('.wpas-checkpwd').keyup(function () {
		var basePwd = $('.wpas-pwd').val();
		var errorMessage = $(this).attr('data-validation');
		if ($(this).val() != basePwd) {
			this.setCustomValidity(errorMessage);
		} else {
			this.setCustomValidity('');
		}
	});

	// Lightweight Modal
	if (jQuery().easyModal) {
		$('.wpas-modal').easyModal({
			overlay: 0.4
		});
		$('.wpas-modal-trigger').click(function (e) {
			e.preventDefault();
			var modal = $(this).attr('href');
			$(modal).trigger('openModal');
		});
	}

	// Responsive Tables
	if (jQuery().ReStable) {
		$('#ticket_details').ReStable({
			rowHeaders: false,
			maxWidth: 768
		});
	}

	// YouTube Video onClick
	$('.wpas-youtube').click(function (e) {
		e.preventDefault();
		var ID = this.id,
			width = $(this).attr('width'),
			height = $(this).attr('height'),
			iframe = '<iframe width="' + width + '" height="' + height + '" src="//www.youtube.com/embed/' + ID + '?autoplay=1&vq=large&rel=0" frameborder="0" allowfullscreen></iframe>';
		$(this).replaceWith(iframe);
		return false;
	});

	// Live Search
	if (jQuery().searchbox) {
		$('#ticket_subject').attr('autocomplete', 'off').after('<div id="wpas-search-results"></div>');
		$('#ticket_subject').searchbox({
			url: '' + wpas_obj.global.baseUrl + '/?wpas_search=true&s=',
			param: 's',
			dom_id: '#wpas-search-results',
			delay: 50
		});
		$(document).bind('after.searchbox', function (e) {
			$('#ticket_subject').removeClass('wpas-loading');
		});
	}

	// Persist form's data client-side
	if (jQuery().sisyphus) {
		$('#wpas-new-reply').sisyphus();
		$('#wpas-new-ticket').sisyphus({
			onRestore: function (e) {
				/* Retrieve Tags */
				if (jQuery().tagsManager) {
					$('.tm-input').tagsManager({
						maxTags: 8,
						tagClass: 'wpas-tags'
					});
					// If input has value (input exists)
					if ($('.tm-input').val()) {
						var tagInput = $('.tm-input');
						var tags = tagInput.val().split(',');
						$.each(tags, function (index, value) {
							tagInput.tagsManager('pushTag', value);
						});
					}
				}
			}
		});
	}

	// Init tags (don't need to retrieve them)
	if (jQuery().tagsManager) {
		$('.tm-input').tagsManager({
			maxTags: 8,
			tagClass: 'wpas-tags'
		});
	}

	// Support for old browsers
	if (jQuery().placeholder) {
		$('input, textarea').placeholder();
	}

	// WYSIWYG Editor
	if (jQuery().wysihtml5) {
		$('.wpas-wysiwyg').wysihtml5({
			'locale': wpas_obj.global.locale,
			'image': false,
			'link': false,
			'lists': false,
			'blockquote': false,
			events: {
				"load": function () {
					// We don't want the Dropdown to be focusable
					$('.wpas .wysihtml5-toolbar .dropdown-toggle').attr('tabindex', '-1');
				}
			}
		});
	}

	// File Attachements: FilePicker (https://developers.inkfilepicker.com/docs/web/)
	if (typeof filepicker !== 'undefined') {
		filepicker.setKey(wpas_obj.attachments.fpApiKey);

		// Security Enabled
		if (typeof wpas_obj.attachments.fpPolicy !== 'undefined' || typeof wpas_obj.attachments.fpSignature !== 'undefined') {
			$('.filepicker').click(function (e) {
				filepicker.pickMultiple({
						policy: wpas_obj.attachments.fpPolicy,
						signature: wpas_obj.attachments.fpSignature,
						extensions: wpas_obj.attachments.allowedExtensions,
						services: wpas_obj.attachments.allowedServices,
						maxSize: wpas_obj.attachments.maxSize
					},
					function (InkBlob) {
						$('input[name="attachments"]').val(encodeURIComponent(JSON.stringify(InkBlob)));
						$.each(InkBlob, function (i, item) {
							$('.wpas-attachments-list').append('<li class="list-group-item"><a href="' + item.url + '?signature=' + wpas_obj.attachments.fpSignature + '&policy=' + wpas_obj.attachments.fpPolicy + '" target="_blank">' + item.filename + '</a> <span class="badge">' + bytesToSize(item.size) + '</span></li>');
						});
						// Answer is needed when uploading files
						if ($('#wpas-reply-wysiwyg').is(':focus')) {
							$('#wpas-reply-wysiwyg').prop('required', true);
						}
						if ($('#wpas-reply-textarea').is(':focus')) {
							$('#wpas-reply-textarea').prop('required', true);
						}
						$('.filepicker').html('<i class="glyphicon glyphicon-plus-sign" aria-hidden="true"></i> ' + wpasL10n.uploadAddMore);
					}
				);
			});
		}

		// Security disabled
		else {
			$('.filepicker').click(function (e) {
				filepicker.pickMultiple({
						extensions: wpas_obj.attachments.allowedExtensions,
						services: wpas_obj.attachments.allowedServices
					},
					function (InkBlob) {
						$('input[name="attachments"]').val(encodeURIComponent(JSON.stringify(InkBlob)));
						$.each(InkBlob, function (i, item) {
							$('.wpas-attachments-list').append('<li class="list-group-item"><a href="' + item.url + '" target="_blank">' + item.filename + '</a> <span class="badge">' + bytesToSize(item.size) + '</span></li>');
						});
					}
				);
			});
		}
	} else {
		if ($('.filepicker').length > 0) {
			$('.filepicker').replaceWith('<div class="alert alert-danger">' + wpasL10n.uploadIssue + '</div>');
		}
	}

	// File Attachements: FineUploader (http://docs.fineuploader.com/)
	if (jQuery().fineUploader) {
		$('#wpas_fileupload').fineUploader({
			template: 'wpas-qq-template',
			request: {
				endpoint: '' + wpas_obj.global.wpasUrl + 'includes/attachments.php'
			},
			validation: {
				allowedExtensions: wpas_obj.attachments.allowedExtensions,
				sizeLimit: wpas_obj.attachments.maxSize,
				itemLimit: wpas_obj.attachments.maxFiles
			},
			showMessage: function (message) {
				var modalupload = $('#wpas-modalupload').find('.modal-body').html(message);
				modalupload.trigger('openModal');
			},
			classes: {
				success: 'qq-upload-success wpas-alert-upload alert alert-success',
				fail: 'qq-upload-fail wpas-alert-upload alert alert-danger',
				dropActive: 'wpas-dz-active'
			}
		})
			.on('complete', function (event, id, name, responseJSON) {
				$('#wpas_fileuploaded').append('<input type="hidden" name="filenames[]" value="' + name + '"}">');
				$('#wpas_fileuploaded').append('<input type="hidden" name="attachments[]" value="' + responseJSON.uploadName + '"}">');
			})
			.on('error', function (event, id, fileName, reason, maybeXhr) {
				alert(reason);
			});
	}

	// BS3 Tooltip
	$('[data-toggle="tooltip"]').tooltip();

});