/**
 * Common box functions
 */

/**
 * Show/Hide the box if the activator element is clicked.
 *
 * @param activatorElement the element to activate the widget with.
 * @param left the left position relative to the parent element.
 * @param top the top position relative to the parent element.
 * @param widgetId the id of the element containing the widget.
 */     
function addActivatorClickEventListner(activatorElement, widgetId) {
    $(activatorElement).click(function (event) {
        $(widgetId).toggle();
    	event.stopPropagation();
    });
}

/**
 * Position the box relative the the activator element.
 *
 * @param widgetId the id of the element containing the widget.
 * @param left the left position relative to the parent element.
 * @param top the top position relative to the parent element.
 */
function positionBox(widgetId, left, top) {
    $(widgetId).css("left", left);
    $(widgetId).css("top", top);
}

/**
 * Close the box with given widget id if the HTML element is clicked.
 *
 * @param widgetId the id of the element containing the widget.
 */     
function addHtmlClickEventListner(widgetId) {
    $(document.html).click(function (event) {
    	event = null;
    	$(widgetId).hide();
    });
}

/**
 * Disables propagation of the event if one of the inner elements 
 * of the box is clicked, preventing it from closing.
 */
function addBoxClickEventListner() {
    $(".boxOuter,.boxInner,.boxInner2,.boxInner2 h2,.boxInner2 h4,boxInner2 p").click(function (event) {
    	event.stopPropagation();
    });
}

/**
 * Closes the box if the close button or the close label is clicked.
 */ 
function addCloseClickEventListner(widgetId) {
    $(".closeButton,.closeLink").click(function (event) {
    	$(widgetId).hide();
    	event.stopPropagation();
    });
}

/**
 * Activate listeners related to a given widget element depending on 
 * if the user has java script enabled or not.
 *
 * @param widgetId the id of the element containing the widget.
 * @param fallbackId the id of the fall back element.
 * @param activatorElement the element to activate the widget with.
 * @param left the left position relative to the parent element.
 * @param top the top position relative to the parent element.
 */
function registerWidget(widgetId, fallbackId, activatorId, left, top) {
	addHtmlClickEventListner(widgetId);
	addBoxClickEventListner();
	addCloseClickEventListner(widgetId);
	addActivatorClickEventListner(activatorId, widgetId);
	positionBox(widgetId, left, top);
	if(fallbackId != "") {
		$(fallbackId).hide();
	}
	$(activatorId).show();
}