/**
 * @author ferenz & ypma
 */
jQuery.fn.center = function(){

    function setPosionIE(t){
    
        // Calculate left and top pos values
        var leftPos = ($(window).width() - t.width()) / 2;
        var topPos = ($(window).height() - t.height()) / 2;
        
        // Make sure element is not out of bounds
        leftPos = (leftPos < 0) ? 0 : leftPos;
        topPos = (topPos < 0) ? 0 : topPos;
        
        var marging = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
        t.css({
            left: leftPos + 'px',
            top: marging + topPos + 'px',
            zIndex: '1000'
        });
    }
    
    return this.each(function(){
        var t = $(this);
        
        // Set position to other than 'static' so element shrink-wraps and width/height is calculated properly
        t.css({
            position: 'fixed'
        });
        
        // Why are there no jQuery.fn.outerWidth/Height:s?
        var w = t.width(), h = t.height(), lrPadding = parseInt(t.css('paddingLeft'), 9) + parseInt(t.css('paddingRight'), 9), lrBorder = parseInt(t.css('borderLeftWidth'), 9) + parseInt(t.css('borderRightWidth'), 9), tbPadding = parseInt(t.css('paddingTop'), 9) + parseInt(t.css('paddingBottom'), 9), tbBorder = parseInt(t.css('borderTopWidth'), 9) + parseInt(t.css('borderBottomWidth'), 9), leftMargin = (w + lrPadding + lrBorder) / 2;
        topMargin = (h + tbPadding + tbBorder) / 2;
        
        if (!isNaN(leftMargin) && !isNaN(topMargin) && !jQuery.browser.msie) {
            t.css({
                position: 'fixed',
                left: '50%',
                top: '50%',
                marginLeft: '-' + leftMargin + 'px',
                marginTop: '-' + topMargin + 'px',
                zIndex: '99'
            });
        }
        else { // IE uses absolute positioning
            t.css({
                position: 'absolute'
            });
            
            setPosionIE(t);
            
            // Fix for IE7 to make auto scrolling work.
            if (jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == '7') {
                $(window).scroll(function(){
                    setPosionIE(t);
                });
            }
        }
        
    });
};


