// http://docs.jquery.com/Using_jQuery_with_Other_Libraries
var $jq = jQuery.noConflict();

// how fast should we fade, slide, ...
var effectTime = 250;

// integer value of the dragNdrop z-index and context-menu z-index
var dragZIndex = 1000;
var menuZIndex = 1000;

// number of chars entered before autocompleting starts
var autoCompleteMinChars = 3;

// time to wait before autocompleting (ms)
var autoCompleteDelay = 500;

// The id counter is used to create autoids
idcounter = 1;

// This array is used to temp. store href attributes
tmphrefs = new Array();

// This array is used to temp. store information for ajax requests
tmpajax = {};


// parameter for the clickmenu
$jq.fn.clickMenu.setDefaults({arrowSrc:'images/arrow_right.gif'});

// The only ow object in use
var ow = {};

// ow.erfurtpublicbase = '../../lib/Erfurt/public/';
// owUriBase = '/~norman/ontowiki-svn/';
// ow.themebase = '../default/';

// TODO: create dynamically
var windowNames = new Array();
/* var windowNames = {
	models:     'Knowledge Bases', 
	languages:  'Languages', 
	classes:    'Classes', 
	popularity: 'Most Populars', 
	
	similars:   'Similar Instances', 
	linking:    'Instances Linking Here', 
	usage:      'Usage as Property', 
	
	predicates: 'Predicates', 
	properties: 'Properties', 
	filter:     'Filter'
}; */

/*
 * core css assignments
 */
