jQuery(document).ready(function(){

	if (jQuery('#popup-overlay').length == 0){
		jQuery('body').append(jQuery('<div id="popup-overlay" style="display: none;"></div>'));
	}

});

/**
 * provide functions to check loading state of images
 * reserved css
 */
(function($) {

    $.fn.extend({
    	id: null, // this popup's css id
		options: null, // global options object
		$popup: null, // global jquery object containing this popup
		popup: function(callid, calloptions) {

			var defaults = {
				zindex: '2100',
				position: 'absolute',
				path: 'fileadmin/templates/es2/content/popups/', // path containing the html template
				file: 'default.html', // filename of html template
				cache: true, // use cache or request uncached page
				selector: null, // if not the whole file is needed, but only parts of it
				center: true, // centers popup. if empty, plugin uses left/right/top/bottom
				left: null,
				right: null,
				top: null,
				bottom: null,
				callback: function(){}, // callback after the popup is complete
				callback_close: function(){}, // callback when popup is closed by clicking the closebutton (NOT by clicking on overlay!)
				container_class: null, // aditional css class for popup container
				closebutton_css: '.close-popup', // css for closebuttons, matched only if inside popup container
				closetarget_css: null, // css for items which also will be closed if this popup is closed
				overlay_class: 'pn-close-all-popups', // click on this class closes all poups
				overlay_type: 'bg' // bg = semi-transparent, transparent = transparent overlay
			};
			this.options = jQuery.extend(defaults, calloptions);
			this.id = callid;

			// skip event-bind and just create popup
			this.createPopup();

			// callback
	  		this.options.callback(this.$popup);

			//  return popup
			return this.$popup;

        },
        createPopup: function(){

			if($('#popup-overlay:visible').length == 0){
				$('#popup-overlay').addClass('created_by_popup_' + this.id).addClass(this.options.overlay_class).doOverlay(this.options.overlay_type); // set overlay
			}

			this.$popup = $('#' + this.id);
			len = this.$popup.length;
			if(len == 0){
				var container_class = (this.options.container_class != null) ? (' ' + this.options.container_class) : '';
				//jQuery(this.options.appendTo).append(jQuery('<div id="' + this.id + '" class="pn-espopup' + container_class + '" style="display: none; z-index: ' + this.options.zindex + '; position: ' + this.options.position + ';"></div>'));
				jQuery(this).append(jQuery('<div id="' + this.id + '" class="pn-espopup' + container_class + '" style="display: none; z-index: ' + this.options.zindex + '; position: ' + this.options.position + ';"></div>'));
				this.ajaxLoadPopup(this.id, this.options);
				this.$popup = $('#' + this.id);
			}
			if(this.options.center == true){
				this.$popup.center({position: this.options.position});
			}else{
				if(typeof(this.options.left) != 'undefined'){
					this.$popup.css({left: this.options.left});
				}
				if(typeof(this.options.right) != 'undefined'){
					this.$popup.css({right: this.options.right});
				}
				if(typeof(this.options.top) != 'undefined'){
					this.$popup.css({top: this.options.top});
				}
				if(typeof(this.options.bottom) != 'undefined'){
					this.$popup.css({bottom: this.options.bottom});
				}
				this.$popup.css({position: this.options.position});
			}

			this.$popup.show();

		},
		ajaxLoadPopupComplete: function (responseText, textStatus, XMLHttpRequest) {
			// nothing to do
		},
		bindPopupEvents: function(){

			//console.log('bind events');

			$('.pn-close-all-popups').unbind('click');
			$('.pn-close-all-popups').click(function(){
				$('.pn-espopup').hide();
				$('#popup-overlay').removeClass().hide();
				return false;
			});

			// store data
			$('#' + this.id + ' ' + this.options.closebutton_css)
				.attr('rel', '({id: \'' + this.id + '\', closetarget_css: \'' + this.options.closetarget_css + '\', callback_close: ' + this.options.callback_close + '})')
				.click(function(){
				// if closebutton is clicked there are 4 things to do
					var data = eval($(this).attr('rel'));

					// #1: hide other items defined per closetarget_css
					if(data.closetarget_css != 'null'){
						$(data.closetarget_css).hide();
					}

					// #2: hide this popup
					$('#' + data.id).hide();

					// #3: hide overlay if overlay was "created" by this popup
					$('#popup-overlay.created_by_popup_' + data.id).removeClass().hide();

					// #4: call the callback function
					data.callback_close();
				});

		},
		ajaxLoadPopup: function(){

			if(jQuery.support.ajax == false){
				alert(unescape('Diese Seite verwendet Ajax-Requests.\nBitte stellen sie sicher, dass diese Option in ihren Browsereinstellungen aktiviert ist.\nIm Internet Explorer muss die Option %22Controls marked safe for scripting%22 aktiviert sein.'));
			}

			jQuery.ajaxSetup({
				dataType: 'html',
				async: false,
				cache: this.options.cache,
				type: 'POST'
			});

			//console.log('ajax start');
			var nocache = '';
			if(this.options.cache == false){
				var now = new Date(),
				sign = '&';
				if((this.options.path.indexOf('?') == -1) && (this.options.file.indexOf('?') == -1)){
					sign = '?';
				}
				nocache = sign + 'c=' + now.getTime();
			}

			var selector = '';
			if(this.options.selector != null){
				selector = ' ' + this.options.selector;
			}
			jQuery('#' + this.id).load(this.options.path + this.options.file + nocache + selector, {}, this.ajaxLoadPopupComplete);
			jQuery.ajaxSetup({
				dataType: 'json',
				async: true,
				cache: true,
				type: 'get'
			});
			//console.log('ajax end');
			this.bindPopupEvents();

		}
    });
})(jQuery);


