/*
 Copyright (C) 2008 Nu Echo Inc.

 This file requires the Prototype.js and tables.js libraries.

*/


/*
 SORTERS
*/

var sortPaths = propertySorter('path');

var pathSorter = propertySorterGenerator('path');
var ownerSorter = propertySorterGenerator('account', 'path');
var privacySorter = propertySorterGenerator('privacy', 'path');
var creationDateSorter = propertySorterGenerator('creation_stamp', 'path');
var updateDateSorter = propertySorterGenerator('update_stamp', 'path');
var lastCommentDateSorter = propertySorterGenerator('last_comment_stamp', 'path');

/*
CONTENT PROVIDERS
*/
function grammarPath(grammar)
{
	var container; 
	var a = document.createElement('a');
	a.setAttribute('href', '/html_app/grammar/' + grammar.account + '?state=view&path=' 
			+ encodeURIComponent(grammar.account) + ":" + encodeURIComponent(grammar.path));
	a.setAttribute('title', 'View grammar code');
	a.setAttribute('class', 'grammar');
	a.appendChild(document.createTextNode(grammar.path));
	
	if (grammar.account == account || account_scope == "discarded" )
	{
		container = document.createElement('span');		
		container.appendChild(a);
		
		if (grammar.account == account) {
			container.appendChild(create_discard_action(grammar));
		}
		
		if (account == "discarded" ) {
			container.appendChild(create_delete_action(grammar));
		}
	}
	else
	{
		container = a;
	}
	
	return container;
}

function owner(grammar)
{
	var a = document.createElement('a');
	a.setAttribute('href', '/html_app/account/' + grammar.account);
	a.setAttribute('title', 'Focus on ' + grammar.account + "' grammars");
	a.setAttribute('class', 'action');
	a.appendChild(document.createTextNode(grammar.account));
	return a;
}


function privacy(grammar)
{
	var container = document.createElement('span');
	
	container.appendChild(create_privacy_toggle_action(grammar, grammar.privacy));
	container.setAttribute('class', 'privacy_toggle');
	
	return container;
	
}

function create_privacy_toggle_action(grammar, privacy)
{
	var a = document.createElement('a');
	a.setAttribute('id', 'grammar' + grammar.id);
	a.setAttribute('name', 'grammar' + grammar.id);
	a.setAttribute('title', 'Toggle grammar privacy');
	a.setAttribute('class', (privacy ? 'to_public' : 'to_private') );
	a.setAttribute('onclick', 'perform_grammar_action("toggle_privacy", "'  + grammar.account +  '", "' + grammar.path + '");');
	
	var icon = document.createElement('img');
	icon.setAttribute('class', 'privacy_toggle');
	icon.setAttribute('height', '16px');
	icon.setAttribute('width', '22px');
	
	if (privacy)
	{
		icon.setAttribute('src', '/icons/padlock.gif');
		a.setAttribute('onmouseover', 'this.getElementsByTagName("img")[0].src="/icons/padlock_open.gif"');
		a.setAttribute('onmouseout',  'this.getElementsByTagName("img")[0].src="/icons/padlock.gif"');
	}
	else
	{
		icon.setAttribute('src', '/icons/padlock_open.gif');
		a.setAttribute('onmouseover', 'this.getElementsByTagName("img")[0].src="/icons/padlock.gif"');
		a.setAttribute('onmouseout',  'this.getElementsByTagName("img")[0].src="/icons/padlock_open.gif"');
	}
	
	a.appendChild(icon);
	a.appendChild(document.createTextNode(privacy ? 'private' : 'public'));
	return a;
}

