//var DEBUG = 1; /* uncomment for debug messages */
var DEBUG = typeof DEBUG != 'undefined' && typeof console != undefined && DEBUG;
if (DEBUG && $.browser.msie) { // add firebug lite for IE
	document.write('<script type="text/javascript" src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>');
}
var	debug = function() {
		if (!DEBUG) return;
		var args = $.makeArray(arguments).join(' ');
		if ($.browser.mozilla || $.browser.msie) console.debug(args);
		else if ($.browser.opera) opera.postError('\t' + args);
		else if ($.browser.safari) console.log(args);
	},
	_groupArgs = [],
	group = function() {
		if (!(DEBUG && ($.browser.mozilla || $.browser.msie))) return;
		_groupArgs.unshift($.makeArray(arguments).join(','));
		if ($.browser.mozilla) console.group(_groupArgs[0]);
		console.time(_groupArgs[0]);
	},
	groupEnd = function() {
		if (!(DEBUG && ($.browser.mozilla || $.browser.msie))) return;
		if ($.browser.mozilla) console.groupEnd();
		console.timeEnd(_groupArgs.shift() || '');
	},
	_hostbase = location.hostname.replace(/(.com|.de|.org|.us|.info|.biz|.net)$/,'').replace(/(^www.)?(\S+)/, '$2'),
	_isEMS = location.pathname.indexOf('/ems') > -1 || location.pathname.indexOf('/public') > -1,
	_isEMSContent = (_isEMS || $.inArray(_hostbase, ['espresto','mywiki.espresto','tagit.espresto']) > -1),
	_postLoadQueue = [];

// ############################################################################
//    request parameter functions
// ############################################################################
// inner function, returns a query String for an Array of name-value-pairs
var _toQueryString = function(params) {
	if (!params) return '';
	var qs = '';
	for (var i=0; i<params.length; i++) {
		var val = params[i][1] || '';
		qs += (i == 0 ? '?' : '&') + params[i][0] + (val.length > 0 ? ('=' + val) : '');
	}
	return qs;
};
// returns an Array containing the name-value-pairs as Array
var getParameters = function(qs) {
	if (!qs || qs.indexOf('?') == -1) return [];
	return $.map(qs.split('?')[1].split('&'), function(nv) {
		return [nv.split('=')];
	});
};
// returns a parameter value for a parameter name
var getParam = function(qs, param) {
	var ps = getParameters(qs);
	for (var i=0; i<ps.length; i++) {
		if (ps[i][0] == param) return ps[i][1];
	}
	return null;
};
// removes a parameter from the given query String
var removeParam = function(qs, param) {
	return _toQueryString($.grep(getParameters(qs), function(p) {
		return p[0] != param;
	}));
};
// adds a parameter to the given query String
var addParam = function(qs, param, value) {
	var ps = getParameters(qs);
	ps.push([param, value]);
	return _toQueryString(ps);
};

// ############################################################################
//    misc functions
// ############################################################################

// returns the path of an element extracted from the 'src' or 'href' attribute
// if not found, return an empty string. input param: node or jQuery object
var getPath = function(elem) {
	if (!elem) return ''; // undefined
	if (!elem.attr) return getPath( $(elem) ); // make jQuery
	var arr = (elem.attr('src') || elem.attr('href') || '').split('/');
	arr[arr.length-1] = ''; // remove last element
	var path = arr.join('/');
	debug('getPath() elem=' + elem[0] + ', returning \'' + path + '\'');
	return path;
};

// ############################################################################
//    cookie functions
// ############################################################################

// sets a cookie, str should be a 'key=value[;key=value]' String
var setCookie = function(name, value, expireDays) {
	debug('setCookie() name=' + name + ', value=' + value + ', expireDays=' + expireDays);
	expireDays = expireDays
		? ' expires=' + new Date(new Date().getTime()
				+ 86400000 * expireDays).toGMTString() + ';'
		: '';
	document.cookie = name + '=' + value + '; path=/;' + expireDays;
};

