/*
 * SoftWiki Plugin Javascript Component(s)
 * Version: $Id: SoftWiki.js 2768 2010-03-12 17:35:32Z triechert $
 */

// pseudo constants
var SWORE_REQUIREMENT           = 'http://ns.softwiki.de/req/Requirement';
var SWORE_ABSTRACT_REQUIREMENT  = 'http://ns.softwiki.de/req/AbstractRequirement';
var SWORE_MODEL                 = 'http://ns.softwiki.de/req/';
var SWORE_FILE_PROPERTY         = 'http://ns.softwiki.de/req/hasLinkedFile';

// softwiki specific ready statements
$jq(document).ready(function() {

	$jq(".replace-inline").livequery("click", function() {
        hideHref($jq(this));
		backParameter="";
		$jq("#backToRequirements > input").each(function(){
			backParameter+=$jq(this).val()+'&';
		});
		if (backParameter.length>0) backParameter=backParameter.substr(0,backParameter.length-1);
		replaceWindow(
			owUriBase + "softwiki/view/",
			"r="+encodeURIComponent($jq(this).attr("about")),
			null,
			function() { showComments(); })
	});

	$jq("#quicksearch").livequery("keypress", function(event) { swQuickSearch(event); });

	$jq("#swEdit").livequery("click", function(event) { swEdit(event); });
	$jq(".swRelationEdit").livequery("click", function(event) { swRelationEdit(event); });
	$jq("#swCancel").livequery("click", function(event) { swCancel(event); });
	$jq("#swSubmit").livequery("click", function(event) { swSubmit(event); });
	$jq("#swDelete").livequery("click", function(event) { swDelete(event); });

	$jq("#swAddExistingFile").livequery("click", function(event) { swAddExistingFile(event); });
	$jq("#swAddNewFile").livequery("click", function(event) { swAddNewFile(event); });
	$jq(".swFile").livequery("click", function(event) { swFile(event); });
	$jq("#swSubmitFile").livequery("click", function(event) { swSubmitFile(event); });
	$jq(".swFileUnlink").livequery("click",function(event) { swFileUnlink(event); });
	$jq("#swFileInput").livequery("change",function(event) {
												var label = $jq("#swFileInput").attr("value");
												var lastpos = label.search(/([^\/\\]+)$/);
												var filename = label.substr(lastpos,label.length);
												$jq("#swLabelInput").attr("value",filename);
												event.stopPropagation();
											});

	// opendirect links via 
    // http://localhost/ontowiki/softwiki/open/?requirement=...&m=...
    var opendirect = $jq("div#opendirect").text();
    if (opendirect != "") {
        selectedResource = SWORE_REQUIREMENT;
		replaceWindow(
			owUriBase + "softwiki/view/",
			"r="+encodeURIComponent(opendirect),
			null,
			function() { 
                showComments();
                // set link to standard url to do full request
                $jq("a.requirement-back").attr(
                    'href',
                    owUriBase + "resource/list/?r=" + selectedResource
                ).removeAttr('class');
            });
    }

	// BEGIN livequeries for the editing of requirement-relations inside a 2nd window BEGIN
	$jq("a.input-reqRelation-ok").livequery("click",function(event) {
		var queryString = $jq("div.window form#input-reqRelation").serialize();	
		var targetwin = $jq("#overlays").next();
		$jq("#overlays").removeAttr("style");
		targetwin.fadeOut("normal");
		$jq.get(owUriBase + "softwiki/relationsservice/",queryString,function(data, textStatus) {
			if (data.search(/warning:no operations performed/) > -1) {
				// do nothing
			} else {
				var showRelated = $jq('input.toggleReqRelatedCheckbox').attr('checked');
				var showSimilar = $jq('input.toggleReqSimilarCheckbox').attr('checked');
				var showAll = $jq('input.toggleReqUnrelatedCheckbox').attr('checked');
			
				showRelations(showRelated,showSimilar,showAll);
			}
		});
		event.stopPropagation();
	});
	
	$jq("a.input-reqRelation-cancel").livequery("click",function(event) {
		var targetwin = $jq("#overlays").next();
		$jq("#overlays").removeAttr("style");
		targetwin.fadeOut("normal");
		event.stopPropagation();
	});
	// END livequeries for the editing of requirement-relations inside a 2nd window END

	$jq(".wrapme").livequery("click", function(event) { swToggleWrap(event); });
	$jq(".wrapme").livequery("mouseover", function(event) { $jq(event.target).css("cursor", "pointer"); });

	// show default reqlist / and Add Requirement Button
	if(typeof(selectedResource)!= "undefined" && opendirect == "") {
		replaceWindow(owUriBase + "softwiki/reqlist/", "all=true&resource=" + getSoftWikiFrickelJson(false));
		$jq("#swNew").show();
		$jq("#swNew").click( function(event) {
			// reload main window and remove all other windows
			replaceWindow(owUriBase + "softwiki/view/", "new&resources=" + getSoftWikiFrickelJson(false), $jq("div.section-mainwindows").children("div.window").eq(0), function() {newRequirement=event; });
			$jq("div.section-mainwindows").children("div.window").slice(1).remove();
			//swEdit(window.event);
		});
	}
	
	// add comment (depends on requirement form now)
	$jq("#softwiki-add-comment").livequery("click", function(event) {
		if ($jq("#softwiki-comment").val().length==0) alert("You must not post an empty comment.");
		else {
			var url = owUriBase + 'service/comments/?' + $jq("form.softwiki-comment").serialize() + "&prefix=softwiki";
			$jq.get(url,'',function() {
				showComments();
			});
		}
	})
	
	// add valuation
	$jq("#softwiki-add-valuation").livequery("click", function(event) {
		if ($jq("#valuation").val()==0) alert("You have to choose the number of stars.");
		else{
			var url = owUriBase + 'service/comments/?' + $jq("form.softwiki-valuation").serialize() + "&prefix=softwiki";
			$jq.get(url,'',function() {
				showComments();
			});
		}
	})
	
	// edit valuation
	$jq("#softwiki-edit-valuation").livequery("click", function() {
		$jq(".softwiki-valuation .disabled").removeClass("disabled").addClass("wasDisabled");
		$jq(".softwiki-valuation :disabled").removeAttr("disabled");
		$jq("#softwiki-cancel-valuation").show();
		$jq("#softwiki-submit-edit-valuation").show();
		$jq("#softwiki-edit-valuation").hide();
	})
	
	// cancel valuation
	$jq("#softwiki-cancel-valuation").livequery("click", function() {
		$jq(".softwiki-valuation .wasDisabled").addClass("disabled").removeClass("wasDisabled").attr("disabled", "disabled");
		$jq(".softwiki-valuation").resetForm();
		var oldvalue=$jq("#valuation").attr("oldvalue");
		$jq("#valuation").attr("value",$jq("#valuation").attr("oldvalue"));
		for (var i=1;i<=5;i++)
			if (i<=oldvalue) $jq('#valuationStar'+i).attr('src',$jq('#valuationStar'+i).attr('src').replace('icon_star_empty.jpg','icon_star_full.png'));
			else $jq('#valuationStar'+i).attr('src',$jq('#valuationStar'+i).attr('src').replace('icon_star_full.png','icon_star_empty.jpg'));
		$jq("#softwiki-cancel-valuation").hide();
		$jq("#softwiki-submit-edit-valuation").hide();
		$jq("#softwiki-edit-valuation").show();
	})
	
	// submit edit valuation
	$jq("#softwiki-submit-edit-valuation").livequery("click", function() {
		if ($jq("#valuation").val()==0) alert("You have to choose the number of stars.");
		else{
			var url = owUriBase + 'service/comments/?' + $jq("form.softwiki-valuation").serialize()
			    + "&edit=" + $jq("#valuation").attr("edit") + "&prefix=softwiki";
			replaceWindow(url, '', $jq("div.section-mainwindows").children("div.window").eq(1));
		}
	})
	
	// add tag-description
	$jq("#softwiki-add-tag-description").livequery("click", function() {
		if ($jq("#tag-description").val().length==0) alert("You must not post an empty tag description.");
		else {
			loadTags(true, $jq("form.softwiki-tag").serialize());
		}
	})
	
	// toggle defined tags
	$jq(".toggleDefinedTags").livequery("click", function() {
		filterTags();
	})
	
	//toggle undefined tags
	$jq(".toggleUndefinedTags").livequery("click", function() {
		filterTags();
	})
	
	$jq('.requirement-back').livequery('click', function() {
		// reload main window
		if (backParameter.length=="") backParameter="all=true&resources="+getSoftWikiFrickelJson(false);
		replaceWindow(owUriBase + "softwiki/reqlist/", backParameter);
		// remove all other windows
		$jq("div.section-mainwindows").children("div.window").slice(1).remove();
	});	
	
	
	// assign search function to tag search field
	$jq('input#tag-search-input').livequery('keyup', function() {
		// using timeout here because tag search via regexp isn't as fast as (case-sensitive) jq contains function
		if (typeof(to) != "undefined")	{
			window.clearTimeout(tagtimeout);
			var tagtimeout = window.setTimeout("filterTags()","750");
		} else {
			var tagtimeout = window.setTimeout("filterTags()","750");
		}
		
	});
	
	// req Relations Checkboxes
	$jq('.toggleReqSimilarCheckbox').livequery('click', function(event) {
		$jq(event.target).parents('div.window').eq(0).addClass('is-processing');
		//alert("related: " + $jq('input.toggleReqRelatedCheckbox').attr('checked'));
		var showRelated = $jq('input.toggleReqRelatedCheckbox').attr('checked');
		//alert("similar: " + $jq('input.toggleReqSimilarCheckbox').attr('checked'));
		var showSimilar = $jq('input.toggleReqSimilarCheckbox').attr('checked');
		//alert("all: " + $jq('input.toggleReqUnrelatedCheckbox').attr('checked'));
		var showAll = $jq('input.toggleReqUnrelatedCheckbox').attr('checked')
		showRelations(showRelated,showSimilar,showAll);
	});

	$jq('.toggleReqRelatedCheckbox').livequery('click', function(event) {
		$jq(event.target).parents('div.window').eq(0).addClass('is-processing');
		//alert("related: " + $jq('input.toggleReqRelatedCheckbox').attr('checked'));
		var showRelated = $jq('input.toggleReqRelatedCheckbox').attr('checked');
		//alert("similar: " + $jq('input.toggleReqSimilarCheckbox').attr('checked'));
		var showSimilar = $jq('input.toggleReqSimilarCheckbox').attr('checked');
		//alert("all: " + $jq('input.toggleReqUnrelatedCheckbox').attr('checked'));
		var showAll = $jq('input.toggleReqUnrelatedCheckbox').attr('checked')
		showRelations(showRelated,showSimilar,showAll);
	});

	$jq('.toggleReqUnrelatedCheckbox').livequery('click', function(event) {
		$jq(event.target).parents('div.window').eq(0).addClass('is-processing');
		//alert("related: " + $jq('input.toggleReqRelatedCheckbox').attr('checked'));
		var showRelated = $jq('input.toggleReqRelatedCheckbox').attr('checked');
		//alert("similar: " + $jq('input.toggleReqSimilarCheckbox').attr('checked'));
		var showSimilar = $jq('input.toggleReqSimilarCheckbox').attr('checked');
		//alert("all: " + $jq('input.toggleReqUnrelatedCheckbox').attr('checked'));
		var showAll = $jq('input.toggleReqUnrelatedCheckbox').attr('checked')
		showRelations(showRelated,showSimilar,showAll);
	});


	// pager links handle
	$jq('a.pager').livequery('click', function() {
		page($jq(this));
	});
	
	// auto resize for the req description
	//$jq("#rdescription").livequery("keyup", function(event) { swReqDescAutoResize(event); });
	
	$jq("span.removetag").livequery('click', function() { if (!$jq(this).parent().hasClass('disabled')) $jq(this).parent().remove(); });
	$jq('#rtagsButton').livequery('click', function(event) { addTagWithButton(event); });
	
	$jq('#rtagsNew').livequery('keyup', function(event) { suggestTags(event) });
	$jq("#rtagsNew").livequery('keyup', function(event) { addTag(event); });
	
	$jq('#rtagsNew-overlay > ul.tag_suggest > li').livequery('click', function(event) { addTagWithClickOnSuggestion($jq(this)); event.stopPropagation(); });
	$jq('html').click(function(event) { $jq('#rtagsNew-overlay').remove() });
	//$jq('#rtagsNew').livequery('blur', function() { $jq('#rtagsNew-overlay').remove() });
});