$jq(document).ready(function(){
	// the body gets a new class to indicate that javascript is turned on
	$jq('body').removeClass('javascript-off').addClass('javascript-on');

	// the body gets the contextmenu clone container
	$jq('body').append('<div class="contextmenu-enhanced"></div>');

	// every click fadeout (and remove) all contextmenus
	// every click un-marks all marked elements
	$jq('html').click(function(){
		$jq('.contextmenu-enhanced .contextmenu').fadeOut(effectTime, function(){ $jq(this).remove(); })
		$jq('.marked').removeClass('marked');
	});

	/* NEWS */
	if (showNews) {
		$jq.each($jq('#news'), function() {
			loadPageInMainWindow(owUriBase + '/service/getTemplate', 'f=micro&t=news')
		});
	}


	/* SECTION RE-SIZER */
	// ToDo: changeSectionRatio at drop time instead of onDrag
//	$jq('.innerwindows').append('<span class="sizer-horizontal"></span>');
	$jq('.section-sidewindows').append('<span class="sizer-horizontal"></span>');
	$jq('.section-sidewindows .sizer-horizontal')
		.draggable({ zIndex: dragZIndex, axis: 'horizontally', grid: 10, helper: "clone",
			revert: true, containment: 'document',
			drag: function(event,ui) { changeSectionRatio(event.pageX); },
			stop: function(event,ui) { setSessionVar ('theme.sectionratio', $jq('div.section-sidewindows').width()); }
			});


	/* RESOURCE CREATION */
	// All RDFa elements with about attribute are resources
	$jq('*[@about]').addClass("Resource");


	/* RESOURCE DRAG AND DROP */
	// all named resources are draggable, drop points, get the move cursor and the Resource class
	// http://interface.eyecon.ro/docs/drag or .../drop
	// $jq('.Resource')
	// 	//.addClass("cursor-move") (nur onclick)
	// 	.draggable({ zIndex: dragZIndex, ghosting: true,
	// 		revert: true, containment: 'document', autoSize: true })
	// 	.droppable({
	// 		accept: 'Resource', activeclass: 'dropactive', hoverclass: 'drophover',
	// 		tolerance: 'pointer', ondrop: function (drag) { showDropMenu (drag, this); }});


	/* EXPANDABLE RESOURCES */
	// $jq.each( $jq('.expandable'), function(id, exp){ enhanceExpandable(exp); });
	$jq('.expandable').livequery(function() {
		enhanceExpandable($jq(this));
	});

	/* RESOURCE CONTEXT MENUS */
	$jq('.has-contextmenus-block .Resource').append('<span class="button"></span>');
	$jq('.has-contextmenus-block .Resource span.button')
		.mouseover(function(){
			hideHref($jq(this).parent());
			$jq('.contextmenu-enhanced .contextmenu').remove(); // remove all other menus
		})
		.click(function(event){ showResourceMenu(event);} )
		.mouseout(function(){ showHref($jq(this).parent())} );

	// all inline links are loaded with ajax into the main window
	// to prevend fast clickers from requesting the real uri, we steal the href attribute
	$jq.each( $jq('a.inline'), function(){hideHref($jq(this));});
	$jq('a.inline')
		.click(function(event){ loadPageInMainWindow(tmphrefs[$jq(this).attr('id')]); });
		//.mouseover(function(){ hideHref($jq(this));} )
		//.mouseout(function(){ showHref($jq(this));} );
	
	/* load registered onload code */
	if (typeof onLoadJson != 'undefined') {
		$jq.each(onLoadJson, function(i, n) {
			eval(n);
		});
	}
	
	/* add property add functionality */
	$jq('.property-add').click(function(event) {
		var table = $jq('#table' + $jq(this).attr('id').replace('property-add', '')).get(0);
		var row = table.insertRow(table.rows.length);
		$jq(row).addClass('editing');
		var c1 = row.insertCell(0);
		var c2 = row.insertCell(1);
		// c1.style.verticalAlign = 'top';
		$jq(c1).mouseover(function(event) {
			$jq(this).children('img').eq(0).css('visibility', '');
		});
		$jq(c1).mouseout(function(event) {
			$jq(this).children('img').eq(0).css('visibility', 'hidden');
		});
		// new Ajax.Updater(c1, owUriBase + 'service/getPropertySelector/?property=', {evalScripts: true});
		$jq(c1).load(owUriBase + 'service/getPropertySelector/');
	});
	
	/* FORM ENHANCEMENTS */
	// inner labels
	$jq.each($jq('input.inner-label'), function(id, input) {
		enhanceInput(input);
	})
	// feature 1787065: add .marked to parents of input fields
	$jq('.row-input input').focus(function(event) {
			$jq('.marked').removeClass('marked');
			$jq(this).parent().addClass('marked');
			event.stopPropagation();
		}).click(function(event) {
			$jq('.marked').removeClass('marked');
			$jq(this).parent().addClass('marked');
			event.stopPropagation();
		});

	
	$jq.each($jq('.inline-edit'), function() {
		if (inlineEditing) {
			$jq(this).css('display','inline');
		} else {
			// .hide() doesn't work here a the element
			// may not have been displayed yet
			$jq(this).css('display', 'none');
		}
	});
	
	$jq('#menu-inline-toggle').click(function(event) {
		toggleInlineEdit(inlineEditing, event);
	}).ready(function() {
		if (inlineEditing) {
			$jq('#menu-inline-toggle').text('Disable Inline Editing');
		} else {
			$jq('#menu-inline-toggle').text('Enable Inline Editing');
		}
	})
	
	/* VIEW WINDOW MENUS: create dynamic menu items (incl. trigger and name)*/
	$jq('.window-view-menu').each(function() {enhanceWindowViewMenu(this); });

	
	// liveQuery Triggers /////////////////////////////////////////////////////
	
	/* add inline (row) edit functionality */
	$jq('table.editable .clickicon.inline-edit').livequery('click', function(event) {
		var td = $jq(this).parents('td').eq(0).prev();
		var resource = td.parents('table').attr('about');
		var property = td.find('[@property]').attr('property');
        editRow(td, event, resource, property);
        // editStatement(td);
	});
	
	/* add events to delete buttons */
	$jq('img.delete').livequery('click', function(event) {
		$jq('#' + $jq(this).attr('id').replace('img', 'value')).val('');
	});
	
	/* add events to statement drop buttons */
	$jq('.drop-statement').livequery('click', function(event) {
		if (confirm('Really delete statement?')) {
			deleteStatement($jq(this).attr('id'));
		}
	});
	
	// liveQuery Triggers End /////////////////////////////////////////////////
	
	// site is ready, processing is finished
	$jq('body').removeClass('is-processing');

	// enhance every window with buttons, menu and resizer
	// this must be done at the end of the onready block (because we generate the menu automatically)
	// $jq.each($jq('.window'), function(id, win){ enhanceWindow(win); });
	$jq('.window').livequery(function() {
		enhanceWindow($jq(this));
	})
	
	// test whether cookies are enabled
	if (navigator.cookieEnabled == false) {
		$jq('#login').children('div').eq(0).children().remove();
		$jq('#login').children('div').eq(0).append('<p class="messagebox info">Cookies must be enabled for login!</p>');
	}
	
	//begin valuation star functions /////////////////////////////////////////
	$jq('img.valuationStar').livequery('mouseover', function(event){
		if (!$jq('#valuationStars').hasClass('disabled')){
			if ($jq('#valuation').attr('active')=='true'){
				var number=$jq(this).attr('id').substr(13);
				for (var i=1;i<=5;i++)
					if (i<=number) $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('img.valuationStar').livequery('mouseout', function(event){
		if (!$jq('#valuationStars').hasClass('disabled')){
			if ($jq('#valuation').attr('active')=='true'){
				for (var i=1;i<=5;i++)
					$jq('#valuationStar'+i).attr('src',$jq('#valuationStar'+i).attr('src').replace('icon_star_full.png','icon_star_empty.jpg'));
			}
		}
	});
	$jq('img.valuationStar').livequery('click', function(event){
		if (!$jq('#valuationStars').hasClass('disabled')){
			if ($jq('#valuation').attr('active')=='true'){
				var number=$jq(this).attr('id').substr(13);
				$jq('#valuation').attr('value',number);
				$jq('#valuation').attr('active','false');
			}
		}
	});
	$jq('#valuationStars').livequery('mouseout',function(event){
		if (!$jq('#valuationStars').hasClass('disabled')){
			var star1=$jq('#valuationStar1').attr('src');
			if ($jq('#valuation').attr('value')>0&&star1.match('icon_star_empty.jpg'+'$')=='icon_star_empty.jpg') $jq('#valuation').attr('value',0);
			$jq('#valuation').attr('active','true');
		}
	});
	// end valuation star functions //////////////////////////////
	
	// begin comment toggle function /////////////////////////////
	$jq('.toggleCommentsCheckbox').livequery('click',function(event){
		var val=new Boolean($jq('.toggleValuationsCheckbox').attr('checked'));
		var com=new Boolean($jq('.toggleCommentsCheckbox').attr('checked'));
		
		queryString = "list&r=" + $jq("form > input[name=r]").attr('value')
		    + "&val=" + val + "&com=" + com + "&prefix=" + $jq("form > input[name=prefix]").attr('value');
		
		$jq(event.target).parent().parent().parent().toggleClass('is-processing');
		function replaceContent (data, textStatus) {
		    var out = $jq(data).children('div.content').children().html();
		    $jq(event.target).parent().parent().parent().toggleClass('is-processing');
            $jq(event.target).parent().parent().parent().html(out);
        }	
        
        $jq.get(owUriBase + "service/comments",
            queryString,
            replaceContent
        );
	});
	
	$jq('.toggleValuationsCheckbox').livequery('click',function(event){
		var val=new Boolean($jq('.toggleValuationsCheckbox').attr('checked'));
		var com=new Boolean($jq('.toggleCommentsCheckbox').attr('checked'));
		
		queryString = "list&r=" + $jq("form > input[name=r]").attr('value')
		    + "&val=" + val + "&com=" + com + "&prefix=" + $jq("form > input[name=prefix]").attr('value');
		
		$jq(event.target).parent().parent().parent().toggleClass('is-processing');
		function replaceContent (data, textStatus) {
		    var out = $jq(data).children('div.content').children().html();
		    $jq(event.target).parent().parent().parent().toggleClass('is-processing');
            $jq(event.target).parent().parent().parent().html(out);
        }	
        
        $jq.get(owUriBase + "service/comments",
            queryString,
            replaceContent
        );
	});
	// end comment toggle function /////////////////////////////
	
	// begin Comment Service Integration ///////////////////////
	
	// adding comments
	$jq("#ontowiki-add-comment").livequery("click", function(event) {
		if ($jq("#ontowiki-comment").val().length==0) alert("You must not post an empty comment.");
		else {
		    queryString = $jq("form.ontowiki-comment").serialize();
		    $jq('div.section-mainwindows > div.window > div.content').addClass('is-processing');
            $jq.get(owUriBase + "service/comments",
                queryString,
                function (data, textStatus) {
                    var out = $jq(data).children('div.content').html();
                    $jq('div.section-mainwindows > div.window > div.content').eq(0).replaceWith(out);
                    $jq('div.section-mainwindows > div.window > div.content').addClass('activetabcontent');
                }
            );
		}
	});
	
	// adding valuations
	$jq("#ontowiki-add-valuation").livequery("click", function(event) {
		if ($jq("#valuation").val()==0) alert("You have to choose the number of stars.");
		else {
		    queryString = $jq("form.ontowiki-valuation").serialize();
		    $jq('div.section-mainwindows > div.window > div.content').addClass('is-processing');
            $jq.get(owUriBase + "service/comments",
                queryString,
                function (data, textStatus) {
                    var out = $jq(data).children('div.content').html();
                    $jq('div.section-mainwindows > div.window > div.content').eq(0).replaceWith(out);
                    $jq('div.section-mainwindows > div.window > div.content').addClass('activetabcontent');
                }
            );
        }
		
	});
	
	// edit valuation
	$jq("#ontowiki-edit-valuation").livequery("click", function() {
		$jq(".ontowiki-valuation .disabled").removeClass("disabled").addClass("wasDisabled");
		$jq(".ontowiki-valuation :disabled").removeAttr("disabled");
		$jq("#ontowiki-cancel-valuation").show();
		$jq("#ontowiki-submit-edit-valuation").show();
		$jq("#ontowiki-edit-valuation").hide();
	});
	
	// cancel valuation
	$jq("#ontowiki-cancel-valuation").livequery("click", function(event) {
		$jq(".ontowiki-valuation .wasDisabled").addClass("disabled").removeClass("wasDisabled").attr("disabled", "disabled");
		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("#ontowiki-cancel-valuation").hide();
		$jq("#ontowiki-submit-edit-valuation").hide();
		$jq("#ontowiki-edit-valuation").show();
	});
	
	// submit edit valuation
	$jq("#ontowiki-submit-edit-valuation").livequery("click", function() {
		if ($jq("#valuation").val()==0) alert("You have to choose the number of stars.");
		else {
		    queryString = $jq("form.ontowiki-valuation").serialize() + "&edit=" + $jq("#valuation").attr("edit");
		    $jq('div.section-mainwindows > div.window > div.content').addClass('is-processing');
            $jq.get(owUriBase + "service/comments",
                queryString,
                function (data, textStatus) {
                    var out = $jq(data).children('div.content').html();
                    $jq('div.section-mainwindows > div.window > div.content').eq(0).replaceWith(out);
                    $jq('div.section-mainwindows > div.window > div.content').addClass('activetabcontent');
                }
            );
		}
	})
	
	// end Comment Service Integration ////////////////////////
	
}) // $jq(document).ready


/*
 * fill view-menu with entries according to displayed windows
 * extract windowNames array
 */
function enhanceWindowViewMenu(target) {
	menu = $jq(target).parent();
	section = $jq(target).parents('.window').parent();

	// main and side sections have different window structure
	if (section.is('.section-sidewindows')) {
		windows = section.children('.window').not('.no-disable');
	} else if (section.is('.section-mainwindows')) {
		windows = section.find('.window .window').not('.no-disable');
	}

	if (windows) {
		menu.append('<ul id="tmp-enhanceWindowViewMenu"></ul>'); // temp. id for better searching
		windows.each(function(){
			submenu = $jq('#tmp-enhanceWindowViewMenu');

			// extract the window-name array id -> title
			win = $jq(this);
			winId = win.attr('id');
			winTitle = win.find('.title').html();
			windowNames[winId] = winTitle;

			// decide list item title
			if (!win.is('.is-disabled'))
				{ liTitle = 'Hide ' + winTitle + ' Box';}
			else
				{ liTitle = 'Show ' + winTitle + ' Box';}

			// append list item to the list
			submenu.append('<li><a class="menu-box-display-toggle" id="menuitem-'+winId+'">'+liTitle+'</a></li>');
		});
		// enhance menu items with click function
		$jq('#tmp-enhanceWindowViewMenu .menu-box-display-toggle')
			.click(function() {toggleBoxDisplay($jq(this).attr('id').replace('menuitem-', ''));} );

		$jq('#tmp-enhanceWindowViewMenu').removeAttr('id');
	}
}


/*
 * enhance expandable links with a buttons
 */
function enhanceExpandable(target) {
	// linkelement = $jq(target);
	// linkelement
	target
		.before('<span class="icon-button expand"></span>')
		.prev()
		.click(function(event){expand(event);});
}

/*
 * function to do the expand and de-expand job
 */
function expand (event) {
	target = $jq(event.target);
	resourceURI = target.next().attr('about');
	encodedResourceURI = encodeURIComponent(resourceURI);
	resource = target.next();

	if (target.is('.expand')) {
		target.removeClass('expand').addClass('deexpand');
		target.next().after('<div class="is-processing expanded-content"></div>');
		url = owUriBase + 'resource/view/';
		params = 'r=' + encodedResourceURI + '&allowEdit=0&maxLength=100&noCaption=true';
		$jq.ajax({
			url: url,
			data: params,
			dataType: 'html',
//			success: function(msg){alert( 'Data Saved: ' + msg );}
			success: function(content){
				resource.next().html(content);
				resource.next().removeClass('is-processing');
				}
		});
	}
	else if (target.is('.deexpand')) {
		target.removeClass('deexpand').addClass('expand');
		target.next().next().remove();		
	}
}


/*
 * enhance every window with buttons, menus and resizers
 */
function enhanceWindow(target) {
	w = $jq(target);
	// all windows get two button container for left and right buttons
	w.children('.window-buttons').remove();
	w.append('<div class="window-buttons"><div class="window-buttons-left"></div><div class="window-buttons-right"></div></div>');



	// overlay windows get close control others minimize only
	if (w.is('div.window.overlay')) {
		w.find('.window-buttons-right')
			.append('<span class="button button-windowclose"></span>');
	} else {
		// all windows with right button container get the minimize button
		w.find('.window-buttons-right')
			.append('<span class="button button-windowminimize"></span>');
	}

	w.addClass('windowbuttonscount-right-1');

	
	// already minimized windows get the restore button instead of the minimize button
	if (w.is('.is-minimized')) {
		w.find('.button-windowminimize')
			.removeClass('button-windowminimize').addClass('button-windowrestore');	
	}
	// the toggle events
	w.find('.button-windowminimize').click(function(){
		toggleWindow($jq(this).parent().parent().parent());
	});
	w.find('.button-windowrestore').click(function(){
		toggleWindow($jq(this).parent().parent().parent());
	});
	w.find('.title').dblclick(function(){
		toggleWindow($jq(this).parent());
	});
	
	// the close event
	w.find('.button-windowclose').click(function() {
		closeWindow($jq(this).parent().parent().parent());
	});

	// all windows with context menu get the contextmenu button
	if (w.children('.contextmenu').length > 0) {
		w.find('.window-buttons-left').append('<span class="button button-contextmenu"></span>');
		w.addClass('windowbuttonscount-left-1');
		// the context menu button gets its function
		w.find('.button-contextmenu').click(function(event){showWindowMenu(event);});
	}

	// add a menu class and start the clickmenu if the is a menu ul
	if (w.children('ul.menu').length > 0) {
		w.addClass('has-menu');
		w.children('ul.menu').clickMenu();
	}

	// create the additional tabbed class
	if (w.children('.tabs').length > 0) {
		w.addClass('tabbed');
		if (w.children('.activetabcontent').length == 0) {
			w.children('.content').eq(0).addClass('activetabcontent');
		}
	}

	// create re-sizer
	// ToDo: drag event for the window resizer
	if (w.is('.has-sizer')) w.append('<span class="sizer-vertical"></span>');
}


/*
 * Change the Ratio between main and side-section
 */
function changeSectionRatio(x) {
	$jq('div.section-sidewindows').css('width', x+'px');
	$jq('div.section-mainwindows').css('width', document.body.clientWidth-x+'px');
	$jq('div.section-mainwindows').css('margin-left', x+'px');
	// ToDo: convert to percent
	// ToDo: save state with setSessionVar
}



/*
 * Save a key-value pair via ajax
 */
function setSessionVar(setName, setValue) {
	if (typeof setValue != 'undefined') {
		$jq.get(owUriBase + 'service/sessionStore/', {name: setName, value: setValue});
	} else {
		$jq.get(owUriBase + 'service/sessionStore/?' + setName);
	}
	
	//new Ajax.Request(owUriBase + '/service/sessionStore?name=' + name + '&value=' + value);
	// $jq.ajax({
	// 	url: owThemeBase + 'ajax.php',
	// 	//url: owUriBase + '/service/sessionStore,
	// 	//success: function(msg){alert( 'Data Saved: ' + msg );},
	// 	data: 'name='+name+'&value='+value
	// });
}


/*
 * This function sets an automatic id attribute if no id exists
 * parameter: el -> jquery element
 */
function setAutoID(el) {
	if (!el.attr('id')) el.attr('id', "autoid" + idcounter++);
}

/*
 * hide a href by putting this attribute into an array
 * parameter: el -> jquery element
 */
function hideHref(el) {
	setAutoID(el);
	if (el.attr('href')) {
		tmphrefs[el.attr('id')] = el.attr('href');
		el.removeAttr('href');
	}
}
function showHref(el) {
	if (tmphrefs[el.attr('id')]) {
		el.attr('href', tmphrefs[el.attr('id')]);
	}
}

/*
 * Close Window
 */
function closeWindow(box) {
	box.fadeOut("normal",function() {
		$jq("#overlays").removeAttr("style");
		box.remove();
	});
	
}
/*
 * Minimize / Restore a window/box and saves the state
 */
function toggleWindow(box) {
	
	if (box.is('.is-minimized')) {
		box.removeClass('is-minimized');
		if (box.is('.has-menu-disabled')) box.removeClass('has-menu-disabled').addClass('has-menu');
		box.children().not('.title').not('.window-buttons')
			.slideDown(effectTime, function() {
				box.find('.button-windowrestore').removeClass('button-windowrestore').addClass('button-windowminimize');
			});
		// if (box.attr('id')) setSessionVar ('windows.'+box.attr('id')+'.stateclass', 'is-opened');
		setSessionVar(box.attr('id') + 'BoxMinimized', 0);
	} else {
		box.children().not('.title').not('.window-buttons').not('.tabs')
			.slideUp(effectTime, function() {
				box.find('.button-windowminimize').removeClass('button-windowminimize').addClass('button-windowrestore');
				// TODO: save state with setSessionValue (if window id is present)
				// set <#id>BoxMinimized to true, if box is minimized (e.g. 'modelsBoxMinimized')
				if (box.is('.has-menu')) box.removeClass('has-menu').addClass('has-menu-disabled');
				box.addClass('is-minimized');
			});
		// if (box.attr('id')) setSessionValue('windows.'+box.attr('id')+'.stateclass', 'is-minimized');
		setSessionVar(box.attr('id') + 'BoxMinimized', 1);
	}
}


/*
 * create and display the drag'n'drop menu
 */
function showDropMenu (dragged, dropped) {
	draggedURI = dragged.getAttribute('about');
	droppedURI = dropped.getAttribute('about');

	if (!draggedURI || !droppedURI || draggedURI == droppedURI) return false;

	// menu position
	menuX = dragged.dragCfg.currentPointer.x - 10;
	menuY = dragged.dragCfg.currentPointer.y - 10;

	menuId = 'dropmenu-'+menuX+'-'+menuY;

	// create the menu at the bottom of body and fade it in
	// ToDo: this menu should depend on the dragged and dropped Resources
	$jq('.contextmenu-enhanced').append(
		'<div id="'+menuId+'" class="contextmenu" style="z-index:'+menuZIndex+'; display:none; top: '+menuY+'px; left: '+menuX+'px;">'+
		'<ol>'+
		'<li><a>Merge ...</a><ol><li><a>Retain A</a></li><li><a>Retain B</a></li></ol></li>'+
		'<li><a>Link ...</a><ol><li><a>From A to B</a></li><li><a>From B to A</a></li></ol></li>'+
		'</ol><hr /><ol>'+
		'<li><a>Move as Subclass</a></li>'+
		'<li><a>Copy as Subclass</a></li>'+
		'</ol><hr /><ol>'+
		'<li><a>Special Actions ...</a></li>'+
		'</ol>');
	$jq('#'+menuId)
		.click(function(event){event.stopPropagation();})
		.fadeIn(effectTime);

	// the menu button is clickable to fade (and remove) the menu
	$jq('#'+menuId+' .button').click(function(){$jq(this).parent().parent().fadeOut(effectTime,function(){$jq(this).remove();})});

	// the menu is draggable by the title (so the title gets the move cursor)
	$jq('#'+menuId+' .title').css('cursor', 'move');
	$jq('#'+menuId).draggable({zIndex: dragZIndex, handle: '.title', containment: 'document'});
};


function showResourceMenu(event) {
	// remove all other menus
	$jq('.contextmenu-enhanced .contextmenu').remove();

	// this is the URI of the clicked resource
	resourceURI = $jq(event.target).parent().attr('about');
	encodedResourceURI = encodeURIComponent(resourceURI);
	resource = $jq(event.target).parent();

	menuX = event.pageX - 30;
	menuY = event.pageY - 20;
	menuId = 'windowmenu-'+menuX+'-'+menuY;

	//create the plain menu with correct style and position
	$jq('.contextmenu-enhanced').append('<div class="contextmenu" id="'+menuId+'"></div>');
	$jq('#'+menuId)
		.attr({style: 'z-index: '+menuZIndex+'; top: '+menuY+'px; left: '+menuX+'px;'})
		.click(function(ev){ev.stopPropagation();});

	// create menu items according to the type of resource
	// ToDo: How to i18n the menu? xxx.php.js?
	if (resource.is(".Model")) {
		$jq('#'+menuId).append(
			'<ul>'+

			'<li><a href="'+owUriBase+'model/select/?m=' + encodedResourceURI + '"><strong>Select Knowledge Base</strong></a></li>'+
			'<li><a href="'+owUriBase+'model/add/?m=' + encodedResourceURI + '">Add Data to Knowledge Base</a></li>'+
			'<li><a href="'+owUriBase+'model/export/?m=' + encodedResourceURI + '&output=xml">Export Knowledge Base as RDF/XML</a></li>'+
			'<li><a href="'+owUriBase+'model/export/?m=' + encodedResourceURI + '&output=json">Export Knowledge Base as RDF/JSON</a></li>'+
			'<li><a href="'+owUriBase+'model/export/?m=' + encodedResourceURI + '&output=n3">Export Knowledge Base as RDF/N3</a></li>'+
			'<li><a href="'+owUriBase+'model/delete/?m=' + encodedResourceURI + '">Delete Knowledge Base</a></li>'+
			'<li><a href="'+owUriBase+'model/emptycache/?m=' + encodedResourceURI + '">Empty Cache</a></li>'+
			'</ul>');
	}
	else if (resource.is(".Class")) {
		$jq('#'+menuId).append(
			'<ul>'+
			'<li><a href="'+owUriBase+'resource/list/?r=' + encodedResourceURI + '"><strong>List Instances</strong></a></li>'+
			'<hr />'+
			'<li><a href="'+owUriBase+'resource/create/?prop[rdf:type]=' + encodedResourceURI + '">Create Instance</a></li>'+
			'<li><a href="'+owUriBase+'resource/create/?prop[rdf:type]=owl:Class&prop[rdfs:subClassOf]=' + encodedResourceURI + '">Create New SubClass</a></li>'+
			'<hr />'+
			'<li><a href="'+owUriBase+'resource/view/?r=' + encodedResourceURI + '">View Class Description</a></li>'+
			'<li><a href="'+owUriBase+'resource/edit/?r=' + encodedResourceURI + '">Edit Class Description</a></li>'+
			'<li><a href="'+owUriBase+'resource/learndef/?r=' + encodedResourceURI + '">Learn Equivalence Class Description</a></li>'+
			'<li><a href="'+owUriBase+'resource/learninc/?r=' + encodedResourceURI + '">Learn Sub Class Description</a></li>'+
			'<li><a href="'+owUriBase+'resource/delete/?r=' + encodedResourceURI + '">Delete Class Description</a></li>'+
			'</ul>');
	}
	else {
		$jq('#'+menuId).append(
			'<ul>'+
			'<li><a href="'+owUriBase+'resource/view/?r=' + encodedResourceURI + '"><strong>View Resource</strong></a></li>'+
			'<li><a href="'+owUriBase+'resource/edit/?r=' + encodedResourceURI + '">Edit Resource</a></li>'+
			'<li><a href="'+owUriBase+'resource/delete/?r=' + encodedResourceURI + '">Delete Resource</a></li>'+
			'</ul>');
	}

	$jq('#'+menuId)
		.fadeIn(effectTime);

	event.stopPropagation();
}


function showWindowMenu (event) {
	// remove all other menus
	$jq('.contextmenu-enhanced .contextmenu').remove();

	menuX = event.pageX - 10;
	menuY = event.pageY - 10;
	menuId = 'windowmenu-'+menuX+'-'+menuY;

	$jq(event.target)
		.parent().parent()
		.siblings('.contextmenu')
		.clone()
		.appendTo('.contextmenu-enhanced')
		.attr({id: menuId, style: 'z-index: '+menuZIndex+'; top: '+menuY+'px; left: '+menuX+'px;'})
		.click(function(event){event.stopPropagation();})
		.fadeIn(effectTime);

	event.stopPropagation();
}


function loadPageInMainWindow(url, params) {
	//return true;
	//http://localhost/OntoWiki/service/getTemplate?f=micro&t=query.php&q=ttt

	if (!params) {
		params = url.split('?')[1];
		url = url.split('?')[0];
	}
	
	var oldCursor = $jq('html').css('cursor');
	//$jq('html').css('cursor', 'progress');

	$jq('div.section-mainwindows').children('div.window').eq(0).remove();
	$jq('div.section-mainwindows').prepend('<div class="window is-processing"></div>');

	$jq.ajax({
		url: url,
		data: params,
		dataType: 'html',
		// processData: false, 
//		success: function(msg){alert( 'Data Saved: ' + msg );}
		success: function(content){
			// select the first window in the mainwindow section and remove it
			targetwin = $jq('div.section-mainwindows').children('div.window').eq(0);

			// put the content in and remove the in-progress cursor
			targetwin.prepend(content);
			//$jq('html').css('cursor', oldCursor);

			// enhancements maybe not here ...
			enhanceWindow(targetwin);

			// ToDo: enhance also all included windows
			$jq('div.section-mainwindows').children('div.window').eq(0).removeClass('is-processing');
		}
	});
}

// replace a target window (or whatever) with an ajax response (with is-processing)
function replaceWindow(url, params, targetwin, successFn) {
	
	// if not specified, the first (main) window is the target
	if (!targetwin) {
		targetwin = $jq('div.section-mainwindows').children('div.window').eq(0);
	}
	if (!targetwin) return;

	// put the target window into the temp box (for this ajax uri)
	setAutoID(targetwin);
	var date = (new Date()).getTime();
	tmpajax[targetwin.attr('id')] = date;

	targetwin.addClass('is-processing');

	$jq.ajax({
		url: url,
		data: params,
		dataType: 'html',
		success: function(content) {
			
			if (tmpajax[targetwin.attr('id')] != date) {
				return;
			}
			
			targetwin.replaceWith(content);
			enhanceWindow(targetwin);

			if (typeof successFn != 'undefined') {
				successFn();
			}
		}
	});
}

/* input fields with inner labels */
function enhanceInput(input) {
	var jQinput   = $jq(input);
	var jQlabel   = $jq('label[@for=' + jQinput.attr('id') + ']');
	var labelText = jQlabel.text();
	
	if (typeof jQlabel != 'undefined') {
		jQinput
			.ready(function() {
				if (jQinput.val() == '') {
					jQinput.val(labelText);
				}
			})
			.focus(function() {
				if (jQinput.val() == labelText) {
					jQinput.val('');
				}
			})
			.blur(function() {
				if (jQinput.val() == '') {
					jQinput.val(labelText);
				}
			})

		jQlabel
			.addClass('onlyAural');
	}
}

function toggleInlineEdit(inlineEdit, event) {
	if (inlineEdit) {
		var pendingEdits = $jq('.editing');
		if ((pendingEdits.length == 0) || confirm('Changes will be lost. Do you want to continue?')) {
			$jq('.inline-edit').fadeOut(effectTime);
			$jq('table.editable').addClass('non-editable').removeClass('editable');
			$jq('#menu-inline-toggle').text('Enable Inline Editing');
			pendingEdits.remove();
			inlineEditing = false;
			setSessionVar('inlineEditingEnabled', 0);
		}
	} else {
		$jq('.inline-edit').css('display','inline');
		$jq('table.non-editable').addClass('editable').removeClass('non-editable');
		$jq('#menu-inline-toggle').text('Disable Inline Editing');
		inlineEditing = true;
		setSessionVar('inlineEditingEnabled', 1);
	}
}

// TODO: check if last inner window is closed and remove has-inner-windows
function toggleBoxDisplay(id) {
	var box = $jq('.window#' + id);
	if (box.length && /* box.css('display') != 'none' && */ !box.is('.is-disabled')) {
		// box visible
		box.fadeOut(effectTime, function() {
			box.addClass('is-disabled');
			// if there are no more open inner windows -> remove innerwindow status
			if ($jq('#'+id).parents('.innerwindows').find('.window').not('.is-disabled').size() == 0) {
				$jq('#'+id).parents('.content').removeClass('has-innerwindows');
			}
		});
		$jq('.menu-box-display-toggle#menuitem-' + id).text('Show ' + windowNames[id] + ' Box');
		setSessionVar(id + 'BoxDisabled', 1);
	} else if (box.length && box.find('.content').length) {
		// box invisible but in DOM
		$jq('.menu-box-display-toggle#menuitem-' + id).text('Hide ' + windowNames[id] + ' Box');
		setSessionVar(id + 'BoxDisabled', 0);
		// add innerwindow status
		$jq('#'+id).parents('.content').addClass('has-innerwindows');
		box.removeClass('is-disabled');
		box.fadeIn(effectTime);
	} else {
		// box not in DOM
		$jq('.menu-box-display-toggle#menuitem-' + id).text('Hide ' + windowNames[id] + ' Box');
		setSessionVar(id + 'BoxDisabled', 0);
		// reload
		// TODO: insert box via Ajax
		document.location.href = document.location.href;
	}
}

/*
 * Comments inside the resource view
 */
function showOntowikiComments(uri) {
  queryString = "list&r=" + encodeURIComponent(uri)+"&val=true&com=true";
  $jq('div.section-mainwindows > div.window > div.content').addClass('is-processing');
  $jq('div.section-mainwindows > div.window > ul > li.active').removeClass('active');
  $jq('div.section-mainwindows > div.window > ul > li:last').addClass('active');
  $jq.get(owUriBase + "service/comments",
      queryString,
      function (data, textStatus) {
          var out = $jq(data).children('div.content').html();
          $jq('div.section-mainwindows > div.window > div.content').eq(0).replaceWith(out);
          $jq('div.section-mainwindows > div.window > div.content').addClass('activetabcontent');
      }
   );
} 

