function saveContent(element, pid, history_descr) {

	// show ajax loader first
	$('#' + element + '_editor').hide();
	$('#loading').show();
	
	ajaxLoader('loading');

	var content = $('#pageContent').val();

	$.ajax({
		type: 		'POST',
		url: 		location.href,
		data: 		'do=editPageContent&do-pid=' + pid + '&content=' + encodeURIComponent(content) + '&history-descr=' + history_descr,
		success: function() {
					window.location.reload(true);
				}
		});	

	return;
}

function saveContentExtra(element, pid) {

	var content = $('#' + element).val();
	
	$.ajax({
		type:		'POST',
		url:		location.href,
		data:		'do=editPageContentExtra&do-pid=' + pid + '&content=' + encodeURIComponent(content),
		success:	function(data) {}
	});

}
	

function revertPage(hid) {

	$.ajax({
		type: 		'POST',
		url: 		location.href,
		data: 'do=revertPage&do-hid=' + hid,
		success: function(data) {
				$('#pageContent').val(data)
			},
		dataType: 'text'
		});
	
	return;
}

function getCKEditor(element, pid) {

	// show ajax loader
	$('#' + element + '_content').hide();
	$('#loading').show();
	ajaxLoader('loading');

	$('#' + element + '_content').show();
	$('#loading').hide();
	boxToggle(element);
	
	$('textarea#pageContent').ckeditor(function() {
			editMode = true;
		},
		{
			height: 400,
			resize_enabled: false,
			filebrowserBrowseUrl : cms.siteurl + 'js/ckeditor/plugins/filemanager/index.html',
			filebrowserUploadUrl: cms.siteurl + 'js/ckeditor/plugins/filemanager/index.html'
		}
	
	);
	
	return;
}

function previewContent() {

	var content = $('#pageContent').val();

	$('#content_content').html(content);
	boxToggle('content');

	// show continue editing button
	$('#continueEdit_btn').show();
	
	// disable edit content button to popup
	 allowContentEdit = false;		
}

function setSortable() {

	if($('#pageMenu') == null) {
		return false;
	}

	var url = cms.siteurl;
	
	$('#pageMenu').nestedSortable({	
		disableNesting: 'no_children',
		forcePlaceholderSize: true,
		handle: 'img.handle',
		items: 'li',
		opacity: .6,
		placeholder: 'placeholder',
		tabSize: 25,
		tolerance: 'pointer',
		toleranceElement: '> div',
		axis: 'y'
	});
	
}

function serializeMenu(ul) {

	var menuArr = [];
	
	$(ul).children("li").each(function() {

		var subTree = $(this).children("ul");

		menuArr.push($(this).attr("id"));
		if(subTree.size() > 0) {
			menuArr.push([serializeMenu(subTree)]);
		}
	});

	return menuArr;
}

function saveMenu() {
	
	var url = cms.siteurl;	
	var menuArr = $('ol#pageMenu').nestedSortable('toArray', {startDepthCount: 0});
	
	$.ajax({
		type: 'POST',
		url: url + "index.php?s=fullview",
		data: 'do=updateMenu&pageMenu=' + _serialize(menuArr),
		dataType: 'String',
		success: function() {
			setTimeout("window.location.reload()", 300);
		}
	});
	
}

function toggleHandles() {

	var elements = $('img.handle');
	
	/** show handles **/
	if(handlesVisible == false) {

		$(elements).css( {display: 'inline'} );
		handlesVisible = true;
		
		/** hide other icons **/
		toggleIcons("hide");
	}
	/** hide handles **/
	else {
		$(elements).css( {display: 'none'} );
		handlesVisible = false;
		
		/** show other icons **/
		toggleIcons("show");
	}
}

function toggleMenuControls() {
	
	if(menuControlsVisible == false) {
		$('#menuControls').show();
		menuControlsVisible = true;
	}
	else {
		$('#menuControls').hide();
		menuControlsVisible = false;
	}
}

function toggleIcons(action) {
	
	var elements = $('#menu img.actionIcon');

	switch(action) {
	
		case "show": {
			elements.css( { 'display': 'inline' } );
			
			break;
		}
		case "hide": {
			elements.css( { 'display': 'none' } );
			
			break;
		}
	}
}

