/*
 * Smoothbox v20070814 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.1x
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// WILL ONLY WORK WITH mootools 1.1
// look for window.ie


// from wzdrag_drop
var dd_u = "undefined";
function WZDD()
{
	this.elements = new Array(0);
	this.obj = null;
	this.n = navigator.userAgent.toLowerCase();
	this.db = (document.compatMode && document.compatMode.toLowerCase() != "backcompat")?
		document.documentElement
		: (document.body || null);
	this.op = !!(window.opera && document.getElementById);
	if(this.op) document.onmousedown = new Function('e',
		'if(((e = e || window.event).target || e.srcElement).tagName == "IMAGE") return false;');
	this.ie = !!(this.n.indexOf("msie") >= 0 && document.all && this.db && !this.op);
	this.iemac = !!(this.ie && this.n.indexOf("mac") >= 0);
	this.ie4 = !!(this.ie && !document.getElementById);
	this.n4 = !!(document.layers && typeof document.classes != dd_u);
	this.n6 = !!(typeof window.getComputedStyle != dd_u && typeof document.createRange != dd_u);
	this.w3c = !!(!this.op && !this.ie && !this.n6 && document.getElementById);
	this.ce = !!(document.captureEvents && document.releaseEvents && !this.n6);
	this.px = this.n4? '' : 'px';
	this.tWait = this.w3c? 40 : 10;
	this.noRecalc = false;
}
dd = new WZDD();

dd.Int = function(d_x, d_y)
{
	return isNaN(d_y = parseInt(d_x))? 0 : d_y;
};
window.getWidth = function()
{
	return dd.Int(
		(dd.db && !dd.op && !dd.w3c && dd.db.clientWidth)? dd.db.clientWidth
		: (window.innerWidth || 0)
	);
};
window.getHeight = function()
{
	return dd.Int(
		(dd.db && !dd.op && !dd.w3c && dd.db.clientHeight)? dd.db.clientHeight
		: (window.innerHeight || 0)
	);
};
window.getScrollLeft = function()
{
	return dd.Int(window.pageXOffset || (dd.db? dd.db.scrollLeft : 0));
};
window.getScrollTop = function()
{
	return dd.Int(window.pageYOffset || (dd.db? dd.db.scrollTop : 0));
};

window.getScrollWidth = function()
{
	return Math.max(document.body.scrollWidth, windowGetWidth());
}

window.getScrollHeight = function()
{
	return Math.max(document.body.scrollHeight, windowGetHeight());
}
// end.



// on page load call TB_init
window.addEvent('load', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0 ;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
	$$("[class=smoothbox]").each(function(el){
		el.onclick=TB_bind;
	} );

}

function ObjectPosition(obj) {
    var curleft = 0;
      var curtop = 0;
      if (obj.offsetParent) {
            do {
                  curleft += obj.offsetLeft;
                  curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
      }
      return [curleft,curtop];
}

function TB_bind(event) {
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
	this.onclick=TB_bind;

	return false;
}


// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel) {

	// create iframe, overlay and box if non-existent

	if ( !$("TB_overlay") )
	{
		new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
		$('TB_HideSelect').setOpacity(0);
		new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
		$('TB_overlay').setOpacity(0);
		TB_overlaySize();
		new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
		$('TB_load').innerHTML = "<img src='"+live_site_url+"templates/webitalia/images/loading.gif' />";
		TB_load_position();
		new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut}).start(0,0.6);
	}

	if ( !$("TB_load") )
	{
		new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
		$('TB_load').innerHTML = "<img src='loading.gif' />";
		TB_load_position();
	}

	if ( !$("TB_window") )
	{
		new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
		$('TB_window').setOpacity(0);
	}

	//$("TB_overlay").onclick=TB_remove;
	window.onscroll=TB_positionEffect;

	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// adedommelin - ignore height & width provided via link, fix the dimensions to 80% H&W
	TB_WIDTH = windowGetWidth() - (windowGetWidth()*0.4)-40;
	TB_HEIGHT = windowGetHeight() - ( windowGetHeight()*0.2 )-40;
	//llebielle small iframe for pictet event map, meeting requests in popup
	if(url.indexOf('TB_smalliframe') != -1){
		TB_WIDTH = 350;
		TB_HEIGHT = 220;
	}

	//code to show html pages

	var queryString = url.match(/\?(.+)/)[1];
	var params = TB_parseQuery( queryString );

	var datenow = (new Date()).getTime();
	var ajaxContentW = TB_WIDTH - 30,
	    ajaxContentH = TB_HEIGHT - 45;

	if(url.indexOf('TB_iframe') != -1){
		urlNoQuery = url.split('TB_');
		$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'><img src='"+live_site_url+"templates/webitalia/images/logo_small_popup.png' alt='logo'/></div><div id='TB_closeAjaxWindow'><a id='TB_iframeContentPrint' href='#'><img src='"+live_site_url+"templates/webitalia/images/print.gif' style='border: none; display: inline;'/></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent"+datenow+"' name='TB_iframeContent"+datenow+"' style='width:"+(ajaxContentW + (window.ie?20:29) )+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showWindow()'> </iframe>";
		$("TB_iframeContentPrint").onclick=function() { window.parent['TB_iframeContent'+datenow].focus(); window.parent['TB_iframeContent'+datenow].print(); return false; }

	}
	else if(url.indexOf('TB_smalliframe') != -1)
	{
		urlNoQuery = url.split('TB_');
		$("TB_window").innerHTML += "<div id='TB_title' class='small'><div id='TB_ajaxWindowTitle' class='small' >"+caption+"</div><input value='' type='button' class='button cancel notext' onclick='TB_remove()' /></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent"+datenow+"' name='TB_iframeContent"+datenow+"' style='width:"+(ajaxContentW + (window.ie?20:29) )+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showWindow()'> </iframe>";
	}
	else {
		$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>";
	}

	//$("TB_closeWindowButton").onclick = TB_remove;
	
	if(url.indexOf('TB_inline') != -1){
		$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
		TB_position();
		TB_showWindow();
	}else if(url.indexOf('TB_iframe') != -1){
		TB_position();
		if(frames['TB_iframeContent'+datenow] == undefined){//be nice to safari
			//$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){ return false;});
			TB_showWindow();
		}
		}else{
			var handlerFunc = function(){
				TB_position();
				TB_showWindow();
			};
			var myRequest = new Ajax(url, {method: 'get',update: $("TB_ajaxContent"),onComplete: handlerFunc}).request();
		}

		window.onresize=function(){ TB_position(); TB_load_position(); TB_overlaySize();}
}





//helper functions below

function TB_showWindow(){
	//$("TB_load").remove();
	//$("TB_window").setStyles({display:"block",opacity:'0'});


	if (TB_doneOnce==0) {
		TB_doneOnce = 1;
		var myFX = new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').remove();}} }).start(0,1);
	} else {
		$('TB_window').setStyle('opacity',1);
		if ($('TB_load')) { $('TB_load').remove();}
	}
}

function TB_remove() {

	try {
		$("TB_overlay").onclick=null;
		document.onkeyup=null;
		document.onkeydown=null;

		if ($('TB_imageOff')) $("TB_imageOff").onclick=null;
		if ($('TB_iframeContentPrint')) $("TB_iframeContentPrint").onclick=null;
		if ($('TB_closeWindowButton')) $("TB_closeWindowButton").onclick=null;
		if ( $('TB_prev') ) { $("TB_prev").onclick = null; }
		if ( $('TB_next') ) { $("TB_next").onclick = null; }


		new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_window').remove();} }).start(1,0);
		new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_overlay').remove();} }).start(0.6,0);

		window.onscroll=null;
		window.onresize=null;

		if ( $('TB_HideSelect') ) $('TB_HideSelect').remove();
		TB_init();
		TB_doneOnce = 0;

	} finally {
		return false;
	}
	return false;
}

function TB_position() {

	$("TB_window").setStyles({width: TB_WIDTH+'px',
				 left: (window.getScrollLeft() + (windowGetWidth() - TB_WIDTH)/2)+'px',
				//top: getNewHeight() + 'px'});
				 top: (window.getScrollTop() + (windowGetHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_positionEffect() {
	new Fx.Styles('TB_window', {duration: 75, transition: Fx.Transitions.sineInOut}).start({
		'left':(window.getScrollLeft() + (windowGetWidth() - TB_WIDTH)/2)+'px',
		//'top': getNewHeight() +'px'});
		'top':(window.getScrollTop() + (windowGetHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize
	$("TB_overlay").setStyles({"height": '0px', "width": '0px'});
	$("TB_HideSelect").setStyles({"height": '0px', "width": '0px'});
	$("TB_overlay").setStyles({"height": window.getScrollHeight()+'px', "width": window.getScrollWidth()+'px'});
	$("TB_HideSelect").setStyles({"height": window.getScrollHeight()+'px',"width": window.getScrollWidth()+'px'});
}

function TB_load_position() {
	if ($("TB_load")) { $("TB_load").setStyles({left: (window.getScrollLeft() + (windowGetWidth() - 56)/2)+'px', top: (window.getScrollTop() + ((windowGetHeight()-20)/2))+'px',display:"block"}); }
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};

	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}

//modification to smoothbox : add correct function for window size retrieving in IE6
// window.getWidth() -> windowGetWidth()
function windowGetWidth()
{
if( !window.getHeight() )return document.body.offsetWidth;
else return window.getWidth();
}
function windowGetHeight()
{
if( !window.getHeight() )return document.body.offsetHeight;
else return window.getHeight();
}
