jQuery(document).ready(function($) {
	var el = $('[data-repeater="icons"]');
	var social = [];

	/* Initialize */

	if( el.length && el.val() != '' ) {
		el.val().split('|').forEach(function(currentValue) {
			var val = currentValue.split(';');
			social.push({
				icon: val[0],
				url: val[1]
			});
		});
	}

	/* Get values */

	function getVals() {
		var vals = '';

		social.forEach(function(currentValue) {
			if( vals != '' ) {
				vals += '|';
			}

			vals += currentValue.icon + ';' + currentValue.url;
		});

		return vals;
	}

	/* Changes on a icon select field */

	$('.redux-container-repeater').on('change', 'input', function(e) {
		var id = $(this).parent().index();

		social[id].url = $(this).val();
		el.val(getVals());
	});

	/* Changes on a URL field */

	$('.redux-container-repeater').on('change', 'select', function(e) {
		var id = $(this).parent().index();

		social[id].icon = $(this).val();
		el.val(getVals());
	});

	/* Remove field */

	$('.redux-container-repeater').on('click', '[data-repeater="remove"]', function(e) {
		e.preventDefault();
		var id = $(this).parent().index();

		$(this).parent().remove();
		social.splice(id, 1);
		el.val(getVals());

		return false;
	});

	/* Add new field */

	$('.redux-container-repeater [data-repeater="add"]').on('click', function(e) {
		e.preventDefault();
		social.push({
			icon: '',
			url: ''
		});

		var template = $('[data-repeater="template"]').clone();

		template.appendTo('[data-repeater="wrapper"]');

		var newSocial = $('[data-repeater="wrapper"] > *').eq(social.length - 1);
		newSocial.removeClass('hidden');
		newSocial.removeAttr('data-repeater');

		return false;
	});
});