

var Snippet = Class.create();

Snippet.prototype = {
	initialize: function() {
		this.defaultDuration = 0.2;
	},
	
	add: function(projectId) {
		// var container = 'newProject';
		var XHTMLContent = '<div><div class="ajaxContainerTitle" class="smallCentered">Create Snippet</div>';
		XHTMLContent += '<form method="post"  action="" id="newSnippetForm">';
		XHTMLContent += '<p>Name <input type="text" name="name" maxlength="255" class="required" /></p>';
		XHTMLContent += '<p>Content <textarea id="formPageContent" name="content" class="required"></textarea>';
		XHTMLContent += '<p><input type="checkbox" name="is_global" value="1" id="is_global_checkbox" /> <label for="is_global_checkbox">Global snippet <em>(global snippets can be accessed from any project you work on)</em></label></p>';
		XHTMLContent += '<p><input type="hidden" name="projectId" value="' + projectId + '" /><input type="submit" value="Create &gt;" /> <a href="javascript:;" onclick="snippet.add()">Cancel</a></p>';
		XHTMLContent += '</form></div>';

		if($('mainAjaxSlider').style.display == 'none')
		{
			// Hide other edit containers
			// $$('.snippetEditForm').each(function(e) { Effect.SlideUp(e.up(), {duration:0.2, afterFinish: function(){ e.up().up().hide(); e.up().remove(); } }); });
			$$('.snippetEditForm').each(function(e) { e.up().up().hide(); e.up().remove();});
			
			$('mainAjaxContainer').appendChild(Builder.build(XHTMLContent));
			// $('mainAjaxContainer').update(XHTMLContent);
			Event.observe('newSnippetForm', 'submit', this.addVerify.bindAsEventListener(this));
			new Effect.SlideDown('mainAjaxSlider', {duration: this.defaultDuration, afterFinish: this._add_callback.bindAsEventListener(this, projectId) });
		}
		else
			new Effect.SlideUp('mainAjaxSlider', {duration: this.defaultDuration, afterFinish: this._add_close_callback.bindAsEventListener(this)});
	},
	
	_add_close_callback: function() {
		// this.closeSyntaxHelpOverlay();
		$('mainAjaxContainer').down().remove();
	},
	
	_add_callback: function(t, projectId) {
		// this.showSyntaxHelp(0, projectId);
		focusFirst('newSnippetForm'); 
	},
	
	addVerify: function(e) {
		Event.stop(e);
		if(Form.check('newSnippetForm'))
			this.addSave();
	},
	
	addSave: function() {
		showLoading('snippetLoader');
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=snippetAddSave&' + $('newSnippetForm').serialize(), onComplete: this._addSave_callback.bindAsEventListener(this) });
	},
	
	_addSave_callback: function(request) {
		hideLoading('snippetLoader');
		if(request.responseText == 'duplicate')
		{
			if($F($('newSnippetForm').down('input[type=checkbox]')) == null)
				alert("Unfortunately you can't have two snippets with the same name under the same project.");
			else
				alert("Unfortunately you already have a snippet under this project with this name. Even though you're trying to create a global snippet, the names must be unique.");
		}
		else if(request.responseText == 'duplicate-global')
		{
			if($F($('newSnippetForm').down('input[type=checkbox]')) == null)
				alert("Unfortunately you already have a global snippet with this same name. Even though you're trying to create a local snippet, the names must be unique.");
			else
				alert("Unfortunately you can't have two global snippets with the same name.");
		}
		else if(request.responseText == 'duplicate-shared')
			alert("Sorry but this project already have a shared snippet with this name. ");
		else if(request.responseText == 'false')
			alert("Sorry but there was an error creating your snippet. Reload the page an try again.");
		else
		{
			if($$('.systemNotice').size() > 0)
			{
				// $$('.systemNotice').each(function(e){ $(e).remove(); });
				$('contentSpacer').hide();
				// $$('.systemNotice').each(function(e){ new Effect.SlideUp(e, {duration:0.2, afterFinish:function(){ e.up().remove();}}); });
				
			}
			
			var newSnippetContainer = Builder.build(request.responseText);
			if($F($('newSnippetForm').down('input[type=checkbox]')) == null)
			{
				$('mySnippets').insertBefore(newSnippetContainer, $('mySnippets').down());
				$('snippetsTitleLocal').show();
			}
			else
			{
				$('globalSnippets').insertBefore(newSnippetContainer, $('globalSnippets').down());
				$('snippetsContainerGlobal').show();
				$('snippetsTitleGlobal').show();
			}

			$(newSnippetContainer).show();
			this.add(0);
		}
	},
	
	view: function(snippetId) {
		var container = $('snippetEditContainer-' + snippetId);

		showLoading('snippetName-' + snippetId);
		if(container.style.display != 'none' && !Element.empty(container))
		{
			hideLoading('snippetName-' + snippetId);
			Effect.SlideUp(container, {duration:this.defaultDuration, afterFinish: this._edit_close_callback.bindAsEventListener(this, snippetId) });
		}
		else
		{
			var self = this;
			$$('#sharedSnippets .snippetEditContainer').each(function(e){
				if(e.visible())
					new Effect.SlideUp(e, {duration:self.defaultDuration});
			});
			var pars = 'ajaxAction=snippetView&id=' + snippetId;
			new Ajax.Request(ajaxUrl, { postBody: pars, onComplete: this._edit_callback.bindAsEventListener(this, snippetId)});	
		}
	},
	
	edit: function(snippetId, projectId) {
		var container = $('snippetEditContainer-' + snippetId);

		showLoading('snippetName-' + snippetId);
		if(container.style.display != 'none' && !Element.empty(container))
		{
			hideLoading('snippetName-' + snippetId);
			Effect.SlideUp(container, {duration:this.defaultDuration, afterFinish: this._edit_close_callback.bindAsEventListener(this, snippetId) });
		}
		else
		{
			// Hide 'create new' container
			if($('mainAjaxSlider').style.display != 'none')
				new Effect.SlideUp('mainAjaxSlider', {duration: this.defaultDuration, afterFinish: function() {$('mainAjaxContainer').down().remove();}});

			// Hide other edit containers
			var self = this;
			$$('.snippetEditContainer').each(function(e) {
				if(e.visible())
					new Effect.SlideUp(e, {duration:self.defaultDuration});
			});

			var pars = 'ajaxAction=snippetEditShow&id=' + snippetId+'&projectId='+projectId;
			new Ajax.Request(ajaxUrl, { postBody: pars, onComplete: this._edit_callback.bindAsEventListener(this, snippetId)});	
		}
	},
	
	_edit_close_callback: function(t, snippetId) {
		$('snippetEditContainer-'+snippetId).update('');
	},

	_edit_callback: function(request, snippetId) {
		var container = $('snippetEditContainer-' + snippetId);
		hideLoading('snippetName-' + snippetId);

		if(!$(container).visible())
		{
			container.update(request.responseText);
			container.insert({'top':'<div class="break"></div>'});
		}
		Effect.SlideDown(container, {duration:this.defaultDuration, afterFinish: this._edit_callback_helper.bindAsEventListener(this,snippetId) });

	},
	
	_edit_callback_helper: function(t, snippetId) {
		focusFirst('snippetEditForm-' + snippetId); 
	},

	editSave: function(snippetId) {
		var name        = $('name-' + snippetId);
		var description = $('content-' + snippetId);
	
		if(!Field.present(name))
		{
			Shake(name);
			return false;
		}

		showLoading('snippetName-' + snippetId);
		var myAjax = new Ajax.Request(
			ajaxUrl + '?ajaxAction=snippetEditSave', 
			{ 
				parameters: Form.serialize('snippetEditForm-' + snippetId), 
				onComplete: this._editSave_callback.bindAsEventListener(this,snippetId)
			});	
	},
	
	_editSave_callback: function(request, snippetId) {
		hideLoading('snippetName-' + snippetId);
	
		if(request.responseText == 'duplicate')
		{
			// if($F($('snippetEditContainer-'+snippetId).down('input[type=checkbox]')))
				alert("Unfortunately you already have a local snippet with this same name");
			// else
				// alert("Unfortunately you already have a snippet under this project with this name. Even though you're trying to edit a global snippet, the names must be unique.");
		}
		else if(request.responseText == 'duplicate-global')
		{
			// if($F($('snippetEditContainer-'+snippetId).down('input[type=checkbox]')))
				// alert("Unfortunately you already have a global snippet with this same name. Even though you're trying to edit a local snippet, the names must be unique.");
			// else
				alert("Unfortunately you already have a global snippet with the same name.");
		}
		else if(request.responseText == 'duplicate-shared')
			alert("Sorry but this project already have a shared snippet with this name. ");
		else if(request.responseText == 'false')
			alert("There was an error processing your request");
		else
		{
			var nameContainer = $('snippetName-' + snippetId);
			var formContainer = $('snippetEditContainer-' + snippetId);
			nameContainer.childNodes[0].innerHTML = request.responseText;
			
			Effect.SlideUp(formContainer, {duration:this.defaultDuration, afterFinish: function (request) {
				// Element.remove(formContainer.childNodes[0]);

				if($F($('snippetEditContainer-'+snippetId).down('input[type=checkbox]')) == null && $('snippetEditContainer-'+snippetId).up('#globalSnippets'))
				{
					$('snippetsTitleLocal').show();

					var content = $('snippet-'+snippetId).cloneNode(true);
					$('snippet-'+snippetId).remove();
					$('mySnippets').insert({'bottom':content});
					if($('globalSnippets').empty())
					{
						$('snippetsTitleGlobal').hide();
						$('snippetsContainerGlobal').hide();
					}
				}
				else if($F($('snippetEditContainer-'+snippetId).down('input[type=checkbox]')) != null && !$('snippetEditContainer-'+snippetId).up('#globalSnippets'))
				{
					$('snippetsTitleGlobal').show();
					$('snippetsContainerGlobal').show();
					var content = $('snippet-'+snippetId).cloneNode(true);
					$('snippet-'+snippetId).remove();
					$('globalSnippets').insert({'bottom':content});
					if($('mySnippets').empty())
						$('snippetsTitleLocal').hide();
				}

				$('snippetEditContainer-'+snippetId).update('');
			}});

		}
	},
	
	remove: function(snippetId) {
		if(confirm("Are your sure you want to remove this snippet?"))
		{
			showLoading('snippetName-'+snippetId);
			new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=snippetRemove&snippetId=' + snippetId, onComplete: this._remove_callback.bindAsEventListener(this, snippetId) });
		}
			
	},
	
	_remove_callback: function(request, snippetId) {
		if(request.responseText == 'false')
			alert("Sorry but we couldn't remove your snippet. Please reload the page and try again.");
		else
			new Effect.BlindUp('snippet-' + snippetId, {duration:this.defaultDuration, afterFinish:function(){ 
				$('snippet-' + snippetId).remove();
				
				if($('globalSnippets').empty())
					$('snippetsTitleGlobal').hide();
				
				if($('mySnippets').empty())
					$('snippetsTitleLocal').hide();
					
				if($('mySnippets').empty() && $('globalSnippets').empty() && $('sharedSnippets').empty() && $('contentSpacer'))
					$('contentSpacer').show();
			}});
	},
	
	showSyntaxHelp: function(snippetId, projectId) {
		if($('syntaxHelpOverlay'))
			this.syntaxHelpUpdateHeight();
		else
		{
			if(typeof(projectId) == 'undefined')
				new Ajax.Request(ajaxUrl, {postBody: 'ajaxAction=showSyntaxHelp&isSnippet=1&snippetId=' + snippetId, onComplete: this._showSyntaxHelp_callback.bindAsEventListener(this) });
			else
			{
				new Ajax.Request(ajaxUrl, {parameters: 'ajaxAction=showSyntaxHelp&isSnippet=1&&projectId=' + projectId, onComplete: this._showSyntaxHelp_callback.bindAsEventListener(this) });
			}
		}
	},
	
	syntaxHelpUpdateHeight: function() {
		window.setTimeout(function() { $('syntaxHelpOverlay').style.height = ($('main').getHeight() - 75) + 'px'; }, 10);
	},

	_showSyntaxHelp_callback: function(request) {
		var XHTMLContent = Builder.build('<div id="syntaxHelpOverlay" style="display:none"></div>');
		XHTMLContent.appendChild(Builder.build(request.responseText));
		$('main').appendChild(XHTMLContent);
		
		var pageWidth = $('wrapper').getWidth();
		// var overlayWidth = (pageWidth-940)/2 + $('rightPageActionsNav').getWidth();
		var overlayWidth = pageWidth;
		// window.setTimeout(function() { XHTMLContent.style.height = ($('main').getHeight() - 75) + 'px'; }, 100);
		
		XHTMLContent.style.width  = overlayWidth + 'px';
		new Effect.Appear('syntaxHelpOverlay', { duration: 0.3, from: 0, to: 0.9});
	},
	
	closeSyntaxHelpOverlay: function() {
		if($('syntaxHelpOverlay'))
		{
			if(!$('newSnippetForm') || $$('.snippetEditInnerContainer').size() == 0)
				new Effect.Fade('syntaxHelpOverlay', {duration: 0.3, from: 0.9, to: 0, afterFinish: function() { $('syntaxHelpOverlay').remove(); }});
			else
				this.syntaxHelpUpdateHeight();
		}
	}
};

var snippet = new Snippet();

