var dfimgsel = { };
var dfurlsel = { };

/*
({ ":o", "/img/emoticons/1.gif" }),
({ ":)", "/img/emoticons/2.gif" }),
({ ":D", "/img/emoticons/3.gif" }),
({ ":/", "/img/emoticons/4.gif" }),
({ ":confused:", "/img/emoticons/5.gif" }),
({ ":cool:", "/img/emoticons/6.gif" }),
({ ":cry:", "/img/emoticons/7.gif" }),
({ ":angry:", "/img/emoticons/8.gif" }),
({ "^_^", "/img/emoticons/9.gif" }),
({ ":love:", "/img/emoticons/10.gif" }),
({ ">:(", "/img/emoticons/11.gif" }),
({ ":drool:", "/img/emoticons/12.gif" }),
({ ":rolleyes:", "/img/emoticons/13.gif" }),
({ "<:(", "/img/emoticons/14.gif" }),
({ ":O", "/img/emoticons/15.gif" }),
*/

var dfcode_emoticons = [
	[":o",         "/img/emoticons/1.gif"],
	[":)",         "/img/emoticons/2.gif"],
	[":D",         "/img/emoticons/3.gif"],
	[":/",         "/img/emoticons/4.gif"],
	[":confused:", "/img/emoticons/5.gif"],
	[":cool:",     "/img/emoticons/6.gif"],
	[":cry:",      "/img/emoticons/7.gif"],
	[":angry:",    "/img/emoticons/8.gif"],
	["^_^",        "/img/emoticons/9.gif"],
	[":love:",     "/img/emoticons/10.gif"],
	[">:(",        "/img/emoticons/11.gif"],
	[":drool:",    "/img/emoticons/12.gif"],
	[":rolleyes:", "/img/emoticons/13.gif"],
	["<:(",        "/img/emoticons/14.gif"],
	[":O",         "/img/emoticons/15.gif"]
];

$(function() {
	$("body").click(function() {
		$(".dfcode_selector").hide();
	});
	
	$(".dfcodetextbox").each(function() {
		dfcode_init($(this).attr("id"), 0);
	});
});

function dfcode_init(_obj, toponly) {
	obj = $("#" + _obj);
	
	// Top toolbar
	res = "<div class='dfcodetoolbar' rel='" + _obj + "'>";
		res += "<img class='dfcodebutton' rel='bold'          src='/img/silk/text_bold.png'          title='Fetstil'/>";
		res += "<img class='dfcodebutton' rel='italic'        src='/img/silk/text_italic.png'        title='Kursiv'/>";
		res += "<img class='dfcodebutton' rel='underline'     src='/img/silk/text_underline.png'     title='Understruken'/>";
		res += "<img class='dfcodebutton' rel='strikethrough' src='/img/silk/text_strikethrough.png' title='Genomstruken'/>";
		res += "<img class='dfcodebutton' rel='center'        src='/img/silk/text_align_center.png'  title='Centrera'/>";
		res += "<img class='dfcodebutton' rel='indent'        src='/img/silk/text_indent.png'        title='Tabb'/>";
		res += "<img class='dfcodebutton' rel='listitem'      src='/img/silk/text_list_bullets.png'  title='Lista'/>";
		res += "<img class='dfcodebutton' rel='hilight'       src='/img/silk/textfield.png'          title='Ruta'/>";
		res += "<img class='dfcodebutton' rel='quote'         src='/img/silk/comment.png'            title='Citat'/>";
		
		res += "<img class='dfcodebutton' rel='link'          src='/img/silk/link.png'               title='Länk' style='margin-left: 16px;'/>";
		res += "<img class='dfcodebutton' rel='image'         src='/img/silk/picture.png'            title='Bild'/>";
		res += "<img class='dfcodebutton' rel='code'          src='/img/silk/tag.png'                title='Kod'/>";
	res += "</div>";
	
	obj.before(res);
	
	// Bottom toolbar
	res = "<div class='dfcodetoolbar' rel='" + _obj + "'>";
	for (var i = 0; i < dfcode_emoticons.length; i++) {
		var x = dfcode_emoticons[i];
		res += "<img class='dfcodebutton' rel='emoticon' src='" + x[1] + "' title='" + x[0] + "'/>";
	}
	res += "</div>";
	
	if (!toponly) obj.after(res);
	
	$(".dfcodetoolbar[rel=" + _obj + "] .dfcodebutton").click(dfcode_button);
	
	// Image selector
	dfimgsel[_obj] = new DFImageSelector(_obj);
	
	// URL selector
	dfurlsel[_obj] = new DFLinkSelector(_obj);
}

