/*
 * Some DHTML JavaScript to show a contextual help div
 * using the wz_tooltip library from
 */

function toggleElement(id) 
{
	// store the current display setting of the element
	var display = document.getElementById(id).style.display;
	
	// check wether the element should be displayed or hidden
	if (display == 'none')
	{
		document.getElementById(id).style.display = 'block';
	}	
	else
	{
		document.getElementById(id).style.display = 'none';
	}
}

/**
 * reregisterDraggables takes an array of class names and registers all elements with this class as draggable
 * 
 */
  function reregisterDraggables(classNames) {
  	for (var elIndex = 0; elIndex < classNames.length; elIndex++) {
	  	drags = document.getElementsByClassName(classNames[elIndex]);
	  	for (var i = 0; i < drags.length; i++){
	  		new Draggable(drags[i].id, {ghosting: true, revert: true});
	  	}
  	}
  }
  
/**
 * checkAllByClass checks all checkbox elements with the given class
 */
function checkAllByClass(classname) {
	if (classname.indexOf('.') != 0){
		classname = '.'+classname;
	}
	checkElements = $$(classname);
  	for (var i = 0; i < checkElements.length; i++){
		el = checkElements[i];
		if (el.type == 'checkbox') {
			if (el.checked){
				el.checked = false;
			} else {
				el.checked = true;
			}
		}
	}
}
/**
 * clickHandler: checks all checkboxes in the row of the clicked checkbox
 * if clicked box is checked then check all in the row, else uncheck all.
 * @return
 */
function checkTableRow(e) {
	var source = $(e);
	var chckd = e.checked;
	
	var ancestors = source.ancestors();
	var row = ancestors.findAll(
			function(el){
				return el.tagName.toLowerCase() == 'tr';
			}
	);
	var checkboxes = $(row[0]).select('input[type="checkbox"]');
	checkboxes.each(function(el){ el.checked = chckd});
	
}

/**
 * Tooltip
**/
var saTooltip = Class.create({
	
	id: 'saTooltip',
	text: null,
	activateEvent : 'mouseover',
	deactivateEvent: 'mouseout',
	
	initialize:function(text, conf) {
		this.text = text;
		if (conf){
			this.activateEvent = conf.activateEvent ? conf.activateEvent : this.activateEvent;
			this.deactivateEvent = conf.deactivateEvent ? conf.deactivateEvent : this.deactivateEvent;
		}
		
	}
});

var saTooltipHandler = {

	currentHideHandler : null,
	
	initialize:function() {
	
	},
	
	handleShowEvent: function (event) {
		var element = event.element();
		
		var helpIndicator = null;
		if (0 <= element.className.indexOf('tooltipIndicator')) {
			helpIndicator = element;		
		} else {
			element.ancestors().each(function(el){
				if (0 <= el.className.indexOf('tooltipIndicator')) {
					helpIndicator = el; 
				}
			});
		}
		var obj = saTooltips.get(helpIndicator.id);
		if ($(saTooltip.prototype.id)) {
			$(saTooltip.prototype.id).remove();		
		}
		
		// build tt
		var helpNode = document.createElement('div');
		var hAttrNode = document.createAttribute('id');
		hAttrNode.nodeValue = saTooltip.prototype.id;
		helpNode.setAttributeNode(hAttrNode);
		var hAttrNode = document.createAttribute('class');
		hAttrNode.nodeValue = 'tooltip';
		helpNode.setAttributeNode(hAttrNode);
		document.body.appendChild(helpNode);
		
		
		// fill tt
		var helpElement = $(saTooltip.prototype.id);
		helpElement.insert(obj.text);
		
		
		// positioning
		helpElement.setStyle({
			height: helpElement.getHeight()+'px'
		});
		helpElement.absolutize();
		helpElement.hide();
		helpElementDimensions = helpElement.getDimensions();
		helpIndicatorDimensions = helpIndicator.getDimensions();
		var body = document.getElementsByTagName('body').item(0);
		var x = Element.cumulativeOffset(element).left + helpIndicatorDimensions.width;
		if (x + helpElementDimensions.width > body.getWidth()) { 
			x = x - helpElementDimensions.width;
		}
		var y = Element.cumulativeOffset(element).top - helpElementDimensions.height;
		if (0 > y){
			y = Element.cumulativeOffset(element).top + helpIndicatorDimensions.height;
		}
		
		var EA = new Effect.Move (
					helpElement, 
					{ 
						x: x, 
						y: y, 
						mode: 'absolute',
						duration: 0,
						queue: 'end' 
					} 
		);
		// close event
		saTooltipHandler.currentHideHandler = saTooltipHandler.handleHideEvent.bindAsEventListener(saTooltipHandler)
		Event.observe(body, 'click', saTooltipHandler.currentHideHandler, false);
		helpElement.show();
	},
	
	handleHideEvent: function (event) {
		var element = event.element();
		var helpIndicator = null;
		if (0 <= element.className.indexOf('tooltipIndicator')) {
			helpIndicator = element;		
		} else {
			element.ancestors().each(function(el){
				if (0 <= el.className.indexOf('tooltipIndicator')) {
					helpIndicator = el; 
				}
			});
		}
		if (null == helpIndicator){
			if ($(saTooltip.prototype.id)) {
				$(saTooltip.prototype.id).remove();		
				var body = document.getElementsByTagName('body').item(0);
				Event.stopObserving(body, 'click', saTooltipHandler.currentHideHandler, false);
			}
		}
	}
}

