/* GLOBALS */

var alreadylinked = false;
var editing = false;
var offset = 1;
var loading = false;
var stop = 3;

function toggle(id) {
	$('#'+id).toggle();
}

function logohover(which) {
	if(which==1) {
		$('#search').css('padding-left','9px');
		$('#logo').css('background-position','0px -120px');
	}
	else {
		$('#search').css('padding-left','10px');
	}
}

function accounthover(which) {
	var w = $('#account').width();
	if(which==1) $('#account').css('width',(w+1)+"px");
	else $('#account').css('width',(w-1)+"px");
	$('#account ul.sub').css('width',(w-1)+'px');
}

function hideRooster() {
	$('#rooster').slideUp();
	$.post(
		"/profile/hideRooster",
		function(data) {
		}
	);
}

function hide(id) {
	var par = $('#r'+id).parent();
	$('#r'+id).fadeOut('fast');
	//var thissound=document.getElementById('hide_sound');
	//if(thissound) thissound.Play();
	$.post(
		"/posts/hide",
		{ id: id },
		function() {
			par.css('padding','5px');
			par.css('background','#f3f3f3');
			par.html('<div class="tac fcg">POST HAS BEEN HIDDEN</div>');
			setTimeout(function() {
				par.slideUp();
			},1000);
		}
	);
}

function submitenter(myfield,e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13) {
		myfield.form.submit();
		return false;
	}
	else return true;
}

function makediv(type,id) {
	var elm = document.createElement(type);
	elm.id = id;
	return elm;
}

function holdme(val,elm) {
	$(elm).val(val);
	$(elm).css('opacity','.6');
}	

function make_popup(content,width,wash) {
	if($('#popup')) closePopup(1);
	var main = makediv('div','popup');
	if(wash) main.className="wash";
	var outer = makediv('div','popup_outer');
	var inner = makediv('div','popup_inner');
	outer.appendChild(inner);
	main.appendChild(outer);
	inner.innerHTML='<div class="loading"><span class="fl_r mtnm"><img src="/static/images/ajax-loader-fb.gif"></span>Loading...</div>';
	if(content) inner.innerHTML=content;
	if(width) outer.style.width=width+"px";
	if(document.all) {
		main.style.position="absolute";
		main.style.top=document.body.scrollTop+"px";
		main.style.left=(document.body.clientWidth/2)-265+"px";
	}
	$('body').append(main);
}

function login() {
	make_popup();
	$.post(
		"/ajax/main.php",
		{ login: true },
		function(data) {
			$('#popup_inner').html(data);
		}
	);
}

function closePopup(fadeout) {
	if(!fadeout) {
		$('#popup').fadeOut('',function() {
			$('#popup').remove();
		});
	}
	else $('#popup').remove();
}

function show_waiting(id) {
	$('#'+id).html('<img src="http://www.lmtmag.com/static/images/ajax-loader-blue.gif">');
}

function focusme(elm,focus) {
	var place = $(elm).attr("placeholder");
	var fid = $(elm).parent().attr('fid');
	if(focus==1) {
		if($(elm).val()==place) {
			$(elm).val('');
			$(elm).parent().parent().removeClass("closed").addClass("open");
			$(elm).css('height','50px');
		}
		$(elm).removeClass("place");
		if(fid) {
			$('#button_'+fid).show();
		}
				
	}
	else {
		var val = $(elm).val();
		if(val.replace(/ /g,'')=='') {
			$(elm).val(place);
			if(fid) {
				$(elm).parent().parent().removeClass("open").addClass("closed");
				$('#button_'+fid).hide();
				$(elm).css("height","13px");
			}
			$(elm).addClass("place");
		}
	}
}

function loadpagelet(elm) {
	$('#subnav a').removeClass('active');
	$(elm).addClass('active');
	var cont = $(elm).attr("data");
	$('#maincontent').html('<center style="margin:130px 0;"><img src="/static/images/ajax-loader-fb.gif"/></center>');
	$.get(
		cont,
		function(data) {
			$('#maincontent').html(data);
			initstuff();
		}
	);
}