function addPage(parentid) {
	var pageName = prompt("Anna sivulle nimi\nPlease give a name for the page", "");

	if(pageName == "") {
		var pageName = prompt("Anna sivulle nimi\nPlease give a name for the page");
		return false;
	}
	else if(pageName == null) {
		return false;
	}
	else {
		
		pageName = encodeURIComponent(pageName);
		
		$.ajax({
			type:		'POST',
			url:		location.href,
			data:		'do=addNewPage&parentid=' + parentid + '&name=' + pageName,
			success:	function(data) {
							location.href = data; 
						},
			dataType:	'text'
		});
	
	}
	
	return;
}

function removePage(pid) {

	if(confirm("Oletko varma - Are you sure?")) {

		$.ajax({
			type:		'POST',
			url:		location.href,
			data:		'do=removePage&pid=' + pid,
			success:	function(data) {
							location.href = cms.siteurl + '?s=fullview';
						},
			dataType:	'text'
		});
		
	}

	return false;		
}

function cloneMenu() {
	
	var lang = $('cloneLang').value;
	location.href = "{URL}index.php?s=fullview&do=cloneMenu&cloneLang=" + lang;

}

allowContentEdit = true;

function showEditDiv(element) {

	// get element height & width
	var divWidth = $('#content_' + element).outerWidth();
	
	$('#editDiv_' + element).css( {width: divWidth + 'px', marginTop: '-10px'} );
	
	if(allowContentEdit) {
		$('#editDiv_' + element).css( {display: 'block'} );
	}
}

function hideEditDiv(element) {
	$('#editDiv_' + element).hide();
}

function addToTagList(tag) {

	var tagStr;
	var curTags = $('#tags').val();
	curTags = curTags.replace(/\s*|\s*$/g,'');

	if(!curTags) {
		curTagsArr = new Array();
	}
	else {
		curTagsArr = curTags.split(",");
	}

	// add clicked tag into array
	curTagsArr.push(tag);

	// clean duplicates
	curTagsArr = curTagsArr.unique();
	
	// set text box value
	$('#tags').val(curTagsArr.join(", "));

	return;
}

function confirmFancyBox() {
	
	if(editMode && !confirm("Olet muokkaamassa sivun sisältöä. Oletko varma, että haluat siirtyä toiselle sivulle tallentamatta muutoksia?\n\nYou are currently in page edit mode. Are you sure you want to move to another page without saving changes?")) {		
		return false;
	}
	
	editMode = false;
	return true;
	
}

$(document).ready(function() {

	// toggle save button
	$('#btn_saveMenu').click(saveMenu);

	// resize edit page link divider
	if($('#editLink_pageimage') != "null") {

		var width = $('#content_pageimage').outerWidth();
		var height = $('#content_pageimage').outerHeight();
		
		$('#editDiv_pageimage').css( {height: height + 'px', width: width + 'px'} );
	}
	

	/* fancybox settings */
	$("a.group_admin").fancybox({
		onStart:			function() { return confirmFancyBox() },
		onClosed:			function() { document.location.reload() },
		'speedIn'		:	300, 
		'speedOut'		:	300, 
		'overlayShow'	:	true,
		'titlePosition'	:	'outside',
		'autoScale'		:	'false'
	});

	$("a.iframe_admin").fancybox({
		onStart:			function() { return confirmFancyBox() },
		onClosed:			function() { document.location.reload() },
		'type'			: 	'iframe',
		'height'		:	'80%',
		'width'			:	'80%'
	});	

	// set editable areas
	var elements = $('[rel|=lightEditable]');
	$(elements).bind('click', function(elem) {

		$.fancybox(
			{
				onStart:			function() { return confirmFancyBox() },
				onClosed:			function() { document.location.reload() },
				'href':				'?s=editmodule&module=' + this.id + '&pid=' + cms.pid,
				'type':				'iframe',
				'width': 			'80%',
				'height': 			'80%',
				'transitionIn':		'none',
				'transitionOut':	'none'
			}
		);
		
	});
	
	// editor links
	editMode = false;
	var hrefArr = new Array();
	var i = 0;
	
	$('a[rel!=lightEditable][rel!=editorLink][rev!=galleryLink]').bind('click', function(event) {
		if(editMode && !confirm("Olet muokkaamassa sivun sisältöä. Oletko varma, että haluat siirtyä toiselle sivulle tallentamatta muutoksia?\n\nYou are currently in page edit mode. Are you sure you want to move to another page without saving changes?")) {		
			return false;
		}
	});

});