// returns a cookie value for a given key, returns null if key doesn't exist
var getCookie = function(key) {
	var val;
	$.each((document.cookie || '').split(';'), function() {
		var kv = $.trim(this).split('=');
		if (kv[0] == key) {
			val = kv[1];
			return false; // break loop
		}
	});
	debug('getCookie() ' + key + '=' + val);
	return val;
};

// deletes cookie with the given name
var deleteCookie = function(key) {
	debug('deleteCookie(' + key + ')');
	var expDate="; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = key + "=deleted" + expDate;
	document.cookie = key + expDate;
};
// ############################################################################
//    image functions
// ############################################################################

// image preloader
var preloadImages = function(imgNames, imgPath) {
	group('preloadImages()', imgNames, imgPath);
	imgNames = $.grep(imgNames, function(n,i) { return n; }); // copy array
	$(document.createElement('img')).load(function() {
		if (imgNames.length > 0) this.src = (imgPath ? imgPath : '') + imgNames.shift();
	}).trigger('load');
	groupEnd();
};

var getImagePath = getPath;

// image rotator for EMS generated content
var rotateImage = function(cssClass, delay) {
	group('rotateImage()', 'cssClass=' + cssClass, 'delay=' + delay);
	delay = delay || 150;
	$('noscript.' + cssClass).each(function() {
		var cookieName = 'rotate-lastimg';
		var $images = $(this).nextAll('img.' + cssClass);
		var oldId = getCookie(cookieName);
		if (oldId && $images.length > 1) {
			$images = $images.not($('#' + oldId)); // remove cookie image
		}
		var target = $images.get(Math.floor($images.length * Math.random()));
		setCookie(cookieName, target.id, 30);

		if ($.browser.opera || target.complete) { // opera can't handle onload
			$(target).fadeIn(delay);
		}
		else {
			$(target).load(function() { $(this).fadeIn(delay); });
		}
	});
	groupEnd();
};

if (_isEMSContent) {
	_postLoadQueue.push([rotateImage, 'rotate', 200]);
}

// ############################################################################
//    email functions
// ############################################################################
var appendMM_params = function(subj) {
	if (subj) document.write('?subject=' + encodeURIComponent(subj));
};

// mail function for EMS generated content
var toMail = function(id, name, domain, subject) {
	if (subject.length) { // normalize html special characters and encode URI afterwards
		subject = '?subject=' + encodeURIComponent($('<span>' + subject + '</span>').text());
	}
	var $elem = $('#' + id);
	$elem.replaceWith(
		$('<a href="&#x6D;&#97;&#105;&#108;&#116;&#111;&#58;' + name + '&#64;'
			+ domain + subject + '">' + $elem.text() + '</a>')
			.addClass($elem.attr('class')).attr('id', id)
		);
	// remove javascript
	var $script = $('#' + id).next();
	if ($script && $script[0].nodeName.toLowerCase() == 'script') $script.replaceWith('');
};

// ############################################################################
//    google analytics
// ############################################################################
var _gat, _ptAnalyzer=null;

// initialize ga Analytics tracker
var gaTrackerAnalyticsInit = function(trackerId) {
	if (!(_gat && trackerId)) return; // ga script not loaded
	debug('gaTrackerAnalyticsInit() trackerId=' + trackerId + ', _gat=' + _gat);
	_ptAnalyzer=_gat._getTracker(trackerId);
	_ptAnalyzer._setDomainName("none");
	_ptAnalyzer._setAllowLinker(true);
	_ptAnalyzer._initData();
	_ptAnalyzer._trackPageview();
};

// insert ga script if host matches
(function() { // insert script the old fashioned way
	var trackerId = null;
	$.each([['espresto','UA-3742254-1'], ['mywiki.espresto','UA-3742254-7']],
		function(i,v) {
			if (_hostbase == v[0]) { // found host to track
				trackerId = v[1];
				return false;
			}
	});
	if (!trackerId) return;
	var proto = document.location.protocol;
	document.write('<script language="JavaScript" src="'
			+ proto + '//' + (proto == 'https:' ? 'ssl' : 'www')
			+ '.google-analytics.com/ga.js" type="text/javascript"></script>');
	_postLoadQueue.push([gaTrackerAnalyticsInit, trackerId]); // call after dom is complete
})();

