var zinLoadIconPrepared = false;
var zinLoadIconTriggered = false;
var zinLoadIconCached = new Image();



function zinGetLoadIconConfig() {
	
	var tmp = new Object({
		'opacity'	:	'0.35',
		'id'		:	'zinLoadIcon',
		'left'		:	'383px',
		'top'		:	'249px',
		'src'		:	'typo3conf/ext/zin_loadicon/img/loader.gif',
		'target'	:	'content',
		'zIndex'	:	'50000'
	});
	
	try {
		if (zinLoadIconConfig) {
			for (var i in zinLoadIconConfig) {
				tmp[i] = zinLoadIconConfig[i];
			}
		}
	} catch(e) {}
	
	return tmp;
}



function zinGetLoadIconTarget(zinLoadIconConfig) {
	if(zinLoadIconConfig.target) {
		if (typeof zinLoadIconConfig.target == 'object') {
			return zinLoadIconConfig.target;
		} else {
			return document.getElementById(zinLoadIconConfig.target);
		}
	} else {
		var tags = document.getElementsByTagName('body');
		return tags[0];
	}
}



function zinTriggerLoadIcon() {
	if (zinLoadIconTriggered) {
		return;
	}
	zinLoadIconTriggered = true;
	tmp = zinGetLoadIconConfig();
	
	var parent = zinGetLoadIconTarget(tmp);
	var children = parent.childNodes;
	var child;

	for (var i = 0; i < children.length; i++) {
		child = children[i];
		if (!child.style) continue;
		child.style.opacity = tmp.opacity;
	}
	
	var el = document.createElement('img');
	
	el.src = tmp.src;
	//	el.setAttribute('src', tmp.src);
	el.setAttribute('id', tmp.id);
	el.style.zIndex = tmp.zIndex;
	el.style.position = 'absolute';
	el.style.left = tmp.left;
	el.style.top = tmp.top;
	
	parent.appendChild(el);
}

// Initialize the load icon
function zinPrepareLoadIcon() {
	
	if (zinLoadIconPrepared) {
		return;
	}
	zinLoadIconPrepared = true;
	
	var bodyTags = document.getElementsByTagName('body');
	
	var config = zinGetLoadIconConfig();
	zinLoadIconCached.src = config.src;
	
	if(bodyTags[0]) {
		var onUnload = bodyTags[0].getAttribute('onunload');
		if (onUnload) {
			bodyTags[0].setAttribute('onunload', 'zinTriggerLoadIcon(); ' + onUnload);
		} else {
			bodyTags[0].setAttribute('onunload', 'zinTriggerLoadIcon()');
		}
		
		var onBeforeUnload = bodyTags[0].getAttribute('onbeforeunload');
		if (onBeforeUnload) {
			bodyTags[0].setAttribute('onbeforeunload', 'zinTriggerLoadIcon(); ' + onBeforeUnload);
		} else {
			bodyTags[0].setAttribute('onbeforeunload', 'zinTriggerLoadIcon()');
		}
	} else {
		alert('no <body> tag found!??!');
	}
}

if (window.onload) {
	var tmp = window.onload;
	window.onload = function(e) {
		tmp(e);
		zinPrepareLoadIcon();
	}
} else {
	window.onload = function() { zinPrepareLoadIcon(); }
}
