//var isCtrlDown = false;
var editingInProgress = false;

/*function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}*/

var getCursorPosition = function(ev)
{
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
};

function getSelectedfullIdArry(){
	var fullIdArray = Array();
	for(var i = 0; i < $("ul.topic li.selected").size(); i++)
	{
		fullIdArray[i] = $($("ul.topic li.selected").get(i)).attr("id");
	}
	return fullIdArray;
}

function switchReset(e){
	e.style.display = 'none';
	document.getElementById("reset").style.display = '';
}

function makeWindowEditable()
{
	$(window).keydown(function(event){
		if(!editingInProgress)
		{
			/*if(event.keyCode == 17)
				isCtrlDown = true;
			else */if(event.keyCode == 49)
			{
				var fullIdArray = getSelectedfullIdArry();
				ajaxChangeMark(fullIdArray, 1);
			}
			else if(event.keyCode == 50)
			{
				var fullIdArray = getSelectedfullIdArry();
				ajaxChangeMark(fullIdArray, 2);
			}
			else if(event.keyCode == 51)
			{
				var fullIdArray = getSelectedfullIdArry();
				ajaxChangeMark(fullIdArray, 3);
			}
			else if(event.keyCode == 8 || event.keyCode == 46)
			{
				var fullIdArray = getSelectedfullIdArry();
				//delete
				ajaxDeleteItems(fullIdArray);
			}
			else if(event.keyCode == 13 || event.keyCode == 68)
			{
				//done
				var fullIdArray = getSelectedfullIdArry();
				if($("ul.topic li.selected").hasClass("done"))
					ajaxChangeStatus(fullIdArray, 0);
				else
					ajaxChangeStatus(fullIdArray, 1);
			}
		}
	});

	/*$(window).keyup(function(event){
		if(event.keyCode == 17)
			isCtrlDown = false;
	});*/

	$(window).click(function(event){
		if(!event.ctrlKey)
		{
			$("ul.topic li.selected").removeClass("selected");
		}
	});

	$(".toggleView").click(function(){
		if($("ul.container").css("display") == "none")
		{
			$("ul.topicView").remove();
			$("ul.container").css({"display":""});
			$(".toggleView").html(textTopicView);
		}
		else
		{
			$("body").append("<ul class=\"topicView\"></ul>");
			$("ul.topic").each(function(){
				$("ul.topicView").append($("<li>"+$(this).siblings("div.topic-header").html()+"</li>").attr("realTopicId", $(this).attr("id")));
			});
			$("ul.topicView").sortable({
				update : function(event, ui){
					if(ui.item.next().size() == 1)
					{
						ajaxSetItemPositions(new Array(ui.item.attr("realTopicId")), 0, ui.item.next().attr("realTopicId"));
					}
					else
					{
						
						ajaxSetItemPositions(new Array(ui.item.attr("realTopicId")), 0, 0);
					}
					$(this).children("li").each(function(i){
						$("ul.topic[id="+$(this).attr("realTopicId")+"]").parent().appendTo("ul.container");
					});
				}
			});
			$("ul.container").css({"display":"none"});
			$(".toggleView").html(textItemView);
		}
	});

	$(".newTopic").click(function(){
		if(!animationActive)
			ajaxNewTopic();
		return false;
	});

	$(".toggleHelp").click(function(){
		$("#help_list").toggle();
	});

	$(".toggleHelpRegister").click(function(){
		$("#help_register").toggle();
	});
};

jQuery.fn.makeTopicEditable = function()
{
	$(this).each(function(){
		$(this).children("li").each(function(){
			$(this).makeItemEditable();
		});
	
		$(this).siblings("span.newItem").click(function(){
			if(!animationActive)
				ajaxNewItem($(this).siblings("ul.topic").attr("id"));
		});
	
		$(this).siblings("div.topic-header").click(function(){
			if(!editingInProgress)
			{
				editingInProgress = true;
				var oldText = html_entity_decode(trim($(this).html()));
				$(this).empty();
				var inputField = $("<input type=\"text\" value=\""+trim(htmlentities(oldText))+"\" />").appendTo($(this));

				inputField.get(0).focus();
				inputField.get(0).focus();

				inputField.blur(function(){
					var newText = htmlentities(trim($(this).val()));
					if(newText.length > 0)
					{
						ajaxSetTopicText($(this).parent().siblings("ul").attr("id"), newText);
					}
					else if(confirm("Oled kindel, et soovid teema kustutada?"))
					{
						ajaxDeleteTopic($(this).parent().siblings("ul.topic").attr("id"));
					}
					else
					{
						$(this).parent().append(htmlentities(oldText));
						$(this).remove();
					}
					editingInProgress = false;
				});
	
				inputField.keydown(function(event){
					if(editingInProgress && event.keyCode == 13)
					{
						$(this).get(0).blur();
					}
				});
				
			}
		});
	});
	return $(this);
};