function pill_select(elm) {
	$('ul.pills a').removeClass('active');
	$(elm).addClass('active');
	var cont = $(elm).attr('data');
	var div = $('#pagecontent');
	if($(elm).attr('tar')) div = $('#'+$(elm).attr('tar'));
	var height = div.height();
	if(height < 300) {
		var h = (height/2)-30;
		var style = 'margin: '+h+'px 0 0 0';
	}
	else var style = 'margin: 130px 0;';
	if($('#pload').length) $('#pload').html('<img style="margin-top:8px;" src="/static/images/ajax-loader-fb.gif" />');
	else div.html('<center style="'+style+'"><img src="/static/images/ajax-loader-fb.gif"/></center>');
	$.get(
		cont,
		function(data) {
			if($('#pload')) $('#pload').empty();
			div.html(data);
			initstuff();
		}
	);
}

function loadContent(which) {
	show_waiting('fload');
	$.post(
		"/ajax/"+which+".php",
		{ more: 1 },
		function(data) {
			$('#posts').append(data);
			$('#fload').html("Show More Posts");
		}
	);
}

function contextual(elm) {
	if($('#contextual').length) $('#contextual').remove();
	var ep = $(elm).attr("ep");
	var pos = $(elm).position();
	var div = document.createElement('div');
	div.id="contextual";
	div.style.left = (pos.left-150)+'px';
	div.style.top = (pos.top+10)+'px';
	div.innerHTML = '<img src="/static/images/ajax-loader-fb.gif" class="pam" />';
	$('body').append(div);
	$.get(
		"/"+ep,
		function(data) {
			$('#contextual').html(data);
		}
	);
}

function dialog(cont,wash) { ajax_get(cont,1,'',wash); }

function dialog_w(cont,width) {
	make_popup('',700,0);
	$.get(
		cont,
		function(data) {
			$('#popup').html(data);
			init_tokens();
		}
	);
}

function ajax_get(cont,isdialog,content,wash) {
	if(!wash) wash = 0;
	if(isdialog) make_popup('','',wash);
	if(!params) var params = null;
	$.get(
		cont,
		{ params: params },
		function(data) {
			if(isdialog) {
				$('#popup').html(data);
				init_tokens();
			}
			else $('#'+content).html(data);
		}
	);
}

function ajax_post(cont) {
	if(!params) params = null;
	$.post(
		"/"+cont,
		{ params : params },
		function(data) {
			//nothing
		}
	);
}

function showmore(cont) {
	if(loading) return;
	show_waiting('loader');
	if(!params) var params = null;
	loading = true;
	$.get(
		"/"+cont,
		{ offset: offset, params: params },
		function(data) {
			if(!data) {
				data = '<div class="empty" id="empty">Nothing more to show :(</div>';
				$('#loader').remove();
				setTimeout(function() {
					$('#empty').fadeOut(function() { $('#empty').remove() });
				},2000);
			}
			else $('#loader').html('Show More');
			$('#all').append(data);
			loading = false;
		}
	);
	offset++;
}

function infiscroll(lim,func,autostart,amount,id) {
	if(amount>0) stop = amount;
	else stop = amount;
	limit = lim;
	if(autostart==1) {		
		$(document).ready(function() {
			eval(func);
		});
	}
	$(window).scroll(function() {
		if($(window).scrollTop() == $(document).height() - $(window).height()) {
			if($('#'+id).length && stop>0) {
				eval(func);
				stop--;
			}
		}
	});
}

function submit_topic() {
	var form = document.forms['topicForm'];
	disable_form(form,'Adding...');
	var params = $('#topicForm').serializeArray();
	params = $.param(params);
	$.post(
		"/games/edit/"+form.game_id.value,
		params,
		function(data) {
			enable_form(form,'+ Add Topic');
			form.display_date.value = data.display_date;
			form.date.value = data.date;
			form.topic.value = '';
			form.starter.value = '';
			$('#all').append(data.response);
		},
		"json"
	);
}

/* SUBMISSIONS */