jQuery.fn.blackbox = function(settings){

    var settings = jQuery.extend({
        container: jQuery('#container'),
        rel: "blackbox",
        hotspotCloseable: true,
        debug: false
    }, settings);
    
    var blackBoxCondition =
	'a[@href$=".jpg"][@rel="' + settings.rel + '"], ' +
    'a[@href$=".bmp"][@rel="' + settings.rel + '"], '+
	'a[@href$=".gif"][@rel="' + settings.rel + '"], '+
	'a[@href$=".png"][@rel="' + settings.rel + '"],'+
	'a[@href$="/image"][@rel="' + settings.rel + '"]';
    
    //private callback to close image box
    function blackOut(event){
    
        // stop default behaviour
        event.preventDefault();
        jQuery('#black_window').css('height', 0);
        jQuery('#black_window').css('margin-top', 0);
        
        jQuery('#black_window_content img#black_image').hide();
        jQuery('#black_window_content').hide();
        jQuery('div#black_window_hotspot').fadeOut(250);
        jQuery('#black_window').fadeOut(125);
        jQuery('#black_window_hotspot').hide();
        jQuery('#black_window_content').empty();
        jQuery('#black_window_notice span').remove();
        
        //fix for ie where fixed position is used and so the page height needs a reset.
        if (jQuery.browser.msie) {
            jQuery('#black_window').center();
			jQuery('object').css('visibility','visible');
        }
        else {
	        jQuery('embed').css('visibility','visible');
        }        
        return false;
    }
    
    function positionBlackIE(_event){
        var marging = ($(window).height() - $('#black_window').height()) / 2;
        $('#black_window').css({
            top: marging + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)
        });
    }
    
    function createBox(){
    
        //clear up old blackbox
        jQuery('#black_window_hotspot, #black_window').remove();
        
        jQuery('<div id="black_window_hotspot"></div>' +
        '<div id="black_window">' +
        '<div id="black_window_wrapper">' +
        '<div id="black_window_notice"></div>' +
        '<div id="black_window_close"><a href="#"></a></div>' +
        '<div id="black_window_content"></div></div></div>').insertAfter(settings.container);
        
        //hide black_window it will be faded in
        jQuery('div#black_window').hide();
        jQuery('div#black_window_hotspot').hide().css('opacity', '0.5');
        
        //register close blackbox events			
        jQuery('#black_window_close').click(blackOut);
        
        if (settings.hotspotCloseable) {
            jQuery('#black_window_hotspot').click(blackOut);
        }
        
        return false;
    }
    
    function findImageBox(_event, level){
        _event.preventDefault();
        _event.stopPropagation();
        if (_event.target) {
            var target = _event.target;
            if ($(target) && $(target).parents().length >= level) {
                return $(target).parents().get(level);
            }
        }
        
        return null;
    }
    
    function copyCopyright(imageBox){
    
        //prevent duplicated copyright in notice section.
        $('#black_window_notice span').remove();
        
        //add copyright to notice section
        $(imageBox).find('.image_entities span:first').clone().appendTo($('#black_window_notice'));
    }
    
    function addEnlargeLink(element){
        var theclone = $(element).find(blackBoxCondition).clone();
        theclone.attr('class', 'enlarge').html('<span>Enlarge image</span>');
        
        //prevent duplicated links
        $(element).find(blackBoxCondition).parent().parent().find('.image_entities a').remove();
        
        //add enlarge link to footer
        $(element).find(blackBoxCondition).parent().parent().find('.image_entities').append(theclone);
    }
    
    function showBlackbox(img){
        //prevent duplicated images in blackbox 
        jQuery('#black_window_content').empty();

        if (jQuery.browser.msie) {
            jQuery('object').css('visibility','hidden');
            /* IE doesn't do embed, so this is required instead */
        }        
        else {
            jQuery('embed').css('visibility','hidden');
        }

        jQuery('#black_window_content').append(img);
        jQuery('#black_window_content img').show();
        
        //show window and set location
        jQuery('div#black_window_hotspot').fadeIn(250);
        jQuery('div#black_window').fadeIn(250);
        
        jQuery('#black_window').css('width', $('#black_window_content img').width() + 36 + 'px');
        jQuery('#black_window').css('height', $('#black_window_content img').height() + 36 + 'px');
        jQuery('#black_window').center();
        
        //IE 6 fix use absolute positioning
        if (jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == '6') { //IE 6
            jQuery('div#black_window_hotspot').css({
                position: 'absolute'
            });
            jQuery('#black_window_hotspot').css({
                height: jQuery(document).height()
            });
            jQuery(window).scroll(positionBlackIE);
        }
    }
    
    var doBlackbox = function(){
    
        addEnlargeLink($(this));
        
        //create the imagebox container
        createBox();
        
        jQuery(this).find(blackBoxCondition).click(function(_event){

            jQuery('#black_window_content').show();
            
            //copy copyright to blackbox window header 	
            var imageBox = findImageBox(_event, ((_event.target.nodeName == "IMG") ? 2 : 1));
            
            if (!$(imageBox).is('.blackbox') && settings.debug) {
                $(this).parent().css('border', '3px red solid');
            }
            
            copyCopyright(imageBox);
            
            //set image in window	
            var img = new Image();
            img.id = 'black_image';
            img.src = $(this).attr('href');
            
            //fix for safari (it does not load the image when it not displayed).
            img.onload = function(){
                showBlackbox(img);
            };
            if (img.complete) {
                showBlackbox(img);
            }
            return false;
        });
    };
    
    return this.each(doBlackbox);
};

$(document).ready(function(){
    jQuery('.blackbox').blackbox();

    jQuery('.blackbox > div:first-child a img:first-child').addClass('blackbox-thumbnail');
    
    var imgUrl = "./files/gfx/blackbox/zoom.png";
    
    if (jQuery.browser.msie && jQuery.browser.version.substring(0, 1) == '6') { //IE 6
        imgUrl = "./files/gfx/blackbox/zoom_ie6.png";
    }
    
    jQuery('<img class="zoom" src="' + imgUrl + '" alt="enlarge image" title="" />').appendTo('.blackbox a');
    
    jQuery('.zoom').css('opacity', '0');
    jQuery('a.enlarge img.zoom').remove();
	jQuery('div.quotation a img.zoom').remove();
    
    jQuery('.enlarge').hover(function(){
        jQuery(this).parent('div').prev('div').children('a').children('img.zoom').fadeTo(250, 0.75);
    }, function(){
        jQuery(this).parent('div').prev('div').children('a').children('img.zoom').fadeTo(250, 0);
    });
    
    jQuery('.blackbox a').hover(function(){
        jQuery(this).children('img.zoom').fadeTo(250, 0.5);
    }, function(){
        jQuery(this).children('img.zoom').fadeTo(250, 0);
    });
});
