
var JQ_Max_Title = 2500;

timer = new Object();
timer.nextCtr = 0;
timer.funcs = new Array();
timer.setTimeout = function _setTimeout(func, time) {
  var id = this.nextCtr++;
  if (typeof func != "function") { // not a function, convert to string
    timer.funcs[id] = new Array(setTimeout("delete timer.funcs["+id+"];"+func, time));
    return id;
  }
  // a function:
  function wrapper() {
     delete timer.funcs[id];
     func();
  }
  wrapper.toString = function () {
    return "timer.funcs["+id+"][1]()";
  };
  timer.funcs[id] = new Array(setTimeout(wrapper, time), wrapper);
  return id;
};

timer.clearTimeout = function _clearTimeout(id) {
  var pair = timer.funcs[id];
  if (pair) {
    delete timer.funcs[id];
    clearTimeout(pair[0]);
  }
}

var viewX;
var viewY;

$().mousemove(function(e){
	viewX = e.pageX;
	viewY = e.pageY;
});

$(document).ready(JQnotes_init);

$.fn.offsetLeft = function() {
  var e = this.get(0);
  if(!e.offsetParent) return e.offsetLeft;
  return e.offsetLeft + $(e.offsetParent).offsetLeft(); }

$.fn.offsetTop = function() {
  var e = this.get(0);
  if(!e.offsetParent) return e.offsetTop;
  return e.offsetTop + $(e.offsetParent).offsetTop(); }

// local vars
var JQ_timer = new Object();
var JQ_addnote = JQ_removenote = JQ_editnote = JQ_addtitle = JQ_hovernote = false;

function JQnotes_addboxes(obj) {
	// first lets check if we already have notes loaded
	if (obj.parents("div.JQnotes_container").find("div.JQnotes_notes").size() > 0) return;

	notes = obj.parents("div.JQnotes_container").find("span.JQnotes_thenotes");
	if (notes.size() > 0) {
		// creating a container
		obj.parents("div.JQnotes_container").append('<div class="JQnotes_notes"></div>');

		// ok there are some notes we have to show
		for (i=0; i<notes.size(); i++) {
			// getting the bounds of the image
			imgPos = new Object();
			imgPos.x = obj.offsetLeft();
			imgPos.y = obj.offsetTop();
			points = notes.slice(i,i+1).attr("lang").split(',');
			if (points.length == 4) {
				info = new Object();
				info['top'] = parseInt(points[1]) + imgPos.y;
				info['left'] = parseInt(points[0]) + imgPos.x;
				info['width'] = parseInt(points[2]);
				info['height'] = parseInt(points[3]);

				info['note'] = notes.slice(i,i+1).attr("title");
				info['key'] = notes.slice(i,i+1).attr("id");

				JQnotes_shownote(info, obj);
			}
		}
	}
}