function check_post(form,checker) {
	if(!checker) checker=0;
	var form = document.forms[form];
	var post = form.post.value;
	var msg = encodeURIComponent(form.post.value);
	var tid = form.tid.value;
	
	if(post.replace(/ /g,"")=="") return;
	
	if(form.starter && form.starter.value !='') {
		if(form.starter.value == post || post.indexOf(form.starter.value)!=-1) {
			highlight('starter');
			if(checker) var stat = '#pstatus';
			else var stat = '#status';
			$(stat).html('<div class="box_yellow pal mbl fwb">Your post can\'t be too similar to the starter</div>');
			$(stat).slideDown();
			form.post.value = '';
			form.post.focus();
			setTimeout(function() { $(stat).slideUp('',function() { $(stat).empty(); }); },2000);
			return;
		}
	}
	if(!tid) {
		alert('No topic specified');
		return;
	}
	if(!checker) {
		show_waiting('load');
		disable_form(form,"Checking...");
	}
	else {
		var pform = document.forms['popup_footer_form'];
		show_waiting('popup_load');
		disable_form(pform,'Checking...');
	}
	$.post(
		"/games/checkpost",
		{ dupes: 1, msg: msg, tid: tid, nopost: checker },
		function(data) {
			if(checker) $('#popup_load').empty();
			else $('#load').empty();
			
			if(data) {
				make_popup('','');
				$('#popup').html(data);
				enable_form(form,'Post',1);
			}
			else {
				if(checker) {
					$('#dupe_result').show();
					pform.submit_button.setAttribute("onclick","submit_gamepost(1)");
					document.forms['dupeForm'].post.disabled = true;
					enable_form(pform,"Okay, Post This Instead",1);
				}
				else submit_gamepost(0);
			}
		}
	);
}

function submit_gamepost(checker) {
	if(!checker) checker = 0;
	if(checker) {
		var form = document.forms['dupeForm'];
		show_waiting('popup_load');
		disable_form(document.forms['popup_footer_form']);
	}
	else {
		var form = document.forms['postForm'];
		show_waiting('load');
		disable_form(form);
	}
	if(form.post.value.replace(/ /g,"")=="") return;
	var msg = encodeURIComponent(form.post.value);
	var tid = form.tid.value;
	if(form.fb && form.fb.checked) var fb = 1;
	else fb = 0;
	if(!tid) {
		alert('No Topic Specified');
		return;
	}
	$.post(
		"/games/post",
		{ posting: true, topic: tid, msg: msg, replace: checker, fb: fb },
		function(data) {
			if(data.length==0) {
				notloggedin();
				return;
			}
			if(checker) {
				closePopup();
				$('#mypost').remove();
			}
			else {
				$('#load').empty();
				$('#post').fadeOut();
				enable_form(form);
			}
			$('#maincontent').prepend(data);
		}
	);
}

function postme(form_name) {
	var form = document.forms[form_name];
	var msg = encodeURIComponent(form.post.value);
	show_waiting('load');
	disable_form(form);
	$.post(
		'/'+form.controller.value,
		{ post: msg, threadID: form.threadID.value },
		function(data) {
			$('#all').append(data);
			$('#load').empty();
			var objDiv = document.getElementById('thread');
			objDiv.scrollTop = objDiv.scrollHeight;
			enable_form(form);
		}
	);
}

/* GENERIC SEND POPUP FORM */

function sendpopup(cont,redirect,close,post) {
	var form = document.forms['popup_postForm'];
	var params = $('#popup_postForm').serializeArray();
	params = $.param(params);
	closePopup(1);
	make_popup('<div class="loading">Sending...</div>');
	$.post(
		'/'+cont,
		params,
		function(data) {
			if(redirect) window.location=redirect;
			else if(close) {
				closePopup();
				$('#'+close).html(data);
			}
			if(post) {
				$('#'+post).prepend(data);
			}
			else $('#popup').html(data);
		}
	);
}

function submit_post() {
	var form = document.forms['postForm'];
	if(form.post.value.replace(/ /g,"")=="" || form.post.value==form.post.getAttribute("placeholder")) return;
	var msg = encodeURIComponent(form.post.value);
	var cid = form.context_id.value;
	if(form.game_id) var gid = form.game_id.value;
	else gid = null;
	if(form.topicID) var tid = form.topicID.value;
	else var tid = null;
	var asgame = null;
	if(form.makegame && form.makegame.checked) {
		if(form.asgame.value.replace(/ /g,"")=="") {
			alert('Please enter a name for this game');
			return;
		}
		else asgame = form.asgame.value;
	}
	show_waiting('load');
	disable_form(form);
	$.post(
		"/forum/post",
		{ posting: true, context: form.context.value, 
		msg: msg, context_id: cid, 
		game_id: gid, topicID: tid, 
		asgame: asgame
		},
		function(data) {
			$('#load').empty();
			enable_form(form);
			if(form.asgame) {
				//$('#game_ex').html('<span id="temp" class="fss fcg" style="position:absolute;right:5px;top:3px;">&larr; What\'s the game title?</span><input type="text" name="asgame" class="text tokenize" max="1" hint="Start typing an existing or new game name…" placeholder="What\'s the name of this game?" link="/search/games" />');
			}
			if(asgame && (asgame.length>2 || asgame==0)) {
				make_popup('','');
				$('#popup').html(data);
			}
			else {
				if(form.asgame) {
					form.makegame.checked = false;
					$('#gameslist').hide();
				}
				if(data.length==0) {
					notloggedin();
					return;
				}
				$('#all').prepend(data);
			}
		}
	);
}