// enable tracking across multiple domains if the tracker is
// initialized and hostname of the link is allowed
var track = function(link) {
	if (!(_ptAnalyzer && link && link.href)) return false; // no pagetracker or invalid param
	// enable tracking for espresto.de/.com
	if (_hostbase == 'espresto'
		&& link.hostname != location.hostname) _ptAnalyzer._link(link.href);
	return false;
};

// ############################################################################
//    summary statistics
// ############################################################################
var summaryStatistics = function(imageId)
{
	var $img = $('#' + (imageId || 'summary-statistics'));
	if (!$img || $img.length != 1) {
		debug('summaryStatistics() missing image ' + $img);
		return;
	}
	group('summaryStatistics()', $img);

	var _addParams = function(extLogKey, summaryKey, val) {
		val = '' + escape(val == null || val.length == 0 ? 'undefined' : val);
		if (extLogKey != null) extLogParams.push([extLogKey, val]);
		if (summaryKey != null) summaryParams.push([summaryKey, val]);
	};

	var summaryParams = [['summarylog', null]], extLogParams = [['st','1']], n = navigator, sc = screen;
	var sz = document.body && document.body.clientWidth
		? [document.body.clientWidth, document.body.clientHeight]
		: [window.innerWidth, window.innerHeight];

	$.each([['js', null, 'true'],['pt', null, n.platform], ['co', 'co', '' + n.cookieEnabled], ['je', 'je', '' + n.javaEnabled()], ['br', null, n.appName + ' ' + n.appVersion], ['sd', 'sd', sc.colorDepth || sc.pixelDepth], ['res', null, sc.width + 'x' + sc.height], ['innerDimension/',null, '' + sz[0] + 'x' + sz[1]], [null, 'sw', sc.width], [null, 'sh', sc.height], [null, 'ww', sz[0]], [null, 'wh', sz[1]], ['la', 'la', n.language || n.userLanguage], ['cpu', null, n.cpuClass], ['od', null, window.outerWidth + 'x' + window.outerHeight], ['his', null, history.length], ['agent', null, n.userAgent]],
		function(i,v) {	_addParams(v[0], v[1], v[2]); });
	$.each(n.plugins, function(i,pl) {
		if (i==0 || pl.name != n.plugins[i-1].name)	_addParams('plugins/name/', 'p', pl.name);
	});

	var extLogImgSrc = $img.attr('src');
	var to = extLogImgSrc.lastIndexOf('?');
	if (to != -1) extLogImgSrc = extLogImgSrc.substring(0, to); // remove params

	$img.replaceWith('<img width="1" height="1" border="0" src="' + getPath($img) + 'log____image.gif' +_toQueryString(summaryParams) + '" />'
		+ '<img id="webbug" width="1" height="1" border="0" src="' + extLogImgSrc + _toQueryString(extLogParams) + '" />');
	groupEnd();
};
_postLoadQueue.push(summaryStatistics);

// ############################################################################
//    search page functions
// ############################################################################

// replaces submit button with a link
var replaceSearchButton = function() {
	group('replaceSearchButton()');	
	$.each($("input[class='search-button']"), function() {
		var $btn = $(this);
		var $form = $btn.parents('form');
		$btn.replaceWith(
			$('<a href=""></a>')
				.addClass($btn.attr('class'))
				.text($btn.attr('value'))
				.click(function() {
					$form.trigger('submit');
					return false;
				})
			);
		});
	groupEnd();
};
_postLoadQueue.push(replaceSearchButton);