function JQnotes_shownote(info, obj) {

	obj.parents("div.JQnotes_container").find("div.JQnotes_notes").append('<div id="JQ_box_'+info['key']+'" style="position: absolute; top: '+info['top']+'px; left: '+info['left']+'px; width: '+info['width']+'px; height: '+info['height']+'px;"></div>');
	$("div#JQ_box_"+info['key']).append('<div id="JQ_box2_'+info['key']+'" style="width: '+parseInt(info['width']-2)+'px; height: '+parseInt(info['height']-2)+'px; border: solid #000000 1px"></div>');
	$("div#JQ_box2_"+info['key']).append('<div id="JQ_box3_'+info['key']+'" lang="'+info['key']+'" style="width: '+parseInt(info['width']-4)+'px; height: '+parseInt(info['height']-4)+'px; border: solid #FFFFFF 1px; background: url(/images/trans.gif);"></div>');

	$("div#JQ_box3_"+info['key']).hover(function(){
		JQ_hovernote = true;

		timer.clearTimeout(JQ_timer[obj.parents("div.JQnotes_container").attr("id")]);
		delete JQ_timer[obj.parents("div.JQnotes_container").attr("id")];

		// changing the parents border
		if (JQ_removenote) borderColor = "#FF0000";
		else if (JQ_editnote) borderColor = "#0000FF";
		else borderColor = "#FFCC00";
		$(this).parent().parent().css("border","solid "+borderColor+" 1px");

		if (info['width'] > 150) width = info['width'];
		else width = 150;

		$("body").append('<div id="JQ_note_'+info['key']+'" class="JQnotes_shownote" style="position: absolute; top: '+(info['top'] + info['height'] + 2)+'px; left: '+info['left']+'px; width: '+width+'px; text-align: left; font-size: 11px; padding: 2px 5px 2px 5px">'+info['note']+'</div>');

	},function() {
		JQ_hovernote = false;

		key = $(this).attr("lang");
		$(this).parent().parent().css("border","transparent");

		// need to remove the note now
		$("div#JQ_note_"+ key).remove();
	})
	.click(function() {
		if (JQ_removenote) {
			if (!confirm("Are you sure you want to delete this note?")) {
				// they did not want to delete
				return;
			}

			// getting the picture info now
			entryid = $(this).parents("div.JQnotes_container").find("input#JQnotes_entryID").val();
			id = $(this).parents("div.JQnotes_container").find("input#JQnotes_imgID").val();
			key = $(this).attr("lang");

			noteObj = $(this);

			$.ajax({
				type: "POST",
				url: "/notes.php",
				data: "opt=2&image="+id+"&key="+key+"&entryid="+entryid,
				success: function(msg) {
					// ok we need to delete this note
					noteObj.parents("div.JQnotes_container").find("span[@id*="+noteObj.attr("lang")+"]").remove();

					if (noteObj.parents("div.JQnotes_container").find("span.JQnotes_thenotes").length == 0) {
						noteObj.parents("div.JQnotes_container").find("img#JQnote_rmvBtn").hide();
						noteObj.parents("div.JQnotes_container").find("img#JQnote_edtBtn").hide();
					}

					// now i need to clear this image
					clearNotes(obj.parents("div.JQnotes_container"));
					JQnotes_addboxes(obj.parents("div.JQnotes_container"));

					// leaving delete mode now
					JQ_removenote = false;
					btn.attr("src", "/images/icon_removenote_1.png");
				}
			});
		}
		else if (JQ_editnote) {
			// grabbing the image
			img = $(this).parents("div.JQnotes_container").find("img.JQnotes_img");

			// grabbing the note
			note = $(this).parents("div.JQnotes_container").find("span[@id*="+$(this).attr("lang")+"]");
			coords = note.attr("lang").split(",");

			newResize();
			dragresize.minLeft = img.offsetLeft();
			dragresize.minTop = img.offsetTop();
			dragresize.maxLeft = dragresize.minLeft + img.width() - 2;
			dragresize.maxTop = dragresize.minTop + img.height() - 2;

			top_pos = (parseInt(dragresize.minTop) + parseInt(coords[1]));
			left_pos = (parseInt(dragresize.minLeft) + parseInt(coords[0]));

			$("body").append('<div class="drsElement drsMoveHandle" id="JQnotes_dragbox" style="width: '+(coords[2]-2)+'px; height: '+(coords[3]-2)+'px; background: url(/images/trans.gif); position: absolute; top: '+top_pos+'px; left: '+left_pos+'px;"></div>');

			entryid = $(this).parents("div.JQnotes_container").find("input#JQnotes_entryID").val();
			id = $(this).parents("div.JQnotes_container").find("input#JQnotes_imgID").val();

			html = '<form>' +
				'<input type="hidden" id="image_name" name="image" value="'+id+'" />'+
				'<input type="hidden" id="entryid" name="entryid" value="'+entryid+'" />'+
				'<textarea id="JQnotes_textbox" name="note" rows="3" cols="25">'+note.attr("title").replace(new RegExp( "<br\ \/>", "g" ),"\r")+'</textarea>' +
				'<input type="button" value="'+$('input#js_edit_button').val()+'" id="JQnotes_addBtn" /> <input type="button" value="'+$('input#js_cancel_button').val()+'" id="JQnotes_cnlBtn" />' +
				'</form>';

			$("body").append('<div id="JQnotes_formbox" style="position: absolute; top: '+(top_pos+65)+'px; left: '+left_pos+'px; width: 170px; height: 90px; background: transparent; z-index: 5;">'+html+'</div>');

			$("input#JQnotes_addBtn").click(function() {
				if ($("textarea#JQnotes_textbox").val() == "") return;

				// getting the coords of the box
				dragresize.select(document.getElementById("JQnotes_dragbox"));
				coords = (dragresize.elmX-dragresize.minLeft)+","+(dragresize.elmY-dragresize.minTop)+","+dragresize.elmW+","+dragresize.elmH;
				title = $("#JQnotes_textbox").val().replace(new RegExp( "\\n", "g" ),"<br>");

				coords = coords.split(",");
				coords[2] -= 2;
				coords[3] -= 2;
				coords = coords[0]+","+coords[1]+","+coords[2]+","+coords[3];

				$.ajax({
					type: "POST",
					url: "/notes.php",
					dataType : 'xml',
					data: 'opt=3&note='+ encodeURIComponent($(this).siblings("textarea").val()) +'&key='+note.attr("id")+'&image='+ $(this).siblings("#image_name").val() +'&cords='+ coords +'&entryid='+ $(this).siblings("#entryid").val(),
					success: function(xml) {

						// adding the note now
						note = img.parents("div.JQnotes_container").find("div#note_holder").find("span[@id*="+$("key",xml).text()+"]");

						// setting the new stuff
						note.attr("title", $("note",xml).text());
						note.attr("lang", coords);

						clearNotes(img.parents("div.JQnotes_container"));

						// leaving delete mode now
						JQ_editnote = false;
						btn.attr("src", "/images/icon_editnote_1.png");

						$("div#JQnotes_formbox").remove();
						$("div#JQnotes_dragbox").remove();
					}
				});
			});
			$("input#JQnotes_cnlBtn").click(function() {
				// remove everything
				$("div#JQnotes_formbox").remove();
				$("div#JQnotes_dragbox").remove();

				JQ_editnote = false;
				btn.attr("src", "/images/icon_editnote_1.png");
			});
		}
	});
}

