// JavaScript Document
var editor = '';

function contentChanger(page, id, direct, returnPage) {
	window.scrollTo(100, 0);
	if (document.getElementById('Submit_Paragraph')) {
		document.getElementById('Submit_Paragraph').style.display = 'none';
	}
	processChangeContent(page, id, direct, returnPage);
}

function processChangeContent(page, id, direct, returnPage) {
	var contentArea = document.getElementById('Content_Area');
	$('#Content_Area').fadeOut('fast', 0.0, function() {
		if ($('#Content_Area').css('visibility', 'hidden')) {
			$('#Content_Area').css('visibility', 'visible');
		}
		var now = new Date();
		var destination = 'includes/ajax/processing-scripts/change-page.php';
		$('#Content_Area').load(
			destination,
			{ Page: page, Id: id, Now: now, Direct: direct, ReturnPage: returnPage },
			function() {
				if (document.getElementById('Admin_Form')) {
					var txtAreas = document.getElementsByTagName('textarea');
					if (txtAreas.length > 0) {
						var fieldName = '';
						for (var k = 0; k < txtAreas.length; k++) {
							fieldName = txtAreas[k].name;
							if (fieldName != 'Comments' 
									&& fieldName != 'Desc' 
									&& fieldName != 'Short_Desc'
									&& fieldName != 'Notes' 
									&& fieldName != 'Question' 
									&& fieldName != 'Answer' 
									&& fieldName != 'Info'  
									&& fieldName != 'Link'  
									&& fieldName != 'Listing_Description'  
									&& fieldName != 'Description') {
								//Create the editor
								//createEditor(fieldName);
								editor = new FroalaEditor('#'+fieldName,
									{
										key: "3AC6eC4F6G4H4A3D3B5B-16UJHAEFZMUJOYGYQEa2d2ZJd1RAeF3C8B5D5E3D3F2G3A17A15==",
										quickInsertButtons: ['image','table','ul','ol','hr'],	
										videoAllowedProviders: ['youtube', 'vimeo'],
										fileUPload: true,
										//spellcheck: true,
										fileUploadURL: 'editor/upload_file.php',
										imageUploadURL: 'editor/upload_image.php',
										imageUploadMethod: 'POST',
										useClasses: false,																		
										// Set max image size to 5MB.
										imageMaxSize: 5 * 1024 * 1024,									
										// Allow to upload PNG and JPG.
										imageAllowedTypes: ['jpeg', 'jpg', 'png'],	
										videoInsertButtons: ['videoBack', '|', 'videoByURL', '|', 'videoEmbed'],
										toolbarButtons: {
											moreText: {
												// List of buttons used in the  group.
												buttons: [
													'bold', 
													'italic', 
													'underline', 
													'strikeThrough', 
													'subscript', 
													'superscript', 
													'fontFamily', 
													'fontSize', 
													'textColor', 
													'backgroundColor', 
													'inlineClass', 
													'inlineStyle', 
													'clearFormatting'],
									
												// Alignment of the group in the toolbar.
												align: 'left',
									
												// By default, 3 buttons are shown in the main toolbar. The rest of them are available when using the more button.
												buttonsVisible: 3
											},																
											moreParagraph: {
												buttons: [
													'alignLeft', 
													'alignCenter', 
													'formatOLSimple', 
													'alignRight', 
													'alignJustify', 
													'formatOL', 
													'formatUL', 
													'paragraphFormat', 
													'paragraphStyle', 
													'lineHeight', 
													'outdent', 
													'indent', 
													'quote'],
												align: 'left',
												buttonsVisible: 3
											},								
											moreRich: {
												buttons: [
													'insertLink', 
													'insertImage', 
													'insertVideo', 
													'insertTable', 
													'emoticons', 
													'fontAwesome', 
													'specialCharacters', 
													//'embedly', 
													'insertFile', 
													'insertHR'
												],
												align: 'left',
												buttonsVisible: 3
											},								
											moreMisc: {
												buttons: [
													'undo', 
													'redo', 
													'fullscreen', 
													'print', 
													//'getPDF', 
													//'spellChecker', 
													'selectAll', 
													'html', 
													//'help'
												],
												align: 'right',
												buttonsVisible: 2
											},										
											events: {	
												'file.beforeUpload': function (files) {
													// Return false if you want to stop the file upload.
												},
												'file.uploaded': function (response) {
													//console.log(response);
												},
												'file.inserted': function ($file, response) {
													// File was inserted in the editor.
												},									
												'file.error': function (error, response) {
													// Bad link.
													if (error.code == 1) {
														//console.log('bad file');
													}								
													// No link in upload response.
													else if (error.code == 2) {
														//console.log('no link in response');
													}								
													// Error during file upload.
													else if (error.code == 3) {
														//console.log('error');
													}								
													// Parsing response failed.
													else if (error.code == 4) {
														//console.log('cant parse');
													}								
													// File too text-large.
													else if (error.code == 5) {
														//console.log('file too large');
													}								
													// Invalid file type.
													else if (error.code == 6) {
														//console.log('invalid file');
													}								
													// File can be uploaded only to same domain in IE 8 and IE 9.
													else if (error.code == 7) {
														//console.log('cross browser error');													
													}
												},
												'image.beforeUpload': function (images) {
													// Return false if you want to stop the image upload.
												},
												'image.uploaded': function (response) {
													// Image was uploaded to the server.
												},
												'image.inserted': function ($img, response) {
													// Image was inserted in the editor.
												},
												'image.replaced': function ($img, response) {
													// Image was replaced in the editor.
												},
												'image.removed': function ($img) {
													console.log('delete image');
													var xhttp = new XMLHttpRequest();
													xhttp.onreadystatechange = function() {
									
														// Image was removed.
														if (this.readyState == 4 && this.status == 200) {
															 console.log ('image was deleted');
														}
													};
													xhttp.open("POST", "editor/delete_image.php", true);
													xhttp.send(JSON.stringify({
														src: $img.attr('src')
													}));
												},												
												'image.error': function (error, response) {
													// Bad link.
													if (error.code == 1) {
													}									
													// No link in upload response.
													else if (error.code == 2) {														
													}									
													// Error during image upload.
													else if (error.code == 3) {														
													}							
													// Parsing response failed.
													else if (error.code == 4) {														
													}									
													// Image too text-large.
													else if (error.code == 5) {														
													}									
													// Invalid image type.
													else if (error.code == 6) {														
													}									
													// Image can be uploaded only to same domain in IE 8 and IE 9.
													else if (error.code == 7) {														
													}
												}
											}
										}										
									});
							}
						}
					}
				}
				if (page == 'gallery/gallery.php') {
					galleryDisplay();
				}
				$('#Content_Area').fadeIn('med');
				if(page != ''){
					let hashIndex = "#"+page;
					window.history.pushState(null,null,hashIndex);
					sessionStorage.setItem('oldState', hashIndex );
					if(id != '' && id != undefined){						
						sessionStorage.setItem('backId', sessionStorage.getItem('currentId'));
						sessionStorage.setItem('currentId', id );
					}
				}
			}
		);
	});
}