// ############################################################################
//    popup functions
// ############################################################################
(function() {
	if (!getParam(location.search, 'popup')) return; // no parameter found

	// change stylesheet path
	var $css = $('#css-screen');
	if ($css == null || $css.length == 0) return;
	$css.attr('href', $css.attr('href').replace(/^(\S+)(.css)$/, '$1_popup$2'));

	_postLoadQueue.push(
		function() {
			var _btn = function(text, func) {
				return $('<span></span>').addClass('button')
					.click(func)
					.click(function() {
						window.close();
					}).append($('<span></span>').html(text));
			};
			debug('popup: replacing DOM..');

			$('.navi').remove();
			var $logo = $('#logo'), $content = $('#top .contentmain');

			$content = $('#header').children().remove().end()
			.append($logo).next().children().remove().end()
			.append($('<div id="main"></div>').append($content));

			try {
				$(opener.document);
			} catch (e) { // forbidden access to dom
				debug('warning:' + e); return;
			}
			var popType = getParam(location.search, 'ptype'),
				popId = getParam(location.search, 'pid'),
				loc = $('html').attr('lang') || 'de', // get locale from html lang attribute
				$btnLeft, $btnRight;

			debug('popup: popType=' + popType + ', popId=' + popId);
			if (popType && popType == 'checkbox' && popId) {
				var $checkbox = $(opener.document).find('input[id="' + popId + '"]:checkbox');
				if (!$checkbox) return;
				$btnLeft = _btn(loc == 'en' ? 'Accept' : 'Akzeptieren', function() { // accept-button
					$checkbox.attr('checked', 'checked');
				});
				$btnRight = _btn(loc == 'en' ? 'Dismiss' : 'Ablehnen', function() {
					$checkbox.attr('checked', '');
				});
			}
			else {
				$btnLeft = _btn(loc == 'en' ? 'Close' : 'Schlie&szlig;en');
			}
			$content.append($('<div id="buttons"></div>')
				.append($btnLeft).append($btnRight ? $btnRight : ''));
		});
})();

