String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}

var SUGGESTER;

function ActionReply(){};

ActionReply.prototype = {
	init: function()
	{
		var handle = this.listener(this);
		$("a.reply").click(handle);
	},
	listener: function(o)
	{
		return function(e)
		{
			e.stopPropagation();
			e.preventDefault();
			var pid = /(\d+) u\-(.+)/.exec( e.currentTarget.className );
			var u = pid[2];
			var eid=pid[1];
			
			//$_('action').selectedIndex = 1;
			/*$_('context_type').selectedIndex = 0;
			$_('context_name').value = u;
			*/
			$_('message').value = '@' + u +" "+ $_('message').value.replace(/^@[\w_ ]+ ?/,"");
			$_('message').focus();
			$_('reply_event').value = eid;
		};
	}
};


function addContext(e)
{
	var CT = $_('c_type');
	var CN = $_('c_name');
	var apif=$_('action-post');
	var context_field = false;

	e.stopPropagation();
	e.preventDefault();
	
	if( CT && CN && CN.value != '' )
	{
		context_field = document.createElement('input');
		context_field.type='hidden';
		switch( CT.nodeName )
		{
			case 'select':
				context_field.name=CT.options[CT.selectedIndex].value;
				break;
			default:
				context_field.name=CT.value;
				break;
		}

		context_field.value=CN.value;
		apif.appendChild(context_field);
	}
	else
	{
		context_field = document.createElement('input');
		context_field.type = 'hidden';
		context_field.name = 'user';
		context_field.value = $_('comment-through').value;
		$_('action').selectedIndex = 1;
		apif.appendChild(context_field);
	}

	var msg = $_('message-text').value.trim();

	$_('message').value = msg;

	var stat = $_('status');

	if( stat )
	{
		if( stat.selectedIndex == 0 )
		{
			alert('Announce requires status');
			return;
		}
		else
		{
			apif.submit();
		}
	}
	
	if( msg.length>0 )
	{
		apif.submit();
		return
	}

	var act = $_('action');
	var selact;
	if( act )
	{
		selact = act.options[act.selectedIndex].value;
	}

	if( selact != 'reply' || context_field.name != 'user' )
	{
		$_('reply_event').value="";
	}
	
	if( msg.length==0 && selact != 'comment' && selact != 'reply' )
	{
		apif.submit();
	}
	else
	{
		alert('Comments and replies must contain a message');
	}

	if( context_field )
	{
		apif.removeChild(context_field);
		delete context_field;
	}
}

function doFriendRequest(e)
{
	var el = e.currentTarget;
	var user = /u\-(.+)/.exec(el.className.toString());
	var reason = prompt("Request reason (optional)");
	if( confirm("Submit request?") )
	{
		$.post(
				"/api.php?op=requestFriend",
				{user: user[1],"reason": reason || ""},
				function(o)
				{
					if(o.valid){ el.innerHTML = 'Friend Requested'; }
					else if(o['error']) { alert(o.error); }
					else if(o['message']) { alert(o.message); }
					else{ alert('There was an error in the API call'); }
				},
				"json"
			);
		}
}


function init()
{
	var links = $('a',$('.activity'));
	for(var i in links)
	{
		if(links[i]['parentNode'] && /h3/i.test(links[i].parentNode.nodeName) )
		{
		  if( ! /^http:\/\/melative/.test(links[i].href) )
  			links[i].target="_blank";
		}
	}

	if( $_('message') )
	{
	  AREPLY = new ActionReply();
	  AREPLY.init();
	}

	if( $_('context_name') )
		SUGGESTER = new SuggestType($_('context_name'),false,$_('autoresults'));
	
	/*if( $_('action-post') )
	{
		$_('action-post').addEventListener('submit', addContext, true);
		$_('message-text').innerHTML='';
	}*/

	if( $('.request') )
	{
		$('.request').click( doFriendRequest );
	}
	
	var SuggestPositioner = function(){ SUGGESTER.position($_('context_name'),$_('autoresults')); }
	if( $('.actions-list') )
	{
	  $("a", $(".actions-list")).click( actionInject );
	  $("a", $(".action-groups")).click( visibleInject );
	  $("a", $(".action-html")).click( htmlTagInject );
	  $(".help-tab", $("#action-content")).click( function(e){ toggleHelp(e); SuggestPositioner();} );
	  $(window).resize( SuggestPositioner );
	}

	$(".tab", $(".stream-column")).click( toggleRightMeta );
	
	if( $_('message') )
	{
	  var msg = $_('message').value;
	  $_('message').value = msg.replace(/^ +/,"");
	}
}

function toggleRightMeta(e)
{
  if( e.currentTarget.innerHTML == '»' )
  {
    e.currentTarget.innerHTML = '«';
    $(".stream-column").addClass("nometa");
  }
  else
  {
    e.currentTarget.innerHTML = '»';
    $(".stream-column").removeClass("nometa");
  }
}

function toggleHelp(e)
{
  var style; var html;
  if( e.currentTarget.innerHTML == 'Show Help' )
  {
    style = 'block'; html = 'Hide Help';
  }
  else
  {
    style = 'none'; html = 'Show Help';
  }
  $('#action-help').css("display", style);
  e.currentTarget.innerHTML = html;
}

$('document').ready(init);

function $_(id){ return document.getElementById(id); }
function N(nm,node){ if(node){ return node.getElementsByTagName(nm); } else { return document.getElementsByTagName(nm); } }
function $C(cn,type)
{
	var all = type ? document.getElementsByTagName(type) : document.getElementsByTagName('*');
	var re = new RegExp("[^\w]?"+cn+"[^\w]?");
	var r=[];
	for(var i in all)
	{
		if( re.test( all[i].className) )
		{
			r.push(all[i]);
		}
	}
	return r;
}