// toggles the wrap of req descriptions
function swToggleWrap (event) {
	target = $jq(event.target);
	if (target.hasClass("nowrap")) {
		target.prev().hide();
		target.hide();
		target.next().show();
		target.next().next().show();
	} else {
		target.hide();
		target.prev().hide();
		target.prev().prev().show();
		target.prev().prev().prev().show();
	}
/*	content = target.html();
	target.toggleClass("nowrap");
	target.after("<div style='white-space:normal;'>"+content+"</div>");
	target.remove();
*/
	// todo: hier weitermachen seebi!
}

// pager
function page(button) {
	// load vars (JSON doesn't work :\)
	var count   = parseInt($jq('input#count').attr('value'));
	var limit   = parseInt($jq('input#limit').attr('value'));
	var offset  = parseInt($jq('input#offset').attr('value'));
// TODO nheino ;)
	var pageUrl = $jq('input#page-url').attr('value').replace(/[\?&]limit=[\d]+/, '').replace(/[\?&]offset=[\d]+/, '');
	
	// which button was clicked
	if (button.hasClass('first-page')) {
		offset = 0;
	} else if (button.hasClass('previous-page')) {
		offset -= limit;
	} else if (button.hasClass('next-page')) {
		offset += limit;
	} else if (button.hasClass('last-page')) {
		offset = count - (count % limit);
	} else {
		var page = parseInt(button.attr('id').replace(/page-/, ''));
		offset = page * limit - limit;
	}
	
	// construct new url
	var newPageUrl = pageUrl + '&limit=' + limit + '&offset=' + offset;

	// load new page
	var view_win = button.parents('div.content').eq(0);
	view_win.addClass('is-processing');
    $jq.get(owUriBase + 'softwiki/reqlist/', newPageUrl,
		function (data, textStatus) {
			// only replace window content (keeps tabs 'activetabconent' and title of window)
			view_win.replaceWith($jq(data).children('.content').addClass('activetabcontent'));
		}
	);
}

// quicksearch in the reqlist
function swQuickSearch (event) {
	if (event.which == 13) { // do only search if user pressed enter
		var searchString = event.target.value;
// TODO nheino
		var pageUrl = $jq('input#page-url').attr('value').replace(/[\?&]search=[a-zA-Z0-9]+/, '');
		var newPageUrl = pageUrl + '&search=' + searchString;
		
		// load new page
		var view_win = $jq(event.target).parents('div.window').eq(0);
		view_win.addClass('is-processing');
		$jq.get(owUriBase + 'softwiki/reqlist/', newPageUrl,
			function (data, textStatus) {
				// only replace window content (keeps tabs 'activetabconent' and title of window)
				$jq(data).children('.content').addClass('activetabcontent');
				view_win.replaceWith($jq(data));
			}
		);
	}
}

// show similar requirements in the second window
function showSimilars () {
	var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
	var queryString = "similar=" + encodeURIComponent($jq("#rtitle").val() + " " + stripTags(oFCKeditor.GetXHTML(false))/*$jq("#rdescription").val()*/);
		
	if ($jq("#requirement").attr("about") == "") {
	    // do nothing
	} else {
	    queryString += "&r=" + $jq("#requirement").attr("about");
	}

	if ($jq("div.section-mainwindows").children("div.window").size() == 1) {
		$jq("div.section-mainwindows").append("<div class='window'></div>");
	}
	var targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
	if (targetwin) {
		replaceWindow(owUriBase + "softwiki/reqlist/", queryString, targetwin);
	}
}

// show comments of requirements in the second window
function showComments (showValuations, showComments) {
	if (arguments.length==0){
		showValuations=true;
		showComments=true;
	}
	else if (arguments.length==1){
		showComments=true;
	}
	if (typeof($jq("#requirement").attr("about")) != 'undefined') {
        var queryString = "list&r=" + encodeURIComponent($jq("#requirement").attr("about"))
                        + "&val="+showValuations+"&com="+showComments
		     + "&prefix=softwiki";
		if ($jq("div.section-mainwindows").children("div.window").size() == 1) {
			$jq("div.section-mainwindows").append("<div class='window'></div>");
		}
		var targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
		targetwin.addClass('is-processing');
		if (targetwin) {
			taboptionsString = "tab[0][string]=comments.title&tab[0][link]=javascript:showComments();&" +
				"tab[1][string]=sw.reqlist.listrelated&tab[1][link]=javascript:showRelations();&" +
				"active=0";
			$jq.get(owUriBase + "softwiki/extratab/", taboptionsString, function (data, textStatus) {
				replaceWindow(owUriBase + "service/comments/", queryString, targetwin, function() {
					$jq("div.section-mainwindows").children("div.window").eq(1).children("h1.title").after(data);
					$jq("div.section-mainwindows").children("div.window").eq(1).children("div.content").addClass("activetabcontent");
				});
			});
		}
	}
}

// show relations of requirements in the second window
function showRelations (showRelated, showSimilar,showAll) {
	try{
		var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
		showSimilar = (showSimilar == null) ? false : showSimilar;
		showRelated = (showRelated == null) ? true : showRelated;
		showAll = (showAll == null) ? false : showAll;
		
		//alert(showRelated + ' # ' + showSimilar + ' # ' + showAll);
		if (showSimilar) {
		    var queryString = "similar="+encodeURIComponent($jq("#rtitle").val()) + "%20"
		                 +  encodeURIComponent(stripTags(oFCKeditor.GetXHTML(false))/*$jq("#rdescription").val()*/);
		} else {
		    var queryString = "";
		}
		
		if (typeof($jq("#requirement").attr("about")) != 'undefined') {
			queryString += "&advancedConfig=true&r=" + encodeURIComponent($jq("#requirement").attr("about"))
			             + "&all=" + showAll + "&relations=" + showRelated;
	
			if ($jq("div.section-mainwindows").children("div.window").size() == 1) {
				$jq("div.section-mainwindows").append("<div class='window'></div>");
			}
			var targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
			if (targetwin) {
				taboptionsString = "tab[0][string]=comments.title&tab[0][link]=javascript:showComments();&" +
					"tab[1][string]=sw.reqlist.listrelated&tab[1][link]=javascript:showRelations();&" +
					"active=1";
				$jq.get(owUriBase + "softwiki/extratab/", taboptionsString, function (data, textStatus) {
					replaceWindow(owUriBase + "softwiki/reqlist/", queryString, targetwin, function() {
						$jq("div.section-mainwindows").children("div.window").eq(1).children("h1.title").after(data);
						$jq("div.section-mainwindows").children("div.window").eq(1).children("div.content").addClass("activetabcontent");
					});
				});
			}
		}
	} catch(e) {}
}