//###########################################################################
//   Slimbox 2
//############################################################################
/*
Slimbox v2.02 - The ultimate lightweight Lightbox clone for jQuery
(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
MIT-style license.
*/
(function(w){var E=w(window),u,g,F=-1,o,x,D,v,y,L,s,n=!window.XMLHttpRequest,e=window.opera&&(document.compatMode=="CSS1Compat")&&(w.browser.version>=9.3),m=document.documentElement,l={},t=new Image(),J=new Image(),H,a,h,q,I,d,G,c,A,K;w(function(){w("body").append(w([H=w('<div id="lbOverlay" />')[0],a=w('<div id="lbCenter" />')[0],G=w('<div id="lbBottomContainer" />')[0]]).css("display","none"));h=w('<div id="lbImage" />').appendTo(a).append(q=w('<div style="position: relative;" />').append([I=w('<a id="lbPrevLink" href="#" />').click(B)[0],d=w('<a id="lbNextLink" href="#" />').click(f)[0]])[0])[0];c=w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0],A=w('<div id="lbCaption" />')[0],K=w('<div id="lbNumber" />')[0],w('<div style="clear: both;" />')[0]])[0]});w.slimbox=function(O,N,M){u=w.extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeEasing:"swing",initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Image {x} of {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},M);if(typeof O=="string"){O=[[O,N]];N=0}y=E.scrollTop()+((e?m.clientHeight:E.height())/2);L=u.initialWidth;s=u.initialHeight;w(a).css({top:Math.max(0,y-(s/2)),width:L,height:s,marginLeft:-L/2}).show();v=n||(H.currentStyle&&(H.currentStyle.position!="fixed"));if(v){H.style.position="absolute"}w(H).css("opacity",u.overlayOpacity).fadeIn(u.overlayFadeDuration);z();k(1);g=O;u.loop=u.loop&&(g.length>1);return b(N)};w.fn.slimbox=function(M,P,O){P=P||function(Q){return[Q.href,Q.title]};O=O||function(){return true};var N=this;return N.unbind("click").click(function(){var S=this,U=0,T,Q=0,R;T=w.grep(N,function(W,V){return O.call(S,W,V)});for(R=T.length;Q<R;++Q){if(T[Q]==S){U=Q}T[Q]=P(T[Q],Q)}return w.slimbox(T,U,M)})};function z(){var N=E.scrollLeft(),M=e?m.clientWidth:E.width();w([a,G]).css("left",N+(M/2));if(v){w(H).css({left:N,top:E.scrollTop(),width:M,height:E.height()})}}function k(M){w("object").add(n?"select":"embed").each(function(O,P){if(M){w.data(P,"slimbox",P.style.visibility)}P.style.visibility=M?"hidden":w.data(P,"slimbox")});var N=M?"bind":"unbind";E[N]("scroll resize",z);w(document)[N]("keydown",p)}function p(O){var N=O.keyCode,M=w.inArray;return(M(N,u.closeKeys)>=0)?C():(M(N,u.nextKeys)>=0)?f():(M(N,u.previousKeys)>=0)?B():false}function B(){return b(x)}function f(){return b(D)}function b(M){if(M>=0){F=M;o=g[F][0];x=(F||(u.loop?g.length:0))-1;D=((F+1)%g.length)||(u.loop?0:-1);r();a.className="lbLoading";l=new Image();l.onload=j;l.src=o}return false}function j(){a.className="";w(h).css({backgroundImage:"url("+o+")",visibility:"hidden",display:""});w(q).width(l.width);w([q,I,d]).height(l.height);w(A).html(g[F][1]||"");w(K).html((((g.length>1)&&u.counterText)||"").replace(/{x}/,F+1).replace(/{y}/,g.length));if(x>=0){t.src=g[x][0]}if(D>=0){J.src=g[D][0]}L=h.offsetWidth;s=h.offsetHeight;var M=Math.max(0,y-(s/2));if(a.offsetHeight!=s){w(a).animate({height:s,top:M},u.resizeDuration,u.resizeEasing)}if(a.offsetWidth!=L){w(a).animate({width:L,marginLeft:-L/2},u.resizeDuration,u.resizeEasing)}w(a).queue(function(){w(G).css({width:L,top:M+s,marginLeft:-L/2,visibility:"hidden",display:""});w(h).css({display:"none",visibility:"",opacity:""}).fadeIn(u.imageFadeDuration,i)})}function i(){if(x>=0){w(I).show()}if(D>=0){w(d).show()}w(c).css("marginTop",-c.offsetHeight).animate({marginTop:0},u.captionAnimationDuration);G.style.visibility=""}function r(){l.onload=null;l.src=t.src=J.src=o;w([a,h,c]).stop(true);w([I,d,h,G]).hide()}function C(){if(F>=0){r();F=x=D=-1;w(a).hide();w(H).stop().fadeOut(u.overlayFadeDuration,k)}return false}})(jQuery);

