/**
 * JS per la gestione dei repeater.
 *
 * @package		Pongho2
 * @author		Daniele De Nobili
 * @version		1.0
 * @copyright	© 2012, Web Agency Meta Line S.r.l.
 *
 * @depends		jquery-1.7.1.min.js
 *				jquery-ui-1.8.17.custom.min.js
 *				jquery.ui.nestedSortable.js
 */

$(document).ready(function () {
	window.Pongho = window.Pongho || {};
	var body = $('body');

	Pongho.Repeater = function() {
		var containers = $('.tabsPanel', 'body'),
			maxLevels = $('#field-max_levels');

		containers.each(function () {
			var container = $(this).find('.repeater-container'),
				form = container.closest('form'),
				repeater = $('ol', container),
				blankItem = repeater.find('.repeater-blank-row').clone(),
				counter = 1,
				language = container.data('language'),
				wrapper = $('<div />').appendTo(container);

			// Correggo un problema con il datepicker
			blankItem.find('.input_date').removeClass('hasDatepicker');
			blankItem.find('.input_datetime').removeClass('hasDatepicker');
			blankItem.find('.input_time').removeClass('hasDatepicker');

			repeater.find('.repeater-blank-row', container).remove();

			// nestedSortable
			repeater.nestedSortable({
				delay: 200,
				disableNesting: 'no-nest',
				forcePlaceholderSize: true,
				handle: '.sortable-handle',
				helper:	'clone',
				items: 'li',
				maxLevels: maxLevels.val() || 1,
				opacity: .6,
				placeholder: 'sortable-placeholder repeater-row',
				revert: 250,
				tabSize: 30,
				tolerance: 'pointer',
				toleranceElement: '> div'
			});

			// correggo un problema con il focus dei campi
			repeater.on('mousedown', '.sortable-handle', function (event) {
				$(this).closest('.repeater-row').find('input, select, textarea').blur();
			});

			// se modifico il numero dei livelli massimi aggiorno il nestedSortable
			maxLevels.keyup(function (event) {
				repeater.nestedSortable('option', 'maxLevels', parseInt(maxLevels.val(), 10));
			});

			// comandi avanzati
			repeater.on('click', '.repeater-actions-open', function () {
				$(this).closest('.repeater-row').addClass('active');
			});
			repeater.on('click', '.repeater-actions-close', function () {
				$(this).closest('.repeater-row').removeClass('active');
			});

			// eliminazione di una voce
			repeater.on('click', '.repeater-delete-row', function (event) {
				var li = $(this).closest('.repeater-row'),
					ol = li.closest('repeater');

				li.fadeOut(function () {
					li.remove();

					if (ol.find('li').length == 0 && !ol.is(repeater)) {
						ol.remove();
					}
				});

				event.preventDefault();
			});

			// pulsante per aggiungere le nuove righe
			$('.repeater-add-row', container).on('click', function (event) {
				var row = blankItem.clone();

				row
                    // Siccome qualsiasi tag contenuto può avere un id o un attributo name, li ciclo per aggiornarli
					.find('*').each(function () {
                        var tag = this;

                        if (tag.name) {
                            tag.name = tag.name.replace('[new]', '[new' + counter + ']');
                        }

                        if (tag.id) {
                            tag.id = tag.id.replace(/\-new\-/g, '-new' + counter + '-');
                        }
					}).end()
					.attr('id', 'repeater-row-new' + counter)
					.attr('data-id', 'new' + counter)
                    .removeClass('repeater-blank-row')
					.appendTo(repeater)
					.show();

				body.trigger('pongho_repeater_add_row', [row]);

				counter++;
				event.preventDefault();
			});

			form.submit(function (event) {
				var code = '';

				$.each(repeater.nestedSortable('toArray'), function (index, data) {
					if (data.item_id === 'root' || data.item_id === 'item') {
						return;
					}

					if (data.parent_id === 'root') {
						data.parent_id = '';
					}

					code += '<input type="hidden" name="items[' + data.item_id + '][parent_id]" value="' + data.parent_id + '">';
					code += '<input type="hidden" name="items[' + data.item_id + '][left]" value="' + data.left + '">';
					code += '<input type="hidden" name="items[' + data.item_id + '][right]" value="' + data.right + '">';
				});

				wrapper.html(code);
			})
		});
	};

	Pongho.Repeater();

	body.bind('pongho_panel_recreate', function () {
		Pongho.Repeater();
	});
});