// the requirement form edit button action
function swEdit (event) {
	try{
		//get instance of the fckeditor
		var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
		
		//show editable title and description
		$jq("#noneditDescription").hide();
		$jq("#editDescription").show();
		
		$jq("#requirement").ajaxForm();
		
		// show similars of current content
		showSimilars();
		$jq("#rtitle").change( function() { showSimilars(); } );
				
		// show delete button not for "new requirements"
		if ( typeof( $jq("#requirement").attr('about') ) != 'undefined' && $jq("#requirement").attr('about').length!=0 
&& !(  $jq("#requirement").attr('userUri') !=  $jq("#requirement").attr('Creator')  && $jq("#requirement").attr('userUri')  != 'http://localhost/OntoWiki/Config/Admin') ) {
			$jq("#swDelete").show();
		}

		$jq("#swSubmit").show();
		$jq("#swCancel").show();
		$jq("#swEdit").hide();
		$jq(".disabled").removeClass("disabled").addClass("wasDisabled");
		$jq(":disabled").removeAttr("disabled");
				
		// show topic selector
		$jq('#rtopic-input').hide();
		$jq('#rtopic-select').show();
			
		// disable tag submit button by default (no empty tags)
		$jq('#rtagsButton').addClass('disabled').removeClass('wasDisabled');
			
		// store suggestable tags 
		var url = owUriBase + 'service/tagsuggestion';
		jQuery.data($jq('#rtagsNew').get(0), 'suggestTags', new Array());
		$jq.getJSON(url, function(data) { jQuery.data($jq('#rtagsNew').get(0), 'suggestTags', data); });
			
		jQuery.data($jq('#rtags').get(0), 'rtagsOrig', $jq('#rtags').children('span'));
		event.stopPropagation();
	} catch(e){}
}

// the requirement form cancel button action
function swCancel (event) {
	//hide editable title and description
	$jq("#editDescription").hide();
	$jq("#noneditDescription").show();
	
	// rebuild second view
	showComments();
	
	// rebuild the original tags
	$jq('#rtags').children('span').remove();
	$jq('#rtagsButton').after(jQuery.data($jq('#rtags').get(0), 'rtagsOrig'));
		
	$jq("#swDelete").hide();
	$jq("#swSubmit").hide();
	$jq("#swCancel").hide();
	$jq("#swEdit").show();
	
	$jq(".wasDisabled").addClass("disabled").removeClass("wasDisabled").attr("disabled", "disabled");
	$jq("#requirement").resetForm();
	
	//get instance of the fckeditor
	var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
	//restore Content
	oFCKeditor.SetHTML(oldFCKcontent);
	
	/*$jq('#rdescription').autoResizeTextArea();*/
	
	event.stopPropagation();
}

// the requirement form submit button action
function swSubmit(event) {
	//get instance of the fckeditor
	var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');

	if ($jq('#rtitle').val() == '' ||
        stripTags(oFCKeditor.GetXHTML(false))  == '' ||
        $jq('#rtopic-select').attr('value') == '' )
    {
        alert(allFields);
        return;
    }

	// submit data and reload windows to match default requirement view
	var targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
	var reqFormElem = $jq("#requirement");

	// Tags serialisieren (als JSON)	
	var tagsJson = '[';
	var tags = $jq('#rtags').children('span');
	for (var i=0; i<tags.length; ++i) {
			tagsJson += '"' + tags.children('span.tag').eq(i).text() + '"';
			
		if (i < (tags.length-1)) {
			tagsJson += ','
		}
	}					
	tagsJson += ']';
	
	// Buttons und Eingaben deaktivieren
	$jq("#swSubmit").hide();
	$jq("#swCancel").hide();
	$jq("#swDelete").hide();
	$jq("#swEdit").hide();
	$jq(".wasDisabled").addClass("disabled").removeClass("wasDisabled").attr("disabled", "disabled");
		
	// Hauptfenster auf is-processing stellen
	$jq("div.section-mainwindows div.window div.content").addClass("is-processing");
	
	// query string bauen
	var queryString = 'rtitle=' + encodeURIComponent($jq('#rtitle').attr('value')) + '&' +
		 			  'rdescription=' + encodeURIComponent(stripGreenTags(oFCKeditor.GetXHTML( false )).replace(/&nbsp;/g,' ')/*$jq('#rdescription').val()*/) + '&' +
					  'rtopic=' + encodeURIComponent($jq('#rtopic-select').attr('value')) + '&' +
					  'rtags=' +  encodeURIComponent(tagsJson) + '&' + 
					  'r=' + $jq("#requirement").attr("about");
	
	$jq.get(owUriBase + "softwiki/update/", queryString , function(data, textStatus) {
	
		if ($jq("#requirement").attr("about")  == "") {
			var response = data.split(":");
			$jq("#requirement").attr("about",decodeURIComponent(response[1]));
		}
		
		var queryString = "r=" + $jq("#requirement").attr("about");
		// reload resource in first window
		var targetwin = $jq("div.section-mainwindows").children("div.window").eq(0);
		if (targetwin) {
			replaceWindow(owUriBase + "softwiki/view/", queryString, targetwin,function() {
			});
		}
		
		// Show default view (comments)
		showComments();
    	// reload tags
    	loadTags();
    	// reload hierarchy
    	$jq('div.hierarchy').livequery(function() {
			var id = $jq(this).attr('id');
			loadHierarchy(id, $jq('#' + id).find('ol').eq(0));
		});
	});

	event.stopPropagation();
}

// Remove Requirement
function swDelete(event) {

	$jq("div.section-mainwindows").children("div.window").eq(0).toggleClass("is-processing");
	$jq("div.section-mainwindows").children("div.window").eq(1).remove();
	var queryString = "r=" + $jq("#requirement").attr("about");
	$jq.get(owUriBase + "resource/delete", queryString, function (data, textStatus) {
		location.reload();
	});


}

function go(select) {
  		var wert = select.options[select.options.selectedIndex].value;
			if ( wert != "Select") {
	     	window.location.href = wert;
	    }
}



/* ------------------------- Tags ---------------------------- */

// tagbox-specific load actions
var selectedTags = new Array();
var tempTags = new Array();

// load tags from service
function loadTags(renewTags,queryParameters) {
	$jq('.window#tags').livequery(function() {
		if (renewTags) {
			selectedTags = new Array();
		}
		
		var url = owUriBase + 'service/tags/';//'?tags=' + getSoftWikiFrickelJson(true);
		if (queryParameters)
			queryParameters+='&tags='+getSoftWikiFrickelJson(true);
		else
			queryParameters='tags='+getSoftWikiFrickelJson(true);
		
		if (selectedResource) {
			url += '?r=' + selectedResource;
			if (queryParameters){
				url += '&' + queryParameters;
			}
		}
		else if (queryParameters){
			url += '?' + queryParameters;
		}
				
		$jq.ajax({
			url: url, 
			dataType: 'html', 
			data: tagParams, 
			success: function(content) {
				$jq('.window#tags').contents('.content').children('ol').remove();
				$jq('.window#tags').contents('.content').children('div').remove();
				$jq('.window#tags').contents('.content').append(content);
				
				tempTags = selectedTags;
				selectedTags = new Array();
			}
		});
	});
}

$jq(document).ready(function() {
	// load json params from dom tree
    eval($jq('.window#tags').find('script').html());
	
	$jq('#tag-search-input').livequery(function() {
		$jq.each($jq('#tag-search-input'), function(id, input) {
			enhanceInput(input);
		})
		$jq('#tag-search-input').clearTagSearchInput();
	});
	
    $jq('.tag.javascript-on').livequery(function() {
        if (tempTags && jQuery.inArray($jq(this).attr('about'), tempTags) > -1) {
            $jq(this).addClass('selected');
            selectedTags.push($jq(this).attr('about'));
        }
    });
		
	$jq('.tag.javascript-on').livequery('click', function() {
		var tagA   = $jq(this);
		var tagUri = tagA.attr('about');
		
		// insert clicked tag into tags array if it isn't
		// already there, else remove it
		var pos = jQuery.inArray(tagUri, selectedTags);
		if (pos > -1) {
			tags = selectedTags.splice(pos, 1);
		} else {
			selectedTags.push(tagUri);
		}
		
		// toggle tag selection
		tagA.toggleClass('selected');
		
		// reload main window
        // selectedTags = new Array();
		replaceWindow(owUriBase + "softwiki/reqlist/", "all=true&resources=" + getSoftWikiFrickelJson(false));
		
		$jq("div.section-mainwindows").children("div.window").slice(1).remove();
		loadTags(false,'tagUri='+tagUri);
		// alert('Reloading page: ' + owUriBase + 'softwiki/reqlist/...');
	});
});