function JQnotes_init(){
	containers = $("div.JQnotes_container");
	for (i=0; i<containers.size(); i++) {
		rand = Math.floor(Math.random()*111111111111);
		containers[i].id = rand;
	}

	// attaching the events to the buttons now
	$("img.JQnote_Btns").hover(function(){

		if ($(this).attr("id") == "JQnote_addBtn") $(this).attr("src", "/images/icon_addnote_2.png");
		else if ($(this).attr("id") == "JQnote_rmvBtn") $(this).attr("src", "/images/icon_removenote_2.png");
		else if ($(this).attr("id") == "JQnote_edtBtn") $(this).attr("src", "/images/icon_editnote_2.png");
		else if ($(this).attr("id") == "JQnote_largeBtn") $(this).attr("src", "/images/icon_enlarge_2.png");
		else if ($(this).attr("id") == "JQnote_exifBtn") $(this).attr("src", "/images/icon_exif_2.png");
		else if ($(this).attr("id") == "JQnote_favBtn") $(this).attr("src", "/images/icon_fav_2.png");
		else if ($(this).attr("id") == "JQnote_critBtn") $(this).attr("src", "/images/icon_crit_2.gif");
		else if ($(this).attr("id") == "JQnote_subBtn") $(this).attr("src", "/images/icon_theme_2.png");
		else if ($(this).attr("id") == "JQnote_flagBtn") $(this).attr("src", "/images/icon_flag_2.png");
	},function() {
		if ($(this).attr("id") == "JQnote_addBtn") {
			if (!JQ_addnote) $(this).attr("src", "/images/icon_addnote_1.png");
		}
		else if ($(this).attr("id") == "JQnote_rmvBtn") {
			if (!JQ_removenote) $(this).attr("src", "/images/icon_removenote_1.png");
		}
		else if ($(this).attr("id") == "JQnote_edtBtn") {
			if (!JQ_editnote) $(this).attr("src", "/images/icon_editnote_1.png");
		}
		else if ($(this).attr("id") == "JQnote_largeBtn") $(this).attr("src", "/images/icon_enlarge_1.png");
		else if ($(this).attr("id") == "JQnote_exifBtn") $(this).attr("src", "/images/icon_exif_1.png");
		else if ($(this).attr("id") == "JQnote_favBtn") $(this).attr("src", "/images/icon_fav_1.png");
		else if ($(this).attr("id") == "JQnote_critBtn") $(this).attr("src", "/images/icon_crit_1.gif");
		else if ($(this).attr("id") == "JQnote_subBtn") $(this).attr("src", "/images/icon_theme_1.png");
		else if ($(this).attr("id") == "JQnote_flagBtn") $(this).attr("src", "/images/icon_flag_1.png");
	})
	.click(function() {
		btn = $(this);

		if ($(this).attr("id") == "JQnote_addBtn") {
			if (JQ_addnote || JQ_removenote || JQ_editnote) return;

			newResize();

			img = $(this).parents("div.JQnotes_container").find("img.JQnotes_img");
			JQnote_obj = $(this).parents("div.JQnotes_container");

			dragresize.minLeft = img.offsetLeft();
			dragresize.minTop = img.offsetTop();
			dragresize.maxLeft = dragresize.minLeft + img.width() - 2;
			dragresize.maxTop = dragresize.minTop + img.height() - 2;

			posX = (((dragresize.minTop + dragresize.maxTop) / 2)- 25);
			posY = (((dragresize.minLeft + dragresize.maxLeft) / 2) - 25);

			$("body").append('<div class="drsElement drsMoveHandle" id="JQnotes_dragbox" style="width: 50px; height: 50px; background: url(/images/trans.gif); position: absolute; top: '+posX+'px; left: '+posY+'px;"><div id="innerBox1" style="border: 1px solid black; height: 48px"><div id="innerBox2" style="border: 1px solid white; height: 46px;"></div></div></div>');

			entryid = $(this).parents("div.JQnotes_container").find("input#JQnotes_entryID").val();
			id = $(this).parents("div.JQnotes_container").find("input#JQnotes_imgID").val();

			html = '<form style="text-align: left;">' +
				'<input type="hidden" id="image_name" name="image" value="'+id+'" />'+
				'<input type="hidden" id="entryid" name="entryid" value="'+entryid+'" />'+
				'<textarea id="JQnotes_textbox" name="note"></textarea>' +
				'<input type="button" value="'+$('input#js_add_button').val()+'" id="JQnotes_addBtn" /> <input type="button" value="'+$('input#js_cancel_button').val()+'" id="JQnotes_cnlBtn" />' +
				'</form>';

			$("body").append('<div id="JQnotes_formbox" style="position: absolute; top: '+(posX+65)+'px; left: '+posY+'px; width: 170px; height: 90px; background: transparent; z-index: 5;">'+html+'</div>');

			// setting it to true
			JQ_addnote = true;

			btn.attr("src", "/images/icon_addnote_2.png");

			// now adding the click methods to the form boxes
			$("input#JQnotes_addBtn").click(function() {
				if ($("textarea#JQnotes_textbox").val() == "") return;

				// getting the coords of the box
				dragresize.select(document.getElementById("JQnotes_dragbox"));
				coords = (dragresize.elmX-dragresize.minLeft)+","+(dragresize.elmY-dragresize.minTop)+","+dragresize.elmW+","+dragresize.elmH;
				title = $("#JQnotes_textbox").val();

				coords = coords.split(",");
				coords[2] = parseInt(coords[2]) + 4;
				coords[3] = parseInt(coords[3]) + 4;
				coords = coords[0]+","+coords[1]+","+coords[2]+","+coords[3];

				$.ajax({
					type: "POST",
					url: "/notes.php",
					dataType : 'xml',
					data: 'opt=1&note='+ encodeURIComponent($(this).siblings("textarea").val()) +'&image='+ $(this).siblings("#image_name").val() +'&cords='+ coords +'&entryid='+ $(this).siblings("#entryid").val(),
					success: function(xml) {

						// adding the note now
						key = $("key",xml).text();
						note = $("note",xml).text();

						JQnote_obj.find("div#note_holder").append('<span class="JQnotes_thenotes" lang="'+coords+'" id="'+key+'" title="'+note+'"></span>');
						// now i need to clear this image
						clearNotes(JQnote_obj);

						// leaving delete mode now
						JQ_addnote = false;

						btn.attr("src", "/images/icon_addnote_1.png");

						$("div#JQnotes_formbox").remove();
						$("div#JQnotes_dragbox").remove();

						// making sure the delete/edit icons get shown
						JQnote_obj.find("img#JQnote_rmvBtn").show();
						JQnote_obj.find("img#JQnote_edtBtn").show();
					},
					error : function(obj, err) {
						alert(err);
					}
				});
			});
			$("input#JQnotes_cnlBtn").click(function() {
				// remove everything
				$("div#JQnotes_formbox").remove();
				$("div#JQnotes_dragbox").remove();

				JQ_addnote = false;
				btn.attr("src", "/images/icon_addnote_1.png");
			});

		}
		else if ($(this).attr("id") == "JQnote_exifBtn") {
			JQnote_obj = $(this).parents("div.JQnotes_container");
			var exifInfo = JQnote_obj.find('div#exif_info');

			if (exifInfo.is(':hidden')) {
				$.ajax({
					type: "POST",
					url: "/ajax/get_exif.php",
					data: 'image='+ JQnote_obj.find('input#JQnotes_imgID').val(),
					success: function(msg) {
						if (msg.length > 0) exifInfo.html(msg).show(400);
					}
				});
			}
			else exifInfo.hide(400);
		}
		else if ($(this).attr("id") == "JQnote_rmvBtn") {
			if (JQ_addnote || JQ_removenote || JQ_editnote) {
				if (JQ_removenote) JQ_removenote = false;
				return;
			}

			JQ_removenote = true;

			btn.attr("src", "/images/icon_removenote_2.png");
		}
		else if ($(this).attr("id") == "JQnote_edtBtn") {
			if (JQ_addnote || JQ_removenote || JQ_editnote) {
				if (JQ_editnote) JQ_editnote = false;
				return;
			}

			JQ_editnote = true;
			btn.attr("src", "/images/icon_editnote_2.png");
		}
		else if ($(this).attr("id") == "JQnote_favBtn") {
			favContainer = $(this).parents("div.JQnotes_container");

			html = '<DIV class="draggable" id="JQnotes_favBox">';
			html += '<DIV class="dragger"><DIV STYLE="position: absolute; left: 0px; top: 0px; width: 180px; height: 20px; padding-top: 2px; padding-left: 10px">'+$("input#fav_title").val()+'</DIV><DIV STYLE="position: absolute; left: 380px; top: -1px; width: 15px; height: 10px; cursor: pointer; font-family: Arial; font-style: normal; font-variant: normal; font-weight: 400; font-size: 20px; line-height: normal" id="fav_close" title="close">&#215;</DIV></DIV>';
			html += '<DIV class="note" id="fav_note">'+$("input#fav_text").val();
			html += '<DIV id="sticky_text"><TEXTAREA name="body" id="fav_note_box"></TEXTAREA></DIV> <P>';
			html += '<INPUT type="button" id="fav_add" value="'+$("input#fav_btn").val()+'">';
			html += '</DIV></DIV>';
			$("body").append(html);
			// setting the buttons
			$("div#fav_close").click(function() { $("div#JQnotes_favBox").remove(); });

			$("input#fav_add").click(function() {

				$.ajax({
					type: "POST",
					url: "/ajax/favorites.php",
					dataType : 'xml',
					data: 'postid=' + favContainer.find("input#JQnotes_entryID").val() + "&picid="+ favContainer.find("input#JQnotes_imgID").val() + "&body="+ encodeURIComponent($("#fav_note_box").val()),
					success: function(xml) {
						if ($("success",xml).text() == 1) {
							msg = "This image has been added into your favorites.";
							type = "done";
						}
						else {
							msg = "Sorry this image is already in your favorites list.";
							type = "error";
						}

						favContainer.prepend('<div id="fav_alert" class="'+type+'">'+msg+'</div>');

						// setting a timer to hide it
						setTimeout('$("div#fav_alert").hide(400)', 4000);

						$("div#JQnotes_favBox").remove();
					}
				});
			});


			// placing it now
			$("div#JQnotes_favBox").css("top", $(this).offsetTop());
			$("div#JQnotes_favBox").css("left", $(this).offsetLeft() - 450);
		}
		else if ($(this).attr("id") == "JQnote_subBtn") {
			subContainer = $(this).parents("div.JQnotes_container");

			$.ajax({
				type: "POST",
				url: "/ajax/theme.php",
				dataType : 'xml',
				data: "opt=2",
				success: function(xml) {
					if (confirm('Current theme: '+ $("title",xml).text() +'\nDo you want to submit this for theme of the week?')) {
						$.ajax({
							type: "POST",
							url: "/ajax/theme.php",
							dataType : 'xml',
							data: "opt=1&image="+subContainer.find("input#JQnotes_imgID").val()+"&id="+subContainer.find("input#JQnotes_entryID").val(),
							success: function(xml) {
								if ($("success",xml).text() == 1) {
									msg = $('input#theme_success').val();
									type = "done";
								}
								else if ($("success",xml).text() == 2) {
									msg = $('input#theme_error').val();
									type = "error";
								}
								else {
									msg = $('input#theme_error2').val();
									type = "error";
								}
								subContainer.prepend('<div id="fav_alert" class="'+type+'">'+msg+'</div>');
								setTimeout('$("div#fav_alert").hide(400)', 8000);
							}
						});
					}
				}
			});
		}
		else if ($(this).attr("id") == "JQnote_flagBtn") {
			subContainer = $(this).parents("div.JQnotes_container");

			if (confirm('Is this image inappropriate?')) {
				$.ajax({
					type: "POST",
					url: "/ajax/flag.php",
					dataType : 'xml',
					data: "image="+subContainer.find("input#JQnotes_imgID").val()+"&id="+subContainer.find("input#JQnotes_entryID").val(),
					success: function(xml) {
						msg = $('input#flag_success').val();
						type = "done";
						
						subContainer.prepend('<div id="fav_alert" class="'+type+'">'+msg+'</div>');
						setTimeout('$("div#fav_alert").hide(400)', 8000);
					}
				});
			}
		}
	});

	// doing all the image titles now
	$("div.JQnotes_container").find("div#JQnotes_imgTitle_own").click(function() {
		JQnotes_addTitle($(this));
	});
}