function create_discard_action(grammar)
{
	var button = document.createElement('img');
	button.setAttribute('class', 'button');
	button.setAttribute('src', '/icons/discard.gif');
	button.setAttribute('onmouseover', 'this.src="/icons/discard_rollover.gif"');
	button.setAttribute('onmouseout', 'this.src="/icons/discard.gif"');

	var a = document.createElement('a');
	a.setAttribute('id', 'discard_' + grammar.id);
	a.setAttribute('name', 'discard_' + grammar.id);
	a.setAttribute('title', 'Discard this grammar');
	a.setAttribute('class', 'action');
	a.setAttribute('onclick', 'perform_grammar_action("discard", "'  + grammar.account +  '", "' + grammar.path + '");');
	a.appendChild(button);
	return a;
}

function create_delete_action(grammar)
{
	var button = document.createElement('img');
	button.setAttribute('class', 'button');
	button.setAttribute('src', '/icons/discard.gif');
	button.setAttribute('onmouseover', 'this.src="/icons/discard_rollover.gif"');
	button.setAttribute('onmouseout', 'this.src="/icons/discard.gif"');

	var a = document.createElement('a');
	a.setAttribute('id', 'delete_' + grammar.id);
	a.setAttribute('name', 'delete_' + grammar.id);
	a.setAttribute('title', 'Delete permanently this grammar');
	a.setAttribute('class', 'action');
	a.setAttribute('onclick', 'perform_grammar_action("delete", "'  + grammar.account +  '", "' + grammar.path + '");');
	a.appendChild(button);
	return a;
}


function create_recover_action(grammar)
{
	var button = document.createElement('img');
	button.setAttribute('class', 'button');
	button.setAttribute('src', '/icons/recover.gif');
	button.setAttribute('onmouseover', 'this.src="/icons/recover_rollover.gif"');
	button.setAttribute('onmouseout', 'this.src="/icons/recover.gif"');

	var a = document.createElement('a');
	a.setAttribute('id', 'recover_' + grammar.id);
	a.setAttribute('name', 'recover' + grammar.id);
	a.setAttribute('title', 'Recover this discarded grammar');
	a.setAttribute('class', 'action');
	a.setAttribute('onclick', 'perform_grammar_action("recover", "'  + grammar.account +  '", "' + grammar.path + '");');
	a.appendChild(button);
	return a;
}

function remove_tag(tag)
{	
	// Recover the existing tags
	tags = document.tag_selector.filter_tags.value;	
	
	// Nice trick to remove the selected tag
	document.tag_selector.filter_tags.value = tags.split( tag ).join('');		
	
	// OK, we are ready to refresh the page
	document.tag_selector.submit();
}

function pick_tag(tag)
{	
	// OK, make sure that our manipulations won't be seen
	document.tag_selector.new_tags.style.color = document.tag_selector.new_tags.style.backgroundColor;
	
	// OK, insert the picked tag in the form
	document.tag_selector.new_tags.value = tag;		
	
	// OK, we are ready to refresh the page
	document.tag_selector.submit();
}

function toggle_tag_cloud()
{
	tag_cloud_open = !tag_cloud_open;
	adjust_tag_cloud(tag_cloud_open);
}

function adjust_tag_cloud( hidden )
{
	// hide/display the tag cloud and update the "open tag cloud" button accordingly
	if (document.getElementById('tag_cloud'))
	{
		document.getElementById('tag_cloud').style.display = hidden ? 'none' : 'inline-block';
	}
	
	if (document.getElementById('open_tag_cloud'))
	{
		label = hidden ? "\u25C4 pick one" : "\u25BC hide tags";
		document.getElementById('open_tag_cloud').firstChild.nodeValue = label;
	}	
}

function perform_grammar_action( action, grammar_account, grammar_path ) {
	   var refreshError = function() {
	         $('allgrammars').innerHTML = "<p class='error_message'>Unable to connect to NuGram Server. Try refreshing the page. If the error persists, contact the <a href='/html_app/doc/support'>support team</a>.</p>.";
	         __grammarUpdater.stop();
	   };

	new Ajax.Request('/grammar/' + grammar_account + '?state=' + action + '&path=' + encodeURIComponent(grammar_path), {
		   method:    'get',

		  onSuccess: function(transport) {
		     refreshGrammarsTable()
	      },
	      onFailure: function() {
	           refreshError();

	      },
	      onException: function(requester, exception) {
	         refreshError();
	      }
	   });
}

