

var $ = jQuery;

$(document).ready(function() {
	'use strict';

	function amy_movie_ajax_date(tag, date, type) {
		$('<div/>', {
			id: 'amy-loading'
		}).appendTo('#wpwrap');

		$('#amy-loading').append('<span></span>');

		$.ajax({
			method: 'POST',
			url: amy_script.ajax_url,
			data: 'action=amy_movie_ajax_change_date_format&date=' + date,
			dataType: 'json',
			beforeSend: function() {
				if (type == 'chosen')
				$('#amy-loading').addClass('open');
			},
			success: function(response) {
				if (type == 'chosen') {
					$('#amy-loading').removeClass('open');
				}

				tag.val(response);
			}
		});
	}

	function amy_movie_date_picker(type) {
		$('.amy-datepicker').each(function () {
			var $this = $(this),
				$hidden = $this.find('input[type="hidden"]'),
				$show = $this.find('input[type="text"]');

			amy_movie_ajax_date($show, $hidden.val(), type);

			$hidden.datepicker({
				dateFormat: 'yy-mm-dd',
				onSelect: function () {
					var newdate = $.datepicker.formatDate('yy-mm-dd', new Date($hidden.val()));

					amy_movie_ajax_date($show, newdate, 'chosen');
				}
			});

			$this.click(function () {
				$hidden.datepicker('show');
			});
		});
	}

	amy_movie_date_picker('loadpage');

	$('.amy-tagsinput').tagsInput({
		'width':		'auto',
		'height': 		'40px',
		'defaultText': 'Add new hour'
	});

	$('.amy-add-group').bind('click').on('click', function (e) {
		amy_movie_date_picker();

		$('.amy-tagsinput').tagsInput({
			'width':		'auto',
			'height': 		'40px',
			'defaultText':  'Add new hour'
		});
	});
});