$(document).ready(function(){
	$('#pun_bbcode_button_url').replaceWith('<input type="button" title="'+PUNBB.lang_pan_smart_form_links.title+'" class=" image" data-tag="url" id="pun_bbcode_button_url" value="" name="url">');
	$(document).mouseup(function (e){
		var bbcode = $("#pun_bbcode_button_url");
		var sForm = $("#pan_smart_form_links");
		if (!bbcode.is(e.target) && (bbcode.has(e.target).length === 0) && !sForm.is(e.target) && (sForm.has(e.target).length === 0)) {
			$("#pan_smart_form_links").remove();
		}
	});
	$("#pun_bbcode_button_url").mouseup(function(e){
		$("#pan_smart_form_links").remove();
		var textArea = $("textarea");
		var len = textArea.val().length;
		var start = textArea[0].selectionStart;
		var end = textArea[0].selectionEnd;
		var sel = textArea.val().substring(start, end);
		if(sel!==''){
			$("body").append('<div id="pan_smart_form_links" class="form-pos" style="left:'+(e.pageX-230)+'px;top:'+(e.pageY+20)+'px;"><form onsubmit="return false"><input class="q-input-link" value="" type="text" size="33" placeholder="'+PUNBB.lang_pan_smart_form_links.link+'" autocomplete="off"><input id="pan_smart_form_button" class="q-input-button" value="'+PUNBB.lang_pan_smart_form_links.button+'" type="button"></form></div>');
			$( ".q-input-link" ).focus();
			$("#pan_smart_form_button").click(function(){
				var link=$(".q-input-link").val();
				if(sel==='') sel=link;
				if(link!=='') link='='+link;
				var replacement='[url'+link+']'+sel+'[/url]';
				textArea.val(textArea.val().substring(0, start)+replacement+textArea.val().substring(end, len));
				$("#pan_smart_form_links").remove();
			});
		}else{
			$("body").append('<div id="pan_smart_form_links" class="form-pos" style="left:'+(e.pageX-230)+'px;top:'+(e.pageY+20)+'px;"><form onsubmit="return false"><input class="q-input-link" value="" type="text" size="33" placeholder="'+PUNBB.lang_pan_smart_form_links.link+'" autocomplete="off"><input class="q-input-text" value="" type="text" placeholder="'+PUNBB.lang_pan_smart_form_links.text+'" autocomplete="off"><input  id="pan_smart_form_button" class="q-input-button" value="'+PUNBB.lang_pan_smart_form_links.button+'" type="button"></form></div>');
			$( ".q-input-link" ).focus();
			$("#pan_smart_form_button").click(function(){
				var link=$(".q-input-link").val();
				var text=$(".q-input-text").val();
				if(text==='') text=link;
				if(link!=='') link='='+link;
				PUNBB.pun_bbcode.insert_text('[url'+link+']'+text+'[/url]', '');
				$("#pan_smart_form_links").remove();
			});
		}
	});
});
