/*
 * Copyright (c) 2010, Augré du vent. Tous droits réservés.
 */

//-- public methods

var isPopup = false;

function init(element) {
	hidePopup(element);
}

function showPopup(element, coord) {
	if (isPopup) element.hide().setStyle({opacity: 0});

	element.setStyle({left:coord.left, top:coord.top});


	new Effect.Appear(element, {duration: 0.2});
	isPopup = true;
}

function hidePopup(element) {
	new Effect.Fade(element, {duration: 0.1});
	isPopup = false;
}


//--- standard popup

function initStandardPopup() {
	document.write("<div id=\"popupBox\" class=\"popupContentBox\"><div id=\"popupContent\"></div><p class=\"closeBox\"><a href=\"javascript:unpop();\" title=\"Fermer\">Fermer</a></div>");
	$("popupBox").hide().setStyle({opacity: 0});
}

function pop(id, width, height) {
	var popupBox = $("popupBox");
	var contentBox = $("popupContent");

	// update content
	contentBox.update($(id).innerHTML);

	// set dimension
	var finalDim = {width:0,height:0};
	var dim = popupBox.getDimensions();
	if (!width || isNaN(width) || width <= 0) finalDim.width = dim.width;
	else {
		finalDim.width = width;
		popupBox.setStyle({width:width});
	}
	if (!height || isNaN(height) || height <= 0) finalDim.height = dim.height;
	else {
		finalDim.height = height;
		popupBox.setStyle({height:height});
	}

	// center popup
	var popupPosition = center(finalDim);

	// show popup
	showPopup(popupBox, popupPosition);
}

function unpop() {
	hidePopup($("popupBox"));
}

function center(size) {
	var dim = getWindowSize();
	return getViewPortPosition({left: dim.width / 2 - size.width / 2, top : dim.height / 2 - size.height / 2});
}

function getViewPortPosition(coord) {
	var coords = {left:0,top:0};
	coords.left =
	coord.left + document.body.scrollLeft - document.body.clientLeft;
	coords.top =
	coord.top + document.body.scrollTop - document.body.clientTop;
	// include html element space, if applicable
	if (document.body.parentElement && document.body.parentElement.clientLeft) {
		var bodParent = document.body.parentElement;
		coords.left += bodParent.scrollLeft - bodParent.clientLeft;
		coords.top += bodParent.scrollTop - bodParent.clientTop;
	}
	return coords;
}

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof( window.innerWidth ) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {width:myWidth, height:myHeight};
}


