

var Jumpchart = Class.create();

Jumpchart.prototype = {
	/*
	 * args: 
	 *  #1 id of the container that will hold new page forms
	 */
	initialize: function() {

	},
	
	add: function() {
		if($('mainAjaxSlider').style.display == 'none')
			new Effect.SlideDown('mainAjaxSlider', {duration: 0.3, afterFinish: function() { focusFirst('newProjectForm'); } });
		else
			new Effect.SlideUp('mainAjaxSlider', {duration: 0.3});
	},
	
	
	addVerify: function()
	{
		if(Form.check('newProjectForm'))
			new Ajax.Request(ajaxUrl, { parameters: 'ajaxAction=verifyNewProject&' + Form.serialize('newProjectForm'), onComplete: this._addVerify_callback });
	},

	_addVerify_callback: function(request)
	{
		if(request.responseText == 'limit-reached')
			alert("You can't create more Jumpcharts because you've reached the limit for this plan. Feel free to upgrade your account at the Account link at the top of this page.");
		else if(request.responseText == 'duplicate')
			alert("You already have a Jumpchart with this name. Please, choose another.");
		else if(request.responseText == 'big')
			alert("The name of your Jumpchart is too big.");
		else if(request.responseText == 'true')
			$('newProjectForm').submit();
	},

	viewArchive: function(el) {
		if($('myArchivedJumpcharts') && $('myArchivedJumpcharts').style.display != 'none')
			Effect.SlideUp('myArchivedJumpcharts', {duration:0.4, afterFinish: this._cleanUpOwnerContainer.bindAsEventListener(this) });
		else
		{
			// check if there's a system notice
			if($$('.systemNotice').size() > 0)
			{
				if($('contentSpacer'))
				{
					$('contentSpacer').style.margin = '10px 0 0 0';
					$('contentSpacer').style.padding = '5px';
				}
				$$('.systemNotice').each(function(el) { el.hide();});
			}
				

			showLoading('loadingArchive');
			el.innerHTML = 'Hide archive';
			var myAjax = new Ajax.Request(
				ajaxUrl, 
				{ 
					parameters: 'ajaxAction=viewArchivedJumpcharts', 
					onComplete: this._viewOwnerArchive_callback.bindAsEventListener(this)
				});
		
		}
	
		if($('invitedArchivedJumpcharts') && $('invitedArchivedJumpcharts').style.display != 'none')
			Effect.SlideUp('invitedArchivedJumpcharts', {duration:0.4, afterFinish: this._cleanUpInvitedContainer.bindAsEventListener(this) });
		else
		{
			var invitedAjax = new Ajax.Request(
				ajaxUrl, 
				{ 
					parameters: 'ajaxAction=viewInvitedArchivedJumpcharts', 
					onComplete: this._viewInvitedArchive_callback.bindAsEventListener(this) 
				});
		}
	
		if(($('myArchivedJumpcharts') && $('myArchivedJumpcharts').style.display != 'none') || ($('invitedArchivedJumpcharts') && $('invitedArchivedJumpcharts').style.display != 'none'))
			el.innerHTML = 'Show archive';
	},
	
	_viewOwnerArchive_callback: function(request) {
		hideLoading('loadingArchive');
		if(request.responseText != 'false')
		{
			var content   = Builder.build(request.responseText);
			var container = newEl('div');
			container.id  = 'myArchivedJumpcharts';
			container.style.display = 'none';
			container.appendChild(content);
		
			if(!$('myJumpcharts'))
			{
				var myJumpchartsContainer = $('myJumpchartsContainer');
				myJumpchartsContainer.appendChild(Builder.build("<h2>Current</h2>"));
				myJumpchartsContainer.appendChild(Builder.build('<div id="myJumpcharts"></div>'));
				$('myJumpcharts').appendChild(container);
				myJumpchartsContainer.style.display = 'none';
				container.style.display = 'block';
				Effect.SlideDown(myJumpchartsContainer, {duration:0.4 });
			}
			else
			{
				$('myJumpcharts').appendChild(container);
				Effect.SlideDown(container, { duration:0.4 });
			}
		}
	},
	
	_viewInvitedArchive_callback: function(request) {
		if(request.responseText != 'false')
		{
			var content   = Builder.build(request.responseText);
			var container = newEl('div');
			container.id  = 'invitedArchivedJumpcharts';
			container.style.display = 'none';
			container.appendChild(content);
		
			if(!$('invitedJumpcharts'))
			{
				var invitedJumpchartsContainer = $('invitedJumpchartsContainer');
				invitedJumpchartsContainer.appendChild(Builder.build("<h2>Invitations</h2>"));
				invitedJumpchartsContainer.appendChild(Builder.build('<div id="invitedJumpcharts"></div>'));
				$('invitedJumpcharts').appendChild(container);
				invitedJumpchartsContainer.style.display = 'none';
				container.style.display = 'block';
				Effect.SlideDown(invitedJumpchartsContainer, {duration:0.4});
			}
			else
			{
				$('invitedJumpcharts').appendChild(container);
				Effect.SlideDown(container, {duration:0.4});
			}
		}
	},
	
	_cleanUpOwnerContainer: function() {
		Element.remove('myArchivedJumpcharts');
		if($('myJumpcharts').childNodes.length == 0) 
			Effect.SlideUp('myJumpchartsContainer', 
			{ 
				duration: 0.4, 
				afterFinish: function () 
				{ 
					Element.remove('myJumpcharts'); 
					$('myJumpchartsContainer').removeChild($('myJumpchartsContainer').childNodes[0]);
				} 
			});
	},
	
	_cleanUpInvitedContainer: function() {
		Element.remove('invitedArchivedJumpcharts'); 
		if($('invitedJumpcharts').childNodes.length == 0) 
			Effect.SlideUp('invitedJumpchartsContainer', 
			{ 
				duration: 0.4, 
				afterFinish: function () 
				{ 
					Element.remove('invitedJumpcharts'); 
					$('invitedJumpchartsContainer').removeChild($('invitedJumpchartsContainer').childNodes[0]);
				} 
			});
	},
	
	
	/*
	 * Add, edit, remove, archive
	 */
	
	edit: function(jumpchartId) {
		var container = $('jumpchartEditContainer-' + jumpchartId);
	
		showLoading('jumpchartName-' + jumpchartId);
		if(container.style.display != 'none' && !Element.empty(container))
		{
			hideLoading('jumpchartName-' + jumpchartId);
			Effect.SlideUp(container, {duration:0.4, afterFinish: function (request) { Element.remove(container.childNodes[0]); } });
		}
		else
		{
			var pars = 'ajaxAction=editJumpchart&id=' + jumpchartId;
			// new Ajax.Request(ajaxUrl, { parameters: pars, onComplete: function(request) { this._edit_callback(jumpchartId, request) } });
			new Ajax.Request(ajaxUrl, { parameters: pars, onComplete: this._edit_callback.bindAsEventListener(this, jumpchartId)});	
		}

	},

	_edit_callback: function(request, jumpchartId) {
		var container = $('jumpchartEditContainer-' + jumpchartId);

		hideLoading('jumpchartName-' + jumpchartId);
		if(Element.empty(container))
		{
			var content   = Builder.build(request.responseText);
			container.appendChild(content);	
		}
		Effect.SlideDown(container, {duration:0.4, afterFinish: function (request) { Scroll(container); } });
	},
	
	editSave: function(jumpchartId) {
		var name        = $('name-' + jumpchartId);
		var description = $('description-' + jumpchartId);
	
		if(!Field.present(name))
		{
			Shake(name);
			return false;
		}

		showLoading('jumpchartName-' + jumpchartId);
		var myAjax = new Ajax.Request(
			ajaxUrl + '?ajaxAction=saveEditJumpchart', 
			{ 
				parameters: Form.serialize('jumpchartEditForm-' + jumpchartId), 
				onComplete: this._editSave_callback.bindAsEventListener(this,jumpchartId)
			});	
	},
	
	_editSave_callback: function(request, jumpchartId) {
		hideLoading('jumpchartName-' + jumpchartId);
	
		if(request.responseText == 'false')
			alert("There was an error processing your request");
		else
		{
			var nameContainer = $('jumpchartName-' + jumpchartId);
			var formContainer = $('jumpchartEditContainer-' + jumpchartId);
			nameContainer.childNodes[0].innerHTML = request.responseText;
			Effect.SlideUp(formContainer, {duration:0.4, afterFinish: function (request) { Element.remove(formContainer.childNodes[0]); } });
		}

	},
	
	remove: function(jumpchartId) {
		if(!confirm('Are your sure you want to delete this jumpchart?'))
			return;
		else
		{
			if($('jumpchartName-' + jumpchartId))
				showLoading('jumpchartName-' + jumpchartId);
			var myAjax = new Ajax.Request(
			ajaxUrl, 
			{ 
				parameters: 'ajaxAction=deleteJumpchart&id=' + jumpchartId, 
				onComplete: this._remove_callback.bindAsEventListener(this, jumpchartId)
			});
		}
	},
	
	_remove_callback: function(request, jumpchartId) {
		if($('jumpchartName-' + jumpchartId))
			hideLoading('jumpchartName-' + jumpchartId);
		if(request.responseText == 'false')
			alert("There was an error processing your request");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to remove this Jumpchart.");
		else
			new Effect.BlindUp($('jumpchartName-' + jumpchartId).up('.jumpchart'), {duration:0.2});
	},
	
	removeInvitation: function(jumpchartId) {
		if(!confirm('Are your sure you want to delete this jumpchart invitation?'))
			return;
		else
		{
			if($('jumpchartName-' + jumpchartId))
				showLoading('jumpchartName-' + jumpchartId);
			new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=deleteJumpchartInvitation&id=' + jumpchartId, onComplete: this._removeInvitation_callback.bindAsEventListener(this, jumpchartId) });
		}
	},

	_removeInvitation_callback: function(request, jumpchartId) {
		if($('jumpchartName-' + jumpchartId))
			hideLoading('jumpchartName-' + jumpchartId);
		if(request.responseText == 'false')
			alert("There was an error processing your request");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to remove this jumpchart invitation.");
		else if(request.responseText == 'true')
			new Effect.BlindUp($('jumpchartName-' + jumpchartId).up('.jumpchart'), {duration:0.2});
	},

	/*
	 * The first element isn't used, but it needs to be here due to the onclick event that the function receives
	 * from the Event.observe method.
	 */
	archive: function(e, jumpchartId, unarchive) {
		if(unarchive == null) unarchive = 0;
		showLoading('jumpchartName-' + jumpchartId);
		var myAjax = new Ajax.Request(
			ajaxUrl, 
			{ 
				parameters: 'ajaxAction=archiveJumpchart&id=' + jumpchartId + '&unarchive=' + unarchive, 
				onComplete: this._archive_callback.bindAsEventListener(this, jumpchartId, unarchive)
			});
	},
	
	_archive_callback: function(request, jumpchartId, unarchive) {
		hideLoading('jumpchartName-' + jumpchartId);
		if(request.responseText == 'false')
			alert("There was an error processing your request");
		else if(request.responseText == 'maxpages')
			alert("We couldn't un-archive this project because it has more pages than the limit set by the current account plan. Please consider an upgrade to a bigger plan in order to continue.");
		else if(request.responseText == 'maxprojects')
			alert("We couldn't un-archive this project because your account has reached the limit of projects set by the current account plan. Please consider an upgrade to a bigger plan in order to continue.");
		else
		{
			if($('myArchivedJumpcharts'))
				new Effect.BlindUp($('jumpchartName-' + jumpchartId).up('.jumpchart'), { duration:0.4, afterFinish: this._showLonelyArchivedJumpchart.bindAsEventListener(this, jumpchartId, unarchive, $('jumpchartName-' + jumpchartId).up('.jumpchart')) });
			else
				new Effect.BlindUp($('jumpchartName-' + jumpchartId).up('.jumpchart'), { duration:0.4, afterFinish: function() { $('jumpchartName-' + jumpchartId).up('.jumpchart').remove(); }});
				
			if(!$('archivesLink'))
			{
				$('rightPageActionsNav').appendChild(Builder.build('<div id="archivesLink"><ul><li><a href="javascript:void(0)" onclick="jumpchart.viewArchive(this);">Show archive</a></li></ul></div>'));
			}
		}
	},
	
	_showLonelyArchivedJumpchart: function(t, jumpchartId, unarchive, el) {
		var container = $('jumpchartName-' + jumpchartId).parentNode;

		container.hide();
		if(unarchive == 0)
		{
			$('archiveLink-' + jumpchartId).update('Un-Archive');
			$('archiveLink-' + jumpchartId).onclick = this.archive.bindAsEventListener(this, jumpchartId, 1);
			$('myArchivedJumpcharts').insert({'top':el});
		}
		else
		{
			$('archiveLink-' + jumpchartId).update('Archive');
			$('archiveLink-' + jumpchartId).onclick = this.archive.bindAsEventListener(this, jumpchartId, 0);
			$('myArchivedJumpcharts').insert({'before':el});
		}
		$(el).down('.spacer').show();
		new Effect.SlideDown(el, {duration: 0.3, afterFinish: function(request) { new Effect.Appear(el);}});
	},
	
	makeCopyShow: function(el) {
		new Effect.SlideUp($(el).up('p'),{duration:0.1});
		new Effect.SlideDown('jumpchartCopyContainer',{duration:0.1});
	},
	
	/*
	 * Added early 2010
	 */
	expandNav: function(el, pageId, projectId) {
		if(typeof(pageId) == 'undefined' || typeof(projectId) == 'undefined')
		{
			var e = $(el).up('.pageNameAndReorderHandle').next('.pageList');
			// var projectId = e.className.split('projectId')[1];
			var projectId = $F('pageProjectId');
			// console.log(e.className);
			// console.log(projectId);
			var pageId = e.id.split('subSections')[1];
		}
		
		// if it's event coming from event.observe, "el" is an event and therefore needs needs to be converted to the trigger element
		if(typeof(el.element) != 'undefined')
			el = el.element();
		
		var subSection = $('subSections'+pageId);

		if(!subSection)
		{
			subSection = $(el).up('.pageNameAndReorderHandle ').next('.pageList');
			if(subSection && !subSection.hasClassName('hasSubPages'))
				subSection.addClassName('hasSubPages');
		}

		if(!subSection)
			return false;
		else
		{
			if(subSection.visible())
			{
				subSection.hide();
				$(el).removeClassName('opened');
				subSection.addClassName('collapsed');
				subSection.up('.reorderableSection').addClassName('collapsed');
			}
			else
			{
				subSection.show();
				$(el).addClassName('opened');
				subSection.removeClassName('collapsed');
				subSection.up('.reorderableSection').removeClassName('collapsed');
			}
		}
		this.expandNavSaveCurrentState(projectId);
	},
	
	/* Ajax call to save expand/collapse state on database */
	expandNavSaveCurrentState: function(projectId) {
		
		var allExpandablePages = [];
		$$('.hasSubPages[class~=collapsed]').each(function(e, key){
			var eId = e.id.split('subSections')[1];
			if(typeof(eId) == 'undefined')
			{
				var eIdTmp = e.up('.reorderableSection');
				if(eIdTmp)
					eId = eIdTmp.id.split('-')[1];
			}
			allExpandablePages[key] = eId;
		});
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=saveExpandState&projectId='+projectId+'&collapsedElements='+allExpandablePages.toJSON(), onComplete: this.expandNav_callback.bindAsEventListener(this)});
	},

	expandNav_callback: function(request) {
		// console.log(request.responseText);
	}
};


var jumpchart = new Jumpchart();