function dfcode_button(event) {
	id = $(this).parent().attr("rel");
	cmd = $(this).attr("rel");
	
	$(".dfcode_selector").hide();
	
	if (cmd == "bold") dfcode_insert(id, "[b]", "[/b]");
	else if (cmd == "italic") dfcode_insert(id, "[i]", "[/i]");
	else if (cmd == "underline") dfcode_insert(id, "[u]", "[/u]");
	else if (cmd == "strikethrough") dfcode_insert(id, "[s]", "[/s]");
	else if (cmd == "center") dfcode_insert(id, "[center]", "[/center]");
	else if (cmd == "indent") dfcode_insert(id, "[tabb]", "[/tabb]");
	else if (cmd == "listitem") dfcode_insert(id, "[li]", "[/li]");
	else if (cmd == "hilight") dfcode_insert(id, "[hi]", "[/hi]");
	else if (cmd == "quote") dfcode_insert(id, "[quote]", "[/quote]");
	
	else if (cmd == "link") dfurlsel[id].show();
	else if (cmd == "image") dfimgsel[id].show();
	else if (cmd == "code") dfcode_insert(id, "[code]", "[/code]");
	
	else if (cmd == "emoticon") dfcode_append(id, $(this).attr("title"));
	
	event.stopPropagation();
}

function dfcode_append(obj, emoticon) {
	o = $("#" + obj);
	t = "";
	x = o.attr("selectionStart");
	
	if (o.attr("selectionStart")) t = o.val().substring(0, o.attr("selectionStart"));
	
	t += " " + emoticon + " ";
	
	t += o.val().substring(o.attr("selectionEnd"), o.val().length);
	
	o.val(t);
	o.attr("selectionStart", x + emoticon.length + 2);
	o.attr("selectionEnd", o.attr("selectionStart"));
	o.focus();
}

function dfcode_insert(obj, start, end) {
	o = $("#" + obj);
	t = "";
	x = o.attr("selectionStart");
	y = o.attr("selectionEnd");
	
	if (o.attr("selectionStart")) t = o.val().substring(0, o.attr("selectionStart"));
	
	t += start;
	if (o.attr("selectionEnd") > o.attr("selectionStart")) {
		t += o.val().substring(o.attr("selectionStart"), o.attr("selectionEnd"));
	}
	t += end;
	
	t += o.val().substring(o.attr("selectionEnd"), o.val().length);
	
	o.val(t);
	o.attr("selectionStart", x + start.length);
	o.attr("selectionEnd", y + start.length);
	o.focus();
}

function dfcode_select_image(id) {
	
}

function DFLinkSelector(id) {
	this.id = id;
	this.object = $("#" + id);
	
	// Create DOM elements
	var res = "<div id='dfcodeurlsel_" + id + "' rel='" + id + "' class='dfcode_selector' style='display: none;'>";
		res += "<div class='blueheader' style='margin-bottom: 2px;'>Välj bild</div>";
		res += "<table cellspacing='0' cellpadding='0' style='margin: 4px;'>";
			res += "<tr>";
				res += "<td style='border-right: 1px dotted #d0d0d0; padding-right: 4px; vertical-align: top;' rel='" + id + "'>";
					res += "<div class='menuitem selected imgsel_menu_ext'>Extern &raquo;</div>";
					//res += "<div class='menuitem imgsel_menu_gallery'>Galleribild &raquo;</div>";
				res += "</td>";
				res += "<td style='padding-left: 4px; vertical-align: top;' rel='external'>";
					res += "URL: <input type='text' value='http://' rel='ext_url' style='width: 290px; margin-left: 4px;'/><br/>";
					res += "Text: <input type='text' value='' rel='ext_text' style='width: 200px; margin-left: 4px;'/><br/>";
					res += "<input type='button' value='OK' class='ext_btn_ok' rel='" + id + "' style='float: right; margin-top: 2px;'/>";
				res += "</td>";
			res += "</tr>";
		res += "</table>";
	res += "</div>";
	
	$(".dfcodetoolbar[rel=" + id + "] .dfcodebutton[rel=link]").parent().append(res);
	
	var p = $(".dfcodetoolbar[rel=" + id + "] .dfcodebutton[rel=image]").position();
	
	$("#dfcodeurlsel_" + id).css("left", (p.left - 200 + 8) + "px");
	$("#dfcodeurlsel_" + id).css("bottom", (p.top + 16) + "px");
	
	$("#dfcodeurlsel_" + id).click(function(event) { event.stopPropagation(); });
	
	$("#dfcodeurlsel_" + id + " .ext_btn_ok").click(function() {
		var id = $(this).attr("rel");
		var url = $("#dfcodeurlsel_" + id + " input[rel=ext_url]").val();
		var text = $("#dfcodeurlsel_" + id + " input[rel=ext_text]").val();
		
		if (text == "") dfcode_append(id, "[a]" + url + "[/a]");
		else dfcode_append(id, "[a " + url + "]" + text + "[/a]");
		$("#dfcodeurlsel_" + id).hide();
	});
	
	// Show selector
	this.show = function() {
		$("#dfcodeurlsel_" + id).show();
	};
}