/* ---------------------- Hierarchy -------------------------- */

// hierarchy-specific load actions
$jq(document).ready(function() {
	loadTags();
	
	// load hierarchy for each hierarchy box
	$jq('div.hierarchy').livequery(function() {
		var id = $jq(this).attr('id');
		loadHierarchy(id, $jq('#' + id).find('ol').eq(0));
		if (selectedResource == 'http://ns.softwiki.de/req/Requirement') {
		    $jq('.resource-select.root').addClass('selected');
		}
	});
	
	// assign search function to hierarchy search field
	$jq('input.hierarchy-search-input').livequery('keyup', function() {
		filterHierarchy($jq(this).attr('id').replace('-search-input', ''));
	});
	
	$jq('.tree-node-toggle').livequery('click', function() {
		toggleTree($jq(this).attr('id'));
	});
	
	$jq('.tree-open').livequery(function() {
		if (!$jq(this).nextAll('ol').children().length) {
			var rootId   = $jq(this).parents('div.window').attr('id');
			var targetOl = $jq(this).nextAll('ol');
			var entryUri = $jq(this).next('a').attr('about');
			targetOl.show();
			loadHierarchy(rootId, targetOl, entryUri);
		}
	});
	
	$jq('.resource-select').livequery('click', function() {
		// store new resource
		/*if (selectedResource == $jq(this).attr('about')) {
			selectedResource = 'http://ns.softwiki.de/req/Requirement';
			$jq('.resource-select.root').addClass('selected');
			$jq(this).removeClass('selected');
		} else {*/
			selectedResource = $jq(this).attr('about');
			$jq(".resource-select[@about="+$jq(this).attr('about')+"]").addClass('selected');
		//}
		// clear tags
		selectedTags = new Array();
		// update tags
		loadTags();
		
		// deselect all others
		$jq('.resource-select').each(function(i) {
			if ($jq(this).attr('about') != selectedResource) {
				$jq(this).removeClass('selected');
			}
		})
		
		// remove topic selector and container
		$jq('#rtopic-select-overlay').remove();
		$jq('#rtopic-tree-container').remove();
		
		// reload main window
		replaceWindow(owUriBase + "softwiki/reqlist/", "all=true&resources=" + getSoftWikiFrickelJson(false));
		// remove all other windows
		$jq("div.section-mainwindows").children("div.window").slice(1).remove();
		// alert('Reloading page: ' + owUriBase + 'softwiki/reqlist/...');
		selectedTags = new Array();
	});
});

function toggleTree(id) {
	var elem      = $jq('#' + id);
	var entryUri  = elem.next('a').attr('about');
	
	if (elem.is('.tree-open')) {
		elem.removeClass('tree-open').addClass('tree-closed');
		
		elem.nextAll('ol').slideUp('fast', function() {
			elem.nextAll('ol').children().remove();
		});
		
		// save node state in session
		setSessionVar('name=nodeState&nodeState[' + encodeURIComponent(entryUri) + ']=closed');
		
	} else {
		elem.removeClass('tree-closed').addClass('tree-open');
		
		// save node state in session
		setSessionVar('name=nodeState&nodeState[' + encodeURIComponent(entryUri) + ']=open');
	}
}

function loadHierarchy(id, target, entryUri) {
	
	target.addClass('is-processing');
	
	$jq('.resource-select.root').show();
	
	// load json params from dom tree
	eval($jq('#' + id).find('script').text());
	
	var url = owUriBase + 'service/gettreenodecontent/';
	
	if (typeof(entryUri) != 'undefined') {
		// url += '?r=' + encodeURIComponent(entryUri);
		hierarchyParams.r = entryUri;
	}
	
	if ($jq('#' + id).hasClass('javascript-on')) {
		hierarchyParams.javascript = true;
	}
	
	$jq.ajax({
		url: url, 
		dataType: 'html', 
		data: hierarchyParams, 
		success: function(content) {
			if (target.children().length) {
				target.children().fadeOut(effectTime, function() {
					target.children().remove();
					target.prepend(content);
					target.removeClass('is-processing');
				});
			} else {
				target.prepend(content);
				target.removeClass('is-processing');
			}
		}
	});
}

// store the text length for the next round
var lastLength = 0;
var count      = 0;

function filterHierarchy(id) {
	var text       = jQuery.trim($jq('#' + id + '-search-input').val());
	var localCount = ++count;
	
	// load json params from dom tree
	eval($jq('#' + id).find('script').text());
	
	window.setTimeout(function() {
		// count has not been changed by another call, i.e. no more text entered
		if (count == localCount) {
			if ((text.length >= autoCompleteMinChars)) {
				// enable javascript-only links
				if ($jq('#' + id).hasClass('javascript-on')) {
					hierarchyParams.javascript = true;
				}
				
				$jq('.resource-select.root').hide();
				
				var input = $jq('#' + id + '-search-input');
				var target = input.parents('.window').find('ol').eq(0);
				target.addClass('is-processing');
				$jq.ajax({
					url: owUriBase + 'service/gettreenodecontent/?s=' + text,
					dataType: 'html', 
					data: hierarchyParams, 
					success: function(content) {
						target.children().fadeOut(effectTime, function() {
							target.children().remove();
							target.removeClass('is-processing');
							if (jQuery.trim(content) != '') {
								target.prepend(content);
							} else {
								target.prepend('<p class="messagebox info">No matches!</p>');
							}
						});
					}
				});
				lastLength  = text.length;
			} else if ((text.length < autoCompleteMinChars) && lastLength >= autoCompleteMinChars) {
				loadHierarchy(id, $jq('#' + id).find('ol').eq(0));
				$jq('.resource-select.root').show();
				lastLength = 0;
			}
		}
	}, autoCompleteDelay);
}

/* ------------------- SoftWiki-Frickel-Funktion -------------------- */
// prepare json string
function getSoftWikiFrickelJson(tagsOnly) {
	var json = '[';
	for (var i = 0; i < selectedTags.length; ++i) {
		json += '"' + encodeURIComponent(selectedTags[i]) + '",';
	}
	
	if (tagsOnly) {
		if (json.length==1) json+=']';
		else json = json.substr(0,json.length - 1)+']';
	} else {
		json += '"' + encodeURIComponent(selectedResource) + '"]';
	}
	
	return json;
}

/* ------------------- SoftWiki-File Management Functions -------------------- */
// add existing file
function swAddExistingFile(event) {
	if (typeof($jq("#requirement").attr("about")) != 'undefined') {
		if ($jq("div.section-mainwindows").children("div.window").size() == 1) {
			$jq("div.section-mainwindows").append("<div class='window'></div>");
		}
		var targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
		if (targetwin) {
			replaceWindow(owUriBase + "softwiki/file/", "type=exist", targetwin);
		}
	}
	event.stopPropagation();
}

// add new file
function swAddNewFile(event) {
	if (typeof($jq("#requirement").attr("about")) != 'undefined') {
		if ($jq("div.section-mainwindows").children("div.window").size() == 1) {
			$jq("div.section-mainwindows").append("<div class='window is-processing'></div>");
		}
		var instance = $jq("#requirement").attr("about");
		targetwin = $jq("div.section-mainwindows").children("div.window").eq(1);
		$jq.get(owUriBase + "softwiki/file/?type=new", '' , function(data, textStatus) {
			targetwin.replaceWith(data);
			$jq("#swFileForm").submit( function () {
				var options = {
					url: owUriBase + 'resource/file/?r=' + instance ,
					success: swUploadFile ,
					type: 'post'
				};
				$jq(this).ajaxSubmit(options);
				return false;
			});
		});
	}
	event.stopPropagation();
}

// add file with about
function swFile(event) {
	var $target = $jq(event.target);
	$target.toggleClass('selected');
	event.stopPropagation();
}

// On Submit of file dialogs
function swSubmitFile(event) {
	var $target = $jq(event.target);
	var resources = new Array();
	$jq('.swFile').each(function () {
		if ($jq(this).hasClass('selected')) {
			//alert('File' + $jq(this).attr('about'));
			resources.push($jq(this).attr('about'));
		}
	});
	
	if ($jq('.swFile.selected').size() != 0 && typeof($jq("#requirement").attr("about")) != 'undefined') {
		var resourcesjson = "[";
		for (var i = 0; i<resources.length ;i++) {
			resourcesjson = resourcesjson + "\"" + resources[i] + "\" , ";
		}
		resourcesjson = resourcesjson.substr(0,(resourcesjson.length) - 3);
		resourcesjson += "]";
		
		var instance = $jq("#requirement").attr("about");
		$jq("div.section-mainwindows").children('div.window').eq(0).addClass('is-processing');
		//replaceWindow(owUriBase + "softwiki/view/","r=" + instance);
		$jq.get(owUriBase + "softwiki/file/", "type=add&resources=" + resourcesjson,
				function(data) {
						var msg = data;
						$jq.get(owUriBase + "softwiki/view/?r=" + instance,
								function (data) {
									$jq("div.section-mainwindows").html(data);
									$jq("div.section-mainwindows").children("div.window").
									children(".content").prepend(msg);
									showComments();
						});
		});
	} else {
		showComments();
	}
	
	event.stopPropagation();
}

