/*
	Newsfactory GmbH, Augsburg
	© 2010
	
	Post load automatism for OMS ads in content area
	
	Usage:
	1.) Declare a "relative" positioned DIV in content- or servicearea (with fix size) as
		defined as OMS ad area (e.g. 300px x 250px)
	2.) Print real ad as hidden DIV at the end of page
	3.) Use this script (with IDs of relative and hidden DIV) to position the
		hidden DIV as absolute positioned one over the relative one.
*/


// Global scoped variables and functions
if (typeof omsPostloaderInstances == 'undefined') {
	var omsPostloaderInstances = new Array();
}
if (typeof omsPostloaderInterval == 'undefined') {
	var omsPostloaderInterval = null;
}
if (typeof omsPostloaderIntervalCount == 'undefined') {
	omsPostloaderIntervalCount = 0;
}
if (typeof omsPostloadIntervalFunction == 'undefined') {
	var omsPostloadIntervalFunction = function() {
		for(i=0; i < omsPostloaderInstances.length; i++) {
			omsPostloaderInstances[i].doPositioning();
		}
	}
}


// Object
function omsPostloader(placeholderDivId, hiddenDivId)
{
	// This function returns an object with properties "left" and "top" which
	// define the offset of the given element. Returns "NULL" if error occurs.
	var absoluteOffset = function(elementNode) {
		if (typeof elementNode == 'object' && elementNode != null && typeof elementNode.offsetParent == 'object' && elementNode.offsetParent != null) {
			returnObject = {top: 0, left: 0};
			do {
				returnObject.top += elementNode.offsetTop;
				returnObject.left += elementNode.offsetLeft;
				elementNode = elementNode.offsetParent;	
			}
			while (typeof elementNode.offsetParent == 'object' && elementNode.offsetParent != null);
			return returnObject;
		}
		return null;
	}
	
	
	// Function called from interval function
	// This function positions the real ad DIV if required
	this.doPositioning = function() {
		var position = absoluteOffset(placeholderDiv);
		if (position != null) {
			if (oldPosition.top != position.top || oldPosition.left != position.left) {
				$(hiddenDiv).show().css('position', 'absolute').css('top', position.top).css('left', position.left);
				return true;
			}
		}
		return false;
	}
	
	
	// Initial function call after successful constructing object
	// This function will start interval.
	var init = function() {
		if (omsPostloaderInterval == null) {
			omsPostloaderInterval = window.setInterval(omsPostloadIntervalFunction, 1500);
		}
	}
	
	
	// CONSTRUCTOR
	var placeholderDiv = document.getElementById(placeholderDivId);
	var hiddenDiv = document.getElementById(hiddenDivId);
	var oldPosition = {top: 0, left: 0};
	if (typeof placeholderDiv == 'object' && typeof placeholderDiv.offsetParent == 'object' && typeof hiddenDiv == 'object' && typeof hiddenDiv.offsetParent == 'object') {
		init();
		omsPostloaderInstances.push(this);
	}
}