var saTooltips = new Hash();
/*
*/
function initSaTooltips() {
	var contextHelpIndicators = $$('.tooltipIndicator');
	contextHelpIndicators.each(function (helpIndicator) {
		var tt = saTooltips.get(helpIndicator.id);
		var activateEvent = 'mouseover';
		if (tt && tt.activateEvent){
			activateEvent = tt.activateEvent;
		}
		Event.observe(helpIndicator.id, activateEvent, saTooltipHandler.handleShowEvent.bindAsEventListener(saTooltipHandler), true);
		//Event.observe(helpIndicator.id, tt.deactivateEvent, saTooltipHandler.handleHideEvent.bindAsEventListener(saTooltipHandler), true);
		
	});
}


var LinkDispatcher = {
	dispatch : function(event, passThroughCond, confirmMsg, xhttpurl, formName, executeAfterSuccess) {
	var source = Event.element(event);
	if ("A" != source.nodeName) {
		element = Event.findElement(event, 'A');
	} else {
		element = source;
	}	

	//default action that is executed after saving the abstract: follow the link
	if (undefined === executeAfterSuccess)
	{
		executeAfterSuccess = "document.location.href = element.href;";
	}
	if ('printPopup' == element.getAttribute('rel'))
	{
		executeAfterSuccess = 'printPopupHandler(element.href, true)';	
		
	}
	
	if (eval(passThroughCond)) {
		eval (executeAfterSuccess);
		return true;
	}
		// get confirmation
		var doSave = confirm(confirmMsg);
		
		// yes send XMLHTTPReq and wait for answer
		if (true == doSave) {
		var req = new Ajax.Request(
			xhttpurl,
			{
				method: 'post',
								
				onSuccess: function(transport) {
  					eval(executeAfterSuccess);
  					Abstract.changed = false;
				},
				onError: function (transport) {
					alert ('Error: '+transport);
				},
				onComplete : function(transport) {
					return false;
				},
				
				postBody: Form.serialize($(formName))
  			});
			Event.stop(event);
		} else {	// no redirect
			return true;
		}
	}
}

// handler for print popup
function printPopupHandler(href, force) {
	if (force || Abstract.changed == false || Abstract.changed == undefined)
	{
		var w=window.open(href,'print_preview','width=800,height=800,left=320,top=0,resizable=yes,scrollbars,yes');w.focus();
	}
	return false;
}
  	
// apply dispatch handler to links
function applyDispatchHandler(passThrougCond, confirmMsg, xhttpurl, formName) {
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		var link = links[i];			
		// apply only to real links and not light box links
		var relAttribute = String(link.getAttribute('rel'));
		
		if (!(
				relAttribute.toLowerCase().match('lightbox') || 
				relAttribute.toLowerCase().match('specialchar') ||
				relAttribute.toLowerCase().match('nosave') ||
				relAttribute.toLowerCase().match('toggleelement')
			) 
		) {
			// check for existing onclickHandlers 
			Event.observe(link, 'click', LinkDispatcher.dispatch.bindAsEventListener(LinkDispatcher, passThrougCond, confirmMsg, xhttpurl, formName));
		}	
	}
}

/**
 * display loading indicator displays a loading indicator on top of an element
 * so that the element below can not be clicked, defaults to body
 */
var LoadingIndicator = Class.create({
	element: null,
	visibility: false,
	text: '',
	
	initialize2: function (el, visibility, text) {
		this.element = $(el);
		this.visibility = visibility;
		this.text = text;
		this.build();
	},
	
	build : function () {
	
	},
	
	show : function () {
		$('page-spinner').setStyle({ display: 'block', width: document.viewport.getWidth() +'px', height: document.viewport.getHeight() +'px'})
		$('page-spinner').setOpacity(0.5);		
	},
	
	hide : function () {
		$('page-spinner').hide();
	}
});

function updateJSON(request, json)
{
  var nbElementsInResponse = json.length;
  for (var i = 0; i < nbElementsInResponse; i++)
  {
     Element.update(json[i][0], json[i][1]);
  }
}