var initSlimBox = function() {
	group('initSlimBox()');
	var lbText = function( $text ) { return '<span class="lb-text">' + $text + '</span>'; };
	$('#lbCenter').find('#lbPrevLink').html(lbText('zurück')).end()
		.find('#lbNextLink').html(lbText('weiter'));
	$('#lbCloseLink').html(lbText('schließen'));
	
	var $el = $("a[rel^='lightbox']").slimbox({
		counterText: "Bild {x} von {y}"
	}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
	groupEnd();
};
_postLoadQueue.push([initSlimBox]);


//###########################################################################
//  Tooltips
//############################################################################
/*
 * tools.tooltip 1.0.2 - Tooltips done right.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/tooltip.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : November 2008
 * Date: 2009-06-12 11:02:45 +0000 (Fri, 12 Jun 2009)
 * Revision: 1911 
 */
(function(c){c.tools=c.tools||{version:{}};c.tools.version.tooltip="1.0.2";var b={toggle:[function(){this.getTip().show()},function(){this.getTip().hide()}],fade:[function(){this.getTip().fadeIn(this.getConf().fadeInSpeed)},function(){this.getTip().fadeOut(this.getConf().fadeOutSpeed)}]};c.tools.addTipEffect=function(d,f,e){b[d]=[f,e]};c.tools.addTipEffect("slideup",function(){var d=this.getConf();var e=d.slideOffset||10;this.getTip().css({opacity:0}).animate({top:"-="+e,opacity:d.opacity},d.slideInSpeed||200).show()},function(){var d=this.getConf();var e=d.slideOffset||10;this.getTip().animate({top:"-="+e,opacity:0},d.slideOutSpeed||200,function(){c(this).hide().animate({top:"+="+(e*2)},0)})});function a(f,e){var d=this;var h=f.next();if(e.tip){if(e.tip.indexOf("#")!=-1){h=c(e.tip)}else{h=f.nextAll(e.tip).eq(0);if(!h.length){h=f.parent().nextAll(e.tip).eq(0)}}}function j(k,l){c(d).bind(k,function(n,m){if(l&&l.call(this)===false&&m){m.proceed=false}});return d}c.each(e,function(k,l){if(c.isFunction(l)){j(k,l)}});var g=f.is("input, textarea");f.bind(g?"focus":"mouseover",function(k){k.target=this;d.show(k);h.hover(function(){d.show()},function(){d.hide()})});f.bind(g?"blur":"mouseout",function(){d.hide()});h.css("opacity",e.opacity);var i=0;c.extend(d,{show:function(q){if(q){f=c(q.target)}clearTimeout(i);if(h.is(":animated")||h.is(":visible")){return d}var o={proceed:true};c(d).trigger("onBeforeShow",o);if(!o.proceed){return d}var n=f.position().top-h.outerHeight();var k=h.outerHeight()+f.outerHeight();var r=e.position[0];if(r=="center"){n+=k/2}if(r=="bottom"){n+=k}var l=f.outerWidth()+h.outerWidth();var m=f.position().left+f.outerWidth();r=e.position[1];if(r=="center"){m-=l/2}if(r=="left"){m-=l}n+=e.offset[0];m+=e.offset[1];h.css({position:"absolute",top:n,left:m});b[e.effect][0].call(d);c(d).trigger("onShow");return d},hide:function(){clearTimeout(i);i=setTimeout(function(){if(!h.is(":visible")){return d}var k={proceed:true};c(d).trigger("onBeforeHide",k);if(!k.proceed){return d}b[e.effect][1].call(d);c(d).trigger("onHide")},e.delay||1);return d},isShown:function(){return h.is(":visible, :animated")},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return f},onBeforeShow:function(k){return j("onBeforeShow",k)},onShow:function(k){return j("onShow",k)},onBeforeHide:function(k){return j("onBeforeHide",k)},onHide:function(k){return j("onHide",k)}})}c.prototype.tooltip=function(d){var e=this.eq(typeof d=="number"?d:0).data("tooltip");if(e){return e}var f={tip:null,effect:"slideup",delay:30,opacity:1,position:["top","center"],offset:[0,0],api:false};if(c.isFunction(d)){d={onBeforeShow:d}}c.extend(f,d);this.each(function(){e=new a(c(this),f);c(this).data("tooltip",e)});return f.api?e:this}})(jQuery);


$(function() { // onload
	debug('_isEMS=' + _isEMS + ', _hostbase=' + _hostbase);
	group('postLoad() len=' + _postLoadQueue.length);

	// tooltips
	$("a.tooltip").tooltip({
		effect: 'slideup',
		slideInSpeed:100,
		slideOutSpeed:100,
		delay: 500
	});

	deleteCookie('fontsize'); // delete old zoom cookie
	while(_postLoadQueue.length) {
		group('postload ' + _postLoadQueue.length);
		var f = _postLoadQueue.shift();
		if ($.isFunction(f)) f();
		else if ($.isFunction(f[0])) {
			var func = f.shift();
			if (f.length == 1) func(f[0]);
			else if (f.length == 2) func(f[0], f[1]);
			else if (f.length == 3) func(f[0], f[1], f[2]);
			else func(f[0], f[1], f[2], f[3]);
		}
		groupEnd();
	}
	groupEnd();
});
