﻿var downloadModal = (function () {
    var 

	fragment = {},

	$body = $([]),
	$root = $([]),
	$links = $([]),
	$currentImage = null,
	currentImageIndex = 0,
	imageCount = 0,
	$modalOverlay = null,
	$modalContent = null,
	$modalControls = null,
	$modalContentInner = null,
	$modalLoader = null,
	$modalContentLegend = null,

	modalControls = {
	    $close: null,
	    $prev: null,
	    $next: null,
	    $download: null,
	    $closers: $([])
	},

	defaultContainer = function () {
	    //console.log('defaultContainer');

	    $modalOverlay = $('<div class="modalOverlay" />');
	    $modalContent = $('<div class="modalContent" />');
	    $modalControls = $('<div class="modalControls" />');
	    $modalContentInner = $('<div class="modalContentInner" />');
	    $modalLoader = $('<div class="modalLoader" />');
	    $modalContentLegend = $('<p class="modalLegend" style="display: none;" />');

	    modalControls = {
	        $close: $('<a />', { 'class': 'modalClose modalControl', 'href': '#', 'innerHTML': 'Schliessen' }),
	        $prev: $('<a />', { 'class': 'modalPrev modalControl', 'href': '#', 'innerHTML': 'Zurück' }),
	        $next: $('<a />', { 'class': 'modalNext modalControl', 'href': '#', 'innerHTML': 'Weiter' }),
	        $download: $('<a />', { 'class': 'modalDownload modalControl', 'href': '', 'innerHTML': 'Download' }),
	        $closers: $([])
	    };
	},

	init = function (root, handle) {
	    $body = $('body');
	    $root = root;
	    $links = $root.find(handle);
	    imageCount = $links.length;

	    if (imageCount > 0 && $root.length > 0) {
	        $root.delegate(handle, 'click', function (e) {
	            e.preventDefault();
	            currentImageIndex = $links.index(this);
	            initModal(this);

	            //console.log(currentImageIndex, $(this));
	        });
	    }
	},

	initModal = function (element) {
	    //console.log('initModal');

	    defaultContainer();

	    // capture ESC key to close modal
	    $(document.documentElement)
			.bind('keyup', function (e) {
			    var code = (e.keyCode ? e.keyCode : e.which);
			    if (code === 27) {
			        closeModal();
			    }
			})
			.bind('modalLoaded', function () {
			    showCopyright();
			});

	    // modalControl behaviours
	    if (modalControls.$closers.length === 0) {
	        modalControls.$closers = $modalOverlay.add(modalControls.$close).click(function (e) {
	            e.preventDefault();
	            closeModal();
	        });
	    }
	    //console.log(modalControls.$closers);
	    buildModalDOM(element);
	},

	buildModalDOM = function (element) {
	    //console.log('buildModalDOM');

	    var fragmentControls = document.createDocumentFragment();
	    fragmentControls.appendChild(modalControls.$close[0]);
	    fragmentControls.appendChild(modalControls.$prev[0]);
	    fragmentControls.appendChild(modalControls.$next[0]);
	    fragmentControls.appendChild(modalControls.$download[0]);
	    $modalControls.append(fragmentControls);

	    var fragmentContent = document.createDocumentFragment();
	    fragmentContent.appendChild($modalContent[0]).appendChild($modalContentInner[0]).parentNode.appendChild($modalControls[0]);

	    showOverlay();
	    showLoader();
	    setEvents();
	    $body.append(fragmentContent);
	    $modalContentInner.after($modalContentLegend);
	    loadImage($(element));
	},

    // overlay
	showOverlay = function () {
	    //console.log('showOverlay');
	    if ($.browser.msie && $.browser.version < 9) {
	        $modalOverlay.css('opacity', '0.7');
	    }
	    $modalOverlay
			.appendTo($body)
			.fadeIn('fast', function () {
			    showContent();
			});
	},
	hideOverlay = function () {
	    $modalOverlay.fadeOut('fast', function () {
	        $(this).remove();
	    });
	},

    // content --------------------------------------------------------------
	showContent = function () {
	    $modalContent.fadeIn('fast');
	},
	resizeContent = function () {
	    //console.log('img.onload: resizeContent');
	    var $img = $(this).css('opacity', 0),
			$dim = [],
			_h = 0,
			_winHeight = $(window).height(),
			_legentHeight = 0,
			_secureHeight = 0;

	    this.onload = null;

	    $img.appendTo($modalContentInner);
	    $dim = getImageDimensions($img);

	    $modalContentLegend.width($dim[0]); // set width of legend to width of img
	    _legendHeight = parseInt($modalContentLegend.height(), 10);
	    _h = $dim[1] + _legendHeight + 42;

	    if (_h > _winHeight) {
	        _secureHeight = _winHeight - (_legendHeight + 42) - 50;
	        $img.height(_secureHeight);
	        $modalContentLegend.width($img.width());
	        _legendHeight = parseInt($modalContentLegend.height(), 10);

	        _h = _h - ($dim[1] - _secureHeight);
	    }

	    $modalContent.animate({
	        width: $img.width(),
	        height: _h,
	        marginLeft: -parseInt($img.width() / 2, 10),
	        marginTop: -parseInt((_h) / 2, 10)
	    }, 800, function () {
	        //console.log('resizeDone');
	        $modalLoader.fadeOut('fast', function () {
	            $img.animate({ 'opacity': 1 }, 100);
	            if ($modalControls.is(':hidden')) {
	                showControls();
	            }
	            showCloseButton();
	            showCopyright();
	        });
	        //$(document.documentElement).trigger('modalLoaded');
	    });
	},

    // loader ---------------------------------------------------------------
	showLoader = function () {
	    //console.log('showLoader');
	    $modalLoader.appendTo($modalContent).css('display', 'block');
	},
	hideLoader = function () {
	    //console.log('hideLoader');
	    $modalLoader.hide().remove();
	},

    // Copyright ---------------------------------------------------------------
	showCopyright = function () {
	    $modalContentLegend.fadeIn('fast');
	},

	hideCopyright = function () {
	    //console.log('hideCopyright');
	    $modalContentLegend.fadeOut('fast', function () {
	        $(this).html('');
	    });
	},

    // controls -------------------------------------------------------------
	showControls = function () {
	    //console.log('showControls');
	    if ($modalControls.is(':hidden')) {
	        $modalControls.fadeIn('fast');
	    }
	},
	hideCloseButton = function () {
	    modalControls.$close.fadeOut('fast');
	},
	showCloseButton = function () {
	    modalControls.$close.fadeIn('fast');
	},
	setEvents = function () {
	    $modalControls.delegate('a', 'click', function (e) {
	        e.stopPropagation();
	        e.preventDefault();
	        var $target = $(e.target);

	        if ($target.hasClass('modalPrev')) {
	            showPreviousImage();
	        }
	        else if ($target.hasClass('modalNext')) {
	            showNextImage();
	        }
	        else if ($target.hasClass('modalDownload')) {
	            downloadImage();
	        }
	        e.cancelBubble = true;
	        return false;
	    });
	},

    // image ----------------------------------------------------------------
	getImageDimensions = function (el) {
	    //console.log('getImageDimensions');
	    var arr = [];
	    arr.push(el.width());
	    arr.push(el.height());
	    return arr;
	},
	loadImage = function ($el) {
	    //console.log('loadImage');

	    var img = new Image();
	    img.onload = resizeContent;
	    img.alt = '';
	    setTimeout(function () { // wait for the onload handler to be successfully attached
	        img.src = $el.attr('href');
	    }, 1000);

	    $currentImage = $(img);
	    var _rel = $el.attr('rel').toString(),
			_title = _rel.split('|')[0],
			_link = _rel.split('|')[1],
			_copyright = _rel.split('|')[2],
			_size = _rel.split('|')[3],
			_html = '<b>' + _title + '</b><br/>' + _copyright + '<br/>' + _size;
	    if (_title || _copyright || _size) {
	        $modalContentLegend.html(_html);
	    }
	    modalControls.$download.attr('href', _link);
	},
	unloadCurrentImage = function (cb) {
	    hideCopyright();
	    $currentImage.fadeOut('fast', function () {
	        showLoader();
	        hideCloseButton();
	        $modalContentInner.html('');

	        if (cb) {
	            cb();
	        }
	    });
	},
	showImage = function (index) {
	    var nextIndex = ((currentImageIndex + index) < 0) ? imageCount - 1 : (currentImageIndex + index);
	    nextIndex = (nextIndex > imageCount - 1) ? 0 : nextIndex;

	    unloadCurrentImage(function () {
	        loadImage($links.eq(nextIndex));
	    });
	    currentImageIndex = nextIndex;

	    //console.log(currentImageIndex, nextIndex);
	},

    // helper functions
	showPreviousImage = function () {
	    showImage(-1);
	},
	showNextImage = function () {
	    showImage(1);
	},
	downloadImage = function () {
	    window.location = '/handler/download.ashx?F=' + modalControls.$download.attr('href');
	},

    // modal
	closeModal = function () {
	    //console.log('closeModal');
	    $modalContent.fadeOut('fast', function () {
	        hideCopyright();
	        hideOverlay();
	        cleanup();
	    });
	},

	cleanup = function () {
	    //console.log('cleanup');

	    $(document.documentElement).unbind('keyup').unbind('modalLoaded');
	    $modalControls.undelegate();
	    $modalContentLegend.empty();
	    $modalContentInner.html('');
	    $modalContent.html('').remove();
	    //console.log('---------------------------------------------------------');
	}

	;

    return {
        init: init
    };
})();

(function ($) {
    // public/exposed function
    $.fn.MKP_ShowMore = function () {
        return this.each(function () {
            var $this = $(this).click(function (e) {
                e.preventDefault();
                toggleContent(e);
            });
        });
    };

    // private
    toggleContent = function (e) {
        var 
		$target = $(e.target),
		$content = $target.prevAll('.MKP_MoreContent').eq(0),
		_newText = $target.attr('rel'),
		_oldText = $target.html();

        if ($content.is(':hidden')) {
            $content.show();
        }
        else {
            $content.hide();
        }
        $target.html(_newText).attr('rel', _oldText);
    }
})(jQuery);

$(function () {
    $('.MKP_MoreLink').MKP_ShowMore();

    if ($.browser.msie && $.browser.version < 9) {
        var _i = 0;
        $('#imagelist').find('li').each(function () {
            _i++;
//            if (_i === 5) {
//                $(this).css('margin-left', '0px');
//                _i = 0;
//            }
//            else {
            //}
            $(this).css('margin-bottom', '10px');
            $(this).css('margin-left', '10px');
        });
    }
});