jQuery.fn.makeItemEditable = function(){
	$(this).each(function(){
		$(this).click(function(event){
			if(!editingInProgress)
			{
				var mousePos = getCursorPosition(event);
				if(event.ctrlKey)
					$(this).toggleClass("selected");
				else if((mousePos.x - parseInt($(this).attr("posX1"))) < 20 && (mousePos.y - parseInt($(this).attr("posY1"))) < 20)
				{
					if($(this).hasClass("done"))
						ajaxChangeStatus(new Array($(this).attr("id")), 0);
					else
						ajaxChangeStatus(new Array($(this).attr("id")), 1);
				}
				else
				{
					editingInProgress = true;
					var oldText = html_entity_decode(trim($(this).html()));
					$(this).empty();
					var inputField = $("<input type=\"text\" value=\""+htmlentities(trim(oldText))+"\" />").appendTo($(this));
					inputField.get(0).focus();
					inputField.blur(function(){
						var newText = htmlentities(trim($(this).val()));
						if(newText.length > 0)
						{
							ajaxSetItemText($(this).parent().attr("id"), newText);
						}
						else
							ajaxDeleteItem($(this).parent().attr("id"));
						editingInProgress = false;
					});
	
					inputField.keydown(function(event){
						if(event.keyCode == 13)
						{
							$(this).get(0).blur();
						}
					});
					
				}
			}
		});

		$(this).bind('dragstart', function(event){
			var newList = $("<ul></ul>").addClass("topicHandle").appendTo("ul.container");
			$(this).addClass("selected");
			newList.append($("li.selected").clone().removeClass("selected"));
			$("li.selected").addClass("hidden");
			newList.children().css({"position":"static"}).removeClass("selected");
			$("ul.topic").setParameters();
			return newList;
		});

		$(this).bind('drag',function( event ){
                	$( event.dragProxy ).css({
                        	top: event.offsetY,
                        	left: event.offsetX
                        });
			var mousePos = getCursorPosition(event);
			$("ul.topic li.dragTargetItem").removeClass("dragTargetItem");
			$("ul.topic.dragTargetTopic").removeClass("dragTargetTopic");
			$("ul.topic.highlight").removeClass("highlight");
			$("ul.topic li.lastItem").removeClass("lastItem");
			$("ul.topic").each(function(){
				if(	$(this).attr("posY1") < mousePos.y &&
					$(this).attr("posY2") > mousePos.y &&
					$(this).attr("posX1") < mousePos.x &&
					$(this).attr("posX2") > mousePos.x	)
				{
					$(this).addClass("dragTargetTopic");
					var column = Math.floor(((mousePos.x - $(this).attr("posX1")) / parseInt($(this).attr("itemRealWidth"))));
					$(this).children("li[col="+column+"]").each(function(){
						if(	$(this).attr("posY1") < mousePos.y &&
							$(this).attr("posY2") > mousePos.y	)
						{
							$(this).addClass("dragTargetItem");
							return false;
						}
					});

					//if(!$("li.dragTargetItem").size() == 1)
					//	$(this).addClass("highlight");
						//$(this).children(":last").addClass("lastItem");
				}
			});
                });

		$(this).bind('dragend',function( event ){
                	$( event.dragProxy ).remove();
			if($("ul.topic li.dragTargetItem").size() == 1)
			{
				if(!$("ul.topic li.dragTargetItem").hasClass("selected"))
				{
					var fullIdArray = new Array();
					for(var i = 0; i < $("ul.topic li.selected").size(); i++)
						fullIdArray[i] = $($("ul.topic li.selected").get(i)).attr("id");

					ajaxSetItemPositions(fullIdArray, $("ul.dragTargetTopic").attr("id"), $("ul.topic li.dragTargetItem").attr("id"));

					var oldParents = $("ul.topic li.selected").parent();
					$("ul.topic li.selected").insertBefore($("ul.topic li.dragTargetItem"));
					$("ul.topic li.dragTargetItem").parent().add(oldParents).buildColumns(true);
				}
			}
			else if($("ul.topic.dragTargetTopic").size() == 1)
			{
				var fullIdArray = new Array();
				for(var i = 0; i < $("ul.topic li.selected").size(); i++)
					fullIdArray[i] = $($("ul.topic li.selected").get(i)).attr("id");

				ajaxSetItemPositions(fullIdArray, $("ul.dragTargetTopic").attr("id"), 0);

				var oldParents = $("ul.topic li.selected").parent();
				$("ul.topic li.selected").appendTo($("ul.topic.dragTargetTopic"));
				$("ul.dragTargetTopic").add(oldParents).buildColumns(true);
			}
			$("ul.dragTargetTopic").removeClass("dragTargetTopic");
			$("li.dragTargetItem").removeClass("dragTargetItem");
			$("li.selected").removeClass("hidden");
			$("li.selected").removeClass("selected");
                });
	});
	return $(this);
};



jQuery.fn.setParameters = function(){
	$(this).each(function(){
		var topicOffset = $(this).getOffset();
		$(this).attr("posX1", topicOffset.x);
		$(this).attr("posY1", topicOffset.y);
		$(this).attr("posX2", topicOffset.x + $(this).outerWidth());
		$(this).attr("posY2", topicOffset.y + $(this).outerHeight());
		var itemRealWidth = parseInt($(this).attr("itemRealWidth"));
		var itemLeft = 0;
		var itemTop = 0;

		$(this).children().each(function(){
			itemLeft = parseInt($(this).css("left"));
			itemTop = parseInt($(this).css("top"));
			$(this).attr("posX1", topicOffset.x + itemLeft);
			$(this).attr("posY1", topicOffset.y + itemTop);
			$(this).attr("posX2", topicOffset.x + itemLeft + itemRealWidth);
			$(this).attr("posY2", topicOffset.y + itemTop + $(this).outerHeight());
		});
	});
};