//On new file upload
function swUploadFile(responseText, statusText) {
	if (typeof($jq("#requirement").attr("about")) != 'undefined') {
		var instance = $jq("#requirement").attr("about");
		$jq("div.section-mainwindows").children('div.window').eq(0).addClass('is-processing');
		$jq.get(
			owUriBase + "softwiki/view/?r=" + instance,
			function (data) {
				$jq("div.section-mainwindows").html(data);
				$jq("div.section-mainwindows > div.window:first > div.content")
				.prepend(responseText);
			}
		);
	}
}

// Unlink event (delete relation from req to file)
function swFileUnlink (event) {
	$jq("div.section-mainwindows").children("div.window").toggleClass("is-processing");
	var resourcesjson = "[ \"" + $jq(event.target).parent().children().attr("about") + "\" ]";
	$jq.get(
		owUriBase + "softwiki/file/","type=unlink&resources=" + resourcesjson,
				function(data) {
						var msg = data;
						$jq.get(owUriBase + "softwiki/view/?r=" + instance,
								function (data) {
									$jq("div.section-mainwindows").html(data);
									$jq("div.section-mainwindows").children("div.window").
									children(".content").prepend(msg);
						});
	});
	event.stopPropagation();
}

/* -------------------------- Hierarchy Dropdown --------------------------- */
$jq(document).ready(function() {
    $jq('#rtopic-select').livequery(function() {
        $jq(this).dropdownHierarchy({
            url:              owUriBase + 'service/gettreenodecontent/', 
            nodeType:         hierarchyParams.nt, 
            subRelation:      hierarchyParams.sr, 
            instanceRelation: hierarchyParams.ir
        });
    });
})

function repositionOverlay() {
    $jq('#rtopic-select').css('width', '20em');
    var offset = $jq('#rtopic-select').offset();
    
    $jq('#rtopic-select-overlay').css('top', offset.top + 'px');
    $jq('#rtopic-select-overlay').css('width', '16em');
    $jq('#rtopic-tree-container').css('top', offset.top + $jq('#rtopic-select').height() + 3 + 'px');
    $jq('#rtopic-tree-container').css('width', '20em');
    
    if ($jq.browser.msie && $jq.browser.version == '6.0') {
        $jq('#rtopic-select-overlay-iframe')
            .css('top', offset.top + 'px')
            .css('width', '16em');
    }
}

jQuery.fn.dropdownHierarchy = function(settings) {
    return this.each(function() {
        var select = $jq(this);
        var offset = select.offset();
        
        if (select.attr('disabled')) {
            $jq('#rtopic-select-overlay').addClass('disabled');
        }
        
        $jq('body').append('<div id="rtopic-select-overlay"></div><div id="rtopic-tree-container"></div>');
            
        $jq('#rtopic-select-overlay')
            .css('position', 'absolute')
            .css('background-image', 'url("' + owUriBase + 'plugins/SoftWiki/trans.gif")')
            .css('background-repeat', 'repeat')
            .css('left', offset.left + 'px')
            .css('top', offset.top + 'px')
            .css('width', '20em')
            .css('height', select.height() + 3 + 'px')
            .css('padding-left', '0.5em')
            .css('zIndex', '101')
            .width(select.width());

        $jq('#rtopic-tree-container')
            .css('position', 'absolute')
            .css('border', '1px solid #ccc')
            .css('display', 'none')
            .css('left', offset.left + 'px')
            .css('top', offset.top + select.height() + 3 + 'px')
            .css('height', '20em')
            .css('font-size', '0.8em')
            .css('opacity', '0.96')
            .css('overflow', 'auto')
            .css('background-color', '#fff')
            .css('zIndex', '101')
            .width(select.width() - 2);
        
        // IE6 specific hack
        if ($jq.browser.msie && $jq.browser.version == '6.0') {
            $jq('body').append('<iframe id="rtopic-select-overlay-iframe"></iframe>');
            $jq('#rtopic-select-overlay-iframe')
                .css('position', 'absolute')
                .css('top', offset.top + 'px')
                .css('left', offset.left + 'px')
                .css('height', select.height() + 3 + 'px')
                .css('width', '16em')
                .css('zIndex', '100')
                .css('filter', 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)');
            
            $jq('#rtopic-select-overlay')
                .css('background-image', 'url("' + owUriBase + 'plugins/SoftWiki/select.gif")')
                .css('background-repeat', 'no-repeat')
                .css('width', '16em');
        }
        
        jQuery('.tree-item').livequery('click', function(event) {
            select.find('option').remove();
            var text = jQuery.trim(jQuery(this).text().replace(/\(\d\)/, ''));
            select.append('<option value="' + jQuery(this).attr('about') + '" selected="selected">' + text + '</option>');
            
            // IE6 specific hack
            if ($jq.browser.msie && $jq.browser.version == '6.0') {
                $jq('#rtopic-select-overlay').text(text);
            }
            
            jQuery('#rtopic-tree-container').fadeOut(effectTime);
            event.stopPropagation();
        })
        
        jQuery('#rtopic-tree-container a').livequery('mouseover', function(event) {
            jQuery(this).addClass('selected');
        })
        
        jQuery('#rtopic-tree-container a').livequery('mouseout', function(event) {
            if (jQuery(this).attr('about') != jQuery('#rtopic-select option').val()) {
                jQuery(this).removeClass('selected');
            }
        })
        
        // hide on any click
        jQuery('html').click(function(event) {
            event.stopPropagation();
            if (jQuery('#rtopic-tree-container').css('display') != 'none') {
                jQuery('#rtopic-tree-container').fadeOut(effectTime);
                jQuery('#rtopic-tree-container').html('');
            }
        })
        
        // load hierarchy on click
        jQuery('#rtopic-select-overlay').mousedown(function(event) {
            jQuery('#rtopic-select').mousedown();
        });
        
        jQuery('#rtopic-select').parents('form').mousemove(function(event) {
            repositionOverlay();
        });
        
        jQuery('#rtopic-select').mousedown(function(event) {                 
            if (!jQuery(this).hasClass('disabled') && jQuery('#rtopic-tree-container').css('display') != 'block') {
                var url = settings.url
                        + '?complete=true&javascript=true'
                        + '&nt=' + encodeURIComponent(settings.nodeType) 
                        + '&sr=' + encodeURIComponent(settings.subRelation)
                        + '&ir=' + encodeURIComponent(settings.instanceRelation);
                jQuery('#rtopic-tree-container').load(url, function() {
                    jQuery('#rtopic-tree-container').fadeIn(effectTime);
                    
                    var current = jQuery('#rtopic-select option').val();
                    jQuery('#rtopic-tree-container').find('a[@about="' + current + '"]').addClass('selected');
                });
            }
            event.preventDefault();
            event.stopPropagation();
        })
    })
}

/* ------------------ Requirement Description Auto Resize ------------------ */
$jq(document).ready(function() {
	/*$jq('#rdescription').livequery(function() { 
		$jq(this).autoResizeTextArea() 
	});*/
});


jQuery.fn.autoResizeTextArea = function() 
{	
	return this.each(function() {
		
		new jQuery.autoResizeTextArea(this);
	});
};

jQuery.autoResizeTextArea = function(elem)
{	
	// quick n dirty msie hack :(
	if (jQuery.browser.msie) {
		jQuery(elem).css('line-height', '100.01%');
	}
	
	this.dummy 			= null;
	this.intervall 		= null;
	this.line_height	= parseInt(jQuery(elem).css('line-height'));
	this.min_height		= parseInt(jQuery(elem).css('min-height'));
	this.max_height		= parseInt(jQuery(elem).css('max-height'));
	this.textarea		= jQuery(elem);
	
	this.init();
};

jQuery.autoResizeTextArea.fn = jQuery.autoResizeTextArea.prototype = { autoResizeTextArea: '0.1' };
jQuery.autoResizeTextArea.fn.extend = jQuery.autoResizeTextArea.extend = jQuery.extend;