// Submit a forum comment

function submit_comment(fid,is_game) {
	var form = document.forms['comment_'+fid];
	var post = encodeURIComponent(form.post.value);
	if(!post || post.replace(/ /g,'')=="") return;
	disable_form(form);
	$.post(
		"/forum/post",
		{ posting: true, msg: post, fid: fid, is_game: is_game },
		function(data) {
			enable_form(form,"Comment");
			$('#list_'+fid).append(data);
		}
	);
}

function show_comments(tId,focus) {
	$('#reply_'+tId).show();
	if(!$('#c'+tId).hasClass("wc")) {
		$('#c'+tId).addClass("wc");
		if(!$('#llist_'+tId).length) $('#c_text_'+tId).prepend('<div class="likelist" id="llist_'+tId+'"></div>');
		$('#c_text_'+tId).prepend('<span class="nub"><img src="/static/images/nub.png"></span>');
	}
	if(focus) {
		document.forms['comment_'+tId].post.focus();
		var pos = $('#reply_'+tId).position();
		$('#main').scrollTop(pos.top);
	}
}

function load_comments(tid,limit,is_game) {
	if(!is_game) is_game = 0;
	show_waiting(tid+'_load');
	$.get(
		"/forum/comments",
		{ loadcomments: tid, limit: limit, is_game: is_game },
		function(data) {
			$('#'+tid+'_load').parent().remove();
			$('#list_'+tid).prepend(data);
		}
	);
}

function attend(id,elm) {
	var e = $(elm).parent();
	$(elm).parent().html('<img src="/static/images/ajax-loader-blue.gif" />');
	$.post(
		"/events/attend/",
		{ id: id },
		function(data) {
			e.remove();
			$("#attending_"+id).html(data);
		}
	);
}

function profilepic(id) {
	make_popup();
	$.get(
		"/profile/pic/"+id,
		function(data) {
			$('#popup_inner').html(data);
		}
	);
}

function ra_collapse(id,elm) {
	$('#'+id).show();
	$(elm).parent().remove();
}

function reset_notifs() {
	$('#notifications').slideUp();
	$.post(
		"/accounts/resetNotifs",
		{ resetNotes: 1 }
	);
}

function game_like(id) {
	if($('#popup').length) {
		var prefix = '#pr';
		var popup = true;
	}
	else {
		var prefix = '#r';
		var popup = false;
	}
	$(prefix+id+' a.delete').parent().html('<img src="/static/images/ajax-loader-fb.gif" />');
	$.post(
		"/games/like",
		{ pid: id, popup: popup },
		function(data) {
			$(prefix+id).parent().addClass('liked');
			$(prefix+id).parent().html(data);
			if(popup && $('#r'+id).length) {
				$('#r'+id).parent().addClass('liked');
				$('#r'+id).parent().html(data);			
			}
		}
	);
}

function heart(id) {
	var par = $('#r'+id+' a.delete').parent();
	par.html('<img src="/static/images/ajax-loader-fb.gif" />');
	$.post(
		"/posts/heart",
		{ id: id },
		function(data) {
			//var thissound=document.getElementById('heart_sound');
			//if(thissound) thissound.Play();
			par.html('<span class="delete" href="javascript:void(0)" onclick="unheart('+id+')"></span>');
		}
	);
}

function unheart(id) {
	if(confirm("Are you sure you want to remove this from your favorites?")) {
		$('#r'+id+' a.delete').html('<img src="/static/images/ajax-loader-fb.gif" />');
		var elm = $('#r'+id).parent();
		$.post(
			"/posts/unheart",
			{ id: id },
			function(data) {
				elm.fadeOut('fast',function() { elm.remove(); } );
			}
		);
	}
}

function checklength(elm) {
	var val = elm.value;
	var max = elm.getAttribute("maxlength");
	if(val.length >= (max-5)) {
		var minus = max - val.length;
		if(minus < 2) color = "#ff0000";
		else color = "#990000";
		elm.style.color = color;
		$('#tip').html('<b style="color:'+color+'">'+minus+' left</b>; max is '+max);
	}
	else {
		elm.style.color = "";
		$('#tip').html('<b>Pro Tip</b>: Press Cmd+F or Ctrl+F to search for potential duplicates! <a href="javascript:void(0)" onclick="dialog(\'/faq/etiquette\')">Learn More</a>');
	}
}