function perform_list_refresh( account ) {

	request = '/grammar/' + account + '?format=json' 
	 		  + '&filter_tags_owner=' + filter_tags_owner
	          + '&filter_tags=' + filter_tags;
	
	new Ajax.Request(request,					 
		{
		   method:    'get',
		   
		   onSuccess: function(transport) {		     
	         __grammars = transport.responseText.evalJSON(true);
	         grammarsTable.dataUpdated();
	      },
	      onFailure: function() {
	    	  grammarsTable.updateFailed();
	    	  __grammarUpdater.stop();
	      },
	      onException: function(requester, exception) {
	    	  grammarsTable.updateFailed();
	    	  __grammarUpdater.stop();
	      }
	   });
}


function creationDate(grammar)
{	
	// return document.createTextNode(grammar.creation_stamp);
	return displayDate(grammar.creation_stamp);
}

function updateDate(grammar)
{	
	if (grammar.update_stamp > grammar.creation_stamp)
	{
		date = grammar.update_stamp;
		return displayDate(date);
	}
	else
	{
		return document.createTextNode("");
	}
}

function lastCommentDate(grammar)
{
	
	if ( grammar.nb_comments > 0)
	{
		var nbCommentsSuffix = " (" + grammar.nb_comments + " comment" + (grammar.nb_comments > 1 ? "s" : "") + ")";
		var dateElement = displayDate(grammar.last_comment_stamp + nbCommentsSuffix); 		
		return dateElement;
	}
	else
	{
		return document.createTextNode("");
	}
}

function displayDate(stamp)
{
	var sliceIndex = stamp.indexOf(" ");

	if ( sliceIndex > 0)
	{
		var container = document.createElement('span');
		var hourElement = document.createElement('span');
		hourElement.setAttribute('class', 'hour');
		hourElement.appendChild(document.createTextNode(stamp.slice(sliceIndex)));
		container.appendChild(document.createTextNode(stamp.slice(0, sliceIndex)));
		container.appendChild(hourElement);
		return container;
	}
	else
	{
		return document.createTextNode(stamp)
	}
}


function discardDate(grammar)
{
	var container = document.createElement('span');
	
	container.appendChild(create_recover_action(grammar));
	container.appendChild(document.createTextNode(grammar.update_stamp));

	return container;
}

function load_grammar_content(grammar_owner, grammar_path)
{
	new Ajax.Request('/grammar?state=view&format=text&grammar_owner=' + encodeURIComponent(grammar_owner) 
			+ '&path=' + encodeURIComponent(grammar_owner) + ":" + encodeURIComponent(grammar_path),					 
			{
			   method:    'get',
			   
			  onSuccess: function(transport) {
				 $('grammar_source').removeChild($('grammar_source').childNodes[0]);
				 text = transport.responseText;
				 				 
				 
				 if (navigator.appName == "Microsoft Internet Explorer"
					 && text.match(/[^\r]\n/))
				 {
					 // Hack made necessary by IE!!!
					 // IE does not properly display lines terminated by a line feed character only.
					 text = text.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
				 }
				 
				 $('grammar_source').appendChild(document.createTextNode(text));				 
		      },
		      onFailure: function() {
		    	  $('grammar_source').removeChild($('grammar_source').childNodes[0]);
			      $('grammar_source').appendChild(document.createTextNode("Unable to recover grammar " + grammar_owner + ":" + grammar_path));
		      },
		      onException: function(requester, exception) {
		    	  $('grammar_source').removeChild($('grammar_source').childNodes[0]);
			      $('grammar_source').appendChild(document.createTextNode("Unable to recover grammar " + grammar_owner + ":" + grammar_path));
		      }
		   });
}