var resizeCount = 0;
jQuery.autoResizeTextArea.fn.extend(
{	
	init: function() 
	{	
		var self = this;
		
		this.textarea.css({overflow: 'hidden', display: 'block'});
		this.textarea
			.bind('keyup', function() { 
				var localCount = ++resizeCount;
				window.setTimeout(function() { 
					if (localCount == resizeCount) {
						self.checkExpand();
					} 
				}, 300) 
			});
		
		this.checkExpand();
	},
	
	checkExpand: function()
	{	
		if (this.dummy == null) {
			this.dummy = $jq('<div></div>');
			
			this.dummy.css({
				'font-size'  : this.textarea.css('font-size'),
				'font-family': this.textarea.css('font-family'),
				'width'      : this.textarea.css('width'),
				'padding'    : this.textarea.css('padding'),
				'line-height': this.line_height + 'px',
				'overflow-x' : 'hidden',
				'display'    : 'none',
				'position'   : 'absolute',
				'top'        : 0,
				'left'       : '-9999px'
			}).appendTo('body');
		}
		
		var html = this.textarea.val().replace(/\n/g, '<br>n');
		
		if (this.dummy.html() != html || html=='') {
			this.dummy.html(html);
			
			var dHeight = this.dummy.height();
			var tHeight = this.textarea.height();
			
			
			
			var newHeight = dHeight + 2*(this.line_height);			
			if (!isNaN(this.max_height) && (newHeight > this.max_height)) {
				this.textarea.css('overflow-y', 'auto');
			} else {
				this.textarea.css('overflow-y', 'hidden');
				if ((tHeight < newHeight) || (dHeight < tHeight)) {
					//this.textarea.animate({height: newHeight + 'px'}, 100);
					this.textarea.css('height', newHeight + 'px');
					
					// HACK:
					repositionOverlay();
				}
			}
		}
	}
});

/*function swReqDescAutoResize(event) {
	
	resizeTextArea($jq('#rdescription'));return;
	
	// only do something if pressed key was one of return, delete or entf
	if ((event.which == 13) || (event.which == 8) || (event.which == 46)) {
		resizeTextArea($jq('#rdescription'));
	}
}

function resizeTextArea(elem) {
	
	var minNRows = 4;
	var maxNRows = 20;
	var tArea = elem;
	var tVal = tArea.val();
	var nRows = parseInt(tArea.attr("rows"));
	
	var dummy = jQuery.data(tArea.get(0), 'dummyElem');
	
	if (typeof dummy == 'undefined') {
		dummy = $jq('<div></div>');
		
		dummy.css({
			'font-size'  : tArea.css('font-size'),
			'font-family': tArea.css('font-family'),
			'width'      : tArea.css('width'),
			'padding'    : tArea.css('padding'),
			'line-height': tArea.css('line-height'),
			'overflow-x' : 'hidden',
			'display'    : 'block',
			'position'   : 'absolute',
			'top'        : 0,
			'left'       : '0px'
		}).appendTo('body');
		
		jQuery.data(tArea.get(0), 'dummyElem', dummy);
	}
	
	var html = tVal.replace(/\n/g, '<br>');
	
	if (dummy.html() != html) {
		dummy.html(html);
		
		var dHeight = dummy.height();
		var tHeight = tArea.height();
		var lHeight = parseInt(tArea.css('line-height'));
		
		if (tHeight != (dHeight + lHeight)) {
			var newHeight = parseInt((dHeight+lHeight)/lHeight);
			
			if (newHeight < minNRows) {
				tArea.attr('rows', minNRows);
			} else if (newHeight > maxNRows) {
				tArea.attr('rows', maxNRows);
			} else {
				tArea.attr('rows', newHeight);
			}
		}
	}
	
	
	return;
	dummy.height();
	tArea.focus();
	return;
	while ((dummy.height() + tArea.css('line-height')) >= tArea.height()) {
		
		var n = parseInt(tArea.attr('rows'));
		if (n >= maxNRows) {
			break;
		}
		
		tArea.attr('rows', (n+1));
	}
	
	dummy.remove();
	return;
	
	
		
	var eolCount = 1;
		
	for (var i=0; i<(tVal.length-1); ++i) {
		if (tVal.charAt(i) == "\n") {
			eolCount++;
		}
	}
		
	if ((eolCount+1) >= nRows) {
		tArea.attr("rows", (nRows + ((eolCount+1) - nRows) + 1));
	} else {
		var diff = nRows - (eolCount+2);
		
		if ((nRows-diff) >= minNRows) {
			tArea.attr("rows", (nRows - diff));
		} else {
			tArea.attr("rows", minNRows);
		}	
	}
}*/

/* ------------------ tagging functionality -------------------------------- */
function addTag(event) {
	
	var addElem = $jq("#rtagsNew");
	var tagList = $jq('#rtags');
	var tagVal = addElem.attr('value');
	var tagButtonElem = $jq('#rtagsButton');
	
	function animateError() {
		
		addElem.animate({backgroundColor: '#f00', opacity: 0.6}, 100);
		addElem.animate({backgroundColor: '#fff', opacity: 1.0}, 600);
		

	}
	
	function isValidTag() {
		
		if ((typeof tagVal != 'undefined') && (tagVal.replace(/\s/g, "") != "")) {
			var tags = tagList.children('span');
			
			var isNew = true;
			for (var i=0; i<tags.length; ++i) {
				curTagText = tags.children('span').eq(i).text();
				
				if (curTagText.toLowerCase() == tagVal.toLowerCase()) {
					isNew = false;
					break;
				}
			}
			
			if (isNew == true) {
				return true;
			}
		}
		
		return false;
	}
	
	if ((event.which == 13)) {
		if (!(addElem.hasClass('disabled'))) {
			if (isValidTag()) {
				var addVal = '<span class="wasDisabled token" >' +
					'<span class="tag">' + tagVal + '</span>' + 
		            '<span class="removetag"></span></span>';


				tagButtonElem.eq(0).after(addVal);
			} else {
				animateError();
			}
			
			// clear the input field and disable button again
			addElem.removeAttr('value');
			tagButtonElem.addClass('disabled').removeClass('wasDisabled');
		}
			
		
	} else {
		if (isValidTag()) {
			tagButtonElem.removeClass('disabled').addClass('wasDisabled');
		} else {
			tagButtonElem.addClass('disabled').removeClass('wasDisabled');
		}
	}
}

function addTagWithButton(event) {
	
	var addElem = $jq("#rtagsNew");
	var tagVal = addElem.attr('value');
	var tagButtonElem = $jq('#rtagsButton');
	
	if (!tagButtonElem.hasClass('disabled')) {
		var addVal = '<span class="wasDisabled token" >' +
			'<span class="tag">' + tagVal + '</span>' + 
            '<span class="removetag"></span></span>';


		tagButtonElem.eq(0).after(addVal);
		
		// clear the input field and disable button again
		addElem.removeAttr('value');
		tagButtonElem.addClass('disabled').removeClass('wasDisabled');
	}
}

function addTagWithClickOnSuggestion(clickedElem) {
	
	var addElem = $jq("#rtagsNew");
	var tagVal = clickedElem.text();
	var tagButtonElem = $jq('#rtagsButton');
	
	if (!tagButtonElem.hasClass('disabled')) {
		var addVal = '<span class="wasDisabled token" >' +
			'<span class="tag">' + tagVal + '</span>' + 
            '<span class="removetag"></span></span>';


		tagButtonElem.eq(0).after(addVal);
		
		// clear the input field and disable button again
		addElem.removeAttr('value');
		tagButtonElem.addClass('disabled').removeClass('wasDisabled');
	}
	
	$jq('#rtagsNew-overlay').remove();
}