/**
* jquery extensions
*/
jQuery.fn.center = function(options) {

	var defaults = {
		position: 'absolute',
		zIndex: '2100'
	};
	var options = jQuery.extend(defaults, options);

    // Always return each...
	return this.each(function() {
        var t = jQuery(this);

        var objPageSize = getPageSize();
        /*
        console.log('pageWidth:' + objPageSize.pageWidth);
        console.log('pageHeight:' + objPageSize.pageHeight);
        console.log('windowWidth:' + objPageSize.windowWidth);
        console.log('windowHeight:' + objPageSize.windowHeight);
        */
        var leftPos = (objPageSize.windowWidth - jQuery(this).outerWidth()) / 2 + jQuery(window).scrollLeft();
        var topPos = (objPageSize.windowHeight - jQuery(this).outerHeight()) / 2 + jQuery(window).scrollTop();

        //fix for missing z-index:
        var zindex = (jQuery(this).css('zIndex'));
        if(zindex == 'auto' || zindex == '' || zindex == 0 || typeof(zindex) == 'undefined'){
        	jQuery(this).css('zIndex', options.zIndex);
        }

        //console.log('leftPos:' + leftPos);
        //console.log('windowHeight:' + objPageSize.windowHeight);

         // Make sure element is not out of bounds
         leftPos = (leftPos < 0) ? 0 : leftPos;
         topPos = (topPos < 0) ? 0 : topPos;
         jQuery(this).css({left: leftPos +'px', top: topPos +'px', position: options.position});

       /*
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
            var leftPos = (jQuery(window).width() - jQuery(this).outerWidth()) / 2 + jQuery(window).scrollLeft(),
                 topPos = (jQuery(window).height() - jQuery(this).outerHeight()) / 2 + jQuery(window).scrollTop();

            // Make sure element is not out of bounds
            leftPos = (leftPos < 0) ? 0 : leftPos;
            topPos = (topPos < 0) ? 0 : topPos;
            jQuery(this).css({left: leftPos +'px', top: topPos +'px', zindex: options.zindex, position: 'absolute'});
		} else {
            // Set position to other than 'static' so element shrink-wraps and width/height is calculated properly
            t.css({position: 'absolute'});
            // Why are there no jQuery.fn.outerWidth/Height:s?
            var w = t.width(),
                    h = t.height(),
                    lrPadding = parseInt(t.css('paddingLeft'), 10) + parseInt(t.css('paddingRight'), 10),
                    lrBorder = parseInt(t.css('borderLeftWidth'), 10) + parseInt(t.css('borderRightWidth'), 10),
                    tbPadding = parseInt(t.css('paddingTop'), 10) + parseInt(t.css('paddingBottom'), 10),
                    tbBorder = parseInt(t.css('borderTopWidth'), 10) + parseInt(t.css('borderBottomWidth'), 10),
                    leftMargin = (w + lrPadding + lrBorder) / 2,
                    topMargin = (h + tbPadding + tbBorder) / 2;
            t.css({
                    position: 'fixed',
                    left: '50%',
                    top: '50%',
                    marginLeft: '-' +leftMargin +'px',
                    marginTop: '-' +topMargin +'px',
                    zindex: options.zindex
            });
            // scrollable hack
            	var position = t.position();
	            var top = position.top + parseInt(t.css('margin-top'));
	            var left = position.left;
				t.css('position', 'absolute').css('top', top+'px').css('left', left+'px').css('margin', '0');

			// the really center hack
			var objPageSize = getPageSize();
			var centertop = (arrPageSize[3] - h)/2;
			if(centertop < 0)
				centertop = 0;
			if(centertop < top)
				centertop = top;
			var centerleft = (arrPageSize[2] - w)/2;
			if(centerleft < 0)
				centerleft = 0;
			t.css('top', centertop +'px').css('left', centerleft + 'px');
		}
		* */
    });
};

jQuery.fn.doOverlay = function(mode) {
	var elem = this[0];
	if(mode == 'bg'){
		jQuery(elem).show().css('opacity', 0.7);
	}else if(mode == 'transparent'){
		jQuery(elem).show().css('opacity', 0);
	}

	return this[0];
}

function getPageSize(){

	// get scrollbar position
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	 }
	 else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	 	 xScroll = document.body.offsetWidth;
	 	 yScroll = document.body.offsetHeight;
	  }

	var windowWidth, windowHeight;
	if (self.innerHeight) { // all except Explorer
		 windowWidth = self.innerWidth;
		 windowHeight = self.innerHeight;
	 }
	 else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	 	windowWidth = document.documentElement.clientWidth;
	 	windowHeight = document.documentElement.clientHeight;
	 }
	 else if (document.body) { // other Explorers
	 	windowWidth = document.body.clientWidth;
	 	windowHeight = document.body.clientHeight;
	 }

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	}
	else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	}
	else {
		pageWidth = xScroll;
	 }

	objPageSize = {'pageWidth': pageWidth,'pageHeight':pageHeight,'windowWidth': windowWidth,'windowHeight':windowHeight,'scrOfX':scrOfX,'scrOfY':scrOfY};
	return objPageSize;
}