function JQnotes_addTitle(obj) {
	if (JQ_addtitle) return;
	JQ_addtitle = true;

	titleContainer = obj.parents("div.JQnotes_container");
	titleDiv = titleContainer.find('div#JQnotes_imgTitle_own');

	$.ajax({
		type: "POST",
		url: "/ajax/photo_title.php",
		data: 'opt=1&id=' + titleContainer.find("input#JQnotes_entryID").val() + "&img="+ titleContainer.find("input#JQnotes_imgID").val(),
		success: function(msg){
			// cleaning out the old div now
			titleDiv.html("");

			// appending the form now
			titleDiv.append(
				$("<div id='blog_form'><div id='formatting'><div class='format'><img title='Bold Text' alt='Bold Text' src='/images/html_bold.gif' class='Titlebb_img' id='bb_bold'></div><div class='format'><img title='Italic Text' alt='Italic Text' src='/images/html_italic.gif' class='Titlebb_img' id='bb_italic'/></div><div class='format'><img title='UnderLine Text' alt='UnderLine Text' src='/images/html_underline.gif' class='Titlebb_img' id='bb_underline'/></div><div class='format'><img title='URL Link' alt='URL Link' src='/images/html_url.gif' class='Titlebb_img' id='bb_url'/></div></div><textarea id='JQnewTitle'>"+msg+"</textarea></div><br />").keyup(function() {
					chars = $('textarea#JQnewTitle').val().length;
					if (!chars) chars = "0";

					$('span#chars_left').html(chars);
				})
				.keydown(function() { if ($('textarea#JQnewTitle').val().length >= JQ_Max_Title) return false; })
			);

			$('img.Titlebb_img').click(function() {
				// getting the text area
				txtBox = $(this).parent().parent().next();

				// getting the id
				bbId = $(this).attr('id');
				bbTitle = $(this).attr('title');

				if (bbId == "bb_bold") txtBox.insertTags('[b]','[/b]', bbTitle, txtBox);
				else if (bbId == "bb_italic") txtBox.insertTags('[i]','[/i]', bbTitle, txtBox);
				else if (bbId == "bb_underline") txtBox.insertTags('[u]','[/u]', bbTitle, txtBox);
				else if (bbId == "bb_url") txtBox.insertTags('[url=http://www.domain.com]','[/url]', bbTitle, txtBox);
			});

			titleDiv.append(
				$("<input type='button' value='"+$('input#js_add_button').val()+"'>")
				.click(function() {
					title = $('textarea#JQnewTitle').val();
					title = encodeURIComponent(title);
  					title = title.replace(/~/g,'%7E').replace(/%20/g,'+');

					$.ajax({
						type: "POST",
						url: "/ajax/photo_title.php",
						data: 'id=' + titleContainer.find("input#JQnotes_entryID").val() + "&img="+ titleContainer.find("input#JQnotes_imgID").val() + "&title="+ title,
						success: function(msg){

							if (title == "") {
								titleContainer.find('input#JQnotes_oldTitle').val(titleContainer.find('input#JQnotes_newTitle').val());
								titleDiv.text(titleContainer.find('div.hidden_title_new').text());
								titleDiv.attr("class", "img_title_box_edit-add");
							}
							else {
								titleDiv.html(msg);
								titleContainer.find('div.hidden_title').text(title);
								titleDiv.attr("class", "img_title_box_edit");
							}

							JQ_addtitle = false;
							titleDiv.click(function() { JQnotes_addTitle(obj); });

							$('img.Titlebb_img').unbind('click');
						}
					});
				})
			);

			titleDiv.append(
				$("<input type='button' value='"+$('input#js_cancel_button').val()+"' style='margin-left: 10px; margin-right: 10px;'>")
				.click(function() {
					titleDiv.html(titleContainer.find('div.hidden_title').text());
					JQ_addtitle = false;
					titleDiv.click(function() { JQnotes_addTitle(obj); });
					return false;
				})
			);

			titleDiv.append("<span id='chars_left'>"+$('textarea#JQnewTitle').val().length+"</span> / "+JQ_Max_Title);
		}
	});

	return;
}