function suggestTags(event) {
	
	// remove suggestions on escape
	if (event.which == 27) {
		$jq('#rtagsNew-overlay').remove();
		return;
	}
	// catch arrow down
	else if (event.which == 40) {
		var selectedElem = $jq('#rtagsNew-overlay').children('ul').children('li.selected');
		
		// check whether overlay exists
		if (typeof $jq('#rtagsNew-overlay').get(0) != 'undefined') {
			// check whether any item is selected
			if (typeof selectedElem.get(0) != 'undefined') {
				//check whether next item exists
				if (typeof selectedElem.next('li').get(0) != 'undefined') {
					selectedElem.removeClass('selected');
					selectedElem.next('li').eq(0).addClass('selected');
					$jq('#rtagsNew').attr('value', selectedElem.next('li').eq(0).text());
				} else {
					selectedElem.removeClass('selected');
					$jq('#rtagsNew').attr('value', jQuery.data($jq('#rtagsNew').get(0), 'userTypedValue'));
				}	
			} 
			// overlay exists, but nothing is selected -> select the first item
			else {
				var suggestItems = $jq('#rtagsNew-overlay').children('ul').children('li');
				
				suggestItems.eq(0).addClass('selected');
				$jq('#rtagsNew').attr('value', suggestItems.eq(0).text());
			}
		
			return;
		} 
	}	
	// catch arrow up
	else if (event.which == 38) {
		var selectedElem = $jq('#rtagsNew-overlay').children('ul').children('li.selected');
		
		// check whether overlay exists
		if (typeof $jq('#rtagsNew-overlay').get(0) != 'undefined') {
			// check whether any item is selected
			if (typeof selectedElem.get(0) != 'undefined') {
				//check whether previous item exists
				if (typeof selectedElem.prev('li').get(0) != 'undefined') {
					selectedElem.removeClass('selected');
					selectedElem.prev('li').eq(0).addClass('selected');
					$jq('#rtagsNew').attr('value', selectedElem.prev('li').eq(0).text());
				} else {
					selectedElem.removeClass('selected');
					$jq('#rtagsNew').attr('value', jQuery.data($jq('#rtagsNew').get(0), 'userTypedValue'));
				}	
			} 
			// overlay exists, but nothing is selected -> select the last item
			else {
				var suggestItems = $jq('#rtagsNew-overlay').children('ul').children('li');
				var lastNumber = suggestItems.length - 1;
				
				suggestItems.eq(lastNumber).addClass('selected');
				$jq('#rtagsNew').attr('value', suggestItems.eq(lastNumber).text());
			}
			
			return;
		}
	}
	// catch right arrow
	else if (event.which == 39) {
		var selectedElem = $jq('#rtagsNew-overlay').children('ul').children('li.selected');
		
		if (typeof selectedElem.get(0) != 'undefined') {
			$jq('#rtagsNew').attr('value', selectedElem.text());
			jQuery.data($jq('#rtagsNew').get(0), 'userTypedValue', $jq('#rtagsNew').attr('value'));
			$jq('#rtagsNew-overlay').remove();
		}
		
		return;
	}
	// catch enter button
	else if (event.which == 13) {
		var selectedElem = $jq('#rtagsNew-overlay').children('ul').children('li.selected');
		
		if (typeof selectedElem.get(0) != 'undefined') {
			$jq('#rtagsNew').attr('value', selectedElem.text());
			$jq('#rtagsNew-overlay').remove();
		}
		
		return;
	} 
	// catch the left arrow (do not store current value and do not suggest something new)
	else if (event.which == 37) {
		return;
	}
	// now that every special button is checked -> store the user typed content of the input field in order to get it
	// back later
	else {
		jQuery.data($jq('#rtagsNew').get(0), 'userTypedValue', $jq('#rtagsNew').attr('value'));
	}

	
	var MAX_COUNT = 10;
	var inputElem = $jq('#rtagsNew');
	
	var content = '<ul class="tag_suggest">';
	var data = jQuery.data($jq('#rtagsNew').get(0), 'suggestTags');
	var searchString = inputElem.attr('value');
		
	var count = 0;
	for (var i=0; i<data.length; ++i) {
		
		if (count >= MAX_COUNT) {
			break;
		}
		
		if (typeof searchString == 'undefined') {
			break;
		}
		
		searchString = searchString.toLowerCase();
		var currentTag = data[i];
		
		// suggested tag can't be shorter than search string
		if (currentTag.length < searchString.length) {
			continue;
		}
		
		var matches = 0;
		for (var j=0; j<searchString.length; ++j) {
			if (currentTag.toLowerCase().charAt(j) < searchString.charAt(j)) {
				matches = -1;
				break;
			}
			if (currentTag.toLowerCase().charAt(j) > searchString.charAt(j)) {
				matches = 1;
				break;
			}
		}
		if (matches < 0) {
			continue;
		} else if (matches > 0) {
			break;
		} else {
			var usedTags = $jq('#rtags').children('span').children('span.tag');
			
			var alreadyUsed = false;
			for (var j=0; j<usedTags.length; ++j) {
				if (currentTag.toLowerCase() == usedTags.eq(j).text().toLowerCase()) {
					alreadyUsed = true;
					break;
				}
			}
			
			if (alreadyUsed) {
				continue;
			}	
			
			content += '<li><b>' + data[i].substring(0, searchString.length) + '</b>' + data[i].substring(searchString.length) + '</li>';
			
			count++;
		}
	}
	
	content += '</ul>';
	
	var overlay = $jq('#rtagsNew-overlay');
	var offset = inputElem.offset();
	
	// only show overlay if there is at least one suggestion
	if (count > 0) {
		overlay.remove();
		overlay = $jq('<div id="rtagsNew-overlay"></div>');
		
		overlay	.css('position', 'absolute')
				.css('top', (offset.top + inputElem.height() + 6) + 'px')
				.css('left', (offset.left) + 'px')
				.css('width', (inputElem.width()) + 'px')
				.css('min-height', '40px')
				.css('background-color', '#fff')
				.css('padding', '2px')
				.css('border', '1px solid #ccc')
				.css('opacity', '0.9');
		
		$jq('body').append(overlay);
		overlay.append(content);
	} else {
		overlay.remove();
	}	
}


/* ------------------- Input Delete Button -------------------- */
$jq(document).ready(function() {
    $jq('.hierarchy-search-input').clearInput();
})

jQuery.fn.clearInput = function() {
    return this.each(function() {
        var input = jQuery(this);
        input.removeClass('width95');
        input.removeClass('width90');
        input.css('width', '85%');
        var link = jQuery('<a><img src="' + owThemeBase + 'images/icon-clear.png" alt="clear"/></a>');
        link.css('float', 'right');
        var marg = (input.height() - 12) / 2 + 1;
        link.css('margin-top', marg + 'px');
        link.css('left', '-' + (12 + marg) + 'px');
        link.mouseover(function() {
            jQuery(this).children('img').attr('src', owThemeBase + 'images/icon-clear-hover.png');
        }).mouseout(function() {
            jQuery(this).children('img').attr('src', owThemeBase + 'images/icon-clear.png');
        })
        link.click(function() {
            var input = jQuery(this).nextAll('input');
            input.val('');
            input.focus();
            var id = input.attr('id').replace(/-search-input/, '');
            // test
            if (selectedResource == 'http://ns.softwiki.de/req/Requirement') {
    		    $jq('.resource-select.root').addClass('selected');
    		}
            loadHierarchy(id, jQuery('div#' + id).find('ol').eq(0));
            // select root #50
            $jq('.resource-select.root').click();
        })
        input.before(link);
    })
}

jQuery.fn.clearTagSearchInput = function() {
    return this.each(function() {
        var input = jQuery(this);
        input.removeClass('width95');
        input.removeClass('width90');
        input.css('width', '85%');
        var link = jQuery('<a><img src="' + owThemeBase + 'images/icon-clear.png" alt="clear"/></a>');
        link.css('float', 'right');
        var marg = (input.height() - 12) / 2 + 1;
        link.css('margin-top', marg + 'px');
        link.css('left', '-' + (12 + marg) + 'px');
        link.mouseover(function() {
            jQuery(this).children('img').attr('src', owThemeBase + 'images/icon-clear-hover.png');
        }).mouseout(function() {
            jQuery(this).children('img').attr('src', owThemeBase + 'images/icon-clear.png');
        })
        link.click(function() {
            var input = jQuery(this).nextAll('input');
            input.val('');
            input.focus();
            var id = input.attr('id').replace(/search-input/, '');
            
            filterTags();
        })
        input.before(link);
    })
}

function filterTags()
{
	$jq('#tags div ol').hide();
	//look at checkboxes
	if ($jq('.toggleDefinedTags').attr('checked')) $jq(".tag.tagGreen").parent().show();
	else $jq(".tag.tagGreen").parent().hide();
	if ($jq('.toggleUndefinedTags').attr('checked')) $jq(".tag.tagBlue").parent().show();
	else $jq(".tag.tagBlue").parent().hide();
	if ($jq('.toggleOtherDefinedTags').attr('checked')) $jq(".tag.tagRed").parent().show();
	else $jq(".tag.tagRed").parent().hide();
	//look at search input
	var text=$jq('input#tag-search-input').val();
	if ( text.length>0 && text != $jq('label[@for="tag-search-input"]').html() ) {
		$jq(".tag").each(function(i,val) {
			var cut = $jq(val).children("span").text().length;
			var fulltext = $jq(val).text();
			var tagtext = fulltext.substring(0,fulltext.length - cut);
			var tagRegExp = new RegExp(text,"i");
			if (tagRegExp.test(tagtext)) {
				// do nothing
			} else {
				// Hide this tag (Not found)
				$jq(".tag").eq(i).hide();
			}
		});
	}
	$jq('#tags div ol').show();
}

/*
 * Creates an UI Window as an Overlay
 * @param event The click event from where the overlay was started
 * @param url A gettable URL which is loaded for the window content
 * @param params The URL parameters as key/value array
 */
function createOverlayWindow(event, url, params) {

  // remove all other overlays
  $jq('.overlay.window').remove();
  
  var menuX = event.pageX - 10;
  var menuY = event.pageY - 50;

  $jq('#overlays').attr("style","height: "+$jq(document).height()+"px; opacity: 0.5;background-color:#AAAAAA;left:0;position:absolute;top:0;width:100%;z-index:90;display:none;");
  $jq('#overlays').fadeIn("normal");
  $jq('#overlays').after(''+
    '<div class="window overlay is-processing" '+
    'style="display: none; width: 35em; position: absolute; '+
    'z-index: 10; top: '+menuY+'px; left: '+menuX+'px;">'+
    '<h2 style="cursor: move;" class="title">loading ...</h2>'+
    '<div class="content">'+
    '</div>'+
    '</div>');

  var targetwin = $jq('#overlays').next();
  targetwin.attr("style","z-index: 100; opacity: 1.0; width: 35em; position: absolute; "+
    "z-index: 100; top: "+menuY+"px; left: "+menuX+"px;");
  targetwin.fadeIn("normal");
  // put the target window into the temp box (for this ajax uri)
  // setAutoID(targetwin);

  $jq.ajax({
    url: url,
    data: params,
    dataType: 'html',
    success: function(content) {
    
      targetwin.children(".content").prepend($jq(content).children(".content").html());
      targetwin.children(".title").text($jq(content).children(".title").text());
      targetwin.removeClass('is-processing');
      enhanceWindow(targetwin);
      targetwin.draggable({handle: '.title', containment: 'document'});
      
    }
  });

  event.stopPropagation();
}