function DFImageSelector(id) {
	this.id = id;
	this.object = $("#" + id);
	
	this.extimgtimer = 0;
	
	// Create DOM elements
	var res = "<div id='dfcodeimgsel_" + id + "' rel='" + id + "' class='dfcode_selector' style='display: none;'>";
		res += "<div class='blueheader' style='margin-bottom: 2px;'>Välj bild</div>";
		res += "<table cellspacing='0' cellpadding='0' style='margin: 4px;'>";
			res += "<tr>";
				res += "<td style='border-right: 1px dotted #d0d0d0; padding-right: 4px; vertical-align: top;' rel='" + id + "'>";
					res += "<div class='menuitem selected imgsel_menu_ext'>Extern &raquo;</div>";
					//res += "<div class='menuitem imgsel_menu_gallery'>Galleribild &raquo;</div>";
				res += "</td>";
				res += "<td style='padding-left: 4px; vertical-align: top;' rel='external'>";
					res += "URL: <input type='text' value='http://' rel='ext_url' style='width: 290px; margin-left: 4px;'/><br/>";
					res += "<input type='button' value='OK' class='ext_btn_ok' rel='" + id + "' style='float: right; margin-top: 2px;'/>";
					res += "<canvas id='ext_preview_canvas_" + id + "' width='128' height='96' style='border: 1px solid #c0c0c0; margin-top: 2px;'></canvas>";
				res += "</td>";
				res += "<td style='padding-left: 4px; vertical-align: top; display: none;' rel='external'>";
					res += "URL: <input type='text' value='http://' rel='ext_url' style='width: 290px; margin-left: 4px;'/><br/>";
					res += "<input type='button' value='OK' class='ext_btn_ok' rel='" + id + "' style='float: right; margin-top: 2px;'/>";
				res += "</td>";
			res += "</tr>";
		res += "</table>";
	res += "</div>";
	
	$(".dfcodetoolbar[rel=" + id + "] .dfcodebutton[rel=image]").parent().append(res);
	
	var p = $(".dfcodetoolbar[rel=" + id + "] .dfcodebutton[rel=image]").position();
	
	$("#dfcodeimgsel_" + id).css("left", (p.left - 200 + 8) + "px");
	$("#dfcodeimgsel_" + id).css("bottom", (p.top + 16) + "px");
	
	$("#dfcodeimgsel_" + id).click(function(event) { event.stopPropagation(); });
	
	$("#dfcodeimgsel_" + id + " .ext_btn_ok").click(function() {
		var id = $(this).attr("rel");
		var url = $("#dfcodeimgsel_" + id + " input[rel=ext_url]").val();
		dfcode_append(id, "[img]" + url + "[/img]");
		$("#dfcodeimgsel_" + id).hide();
	});
	
	$("#dfcodeimgsel_" + id + " input[rel=ext_url]").keydown(function() {
		var n = dfimgsel[id];
		if (n.extimgtimer) clearTimeout(n.extimgtimer);
		n.extimgtimer = setTimeout("dfimgsel['" + id + "'].loadextimg();", 300);
	});
	
	// Show selector
	this.show = function() {
		$("#dfcodeimgsel_" + id).show();
	};
	
	// Load external image
	this.loadextimg = function() {
		clearTimeout(this.extimgtimer);
		var url = $("#dfcodeimgsel_" + this.id + " input[rel=ext_url]").val();
		
		var img = new Image();
		img.imgselparent = this;
		img.onload = function() {
			var id = this.imgselparent.id;
			var c = document.getElementById("ext_preview_canvas_" + id);
			var ctx = c.getContext("2d");
			ctx.drawImage(this, 0, 0, 128, 96);
		};
		img.src = url;
	};
}