function clearNotes(obj) {
	obj.find("div.JQnotes_notes").remove();
	$("body").find("div.JQnotes_shownote").remove();

}

function ElementPosition(obj) {
	this.x=0, this.y=0;
	if (obj) {
		x = obj.offsetLeft;
		y = obj.offsetTop;
		var body = document.getElementsByTagName('body')[0];
		while (obj.offsetParent && obj!=body){
			x += obj.offsetParent.offsetLeft;
			y += obj.offsetParent.offsetTop;
			obj = obj.offsetParent;
		}
	}

	this.x = x;
	this.y = y;
}



function newResize() {
	// setting up the dragresize library
	dragresize = new DragResize('dragresize', { allowBlur: false });
	dragresize.isElement = function(elm) {
		if (elm.className && elm.className.indexOf('drsElement') > -1) return true;
	};
	dragresize.isHandle = function(elm) {
		if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true;
	};
	dragresize.ondragfocus = function() { };
	dragresize.ondragstart = function(isResize) { };
	dragresize.ondragmove = function(isResize) { };
	dragresize.ondragend = function(isResize) { };
	dragresize.ondragblur = function() { };
	dragresize.apply(document);
}

/*

DragResize v1.0
(c) 2005-2006 Angus Turnbull, TwinHelix Designs http://www.twinhelix.com

Licensed under the CC-GNU LGPL, version 2.1 or later:
http://creativecommons.org/licenses/LGPL/2.1/
This is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/

if (typeof addEvent != 'function')
{
 var addEvent = function(o, t, f, l)
 {
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) return o[d](t, f, false);
  if (!o._evts) o._evts = {};
  if (!o._evts[t])
  {
   o._evts[t] = o[n] ? { b: o[n] } : {};
   o[n] = new Function('e',
    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
     '} return r');
   if (t != 'unload') addEvent(window, 'unload', function() {
    removeEvent(rO, rT, rF, rL);
   });
  }
  if (!f._i) f._i = addEvent._i++;
  o._evts[t][f._i] = f;
 };
 addEvent._i = 1;
 var removeEvent = function(o, t, f, l)
 {
  var d = 'removeEventListener';
  if (o[d] && !l) return o[d](t, f, false);
  if (o._evts && o._evts[t] && f._i) delete o._evts[t][f._i];
 };
}


function cancelEvent(e, c)
{
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};







// *** DRAG/RESIZE CODE ***

function pxInt(el) { return parseInt(el.split("px")[0]); }

function DragResize(myName, config)
{
 var props = {
  myName: myName,                  // Name of the object.
  enabled: true,                   // Global toggle of drag/resize.
  handles: ['tl', 'tr', 'bl', 'br'], // Array of drag handles: top/mid/bot/right.
  isElement: null,                 // Function ref to test for an element.
  isHandle: null,                  // Function ref to test for move handle.
  element: null,                   // The currently selected element.
  handle: null,                  // Active handle reference of the element.
  minWidth: 20, minHeight: 20,     // Minimum pixel size of elements.
  minLeft: 0, maxLeft: 9999,       // Bounding box area, in pixels.
  minTop: 0, maxTop: 9999,
  zIndex: 1,                       // The highest Z-Index yet allocated.
  mouseX: 0, mouseY: 0,            // Current mouse position, recorded live.
  lastMouseX: 0, lastMouseY: 0,    // Last processed mouse positions.
  mOffX: 0, mOffY: 0,              // A known offset between position & mouse.
  elmX: 0, elmY: 0,                // Element position.
  elmW: 0, elmH: 0,                // Element size.
  allowBlur: true,                 // Whether to allow automatic blur onclick.
  ondragfocus: null,               // Event handler functions.
  ondragstart: null,
  ondragmove: null,
  ondragend: null,
  ondragblur: null
 };

 for (var p in props)
  this[p] = (typeof config[p] == 'undefined') ? props[p] : config[p];
};


DragResize.prototype.apply = function(node)
{
 // Adds object event handlers to the specified DOM node.

 var obj = this;
 addEvent(node, 'mousedown', function(e) { obj.mouseDown(e) } );
 addEvent(node, 'mousemove', function(e) { obj.mouseMove(e) } );
 addEvent(node, 'mouseup', function(e) { obj.mouseUp(e) } );
};


DragResize.prototype.select = function(newElement) { with (this)
{
 // Selects an element for dragging.
 if (!document.getElementById || !enabled) return;

 // Activate and record our new dragging element.
 if (newElement && (newElement != element) && enabled)
 {
  element = newElement;
  // Elevate it and give it resize handles.
  element.style.zIndex = ++zIndex;
  if (this.resizeHandleSet) this.resizeHandleSet(element, true);
  // Record element attributes for mouseMove().
  elmX = parseInt(element.style.left);
  elmY = parseInt(element.style.top);
  elmW = element.offsetWidth;
  elmH = element.offsetHeight;
  if (ondragfocus) this.ondragfocus();
 }
}};


DragResize.prototype.deselect = function(delHandles) { with (this)
{
 // Immediately stops dragging an element. If 'delHandles' is true, this
 // remove the handles from the element and clears the element flag,
 // completely resetting the .

 if (!document.getElementById || !enabled) return;

 if (delHandles)
 {
  if (ondragblur) this.ondragblur();
  if (this.resizeHandleSet) this.resizeHandleSet(element, false);
  element = null;
 }

 handle = null;
 mOffX = 0;
 mOffY = 0;
}};


DragResize.prototype.mouseDown = function(e) { with (this)
{
 // Suitable elements are selected for drag/resize on mousedown.
 // We also initialise the resize boxes, and drag parameters like mouse position etc.
 if (!document.getElementById || !enabled) return true;

 var elm = e.target || e.srcElement,
  newElement = null,
  newHandle = null,
  hRE = new RegExp(myName + '-([trmbl]{2})', '');

 while (elm)
 {
  // Loop up the DOM looking for matching elements. Remember one if found.
  if (elm.className)
  {
   if (!newHandle && (hRE.test(elm.className) || isHandle(elm))) newHandle = elm;
   if (isElement(elm)) { newElement = elm; break }
  }
  elm = elm.parentNode;
 }

 // If this isn't on the last dragged element, call deselect(),
 // which will hide its handles and clear element.
 if (element && (element != newElement) && allowBlur) deselect(true);

 // If we have a new matching element, call select().
 if (newElement && (!element || (newElement == element)))
 {
  // Stop mouse selections if we're dragging a handle.
  if (newHandle) cancelEvent(e);
  select(newElement, newHandle);
  handle = newHandle;
  if (handle && ondragstart) this.ondragstart(hRE.test(handle.className));
 }

 // setting the elmX and such

}};


DragResize.prototype.mouseMove = function(e) { with (this)
{
 // This continually offsets the dragged element by the difference between the
 // last recorded mouse position (mouseX/Y) and the current mouse position.
 if (!document.getElementById || !enabled) return true;

 // We always record the current mouse position.
 mouseX = e.pageX || e.clientX + document.documentElement.scrollLeft;
 mouseY = e.pageY || e.clientY + document.documentElement.scrollTop;
 // Record the relative mouse movement, in case we're dragging.
 // Add any previously stored & ignored offset to the calculations.
 var diffX = mouseX - lastMouseX + mOffX;
 var diffY = mouseY - lastMouseY + mOffY;
 mOffX = mOffY = 0;
 // Update last processed mouse positions.
 lastMouseX = mouseX;
 lastMouseY = mouseY;

 // That's all we do if we're not dragging anything.
 if (!handle) return true;

 // If included in the script, run the resize handle drag routine.
 // Let it create an object representing the drag offsets.
 var isResize = false;
 if (this.resizeHandleDrag && this.resizeHandleDrag(diffX, diffY))
 {
  isResize = true;
 }
 else
 {
  // If the resize drag handler isn't set or returns fase (to indicate the drag was
  // not on a resize handle), we must be dragging the whole element, so move that.
  // Bounds check left-right...
  var dX = diffX, dY = diffY;
  if (elmX + dX < minLeft) mOffX = (dX - (diffX = minLeft - elmX));
  else if (elmX + elmW + dX > maxLeft) mOffX = (dX - (diffX = maxLeft - elmX - elmW));
  // ...and up-down.
  if (elmY + dY < minTop) mOffY = (dY - (diffY = minTop - elmY));
  else if (elmY + elmH + dY > maxTop) mOffY = (dY - (diffY = maxTop - elmY - elmH));
  elmX += diffX;
  elmY += diffY;
 }

 // Assign new info back to the element, with minimum dimensions.
 with (element.style)
 {
  left =   elmX + 'px';
  width =  elmW + 'px';
  top =    elmY + 'px';
  height = elmH + 'px';

  // ok i am dragging around the selector
  form = document.getElementById("JQnotes_formbox");

  $('div#innerBox1').css("height", elmH-2+'px');
  $('div#innerBox2').css("height", elmH-4+'px');

  // bound checking on the width
  if ((elmX + pxInt(form.style.width)) < maxLeft) form.style.left = (elmX) + "px";

  // doing some bound checking now on the height
  //document.getElementById("debug").value = (elmX + pxInt(form.style.width))
  //document.getElementById("debug2").value = maxLeft;
  if ((elmY + elmH + 10 + pxInt(form.style.height)) > maxTop) form.style.top = (elmY - 10 - pxInt(form.style.height)) + "px";
  else form.style.top = (elmY + elmH + 10) + "px";

 }

 // Evil, dirty, hackish Opera select-as-you-drag fix.
 if (window.opera && document.documentElement)
 {
  var oDF = document.getElementById('op-drag-fix');
  if (!oDF)
  {
   var oDF = document.createElement('input');
   oDF.id = 'op-drag-fix';
   oDF.style.display = 'none';
   document.body.appendChild(oDF);
  }
  oDF.focus();
 }

 if (ondragmove) this.ondragmove(isResize);

 // Stop a normal drag event.
 cancelEvent(e);
}};


DragResize.prototype.mouseUp = function(e) { with (this)
{
 // On mouseup, stop dragging, but don't reset handler visibility.
 if (!document.getElementById || !enabled) return;

 var hRE = new RegExp(myName + '-([trmbl]{2})', '');
 if (handle && ondragend) this.ondragend(hRE.test(handle.className));
 deselect(false);
}};



/* Resize Code -- can be deleted if you're not using it. */