//its a hack, don't know better at the moment
function swRelationEdit(event) {
  var params = "";
  params += "r=" + encodeURIComponent($jq("#requirement").attr("about"))
         + "&object=" + encodeURIComponent($jq(event.target).parents("td").attr("about"))
         + "&r_title=" + encodeURIComponent($jq("#noneditDescription h3").text())
         + "&object_title="
         + encodeURIComponent($jq(event.target).parents("tr").eq(0).children("td").eq(2).children("p").text());
  createOverlayWindow(event,owUriBase + "softwiki/relationsservice",params);
}

function stripTags(oldString){
	return oldString.replace(/<\/?[^>]+>/gi, "");
}

function stripGreenTags(oldString){
	return oldString.replace(/<\/?font[^>]*>/gi, "");
}

//FCKeditor specific functions///////////////////


/*$jq("#rdescription___Frame").livequery(function() {
	
});*/
/*
function disableEditor(){
	var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
	disableFCKeditor(oFCKeditor);
}

function enableEditor(){
	var oFCKeditor = FCKeditorAPI.GetInstance('rdescription');
	enableFCKeditor(oFCKeditor);
}

// what do we do with the toolbar when disabling the editor. Possibilities are 'disable', 'hide', 'collapse'.
// When collapsed the toolbar can be expanded again by the user, but he'll find a disabled toolbar.
var toolbarDisabledState = "disable";

function disableFCKeditor(editorInstance){
	if ((!document.all && editorInstance.EditorDocument.designMode.toLowerCase() != "off") || (document.all && editorInstance.EditorDocument.body.disabled == false))
	{
		//opacity
		document.getElementById('rdescription___Frame').contentWindow.document.getElementsByTagName('html')[0].getElementsByTagName('body')[0].style.MozOpacity=0.5;
		
		// disable the editArea
		if (document.all)
		{
			editorInstance.EditorDocument.body.disabled = true;
		}
		else
		{
			editorInstance.EditorDocument.designMode = "off";
		}
		// disable the toolbar
		switch (toolbarDisabledState)
		{
			case "collapse" :		editorInstance.EditorWindow.parent.FCK.ToolbarSet._ChangeVisibility(true);
			case "disable" :		editorInstance.EditorWindow.parent.FCK.ToolbarSet.Disable();
										buttonRefreshStateClone = editorInstance.EditorWindow.parent.FCKToolbarButton.prototype.RefreshState;
										specialComboRefreshStateClone = editorInstance.EditorWindow.parent.FCKToolbarSpecialCombo.prototype.RefreshState;
										editorInstance.EditorWindow.parent.FCKToolbarButton.prototype.RefreshState = function(){return false;};
										editorInstance.EditorWindow.parent.FCKToolbarSpecialCombo.prototype.RefreshState = function(){return false;};
										break;
				case "hide" :		if (editorInstance.EditorWindow.parent.document.getElementById("xExpanded").style.display != "none")
										{
											editorInstance.EditorWindow.parent.document.getElementById("xExpanded").isHidden = true;
											editorInstance.EditorWindow.parent.document.getElementById("xExpanded").style.display = "none";
										}
										else
										{
											editorInstance.EditorWindow.parent.document.getElementById("xCollapsed").style.display = "none";
										}
										break;
		}
	}
}

function enableFCKeditor(editorInstance)
{
	//opacity
	document.getElementById('rdescription___Frame').contentWindow.document.getElementsByTagName('html')[0].getElementsByTagName('body')[0].style.MozOpacity=1;
		
	// enable the editArea
	if (document.all)
	{
		editorInstance.EditorDocument.body.disabled = false;
	}
	else
	{
		editorInstance.EditorDocument.designMode = "on";
	}
	// enable the toolbar
	switch (toolbarDisabledState)
	{
		case "collapse" :		editorInstance.EditorWindow.parent.FCK.ToolbarSet._ChangeVisibility(false);
		case "disable" :		editorInstance.EditorWindow.parent.FCK.ToolbarSet.Enable();
									editorInstance.EditorWindow.parent.FCKToolbarButton.prototype.RefreshState = buttonRefreshStateClone;
									editorInstance.EditorWindow.parent.FCKToolbarSpecialCombo.prototype.RefreshState = specialComboRefreshStateClone;
									break;
			case "hide" :		if (editorInstance.EditorWindow.parent.document.getElementById("xExpanded").isHidden == true)
									{
										editorInstance.EditorWindow.parent.document.getElementById("xExpanded").isHidden = false;
										editorInstance.EditorWindow.parent.document.getElementById("xExpanded").style.display = "";
									}
									else
									{
										editorInstance.EditorWindow.parent.document.getElementById("xCollapsed").style.display = "";
									}
									break;
	}
	// set focus on editorArea
	editorInstance.EditorWindow.focus();
	// and update toolbarset
	editorInstance.EditorWindow.parent.FCK.ToolbarSet.RefreshModeState();
}*/

var oldFCKcontent;
var FCKloaded=false;
var newRequirement=false;

function FCKeditor_OnComplete(editorInstance)
{
	// Just hiding the toolbar can be done too
	editorInstance.EditorWindow.parent.document.getElementById("xExpanded").style.display = "none";
	//disableFCKeditor(editorInstance);
	oldFCKcontent=editorInstance.GetXHTML(false);
	FCKloaded=true;
	editorInstance.ResetIsDirty();
	
	if (newRequirement){
		swEdit(newRequirement);
		$jq("#swCancel").hide();
		newRequirement=false;
	}
	if (document.all) {
		// IE
        editorInstance.EditorDocument.attachEvent("onkeydown", FCKkeyup) ;
        editorInstance.Events.AttachEvent('OnBlur',FCKchange);
    } else {
       // other browser
       editorInstance.EditorDocument.addEventListener( 'keyup', FCKkeyup, true ) ;
       editorInstance.EditorDocument.addEventListener( 'blur', FCKchange, true ) ;
    }
}

function FCKchange(event){
	//get instance of the fckeditor
	/*var editorInstance = FCKeditorAPI.GetInstance('rdescription');
	
	if (editorInstance.IsDirty()){
		editorInstance.ExecuteNamedCommand ('SelectAll');
		editorInstance.InsertHtml(changeTagsGreen(editorInstance.GetXHTML(false)));
		showSimilars();
		editorInstance.ResetIsDirty();
	}*/
}

function FCKkeyup(event){
	//get instance of the fckeditor
	var editorInstance = FCKeditorAPI.GetInstance('rdescription');

	// load similar req on space
	//IE
	if (document.all){
		if ((event.keyCode == 32)||(event.keyCode == 13)) {
			oldText=editorInstance.GetXHTML(false);
			newText=changeTagsGreen(oldText);
			//the editor inserts a &nbsp; when a new paragraph is started
			//this whitespace is being deleted
			if (event.keyCode == 13 && newText.toLowerCase().substr(newText.length-13)=='<p>&nbsp;</p>') newText=newText.substr(0,newText.length-13)+'<p></p>';
			if (newText!=oldText){
				editorInstance.ExecuteNamedCommand ('SelectAll');
				editorInstance.InsertHtml(newText);		
			}
			showSimilars();
		}
	}
	//other browsers
	else{
		if ((event.which == 32)||(event.which == 13)) {
			showSimilars();
			/* This is switched of to prevent the firefox bug that the editor lost focus
			var oldText=editorInstance.GetXHTML(false);
			var newText=changeTagsGreen2(oldText);
			if (oldText!=newText){
				editorInstance.ExecuteNamedCommand ('SelectAll');
				editorInstance.InsertHtml(changeTagsGreen(editorInstance.GetXHTML(false)));
				showSimilars();
				$jq('#rtitle').blur();
			}
			*/
		}
	}
}

var backParameter="";

function changeTagsGreen(text){
	var myregex=new RegExp(/<\/font>/g);
	text=text.replace(myregex,'');
	myregex=new RegExp(/<font[^>]*>/g);
	text=text.replace(myregex,'');
	myregex=new RegExp(/&nbsp;/g);
	text=text.replace(myregex,' ');
	if (text.substr(text.length-5,1)==' ') text=text.substr(0,text.length-5)+'&nbsp;'+text.substr(text.length-4);
	for (var i=0;i<glossaryTags.length;i++){
		myregex=new RegExp('(\\W)'+glossaryTags[i]['tagName']+'(\\W)','g');
		text=text.replace(myregex,'$1<font style="color: rgb(0, 178, 82);" title="'+glossaryTags[i]['tagComment']+'">'+glossaryTags[i]['tagName']+'</font>$2');
	}
	return text;
}

function changeTagsGreen2(text){
	var myregex=new RegExp(/<\/font>/g);
	text=text.replace(myregex,'');
	myregex=new RegExp(/<font[^>]*>/g);
	text=text.replace(myregex,'');
	for (var i=0;i<glossaryTags.length;i++){
		myregex=new RegExp('(\\W)'+glossaryTags[i]['tagName']+'(\\W)','g');
		text=text.replace(myregex,'$1<font title="'+glossaryTags[i]['tagComment']+'" style="color: rgb(0, 178, 82);">'+glossaryTags[i]['tagName']+'</font>$2');
	}
	return text;
}