function imageHandler() {
	var range = this.quill.getSelection();
	var value = prompt('What is the image URL');
	this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}

function ctrlBckBtn(){
	let oldState = sessionStorage.getItem('oldState');
	let id = sessionStorage.getItem('backId');
	let windowLocation = window.location.href;
	let currentState = windowLocation.substring(windowLocation.indexOf('#'));	
	if (currentState.length > 1) { // this check is added to avoid different browser related issues.
		if (currentState != oldState || (id != '' && id != undefined)) { // this check is also added to avoid different browser related issues.
			let page = currentState.substring(1);
			if(page.includes('ttps://') === false){
				contentChanger(page,id);				
			}
		}
	}
}

function updateGalleryAlbums(AlbumId){
	$( "#AlbumArea" ).fadeOut( "slow", 0.0, function(){ 
		let categoryChoice = document.getElementById('Gallery_Category').selectedIndex;
		let albumCategoryId = document.getElementById('Gallery_Category').options[categoryChoice].value;		
		var destination = 'includes/ajax/processing-scripts/process-update-albums.php';
		var data = new FormData();
		var now = new Date;
		data.append('AlbumCategoryId',albumCategoryId);
		data.append('AlbumId',AlbumId);
		data.append('Now',now);
		request = new XMLHttpRequest();		
		request.open("POST",destination,true);
		request.send(data);
		request.onreadystatechange = function(){              
				if(request.readyState == 4 && request.status == 200){                  
						document.getElementById("AlbumArea").innerHTML = request.responseText;
						$( "#AlbumArea" ).fadeIn( "slow" );				
				}
		} 
		
	});        
}

function updateNavigation(navId){
	let data = new FormData();
	let checkedValue = '';
	if(document.getElementById('Status_Active_'+navId).checked == true){
		checkedValue = '1';
	}else if(document.getElementById('Status_Inactive_'+navId).checked == true){
		checkedValue = '0';
	}
	data.append('Status', checkedValue);
	data.append('NavCat', navId);		
	let destination = 'includes/ajax/processing-scripts/process-update-nav.php';
	let now = new Date;
	data.append('Now',now);
	request = new XMLHttpRequest();		
	request.open("POST",destination,true);
	request.send(data);
	request.onreadystatechange = function(){              
		if(request.readyState == 4 && request.status == 200){                  
			//do nothing
		}
	} 
}