DragResize.prototype.resizeHandleSet = function(elm, show) { with (this)
{
 // Either creates, shows or hides the resize handles within an element.

 // If we're showing them, and no handles have been created, create 4 new ones.
 if (!elm._handle_tr)
 {
  for (var h = 0; h < handles.length; h++)
  {
   // Create 4 news divs, assign each a generic + specific class.
   var hDiv = document.createElement('div');
   hDiv.className = myName + ' ' +  myName + '-' + handles[h];
   elm['_handle_' + handles[h]] = elm.appendChild(hDiv);
  }
 }

 // We now have handles. Find them all and show/hide.
 for (var h = 0; h < handles.length; h++)
 {
  elm['_handle_' + handles[h]].style.visibility = show ? 'inherit' : 'hidden';
 }
}};


DragResize.prototype.resizeHandleDrag = function(diffX, diffY) { with (this)
{
 // Passed the mouse movement amounts. This function checks to see whether the
 // drag is from a resize handle created above; if so, it changes the stored
 // elm* dimensions and mOffX/Y.

 var hClass = handle && handle.className &&
  handle.className.match(new RegExp(myName + '-([tmblr]{2})')) ? RegExp.$1 : '';

 // If the hClass is one of the resize handles, resize one or two dimensions.
 // Bounds checking is the hard bit -- basically for each edge, check that the
 // element doesn't go under minimum size, and doesn't go beyond its boundary.
 var dY = diffY, dX = diffX, processed = false;
 if (hClass.indexOf('t') >= 0)
 {
  rs = 1;
  if (elmH - dY < minHeight) mOffY = (dY - (diffY = elmH - minHeight));
  else if (elmY + dY < minTop) mOffY = (dY - (diffY = minTop - elmY));
  elmY += diffY;
  elmH -= diffY;
  processed = true;
 }
 if (hClass.indexOf('b') >= 0)
 {
  rs = 1;
  if (elmH + dY < minHeight) mOffY = (dY - (diffY = minHeight - elmH));
  else if (elmY + elmH + dY > maxTop) mOffY = (dY - (diffY = maxTop - elmY - elmH));
  elmH += diffY;
  processed = true;
 }
 if (hClass.indexOf('l') >= 0)
 {
  rs = 1;
  if (elmW - dX < minWidth) mOffX = (dX - (diffX = elmW - minWidth));
  else if (elmX + dX < minLeft) mOffX = (dX - (diffX = minLeft - elmX));
  elmX += diffX;
  elmW -= diffX;
  processed = true;
 }
 if (hClass.indexOf('r') >= 0)
 {
  rs = 1;
  if (elmW + dX < minWidth) mOffX = (dX - (diffX = minWidth - elmW));
  else if (elmX + elmW + dX > maxLeft) mOffX = (dX - (diffX = maxLeft - elmX - elmW));
  elmW += diffX;
  processed = true;
 }

 return processed;
}};

