
var Page = Class.create();

Page.prototype = {
	/*
	 * args: 
	 *  #1 id of the container that will hold new page forms
	 */
	initialize: function(container) {
		this.container = container;
		this.isEditing = {};
		this.isShowingEditLink = false;
		this.isShowingEditLoadingSpinner = false;
	
	
		this.hoverCount = 0;
	},

	_destroyContainer: function() {
		$(this.container).down('div').down().remove();
	},

	add: function(el, projectId, parentPageId, currentPageBeingViewed) {
		/* if the user is currently reodering pages, this function shouldn't work */
		if(reorder.isReorderingNow)
		{
			alert("Sorry but you can't add new pages while you're reordering your Jumpchart. Please save or cancel your alts through the green buttons at the bottom of your sidebar.");
			return;
		}
		
		// isSlided = true;
		this.projectId = projectId;

		if(el.hasClassName('current'))
		{
			el.removeClassName('current');
			Effect.SlideUp(this.container, {duration:0.4, afterFinish: this._destroyContainer.bind(this)});
			return;
		}

		$$('.current').each(function(currentEls) { currentEls.removeClassName('current');});

		// el.id = 'current';
		el.addClassName('current');

		var content = '<div id="innerContainer"><span class="ajaxContainerTitle">';
		if(el.innerHTML.indexOf('Sub') != -1 || el.innerHTML.indexOf('sub') != -1)
			content += 'Add Sub-Page';
		else
			content += 'Add Page';
		content += '</span> ';

		content += '<form id="addPageForm" onsubmit="return false;">';
		content += '<input class="text" type="text" name="title" value="Title" id="newpageTitle" />';
		content += ' <span class="topAjaxContainerButtonsAligner"><input type="submit" class="button" value="Add" />';
		content += ' <a class="cancelLink" href="javascript:;" id="closeContainer">Cancel</a></span>';
		content += '<input type="hidden" name="project_id" value="' + projectId + '" />';
		content += '<input type="hidden" name="current_page_id" value="' + currentPageBeingViewed + '" />';
		content += '<input type="hidden" name="parent_id" value="' + parentPageId + '" /></form>';
		if(el.innerHTML.indexOf('Sub') != -1 || el.innerHTML.indexOf('sub') != -1)
			content += "<div class=\"sliderTip\"><span class=\"question\">What's a sub-page?</span> <span class=\"answer\">A sub-page is created hierarchically beneath the one you are currently viewing.</span></div>";
		content += '</div>';

		this.newContainer = Builder.build(content);

		if(!$('innerContainer'))
		{
			$(this.container).down('div').appendChild(this.newContainer);
			$('closeContainer').observe('click', this.closeContainer.bindAsEventListener(this,el));
			$('addPageForm').observe('submit', this.addSave.bindAsEventListener(this));
			new Effect.SlideDown(this.container, { duration: 0.4, afterFinish: this._add_callback.bindAsEventListener(this)});
		}
		else
			new Effect.SlideUp(this.container, { duration:0.4, afterFinish: this._topContainerReconstruct.bind(this, el) });
	},

	_add_callback: function() {
		focusFirst('addPageForm'); //window.setTimeout( function() { $('').focusFirstElement(); }, 1 );
	},

	addSave: function() {
		showLoading('addPage');
		new Ajax.Request(ajaxUrl, {
			parameters: 'ajaxAction=addPageSave&' + Form.serialize('addPageForm'), 
			onComplete: this._addSave_callback.bindAsEventListener(this)
		});
		return false;
	},

	_addSave_callback: function(request) {
		hideLoading('addPage');

		if(request.responseText == 'no-access')
			alert("You don't have permission to add a page to this project.");
		else if(request.responseText == 'false')
			alert('There was an error processing your request.');
		else if(request.responseText == 'duplicate')
		{
			alert("Unfortunately your Jumpchart can't have two pages with the same name and the same parent.");
			Form.Element.focus('newpageTitle');
		}
		else if(request.responseText == 'pages-limit')
		{
			alert("We couldn't create the page because this jumpchart has reached its limit of pages per project, as set by the current account plan.\n\nIf you're the owner of this jumpchart, consider upgrading to a bigger plan.");
		}
		else
		{
			var response = request.responseText.evalJSON();
			if(!this.isEditing.main && !this.isEditing.second)
				location.href = sysUrl + 'page/view/' + response.id;
			else
			{
				var newItem  = '<div class="reorderableSection" id="sidebarSections-' + response.id + '"><div class="pageNameAndReorderHandle">';
				newItem     += '<img src="'+sysUrl+'template/images/move.png" class="reorderHandle" alt="Drag to Reorder" /> ';
				newItem     += '<a href="'+sysUrl+'page/view/' + response.id + '/' + '">' + response.title + '</a></div><div class="break"></div></div>';

				if(response.parent_id == 0)
					$('reorderablePages').insert({'bottom':newItem});
				else
				{
					if($('subSections' + response.parent_id))
						$('subSections' + response.parent_id).insert({'bottom':newItem});
					else
					{
						var newItem = '<span class="pageList" id="subSections' + response.parent_id + '">'+newItem+'</span>';
						$('sidebarSections-' + response.parent_id).insert({'bottom':newItem});
					}
				}
				// reorder.startList(response.project_id);
				new Effect.SlideUp(this.container, {duration:0.4, afterFinish: this._destroyContainer.bindAsEventListener(this) });
				$('addSubPageLink').removeClassName('current');
				$('addPageLink').removeClassName('current');
			}	
		}
	},

	rename: function(pageId) {
		/* if the user is currently reodering pages, this function shouldn't work */
		if(reorder.isReorderingNow)
		{
			alert("Sorry but you can't rename the page while you're reordering your Jumpchart. Please save or cancel your alts through the green buttons at the bottom of your sidebar.");
			return;
		}
		showLoading('pageName');
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=renamePage&pageId=' + pageId, onComplete: this._rename_callback.bindAsEventListener(this) });
	},

	_rename_callback: function(request) {
		hideLoading('pageName');
		if(request.responseText == 'false')
			alert("There was an error editing this page.");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to edit this page");
		else
		{
			$('pageName').update(request.responseText);
			focusFirst('formRenamePage');
		}
		
	},

	renameSave: function(pageId) {
		if(Form.check('formRenamePage'))
		{
			showLoading('pageName');
			new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=renamePageSave&' + $('formRenamePage').serialize(), onComplete: this._renameSave_callback.bindAsEventListener(this, pageId)});
		}

	},

	_renameSave_callback: function(request, pageId) {
		hideLoading('pageName');
		if(request.responseText == 'false')
			alert("There was an error editing this page.");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to edit this page");
		else
		{
			$('pageName').update('');
			var renameLink = Builder.build('<span>' + request.responseText + ' <a href="javascript:void(0)" onclick="page.rename(' + pageId + ')" id="pageRenameLink">Rename</a></span>');
			$('pageName').insert({'bottom':renameLink});
			$('sidebarSections-' + pageId).down('a').update(request.responseText);

			if(!this.isEditing.main && !this.isEditing.second)
			{
				this.rebuildPageContent();
				// showLoading('pageContent', true);
				// new Ajax.Updater('pageContent', ajaxUrl, { parameters: 'ajaxAction=editPageCancel&pageId=' + pageId});
			}				
		}
	},

	renameCancel: function(pageId) {
		showLoading('pageName');
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=renamePageCancel&pageId=' + pageId, onComplete: this._renameCancel_callback.bindAsEventListener(this)});
	},

	_renameCancel_callback: function(request) {
		hideLoading('pageName');
		if(request.responseText == 'false')
			alert("There was an error editing this page.");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to edit this page");
		else
		{
			$('pageName').update(request.responseText);
		}

	},

	edit: function(pageId, fragment) {
		if(typeof(fragment) == 'undefined') fragment = 'main';
		
		if(typeof(this.isEditing[fragment]) != 'undefined' && this.isEditing[fragment])
			return true;

		this.isEditing[fragment] = true;
		// this._editLinkShowLoading();
		new Ajax.Request(ajaxUrl, { parameters: 'ajaxAction=editPage&pageId=' + pageId + '&fragment=' + fragment,
			onComplete: this._edit_callback.bindAsEventListener(this, pageId, fragment)
		});

		pageChangeConfirmationOn();
	},

	// _editLinkShowLoading: function() {
	// 	this.isShowingEditLoadingSpinner = true;
	// 	$('editLink').down().hide();
	// 	$('editLink').addClassName('loading');
	// 	showLoading($('editLink'));
	// },
	// 
	// _editLinkHideLoading: function() {
	// 	this.isShowingEditLoadingSpinner = false;
	// 	hideLoading($('editLink'));
	// },

	/*
	 * the loading spinner messes with the display of some elements of the floating
	 * edit link, so we need to get them back to initial state
	 */
	_editLinkReconstruct: function(fragment) {
		$('editLink-'+fragment).down().show();
		// $('editLink').removeClassName('loading');
	},

	_edit_callback: function(request, pageId, fragment)
	{
		// this._editLinkHideLoading();

		var response = request.responseText.evalJSON();
		var pageContent = response.editPage;
		var syntaxHelperContent = response.syntaxHelp;

		var container = 'pageContent-' + fragment;
		if(pageContent == 'false')
			alert("There was an error editing this page.");
		else if(pageContent == 'no-access')
			alert("You don't have permission to edit this page");
		else
		{
			var formName = 'formEditPage-content-' + fragment;
			var form = '<form method="post" id="' + formName + '" onsubmit="return false;"></form>';

			form = Builder.build(form);

			$(container).innerHTML = '';
			$(container).appendChild(form);

			form.observe('submit', this.editSave.bindAsEventListener(this, pageId, fragment));

			form.appendChild(Builder.build(pageContent));
			this._editButtons(pageId,fragment);
			this._resizePageTextarea(fragment);

			$(formName).down('textarea').focus();
			// this.hideEditLink();
			
			// syntaxHelperBar.showBar('formPageContent-'+fragment);
		}
	},

	/*
	 * If pageId is a string, then the function assumes that this is the content of the sidebar. (had to build this to workaround IE7 crappiness)
	 */
	showSyntaxHelp: function(pageId) {
		if(typeof(pageId) == 'string')
			this._showSyntaxHelp_callback(pageId);
		else
			new Ajax.Request(ajaxUrl, {parameters: 'ajaxAction=showSyntaxHelp&pageId=' + pageId, onComplete: this._showSyntaxHelp_callback.bindAsEventListener(this) });
	},
	
	_showSyntaxHelp_callback: function(request) {
		$('main').insert({'bottom':'<div id="syntaxHelpOverlay" style="display:none">'+request+'</div>'});
		var pageWidth = $('wrapper').getWidth();
		var overlayWidth = (pageWidth-940)/2 + $('rightPageActionsNav').getWidth();
		window.setTimeout(function() { $('syntaxHelpOverlay').style.height = ($('main').getHeight() - 75) + 'px'; }, 100);
		$('syntaxHelpOverlay').style.width  = overlayWidth + 'px';
		if(Prototype.Browser.IE)
			$('syntaxHelpOverlay').show();
		else
			new Effect.Appear('syntaxHelpOverlay', { duration: 0.3, from: 0, to: 0.9});
		return;
	},
	

	_editButtons: function(pageId, fragment) {
		var div = '<div class="editPageButtons" id="editPageButtons-content"><input type="submit" value="Save" /> <a class="cancelLink" href="javascript:void(0);" onclick="page.editCancel(page, '+pageId+',\''+fragment+'\')">Cancel</a></div>';
		$('formEditPage-content-' + fragment).insert({'bottom':div});
	},

	editCancel: function(e, pageId, fragment) {
		if(this.isEditing[fragment])
		{
			this.isEditing[fragment] = false;
			this._editLinkReconstruct(fragment);
			var container = 'pageContent-'+fragment;
			showLoading(container);
			// if($('syntaxHelpOverlay')) new Effect.Fade('syntaxHelpOverlay', {duration: 0.3, from: 0.9, to: 0, afterFinish: function() { $('syntaxHelpOverlay').remove(); }});
			if($('syntaxHelperBar')) Effect.BlindUp('syntaxHelperBar',{duration:0.3});

			new Ajax.Updater(container, ajaxUrl, { parameters: 'ajaxAction=editPageCancel&pageId=' + pageId + '&fragment=' + fragment});
			
			if(!this.isEditing.main && !this.isEditing.second)
				pageChangeConfirmationOff();
		}
	},

	editSave: function(e, pageId, fragment) {
		if(this.isEditing[fragment])
		{
			showLoading('pageContent-'+fragment);
			this._editLinkReconstruct(fragment);
		 	new Ajax.Request(ajaxUrl, { 
				parameters: 'ajaxAction=editPageSave&pageId=' + pageId + '&fragment=' + fragment + '&' + Form.serialize('formEditPage-content-' + fragment),
				onComplete: this._editSave_callback.bindAsEventListener(this, pageId, fragment) 
			});
		}
	},

	_editSave_callback: function (request, pageId, fragment) {
		if(request.responseText == 'false')
			alert('There was an error processing your request.');
		else if(request.responseText == 'duplicate')
		{
			alert("Unfortunately your Jumpchart can't have two pages with the same name and the same parent.");
			Form.Element.focus('formPageTitle');
			return false;
		}
		else
		{
			this.isEditing[fragment] = false;
			if(request.responseText.strip() == '') request.responseText = '<p>Content here</p>';
			$('pageContent-'+fragment).innerHTML = request.responseText;
			// new Effect.Fade('syntaxHelpOverlay', {duration: 0.3, from: 0.9, to: 0, afterFinish: function() { $('syntaxHelpOverlay').remove(); }});
			if($('syntaxHelperBar')) Effect.BlindUp('syntaxHelperBar',{duration:0.3});
			if(!this.isEditing.main && !this.isEditing.second)
				pageChangeConfirmationOff();
		}
	},

	remove: function(pageId) {
		/* if the user is currently reodering pages, this function shouldn't work */
		if(reorder.isReorderingNow)
		{
			alert("Sorry but you can't delete this page while you're reordering your Jumpchart. Please save or cancel your alts through the green buttons at the bottom of your sidebar.");
			return;
		}
		
		if(pageId == null)
			alert('Error.');
		else
		{
			if(confirm("Are you sure you want to remove this page?\n(all sub-pages will be removed too)"))
			{
				var theForm = Builder.build('<form action="' + sysUrl + 'page/remove/" method="post" id="removePageTempForm"></form>');
				$('main').appendChild(theForm);
				var input   = Builder.build('<input type="hidden" name="pageId" value="' + pageId + '" />');
				theForm.appendChild(input);
			
				/* timeout hack to make it work on IE6 */
				window.setTimeout(function(){ $('removePageTempForm').submit(); }, 1);
			}
			
		}
	},

	syntaxHelperInsert: function (type, el)
	{
		var textarea = $('formPageContent');
		syntaxHelperBar.insert(textarea, type);
		
		// $('formPageContent').value += "\n";
		// switch(type)
		// {
		// 	case 'snippet':
		// 		$('formPageContent').value = $('formPageContent').value + '[[' + el.innerHTML + ']]';
		// 	break;
		// 
		// 	case 'file':
		// 		$('formPageContent').value = $('formPageContent').value + '(' + el.innerHTML + ')';
		// 	break;
		// 
		// 	case 'heading':
		// 		$('formPageContent').value = $('formPageContent').value + 'h1. Heading';
		// 	break;
		// 
		// 	case 'bold':
		// 		$('formPageContent').value = $('formPageContent').value + '*bold*';
		// 	break;
		// 
		// 	case 'italic':
		// 		$('formPageContent').value = $('formPageContent').value + '_italic_';
		// 	break;
		// 
		// 	case 'bullet':
		// 		$('formPageContent').value = $('formPageContent').value + '* Bullet point';
		// 	break;
		// 
		// 	case 'image':
		// 		$('formPageContent').value = $('formPageContent').value + '!http://www.domain.com/image.jpg!';
		// 	break;
		// 
		// 	case 'link':
		// 		$('formPageContent').value = $('formPageContent').value + '"Click me":http://www.jumpchart.com';
		// 	break;
		// 
		// 	case 'file-string':
		// 		$('formPageContent').value = $('formPageContent').value + '(File name)';
		// 	break;
		// 
		// 	case 'link-internal':
		// 		$('formPageContent').value = $('formPageContent').value + '"Go to home page":[Home page]';
		// 	break;
		// 
		// 	case 'input':
		// 		$('formPageContent').value = $('formPageContent').value + '[input]';
		// 	break;
		// 
		// 	case 'radio':
		// 		$('formPageContent').value = $('formPageContent').value + '[radio]';
		// 	break;
		// 
		// 	case 'checkbox':
		// 		$('formPageContent').value = $('formPageContent').value + '[checkbox]';
		// 	break;
		// 
		// 	case 'submit':
		// 		$('formPageContent').value = $('formPageContent').value + '[submit]';
		// 	break;
		// 
		// 	case 'select':
		// 		$('formPageContent').value = $('formPageContent').value + '[select]:"Option 1, Option 2, Option 3"';
		// 	break;
		// }
	
	},

	_resizePageTextarea: function(fragment) {
		var height = Element.getHeight('formPageContentTemp') + 50;
		if(height < 400)
			height = 400;
		$('formPageContentTemp').remove();

		$('formPageContent-'+fragment).style.height = height + 'px';
	},

	_topContainerReconstruct: function(el) {
		this._destroyContainer();
		$(this.container).down('div').appendChild(this.newContainer);
		$('closeContainer').observe('click', this.closeContainer.bindAsEventListener(this, el));
		$('addPageForm').observe('submit', this.addSave.bindAsEventListener(this));
		new Effect.SlideDown(this.container, { duration: 0.4});	
	},

	closeContainer: function (event,el) {
		if(el.hasClassName('current'))
			el.removeClassName('current');
		new Effect.SlideUp(this.container, {duration:0.4, afterFinish: this._destroyContainer.bindAsEventListener(this) });
	},

	/*
	 * Public preview
	 */
	makePublicPreview: function(el, projectId) {
		if(el.checked == true)
			var confirmation = confirm("By making this a public preview, it will be accessible online without a login. Are you sure you want to continue?");
		else
			var confirmation = true;

		if(confirmation)
		{
			this.projectId = projectId;
			var checked = (el.checked) ? 1 : 0;
			new Ajax.Request(ajaxUrl, { parameters: 'ajaxAction=makePublicPreview&projectId=' + projectId + '&checked=' + checked, onComplete: this.makePublicPreview_callback });			
		}
		else
			el.checked = false;
		
	},

	makePublicPreview_callback: function(request) {
		if(request.responseText == 'no-access')
			alert("You don't have permission to access this function.");
		else if(request.responseText == 'false')
			alert("There was an error processing your request.");
		else if(request.responseText == 'true')
		{
			if($('shareableAt'))
				new Effect.Fade('shareableAt', { afterFinish: function() {$('shareableAt').remove();}});
		}
		else
			$('previewToolbar').down().insert({'bottom':'<span id="shareableAt"> &ndash; Shareable at: <a href="' + request.responseText + '">' + request.responseText + '</a></span>'});
	},

	/*
	 * Floating edit link
	 */
	registerEvents: function() {
		var self = this;
		$$('.pageContent').each(function(container){
			Event.observe(container, 'mousemove', self.showEditLink.bindAsEventListener(self, container), true);
			Event.observe(container, 'mouseout', self.hideEditLink.bindAsEventListener(self, container), true);
		});

		$$('.editLink').each(function(linkElement) {
			Event.observe(linkElement, 'mousemove', self.showEditLink.bindAsEventListener(self, linkElement), true);
			Event.observe(linkElement, 'mouseout', self.hideEditLink.bindAsEventListener(self, linkElement), true);
		});

		this.lastElement = '';
		this.isShowingEditLink = false;
	},

	findFragmentOfString: function(e, el) {
		var fragment = el.id.split('-')[1];
		return fragment;
	},

	showEditLink: function(e, element) {
		var fragment = this.findFragmentOfString(e, element);
		var editLinkElement = $('editLink-' + fragment);
		if(!editLinkElement)
			return;
		
		this.hoverCount++;
		
		if(this.isShowingEditLoadingSpinner)
			return;
		else if(this.isEditing[fragment])
		{
			this.hideEditLink(e, element);
			return;
		}
		else
		{
			if((Event.pointerY(e) < 130) || (Event.pointerY(e) > ($('middleContent').getHeight()+150)))
				this.hideEditLink(e, element);
			else
			{
				if(this.lastElement == '' || this.lastElement != Event.element(e))
					this.lastElement = Event.element(e);

				this.isShowingEditLink = true;
				
				if($$('.flaggedUserWarning').size()==0)
					var top = ( Event.pointerY(e) - 90 )+ 'px';
				else
					var top = (Event.pointerY(e) - 90 - $$('.flaggedUserWarning')[0].getHeight())+ 'px';


				$(editLinkElement).style.top = top;
				if(!$(editLinkElement).visible())
					$(editLinkElement).show();
			}
		}
	},

	hideEditLink: function(e,element) {
		var fragment = this.findFragmentOfString(e, element);
		var editLinkElement = $('editLink-' + fragment);
		if(!editLinkElement)
			return;
		this.isShowingEditLink = false;
		window.setTimeout(this._hideEditLink_callback.bindAsEventListener(this,editLinkElement), 500);
	},

	_hideEditLink_callback: function(t,editLinkElement) {
		if(this.isShowingEditLink)
			return;
		else
		{
			if(this.isShowingEditLoadingSpinner)
				return;
			else
				$(editLinkElement).hide();
		}
	},

	exportShow: function(el, projectId, pageId, hasWPExport)
	{
		isSlided = true;
		el = $(el);
		if(el.hasClassName('current'))
		{
			el.removeClassName('current');
			Effect.SlideUp('mainAjaxSlider', {duration:0.4, afterFinish: this._destroyContainer.bind(this)});

			return;
		}

		$$('.current').each(function(currentEls) { currentEls.removeClassName('current');});
		el.addClassName('current');

		var container = $('mainAjaxContainer');
		// var content = Builder.build('<div id="innerContainer"><div class="ajaxContainerTitle" class="smallCentered">Export</div> <p>The export function lets you export your jumpchart to clean XHTML and CSS.<br /> You can export only the current <a href="' + sysUrl + 'page/export/' + pageId + '">page</a> or the whole <a href="' + sysUrl + 'site/export/' + projectId + '">site</a>.</p></div>');
		
		var content = '<div id="innerContainer">';
		content += ' 	<div class="ajaxContainerTitle" style="margin-bottom: 20px;">Export</div>';
		content += '	<div class="exportPane" id="exportPaneXHTML">';
		content += '		<div class="exportPaneTitle">XHTML / CSS</div>';
		content += '		<div class="exportPaneDescription">Export your jumpchart to clean XHTML and CSS</div>';
		content += '		<div class="exportPaneButtons">';
		content += '			<a href="' + sysUrl + 'page/export/' + pageId + '">Export page</a>';
		content += '			<a href="' + sysUrl + 'site/export/' + projectId + '">Export whole site</a>';
		content += '		</div>';
		content += '		<div class="break"></div>';
		content += '	</div>';
		
		
		if(location.href.indexOf('core.jumpchart.com') != -1)
			var wpLogo = sysUrl + 'template/images/2/wordpress-logo.png';
		else
			var wpLogo = sysUrl + 'core/template/images/2/wordpress-logo.png';
		
		if(hasWPExport)
			content += '	<div class="exportPane" id="exportPaneWP">';
		else
			content += '	<div class="exportPane noWPSupport" id="exportPaneWP">';
		
		content += '		<div class="exportPaneTitle"><img src="' + wpLogo + '" alt="" /></div>';
		if(hasWPExport)
			content += '		<div class="exportPaneDescription">The WordPress export format imports into most popular CMS\'s. <br /><a href="'+sysUrl+'help/article/28" target="_blank">See our guide</a>.</div>';
		else
			content += '		<div class="exportPaneDescription">The WordPress export format imports into most popular CMS\'s.<br /> Currently the account that owns this project doesn\'t support the WordPress exports.<br /><a href="http://www.jumpchart.com/tour/wordpress/" target="_blank">Learn more</a> and consider an upgrade or talk to the account owner.</div>';
		content += '		<div class="exportPaneButtons">';
		if(hasWPExport)
		{
	 		content += '			<form action="' + sysUrl + 'wp-exporter-do" method="post" id="wpExportForm" onsubmit="exportToWordpress();return false;">';
			content += '				<p>URL for WordPress Install<br /> <input type="text" class="text" name="url" id="wpExportURL" value="" /></p>';
			content += '				<p>';
			content += '					<input type="hidden" name="project_id" value="' + projectId + '" />';
			content += '					<a href="javascript:void(0);" onclick="exportToWordpress()">Export to WordPress</a>';
			content += '					<input type="submit" value="Export &gt;" style="display: none;" />';
			content += '				</p>';
			content += '			</form>';
		}
		content += '		</div>';
		content += '		<div class="break"></div>';
		content += '	</div>';
			


		content += '	</div>';

		if($('innerContainer'))
		{
			Effect.SlideUp('mainAjaxSlider', {duration:0.4, afterFinish: 
					function() 
					{ 
						DestroyAjaxInnerContainer();
						container.update(content); 
						Down('mainAjaxSlider');
					}});
		}
		else
		{
			container.update(content);
			Down('mainAjaxSlider');
		}
	},
	
	exportShowPane: function(el, newPane) {
		$(el).up('.exportPane').hide();
		$('exportPane-'+newPane).show();
	},

	/*
	 * Keyboard Shortcuts, Added 01/2008
	 * Shortcuts available:
	 *  - Ctrl+E: edit page
	 *  - Ctrl+S: save edit page
	 *  - Ctrl+Q: cancel edit page
	 *  - Ctrl+A: add page 
	 *  - Ctrl+U: add subpage 
	 *  - Ctrl+D: delete page 
	 *  - Ctrl+X: export
	 *  - Ctrl+O: reorder
	 *  - Ctrl+I: add file
	 *  - Ctrl+M: add comment
	 *  - Ctrl+K: go to next page in the navigation tree 
	 *  - Ctrl+J: go to previous pag ein the navigation tree 
	 */
	startShortcuts: function() {
		// var keyEvent = (Prototype.Browser.Gecko) ? 'keypress' : 'keydown';
		var keyEvent = 'keydown';

		shortcut.add('Ctrl+E', function(){page.edit($F('pagePageId'));}, {'propagate': false, 'type':keyEvent});
		shortcut.add('Ctrl+A', function(){page.add($('addPageLink'), $F('pageProjectId'), $F('pageParentId'));}, {'propagate':false, 'disable_in_input':true, 'type':keyEvent});
		shortcut.add('Ctrl+U', function(){page.add($('addSubPageLink'), $F('pageProjectId'), $F('pagePageId'));}, {'propagate': false, 'disable_in_input':true, 'type':keyEvent});
		shortcut.add('Ctrl+D', function(){page.remove($F('pagePageId'));}, {'propagate': false, 'type':keyEvent});
		shortcut.add('Ctrl+X', function(){page.exportShow($('exportLink'), $F('pageProjectId'), $F('pagePageId'));}, {'propagate': false, 'disable_in_input':true, 'type':keyEvent});
		shortcut.add('Ctrl+I', function(){files.addShow();}, {'propagate': false, 'type':keyEvent});
		shortcut.add('Ctrl+M', function(){comments.showCommentForm();}, {'propagate': false, 'type':keyEvent});
		shortcut.add('Ctrl+K', function(){page.goToNextPage($F('pagePageId'));}, {'propagate': false, 'type':keyEvent});
		shortcut.add('Ctrl+J', function(){page.goToPreviousPage($F('pagePageId'));}, {'propagate': false, 'type':keyEvent});
	},
	
	goToNextPage: function(pageId) {
		var currentPage = $('sidebarSections-' + pageId);

		if(currentPage)
		{
			var goToNext = false;
			var isGoing = false;
			$$('#reorderablePages div.reorderableSection').each(function(navEl) {
				if(goToNext)
				{
					var nextPageEl = navEl;
					isGoing = true;
					location.href = nextPageEl.down('a').href;
					throw $break;
				}
				if(currentPage == navEl)
					goToNext = true;
			});
		}

		if(goToNext && !isGoing)
			location.href = $$('#reorderablePages div.reorderableSection')[0].down('a').href;
	},
	
	goToPreviousPage: function(pageId) {
		var currentPage = $('sidebarSections-' + pageId);
		if(currentPage)
		{
			var goToPrevious = false;
			var allNavEls = $$('#reorderablePages div.reorderableSection');
			var previousPageEl = false;
			
			if(allNavEls[0] == currentPage)
				location.href = allNavEls[allNavEls.size()-1].down('a').href;
			else
			{
				allNavEls.each(function(navEl, index) {
					if(currentPage == navEl)
					{
						goToPrevious = true;
						previousPageEl = allNavEls[index-1];
						throw $break;
					}
				});

				if(previousPageEl != false && typeof(previousPageEl) != 'undefined')
					location.href = previousPageEl.down('a').href;
			}
		}
	},
	
	settingsShow: function(el, pageId) {
		if($(el).hasClassName('bottomCurrent'))
		{
			$(el).removeClassName('bottomCurrent');
			Effect.BlindUp($('bottomAjaxSlider'), {duration:0.3, afterFinish: function(){$('bottomAjaxContainer').update('');}});
			return;
		}

		$$('.bottomCurrent').each(function(currentEls) { currentEls.removeClassName('bottomCurrent');});
		$(el).addClassName('bottomCurrent');


		new Ajax.Request(ajaxUrl, { postBody: 'pageId='+pageId+'&ajaxAction=pageSettingsShow', 
			onComplete:function(request) {
				if(!$('bottomInnerContainer'))
				{
					$('bottomAjaxContainer').update(request.responseText);
					new Effect.SlideDown('bottomAjaxSlider', {duration:0.3});
				}
				else
				{
					new Effect.SlideUp('bottomAjaxSlider', {duration:0.3, afterFinish: function() 
						{ 
							$('bottomAjaxContainer').update(''); 
							$('bottomAjaxContainer').update(request.responseText);
							new Effect.SlideDown('bottomAjaxSlider', {duration:0.3});
						}});
				}
				
				// Effect.BlindDown('bottomAjaxSlider',{duration:0.3});
			}});
	},
	
	settingsSave:function(form) {
		var needsConfirmation = false;
		if($('pageContent-second'))
			if(!$('pageContent-second').down('div').innerHTML.empty() && $F('has_multiple_columns') == '0')
			{
				needsConfirmation = true;
			}
		
		if(!needsConfirmation)
			new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=pageSettingsSave&' + $(form).serialize(), onComplete: this.settingsSave_callback.bindAsEventListener(this)});
		else if(confirm('When you revert to a 1 column layout, the information from column 2 is appended to the first column. Continue?'))
			new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=pageSettingsSave&' + $(form).serialize(), onComplete: this.settingsSave_callback.bindAsEventListener(this)});
	},
	
	settingsSave_callback:function(request) {
		if(request.responseText == 'false')
			alert('Sorry but there was an error saving your new settings. Please refresh the page and try again.');
		else
		{
			this.isEditing.main   = false;
			this.isEditing.second = false;
			if($('syntaxHelperBar') && $('syntaxHelperBar').visible()) Effect.BlindUp('syntaxHelperBar',{duration:0.3});
			CloseBottomSlider();
			this.rebuildPageContent();
		}
	},
	
	rebuildPageContent:function() {
		var actualPageContentDimensions       = $('actualPageContent').getDimensions();
		$('actualPageContent').style.height   = (actualPageContentDimensions.height)+'px';
		$('actualPageContent').style.width    = actualPageContentDimensions.width+'px';
		$('actualPageContent').style.position = 'relative';
		var vAlignCenter                      = (actualPageContentDimensions.height/2)-16;

		$('actualPageContent').update('<div class="loadingRebuildPage" style="top:'+vAlignCenter+'px"><img src="'+sysUrl+'template/images/spinner-big.gif" alt="loading..."/></div>');
		
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=pageRefreshContent&pageId=' + $F('pagePageId'), onComplete:function(request){
			$('actualPageContent').style.height   = 'auto';
			$('actualPageContent').style.width    = 'auto';
			$('actualPageContent').style.position = 'static';
			var response = request.responseText.evalJSON();
			$('actualPageContent').update(response.content);
			if(response.hasMultipleColumns == 1 && !$('middleContent').hasClassName('multipleColumns'))
				$('middleContent').addClassName('multipleColumns');
			else if(response.hasMultipleColumns == 0)
				$('middleContent').removeClassName('multipleColumns');
		
			page.registerEvents();
		}});
	},
	
	updateCurrentBreadcrumb: function(projectId) {
		new Ajax.Request(ajaxUrl + '?ajaxAction=reorderUpdateBreadcrumb', { postBody: 'projectId='+projectId+'&pageId='+$F('pagePageId'), onComplete: function(request){
			if(request.responseText != 'false')
				$('pageBreadcrumbs').update(request.responseText);
		} });
	}

};

var page = new Page('mainAjaxSlider');
var pageTitle = new Page('mainAjaxSlider');



// window.onbeforeunload = function() { return "You have not saved your document yet.  If you continue, your work will not be saved.";};