function like(id,is_comment,is_game) {
	if(!is_game) is_game = 0;
	$('#c'+id+' span.actions a.like').parent().html('<a class="action like" title="Unlike" href="javascript:unlike('+id+','+is_comment+')">Unlike</a>');
	if($('#l_'+id).length) show_waiting(id+'_l_load');
	$.post(
		"/forum/like",
		{ like: 1, fid: id, is_game: is_game },
		function(data) {
			if(data.length==0) {
				notloggedin();
				return;
			}
			if(!is_comment) {
				show_comments(id);
				if(!$('#l_'+id).length) {
					$('#llist_'+id).html('<div class="commentbox"><span class="fl_r load" id="'+id+'_l_load"></span><span class="likecount" id="l_'+id+'">'+data+' liked this</span></div>');
				}
				else $('#l_'+id).html(data+' liked this');
				$('#'+id+'_l_load').empty();
			}
			else {
				$('#l_'+id).html('<em> &middot; </em><span class="clike"> '+data+'</span>');
			}
		}
	);
}

function unlike(id,is_comment) {
	$('#c'+id+' span.actions a.like').parent().html('<a class="action like" title="Like" href="javascript:like('+id+','+is_comment+')">Like</a>');
	if($('#l_'+id).length) show_waiting(id+'_l_load');
	$.post(
		"/forum/like",
		{ unlike: 1, fid: id },
		function(data) {
			if(!is_comment) {
				if(!data) {
					$('#l_'+id).parent().remove();
				}
				else $('#l_'+id).html(data+' liked this');
				$('#'+id+'_l_load').empty();
			}
			else {
				if(!data) {
					$('#l_'+id).remove();
					$('#c'+id+' small em').remove();
				}
				else $('#l_'+id).html('<em> &middot; </em><span class="clike"> '+data+'</span>');
			}
		}
	);
}

function follow(id,elm) {
	$(elm).removeClass("gray").removeClass("red").addClass("depressed");
	$(elm).html("Following...");
	$.post(
		"/profile/follow",
		{ follow: true, id: id },
		function(data) {
			$(elm).remove();
			//$(elm).html("Unfollow");
			//$(elm).click(function() { unfollow(id,this); });
		}
	);
}

function unfollow(id,elm) {
	$(elm).val("Unfollowing...");
	$.post(
		"/profile/follow",
		{ unfollow: true, id: id },
		function(data) {
			$(elm).val("+ Follow");
			$(elm).removeClass("depressed").addClass("red");
			$(elm).click(function() { follow(id,this); });
		}
	);
}

function highlight(elm) {
	$("#"+elm+' span').effect("highlight", { color: '#f7f1b2' }, 3000);
}

function notloggedin() {
	var content = '<div class="title">You\'re Not Logged In</div>';
	content += '<div class="content">Your user ID is missing! You might not be logged in.</div>';
	content += '<div class="footer"><span class="fl_r"><input type="button" onclick="window.location=\'/index.php\'" class="button blue" value="Close">';
	make_popup(content,500);
}

/* FORM FUNCTIONS */

function disable_form(form,val) {
	if(!val) val="Posting...";
	if(form.post) form.post.disabled=true;
	if(form.submit_button) {
		form.submit_button.disabled=true;
		form.submit_button.value=val;
	}
	form.parentNode.style.opacity=".5";
}

function enable_form(form,val,clear) {
	if(!val) val = "Share";
	if(form.post) {
		form.post.disabled=false;
		if(!clear) form.post.value="";
	}
	if(form.submit_button) {
		form.submit_button.disabled=false;
		form.submit_button.value = val;
	}
	form.parentNode.style.opacity="1";
	remove_link();
}

function extract_links(e) {
	var code = e.keyCode ? e.keyCode : e.charCode;
	if(code==32 && !alreadylinked) {
		var form = document.forms['postForm'];
		var val = form.post.value;
		var matches = val.match( /(http:\/\/[^\s]+)/gi);
		if(matches) {
			$('#link_ex').show();
			$('#link_ex').html('<center class="pvl"><img src="/static/images/ajax-loader-blue.gif"></center>');
			alreadylinked=true;
			$.post(
				"/forum/getlink",
				{ checklinks: 1, text: encodeURIComponent(matches[0]) },
				function(data) {
					if(data) $('#link_ex').html(data);
					else remove_link();
				}
			);
		}
	}
}

