/**
 * This file is part of DeltaCMS.
 */

/**
 * Liste des dossiers
 */
var oldResult = [];
var directoryDOM = $("#galleryEditDirectory");
var directoryOldDOM = $("#galleryEditDirectoryOld");
function dirs() {
	$.ajax({
		type: "POST",
		url: "<?php echo helper::baseUrl() . $this->getUrl(0); ?>/dirs",
		success: function(result) {
			if($(result).not(oldResult).length !== 0 || $(oldResult).not(result).length !== 0) {
				directoryDOM.empty();
				for(var i = 0; i < result.length; i++) {
					directoryDOM.append(function(i) {
						var textshort = result[i];
						textshort = textshort.replace("site/file/source/","");
						var option = $("<option>").val(result[i]).text(textshort);
						if(directoryOldDOM.val() === result[i]) {
							option.prop("selected", true);
						}
						return option;
					}(i))
				}
				oldResult = result;
			}
		}
	});
}
dirs();
// Actualise la liste des dossiers toutes les trois secondes
setInterval(function() {
	dirs();
}, 3000);

/**
 * Stock le dossier choisi pour le re-sélectionner en cas d'actualisation ajax de la liste des dossiers
 */
directoryDOM.on("change", function() {
	directoryOldDOM.val($(this).val());
});

$('.homePicture').click(function(){
	$('.homePicture').prop('checked', false);
	$(this).prop('checked', true);
});

/**
 * Tri dynamique de la galerie
 */

$( document ).ready(function() {

	$("#galleryTable").tableDnD({
		onDrop: function(table, row) {
			$("#galleryEditFormResponse").val($.tableDnD.serialize());
			sortPictures();
		},
		serializeRegexp:  ""
	});

	if ($("#galleryEditSort").val() !==  "SORT_HAND") {
		$("#galleryTable tr").addClass("nodrag nodrop");
		$(".delta-ico-sort").hide();
		$("#galleryTable").tableDnDUpdate();
	} else {
		$("#galleryTable tr").removeClass("nodrag nodrop");
		$(".delta-ico-sort").show();
		$("#galleryTable").tableDnDUpdate();
	}

});

$("#galleryEditSort").change(function() {
	if ($("#galleryEditSort").val() !==  "SORT_HAND") {
		$("#galleryTable tr").addClass("nodrag nodrop");
		$(".delta-ico-sort").hide();
		$("#galleryTable").tableDnDUpdate();
	} else {
		$("#galleryTable tr").removeClass("nodrag nodrop");
		$(".delta-ico-sort").show();
		$("#galleryTable").tableDnDUpdate();
	}
});

/**
 * Tri dynamique des images
 */

function sortPictures() {
	var url = "<?php echo helper::baseUrl() . $this->getUrl(0); ?>/sortPictures";
	var d1 = $("#galleryEditFormResponse").val();
	var d2 = $("#galleryEditFormGalleryName").val();
	//var data = $('#galleryEditForm').serialize();
	$.ajax({
		type: "POST",
		url: url ,
		data: {
			response : d1,
			gallery: d2
		}
	});
}
//******** tinyMCE
if ( typeof(privateKey) == 'undefined') {
	var privateKey = null;
};
if ( typeof(lang_admin) == 'undefined') {
	var lang_admin = "fr_FR";
};
	tinymce.init({
	selector: '#GeoGalDesc',
	// Classe à ajouter à la balise body
	body_class: "editorWysiwyg",
	setup:function(ed) {
		// Suppression des normes de balisage xhtml
		ed.on('GetContent', function (e) {
			e.content = e.content.replace(/ \/>/g, '>');
			e.content = e.content.replace(/(height|width)="(\d+)px"/g, '$1="$2"');
			e.content = e.content.replace(/(controls)(="controls")/g, '$1');
		});
	},
	// Mode d'affichage de la barre d'outils
	toolbar_mode: 'wrap',
	// Langue
	language: lang_admin,
	// hauteur du textarea
	height: 520,
	// Titre des images
	image_title: true,
	// figure html5
	image_caption: true,
	// Active l'onglet avancé lors de l'ajout d'une image
	image_advtab: true,
	// Autoriser tous les éléments
	valid_elements : '*[*]',
	// Urls relatives
	relative_urls: true,
	// Url de base
	document_base_url: baseUrl,
	// Gestionnaire de fichiers
	filemanager_access_key: privateKey,
	external_filemanager_path: baseUrl + "core/vendor/filemanager/",
	external_plugins: {
		"filemanager": baseUrl + "core/vendor/filemanager/plugin.min.js"
	},
	// Pages internes
	link_list: baseUrl + "core/vendor/tinymce/links.php",
	// Fichiers CSS à intégrer à l'éditeur
	content_css: [
		baseUrl + "core/layout/common.css",
		baseUrl + "core/layout/mediaqueries.css",
		baseUrl + "core/vendor/tinymce/content.css",
		baseUrl + "site/data/theme.css",
		baseUrl + "site/data/custom.css"
	],
	fontsize_formats: "8px 9px 10px 11px 12px 13px 14px 15px 16px 18px 20px 24px 30px 36px 48px 60px 72px 96px",
	// CodeMirror
	codemirror: {
		indentOnInit: true, // Whether or not to indent code on init.
		path: 'codemirror', // Path to CodeMirror distribution
		saveCursorPosition: false,    // Insert caret marker
		config: {           // CodeMirror config object
			fullscreen: true,
			indentUnit: 4,
			lineNumbers: true,
			mode: "htmlmixed",
		},
		jsFiles: [
			'mode/php/php.js',
			'mode/css/css.js',
			'mode/htmlmixed/htmlmixed.js',
			'mode/htmlembedded/htmlembedded.js',
			'mode/javascript/javascript.js',
			'mode/xml/xml.js',
			'addon/search/searchcursor.js',
			'addon/search/search.js',
		],
		cssFiles: [
			/*'theme/ambiance.css',*/
		],
		width: 800,         // Default value is 800
		height: 500       // Default value is 550
	},
	// Cibles de la target
	target_list: [
		{title: 'None', value: ''},
		{title: 'Nouvel onglet', value: '_blank'}
		],
	// Target pour lightbox
	rel_list: [
		{title: 'None', value: ''},
		{title: 'Une popup (Lity)', value: 'data-lity'},
		{title: 'Une galerie d\'images (SimpleLightbox)', value: 'gallery'}
	],
	menubar: 'edit insert table format tools',
	plugins: [
	'paste', 'advlist', 'autolink', 'lists', 'link', 'image',
	'anchor', 'searchreplace', 'codemirror', 'fullscreen',
	'media', 'table', 'tabfocus', 'hr', 'nonbreaking'
	],
	toolbar: 'undo redo | bold italic backcolor | formatselect ' +
	'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | ' +
	'link image media | code fullscreen',
	contextmenu: 'cut copy paste | selectall searchreplace | link image media'
	});

// blocage popup warning navigateurs
window.addEventListener("beforeunload", function () {
  $(window).off("beforeunload");
});
