var editing = false;
var current_edit;

function editPage(){
	if(editing == false){
		$('.edit_page_button').css('display','none');
		$('.save_page_button').css('display','block');
		
		editing = true;
	}
		else{
			savePage();
			editing = false;
		}
	
	if(editing == true){
		/**
		 * Make the header text editable
		 */
		$('.header_text').css('cursor','pointer').attr('title','Click to edit the header').click(function(){
			editTitle();
		});
		
		$('.content').css('cursor','pointer').attr('title','Click to edit').click(function(){
			$('#content_area').val($('.content').html());
			$('#content_area').wysiwyg();
			
			$('#content_editor').jqmShow();
			
			current_edit = 'content';
		});
	}
}

var saving = false;

function savePage(){
	data = {
		page_id: page_id,
		header: $('.header_text img').attr('alt'),
		content: $('.content').html()
	}
		
	if(saving == false){
		saving = true;
		
		$('.save_page_button span').text('Saving...');
		
		$.post('/common/actions/save/template_2.php', data, function(d){
			$('.save_page_button span').text('Saved!');
			
			saving = false;
			
			$('#debug').html(d);
			
			setTimeout(function(){
				$('.save_page_button').css('display','none');
				$('.edit_page_button').css('display','block');
				
				$('.save_page_button span').text('Save this page');
			}, 500);
		});
		
		resetPage();
	}
}

function editTitle(){
	if(editing == true){
		title = prompt('Please enter a new title','');
		
		if(title !== '' && title !== null){
			$('.header_text img').attr('src','/common/actions/image.php?text=' + title).attr('alt',title);
		}
		
		data = {
			header: title
		}
	}
}

function resetPage(){
	$('.header_text').css('cursor','default').attr('title','').unbind('click');
	$('.content').css('cursor','default').attr('title','').unbind('click');
}

function saveContentChanges(){
	$('.' + current_edit).html($('#content_area').val());

	$('#content_editor').jqmHide();
	$('#content_editor div.wysiwyg').remove();
}

function discardContentChanges(){
	$('#content_editor').jqmHide();
	$('#content_editor div.wysiwyg').remove();
}