function areyousure(func) {
	if(confirm("Are you sure you want to delete this?\nThis action can't be undone!")) {
		eval(func);
	}
/*
	var content='<div class="title">Delete Post</div>';
	content += '<div class="content">Are you sure you want to delete this?</div>';
	content += '<div class="footer"><span class="right"><input type="button" onclick="'+func+';closePopup()" class="button" value="Delete"> <input type="button" class="button gray" onclick="closePopup();" value="Cancel">';
	make_popup(content,500);
*/
}

function inprogress(val) {
	if(!val) val = 'Saving...';
	var form_name = $('div.edit form').attr('name');
	var form = document.forms[form_name];
	form.parentNode.style.opacity = ".5";
	if(form.submit_button) form.submit_button.value = val;
}

function remove_post(pid) {
	if(confirm("Are you sure you want to remove your entry? You can't undo, but you can repost")) {
		if($('#r'+pid).parent().attr('id')=='mypost') $('#mypost').slideUp();
		else $('#r'+pid).fadeOut();
		$.post(
			"/games/remove",
			{ removeme: 1, postID: pid },
			function() {
				$('#post').slideDown();
			}
		);
	}
}

function remove_comment(cId,is_comment,is_game) {
	if(!is_game) is_game = 0;
	$('#c'+cId).fadeOut();
	$('#comments_c'+cId).fadeOut();
	$.post(
		"/forum/remove",
		{ deletecomment: 1, cId: cId, is_game: is_game },
		function(data) {
			if(!is_comment) $('#c'+cId).parent().remove();
			else $('#c'+cId).remove();
		}
	);
}

function remove_link() {
	if($('#link_ex').length) {
		$('#link_ex').empty();
		$('#link_ex').hide();
	}
	alreadylinked=false;
}

function loadlikes(id,is_game) {
	var url = "/search/likes";
	if(is_game) var url = '/topics/likes';
	var elm = $('#l_'+id+' span.tooltip_text');
	if(elm.text() == "") {
		elm.html('Loading...');
		$.get(
			url,
			{ id: id, arr: 1, is_game: is_game },
			function(data) {
				elm.html(data);
			}
		);
	}
}

function init_tokens() {
	jQuery('input.tokenize').each(function() {
		if($(this).attr("done")) return;
		$(this).attr("done",1);
		var link = $(this).attr("link");
		var max = ($(this).attr("max")) ? $(this).attr("max") : null;
		var pics = ($(this).attr("pics")) ? true : false;
		var prep = ($(this).attr("prep")) ? $(this).attr("prep") : null;
		var hint = ($(this).attr("hint")) ? $(this).attr("hint") : 'Start typing a name…';
		$(this).tokenInput(link,{
			hintText: hint,
			minChars: 3,
			animateDropdown: false,
			tokenLimit: max,
			preventDuplicates: true,
			queryParam: "term",
			pictures: pics,
			prePopulate: [prep]
		});
	});
}

function init_tokenizer(elm,endpoint) {
	jQuery(elm).tokenInput(endpoint,{
        animateDropdown: false,
        preventDuplicates: true,
        minChars: 3,
        searchDelay: 1000,
        theme: "facebook"
    });
}

function init_typeahead(elm,endpoint) {
	var id = $(elm).attr("name").split("_");
	jQuery(elm).autocomplete({
    	source: endpoint,
    	minLength: 2,
    	delay: 1,
    	appendTo: $(elm).parent(),
    	select: function(event, ui) {
    		if(ui.item && ui.item.id) {
    			$('#form_'+id[1]).val(ui.item.id);
    			$(elm).addClass('filled');
    			return false;
    		}
    		return false;
    	}
    })
    .data( "autocomplete" )._renderItem = function( ul, item ) {
    	var str = "<a>";
    	if (item.img && item.img!='') str += '<img src="/' + item.img + '" /><div class="pts fss">';
    	else str += '<center class="pvm">';
    	str += item.label;
    	if (item.subtitle) str += '<div class="fwn fcg">' + encodeURIComponent(item.subtitle) + '</div>';
    	if (item.img) str += '<div class="clear"></div></div>';
    	else str += '</center>';
    	str += '</a>';
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( str )
			.appendTo( ul );
	};
}