function findPos(obj)
{
	var cl = ct =0;
	if(obj.offsetParent)
	{
		do{
			cl += obj.offsetLeft;
			ct += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [cl,ct];
}

function actionInject(e)
{
  e.stopPropagation();
  e.preventDefault();
  var action = e.currentTarget.href.toString().split(/#/)[1];
  
  var msg = $_('message').value;
  
  $_('message').value = ("/"+action+" ") + msg.replace( /^\/\w+( |$)/, "");
}

function visibleInject(e)
{
  e.stopPropagation();
  e.preventDefault();
  var group = e.currentTarget.innerHTML;
  var msg = $_('message').value;
  $_('message').value = msg.replace(/ ?!(everyone|users|followers|friends|hidden|locked)/,"") +" "+ group;
}

function htmlTagInject(e)
{
  e.stopPropagation();
  e.preventDefault();
  var tag = e.currentTarget.innerHTML;
  var msg = $_('message').value;
  var start = $_('message').selectionStart;
  var end = $_('message').selectionEnd;

  var inner = "";
  if( start != end )
  {
    inner = msg.substring(start,end);
  }

  var html = "<"+ tag + ">" + inner + "</" + tag + ">";

  $_('message').value = msg.substring(0,start) + html + msg.substring(end);
}

function fillClick(e)
{
	var el = e.currentTarget;
	e.stopPropagation();
	e.preventDefault();
	
	var anch =el.getElementsByTagName('a')[0];
	var m = /http:\/\/.+\.com\/(\w+)\/(.+)/.exec(anch.href.toString());

	var media = m[1];
	var title = anch.innerHTML;
	
	var typeid = $_('context_type') ? 'context_type' : $_('media') ? 'media' : false;

	if( typeid )
	{
		if( $_(typeid)['options'] )
		{
		var opts = $_(typeid).options;
		for(var i in opts)
		{
			if( opts[i].value == media )
				$_(typeid).selectedIndex = i;
		}
		}
		else
		{
			$_(typeid).value = media;
		}
	}
	
	if( $_('context_name') )
	{
		//$_('context_name').value = title;
	}
	else if( $_('title') )
	{
		$_('title').value = title;
	}
	
	$_('autoresults').style.visibility = 'hidden';
	
	// break for message
	addContextInMessage(media,title);
}

function addContextInMessage(media,title)
{
  var msg = $_('message');
  var start = msg.selectionStart;
  
  var pre = "";
  var post = ".";
  
  if( start>0 )
  {
    if( msg.value.substring(start-1,start)!=" " )
      pre = " ";
    post=". ";
  }
  
  msg.value = msg.value.substring(0,start) + pre + "/" + media + "/" + title + "/" + post + msg.value.substring(start);
  $_('context_name').value="";
}

function SuggestType(e,m,l){this.init(e,m,l);};

SuggestType.prototype = {
	_script: null,
	_list:null,
	_blank:null,
	_kill:false,
	_hadResults:true,

	showResults: function(m)
	{
		this._list.style.visibility = m ? 'visible' : 'hidden';
	},
	
	clearResults: function()
	{
		while( this._list.firstChild != this._list.lastChild )
		{
			this._list.removeChild(this._list.lastChild);
		}
	},

	append: function(result)
	{
		var node = this._blank.cloneNode(true);
		node.id="";
		var el = node.getElementsByTagName('*');
		el[0].src='http://images.melative.com' + result.image + '_32.jpg?void';
		el[2].href= 'http://melative.com/'+result.media+'/'+result.title;
		el[2].innerHTML= result.title;
		el[3].innerHTML= "("+ result.year + ", " + result.media +")";
		this._list.appendChild(node);
		
		// list for click
		node.onclick = fillClick;
	},

	inject: function(o)
	{
		if( o.results.length>0 )
		{
		  this.clearResults();
		  this._hadResults = true;
			//this.clearResults();
			for(var i in o.results)
			{
			  //if( this._kill ) break;
			  this.append(o.results[i]);
			}
		}
		else
		{
		  this._hadResults = false;
		}
	},
	
	request: function(str,med)
	{
		if( this._hadResults )
		{
		if( this._script ){ this._script.parentNode.removeChild(this._script); }

		var s = document.createElement('script');
		s.id='txt_inject';
		s.src='http://melative.com/api/entity/search.json?begin_with&callback=SUGGESTER.inject&q='+str + (med? '&media='+med:'');
		document.body.appendChild(s);
		this._script =s;
		}
	},

	listener: function(o,e,m)
	{
		return function(event)
		{
			var eve = event || window.event;

			if( (eve.keyCode>44 || eve.keyCode==8) && e.value.toString().length>1 )
			{
				var med=false
				if( m && m.selectedIndex>0 )
				{
					med = m.options[m.selectedIndex].value;
				}
				if( eve.keyCode==8 || eve.keyCode==46 )
				{
				  o._hadResults = true;
				}
				o.showResults(true);
				o.request(e.value,med);
			}
			
			if( event.keyCode==27 || e.value.toString()==0 )
			{
				o.showResults(false);
			}
		};
	},
	init: function(e,m,l){
		this._list = l;
		e.onkeyup = this.listener(this,e,m);
		this.position(e,l);
		this._blank = l.getElementsByTagName('li')[0];
	},
	position: function(e,l)
	{
		// need to calculate e size
		var pos = findPos(e);
		l.style.top = (pos[1]+24) +'px';
		l.style.left = pos[0] + 'px';
  }
};

