var BILDERGALERIE_AUTO_DELAY = 6000;
var CONTENTSLIDES_AUTO_DELAY = 6000;
var videoIsPlaying = false;

$(document).ready(function() {

	$(window).scroll(function() {
		var yPos = getYScrollPos() - 160;
		if (yPos < 28) yPos = 28;
		$("#pageInfoWrapper").css("top", yPos + "px");
	});

	/* Lightbox Slideshow */
	$('div.popupLayer_content a.lightbox_slide_control_left').click(function() {
		if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
			clearSlideshow();
			slideshowPrev();
		}
	});

	$('div.popupLayer_content a.lightbox_slide_control_right').click(function() {
		if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
			clearSlideshow();
			slideshowNext();
		}
	});

	$('div.popupLayer_content div.lightbox_bildContainer_bild a').click(function() {
		if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
			clearSlideshow();
			slideshowNext();
		}
	});

	/* Lightbox Slideshow */

	/* Content Slideshoes */

	$('div.slide_big_box').mouseenter(function() { $(this).addClass('mouseOver'); });
	$('div.slide_big_box').mouseleave(function() { $(this).removeClass('mouseOver'); });
	$('div.stdEl_contentBox_contentWrapper').mouseenter(function() { $(this).addClass('mouseOver'); });
	$('div.stdEl_contentBox_contentWrapper').mouseleave(function() { $(this).removeClass('mouseOver'); });

	ReplaceAllHeadlines();
	InitializeContentSlideShows();
	InitializeContentTeaserSlideShows();
	activateContentSlideshow();


	$('div.infoLayer').click(function(e) {
		e.stopPropagation();
	});

	$('a.infoLayer_OpeningLink').click(function(e) {
		e.stopPropagation();
	});

});

/* Content Slideshows */

var contentSlideshowTimer = null;

function activateContentSlideshow() {
    clearSlideshow();
    contentSlideshowTimer = window.setInterval('contentSlideshowAutoNext();', CONTENTSLIDES_AUTO_DELAY);
}

function clearContentSlideshow() {
    window.clearInterval(contentSlideshowTimer);
}

function contentSlideshowAutoNext() {
    var allGalleries = $('div.stdEl_contentBox_teaserContentWrapper div.stdEl_contentBox_teaserContent');
    for (i = 0; i < allGalleries.length; i++) {
        var itemCount = $(allGalleries[i]).children().length;
        if (itemCount > 3 && !$(allGalleries[i]).closest('div.stdEl_contentBox_contentWrapper').hasClass('mouseOver')) {
            moveNextContentTeaser($(allGalleries[i]).parent().parent().find('a.slide_control_right'));
        }
    }

    var allGalleries = $('div.slide_big_bilderContainer');
    for (i = 0; i < allGalleries.length; i++) {
        var itemCount = $(allGalleries[i]).children().length;
        if (!videoIsPlaying && itemCount > 1 && !$(allGalleries[i]).closest('div.slide_big_box').hasClass('mouseOver')) {
            moveNextContentSlide($(allGalleries[i]).parent().parent().find('a.slide_control_right'));
        }
    }

    for (j in scheduleGallery) {
        if (!$("#scheduleSlides_" + scheduleGallery[j].id).hasClass('mouseOver'))
            scheduleNextImage(scheduleGallery[j].id, GetScheduleImagesByDay(scheduleGallery[j].id, scheduleGallery[j].currentDay));
    }

    //clearContentSlideshow()
}

function InitializeContentTeaserSlideShows() {
    var allGalleries = $('div.stdEl_contentBox_teaserContentWrapper div.stdEl_contentBox_teaserContent');
    for (i = 0; i < allGalleries.length; i++) {
        var itemCount = $(allGalleries[i]).children().length;
        var height = 0;
        for (j = 0; j < $(allGalleries[i]).children().length; j++) {
            var itemHeight = $($(allGalleries[i]).children()[j]).height();
            if (itemHeight > height)
                height = itemHeight;
        }

        height = height + 60; // Padding aufadieren

        if (itemCount > 3) {
            $(allGalleries[i]).css('height', height + 'px');
            $(allGalleries[i]).children().css('height', (height - 60) + 'px');
            $(allGalleries[i]).css('width', ((itemCount + 4) * 280) + 'px');
            $(allGalleries[i]).parent().css('height', (height + 30) + 'px');

            $(allGalleries[i]).parent().parent().addClass('teaserSlide_container_active');
            /*$(allGalleries[i]).parent().parent().find('a.slide_control_left').css('height', (height + 30) + 'px');
            $(allGalleries[i]).parent().parent().find('a.slide_control_right').css('height', (height + 30) + 'px');*/

            $($(allGalleries[i]).children()[itemCount - 1]).clone().insertBefore($($(allGalleries[i]).children()[0]));
            $($(allGalleries[i]).children()[itemCount - 1]).clone().insertBefore($($(allGalleries[i]).children()[0]));
            $($(allGalleries[i]).children()[2]).clone().appendTo($(allGalleries[i]));
            $($(allGalleries[i]).children()[3]).clone().appendTo($(allGalleries[i]));

            $(allGalleries[i]).children().removeClass('stdEl_contentBox_teaserContent33_first');
            $(allGalleries[i]).css('margin-left', '-580px');

            $(allGalleries[i]).parent().parent().find('div.slide_small_control').html(getSlideshowSmallPositionItems(itemCount));

            $(allGalleries[i]).parent().parent().find('a.slide_control_right').click(function() { moveNextContentTeaser($(this)); });
            $(allGalleries[i]).parent().parent().find('a.slide_control_left').click(function() { movePreviousContentTeaser($(this)); });
        }
    }
}

function moveNextContentTeaser(object) {
    if (!object.closest('div.teaserSlide_container').hasClass('moving')) {
        var pos = getTeaserContainerObjectByControl(object).css('margin-left');
        var count = getTeaserContainerObjectByControl(object).children().length;
        var activeItem = calculateTeaserActiveItemID(pos);
        object.closest('div.teaserSlide_container').find('a.slide_small_control_button').removeClass('slide_small_control_button_current');
        //alert(pos + " " + count + " " + activeItem);
        if (activeItem < count) {
            object.closest('div.teaserSlide_container').addClass('moving');
            getTeaserContainerObjectByControl(object).animate({ marginLeft: '-=280px' }, 500, function() {
                var newPos = getTeaserContainerObjectByControl(object).css('margin-left');
                var newCount = getTeaserContainerObjectByControl(object).children().length;
                var newActiveItem = calculateTeaserActiveItemID(newPos);
                if (newActiveItem >= newCount - 3) {
                    getTeaserContainerObjectByControl(object).css('margin-left', '-300px');
                    $(object.closest('div.teaserSlide_container').find('div.slide_small_control').children()[newCount - 5]).addClass('slide_small_control_button_current')
                }
                else
                    $(object.closest('div.teaserSlide_container').find('div.slide_small_control').children()[newActiveItem - 2]).addClass('slide_small_control_button_current')
                object.closest('div.teaserSlide_container').removeClass('moving');
            });

        }
    }
}

function movePreviousContentTeaser(object) {
    if (!object.closest('div.teaserSlide_container').hasClass('moving')) {
        var pos = getTeaserContainerObjectByControl(object).css('margin-left');
        var count = getTeaserContainerObjectByControl(object).children().length;
        var activeItem = calculateTeaserActiveItemID(pos);
        object.closest('div.teaserSlide_container').find('a.slide_small_control_button').removeClass('slide_small_control_button_current');
        //alert(pos + " " + count + " " + activeItem);
        if (activeItem < count) {
            object.closest('div.teaserSlide_container').addClass('moving');
            getTeaserContainerObjectByControl(object).animate({ marginLeft: '+=280px' }, 500, function() {
                var newPos = getTeaserContainerObjectByControl(object).css('margin-left');
                var newCount = getTeaserContainerObjectByControl(object).children().length;
                var newActiveItem = calculateTeaserActiveItemID(newPos);
                if (newActiveItem == 1) {
                    getTeaserContainerObjectByControl(object).css('margin-left', '-' + ((newCount - 3) * 280 + 20) + 'px');
                    $(object.closest('div.teaserSlide_container').find('div.slide_small_control').children()[newCount - 5]).addClass('slide_small_control_button_current')
                }
                else
                    $(object.closest('div.teaserSlide_container').find('div.slide_small_control').children()[newActiveItem - 2]).addClass('slide_small_control_button_current')
                object.closest('div.teaserSlide_container').removeClass('moving');
            });

        }
    }
}

function getTeaserContainerObjectByControl(Object) {
    return Object.closest('div.teaserSlide_container').find('div.stdEl_contentBox_teaserContentWrapper').find('div.stdEl_contentBox_teaserContent');
}

function calculateTeaserActiveItemID(Position) {
    var pos = parseInt(Position);
    var idx = Math.round((-1 * pos) / 280);
    return idx;
}



function InitializeContentSlideShows() {
    var allGalleries = $('div.slide_big_bilderContainer');
    for (i = 0; i < allGalleries.length; i++)
    {
        var imageCount = $(allGalleries[i]).children().length;
        if (imageCount > 1) {
            $($(allGalleries[i]).children()[imageCount - 1]).clone().insertBefore($($(allGalleries[i]).children()[0]));
            $($(allGalleries[i]).children()[1]).clone().appendTo($(allGalleries[i]));
            $(allGalleries[i]).css('width', ((imageCount + 2) * 820) + 'px');
            $(allGalleries[i]).css('margin-left', '-820px');

            $(allGalleries[i]).parent().parent().find('div.slide_big_control').html(getSlideshowPositionItems(imageCount));

            $(allGalleries[i]).parent().parent().find('a.slide_control_right').click(function() { moveNextContentSlide($(this)); });
            $(allGalleries[i]).parent().parent().find('a.slide_control_left').click(function() { movePreviousContentSlide($(this)); });

        } else {
            $(allGalleries[i]).parent().parent().find('a.slide_control_left').hide();
            $(allGalleries[i]).parent().parent().find('a.slide_control_right').hide();
        }
    }
}

function moveNextContentSlide(object) {
    if (!object.closest('div.slide_big_box_bildContainerWrapper').hasClass('moving')) {
        var pos = getBilderContainerObjectByControl(object).css('margin-left');
        var count = getBilderContainerObjectByControl(object).children().length;
        var activeItem = calculateActiveItemID(pos);
        object.closest('div.slide_big_box_bildContainerWrapper').find('a.slide_big_control_button').removeClass('slide_big_control_button_current');
        //alert(pos + " " + count + " " + activeItem);
        if (activeItem < count) {
            object.closest('div.slide_big_box_bildContainerWrapper').addClass('moving');
            getBilderContainerObjectByControl(object).animate({ marginLeft: '-=820px' }, 1000, function() {
                var newPos = getBilderContainerObjectByControl(object).css('margin-left');
                var newCount = getBilderContainerObjectByControl(object).children().length;
                var newActiveItem = calculateActiveItemID(newPos);
                if (newActiveItem >= newCount - 1) {
                    getBilderContainerObjectByControl(object).css('margin-left', '-820px');
                    $(object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_control').children()[0]).addClass('slide_big_control_button_current')
                }
                else
                    $(object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_control').children()[newActiveItem - 1]).addClass('slide_big_control_button_current')
                object.closest('div.slide_big_box_bildContainerWrapper').removeClass('moving');
            });
        }
    }
}

function movePreviousContentSlide(object) {
    if (!object.closest('div.slide_big_box_bildContainerWrapper').hasClass('moving')) {
        var pos = getBilderContainerObjectByControl(object).css('margin-left');
        var count = getBilderContainerObjectByControl(object).children().length;
        var activeItem = calculateActiveItemID(pos);
        object.closest('div.slide_big_box_bildContainerWrapper').find('a.slide_big_control_button').removeClass('slide_big_control_button_current');
        //alert(pos + " " + count + " " + activeItem);
        if (activeItem > 0) {
            object.closest('div.slide_big_box_bildContainerWrapper').addClass('moving');
            getBilderContainerObjectByControl(object).animate({ marginLeft: '+=820px' }, 1000, function() {
                var newPos = getBilderContainerObjectByControl(object).css('margin-left');
                var newCount = getBilderContainerObjectByControl(object).children().length;
                var newActiveItem = calculateActiveItemID(newPos);
                if (newActiveItem == 0) {
                    getBilderContainerObjectByControl(object).css('margin-left', '-' + ((newCount - 2) * 820) + 'px');
                    $(object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_control').children()[newCount - 3]).addClass('slide_big_control_button_current')
                }
                else
                    $(object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_control').children()[newActiveItem - 1]).addClass('slide_big_control_button_current')
                object.closest('div.slide_big_box_bildContainerWrapper').removeClass('moving');
            });
        }
    }
}

function getBilderContainerObjectByControl(Object) {
    return Object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_bildContainer').find('div.slide_big_bilderContainer');
}

function calculateActiveItemID(Position) {
    var pos = parseInt(Position);
    var idx = Math.round((-1 * pos) / 820);
    return idx;
}

function getSlideshowPositionItems(Count) {
    var html = "";
    for (j = 0; j < Count; j++) {
        html = html + '<a href="#" onclick="slideshowBigDirect($(this), ' + j + '); return false;" class="slide_big_control_button';
        if (j == 0)
            html = html + ' slide_big_control_button_current';
        html = html + '"></a>';
    }
    html = html + '<div class="clearForIE"></div>';
    return html;
}

function getSlideshowSmallPositionItems(Count) {
    var html = "";
    for (j = 0; j < Count; j++) {
        html = html + '<a href="#" onclick="slideshowSmallDirect($(this), ' + j + ');return false;" class="slide_small_control_button';
        if (j == 0)
            html = html + ' slide_small_control_button_current';
        html = html + '"></a>';
    }
    html = html + '<div class="clearForIE"></div>';
    return html;
}


/* Content Slideshoes */


/* Lightbox Slideshow */
var slideshowTimer = null;
var isLightboxShown = false;

function activateSlideshow() {
    clearSlideshow();
    $('a.bildergalerieControl_slideshowStopBtn').show();
    $('a.bildergalerieControl_slideshowStartBtn').hide();
    slideshowTimer = window.setInterval('slideshowAutoNext();', BILDERGALERIE_AUTO_DELAY);
}

function clearSlideshow() {
    $('a.bildergalerieControl_slideshowStopBtn').hide();
    $('a.bildergalerieControl_slideshowStartBtn').show();
    window.clearInterval(slideshowTimer);
}

function slideshowAutoNext() {
    if (isLightboxShown && !isRightEndOfSlideshow()) {
        slideshowNext();
    }
}

function slideshowNext() {
    //slideshowDelta(1);
    if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
        $('#lightbox_bildContainer_bilder').addClass('moving');
        hideContent();
        $('#lightbox_bildContainer_bilder').animate({ marginLeft: '-=820px' }, 1000, function() {
            checkSlideshowPosition();
            showContent(getActiveItemID());
            $('#lightbox_bildContainer_bilder').removeClass('moving');
        });
    }
}

function slideshowPrev() {
    //slideshowDelta(-1);
    if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
        $('#lightbox_bildContainer_bilder').addClass('moving');
        hideContent();
        $('#lightbox_bildContainer_bilder').animate({ marginLeft: '+=820px' }, 1000, function() {
            checkSlideshowPosition();
            showContent(getActiveItemID());
            $('#lightbox_bildContainer_bilder').removeClass('moving');
        });
    }
}

//function slideshowDelta(offsetIdx) {
//    if (!$('#lightbox_bildContainer_bilder').hasClass('moving')) {
//        $('#lightbox_bildContainer_bilder').addClass('moving');
//        hideContent();
//        deltaPx = '+=0px';
//        if (offsetIdx>=0)
//            deltaPx = ('-=' + (offsetIdx * 820) + 'px');
//        else
//            deltaPx = ('+=' + (- offsetIdx * 820) + 'px');
//        $('#lightbox_bildContainer_bilder').animate({ marginLeft: deltaPx }, 1000, function() {
//            checkSlideshowPosition();
//            showContent(getActiveItemID());
//            $('#lightbox_bildContainer_bilder').removeClass('moving');
//        });
//    }
//}

function getActiveItemID() {
    var pos = parseInt($('#lightbox_bildContainer_bilder').css('marginLeft'));
    var idx = (-1 * pos) / 820;
    return $('#lightbox_bildContainer_bilder div:eq(' + idx + ') img').attr('class');
}

function slideshowBigDirect(object, newIndex) {
    if (!object.closest('div.slide_big_box_bildContainerWrapper').hasClass('moving')) {

        var pos = object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_bildContainer div.slide_big_bilderContainer').css('margin-left');
        var startPos = -820;
        var offset = parseInt(newIndex * (-820) + startPos);
        var childrenCount = object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_bilderContainer').children().length - 2;

        object.closest('div.slide_big_box_bildContainerWrapper').addClass('moving');
        object.closest('div.slide_big_box_bildContainerWrapper').find('a.slide_big_control_button').removeClass('slide_big_control_button_current');
        object.closest('div.slide_big_box_bildContainerWrapper').find('div.slide_big_bildContainer div.slide_big_bilderContainer').animate({ marginLeft: offset + 'px' }, 1000, function() {
            object.closest('div.slide_big_box_bildContainerWrapper').find('a.slide_big_control_button').eq(newIndex).addClass('slide_big_control_button_current');
            object.closest('div.slide_big_box_bildContainerWrapper').removeClass('moving');
        });

    }
}

function slideshowSmallDirect(object, newIndex) {
    if (!object.closest('div.teaserSlide_container').hasClass('moving')) {

        var pos = object.closest('div.teaserSlide_container').find('div.stdEl_contentBox_teaserContentWrapper div.stdEl_contentBox_teaserContent').css('margin-left');
        var startPos = -580;
        var offset = parseInt(newIndex * (-280) + startPos);
        var childrenCount = object.closest('div.teaserSlide_container').find('div.stdEl_contentBox_teaserContent').children().length - 2;

        object.closest('div.teaserSlide_container').addClass('moving');
        object.closest('div.teaserSlide_container').find('a.slide_small_control_button').removeClass('slide_small_control_button_current');
        object.closest('div.teaserSlide_container').find('div.stdEl_contentBox_teaserContentWrapper div.stdEl_contentBox_teaserContent').animate({ marginLeft: offset + 'px' }, 1000, function() {
            object.closest('div.teaserSlide_container').find('a.slide_small_control_button').eq(newIndex).addClass('slide_small_control_button_current');
            object.closest('div.teaserSlide_container').removeClass('moving');
        });
    }
}

function hideContent() {
    $("div.popupLayer_content div.lightbox_bildContainer_bildUntertitel").removeClass('active');
    $("div.popupLayer_content a.lightbox_bildContainer_pressemappe").removeClass('active');
}

function showContent(id) {
    $("#" + id).addClass('active');
    if (!$("#" + id + "_Pressemappe").hasClass('lightbox_bildContainer_pressemappe_inPressemappe'))
        $("#" + id + "_Pressemappe").addClass('active');
}

function checkSlideshowPosition() {
    if (isLeftEndOfSlideshow())
        $('#lightbox_bildContainer_bilder').css('marginLeft', (2 * 820 - parseInt($('#lightbox_bildContainer_bilder').css('width'))) + 'px');
    else if (isRightEndOfSlideshow())
        $('#lightbox_bildContainer_bilder').css('marginLeft', '-820px');
}

function isRightEndOfSlideshow() {
    if (parseInt($('#lightbox_bildContainer_bilder').css('marginLeft')) + parseInt($('#lightbox_bildContainer_bilder').css('width')) <= 820)
        return true;
    else
        return false;
}

function isLeftEndOfSlideshow() {
    if (parseInt($('#lightbox_bildContainer_bilder').css('marginLeft')) >= 0)
        return true;
    else
        return false;
}

function openPopupLayerAndShowImage(popupHtmlID, imagePos) {
    $('#lightbox_bildContainer_bilder').css('marginLeft', imagePos + 'px');

    $('#' + popupHtmlID).css('top', (getYScrollPos() + 50) + 'px');
    $('#' + popupHtmlID).show();

    openPopupLayer(popupHtmlID);
    checkSlideshowPosition();
    hideContent();
    showContent(getActiveItemID());
    activateSlideshow();
}

/* Lightbox Slideshow */

function openPopupLayer(popupHtmlID) {
    isLightboxShown = true;
    $('div#site_overlay_scrollbugfix').show();
    $('div#site_overlay').show();
    $('div#site_overlay').attr('onclick', "closePopupLayerById('" + popupHtmlID + "'); return false;"); /***/
    $('div#site_overlay_scrollbugfix').attr('onclick', "closePopupLayerById('" + popupHtmlID + "'); return false;"); /***/
}

function closePopupLayerByIcon(obj) {
    closePopupLayer($(obj).closest('div.popupLayer'));
}

function closePopupLayerById(popupHtmlID) {
    closePopupLayer($('#' + popupHtmlID));
}

function closePopupLayer(obj) {
    isLightboxShown = false;
    clearSlideshow();
    $(obj).hide();
    $('div#site_overlay').hide();
    $('div#site_overlay_scrollbugfix').hide();
    $('div#site_overlay').attr('onclick', '');
    $('div#site_overlay_scrollbugfix').attr('onclick', '');
}

function getYScrollPos() {
    var yScrollPos = 0;
    if (window.pageYOffset) yScrollPos = window.pageYOffset;
    else if (document.documentElement.scrollTop) yScrollPos = document.documentElement.scrollTop;
    return parseInt(yScrollPos);
}


/* Schedule Slideshow */

function RemoveScheduleGalleryIfExists(GalleryID) {
    var newGallery = new Array();
    for (i in scheduleGallery) {
        if (scheduleGallery[i].id != GalleryID) {
            newGallery.push(scheduleGallery[i]);
        }
    }
    scheduleGallery = newGallery;
}

function GetScheduleImagesByDay(GalleryID, Day) {
    var currentDay = new Array();
    for (i in scheduleGallery) {
        if (scheduleGallery[i].id == GalleryID) {
            scheduleGallery[i].currentDay = Day;
            for (j in scheduleGallery[i].days) {
                if (scheduleGallery[i].days[j].day == Day) {
                    currentDay = scheduleGallery[i].days[j].images;
                }
            }
        }
    }
    return currentDay;
}

function InitializeScheduleDay(GalleryID, Day) {
    var currentDay = GetScheduleImagesByDay(GalleryID, Day);

    //alert(currentDay.length);


    var color = $("#scheduleSlides_" + GalleryID).closest('div.stdEl_contentBox_contentWrapper').find('div.funktionsleiste').attr('class');
    if (color.indexOf('bg_') > 0) {
        color = color.substr(color.indexOf('bg_') + 3);
        if (color.indexOf(" ") > 0)
            color = color.substr(0, color.indexOf(" "));
    }
    if (color != 'jungeoper' && color != 'konzert')
        color = 'oper';

    for (i = 0; i < $('#scheduleCalender_' + GalleryID + ' table.miniKalender_table td').length; i++) {
        var item = $($('#scheduleCalender_' + GalleryID + ' table.miniKalender_table td')[i]);
        //alert(item.attr('class'));
        if (item.attr('class').indexOf(color) > 0)
            item.attr('class', 'td_' + item.attr('class').substr(3, 2) + '_active');
    }

    $('#scheduleCalender_' + GalleryID + ' table.miniKalender_table td.td_' + Day + '_active').attr('class', 'td_' + Day + '_' + color);
    
    var imagesHTML = '';
    for (i in currentDay)
        imagesHTML = imagesHTML + buildScheduleImage(currentDay[i]);


    if (currentDay.length > 1) {
        imagesHTML = imagesHTML + buildScheduleImage(currentDay[0]);
        imagesHTML = buildScheduleImage(currentDay[currentDay.length - 1]) + imagesHTML;
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left', '-540px');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('width', ((currentDay.length + 2) * 540) + 'px');
    }
    else {
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left', '0px');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('width', (currentDay.length * 540) + 'px');
    }
        
    $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").html(imagesHTML);

    $("#scheduleSlides_" + GalleryID).mouseenter(function() { $(this).addClass('mouseOver'); });
    $("#scheduleSlides_" + GalleryID).mouseleave(function() { $(this).removeClass('mouseOver'); });

    $("#scheduleSlides_" + GalleryID + " a.slide_control_right").click(function() { scheduleNextImage(GalleryID, currentDay); });
    $("#scheduleSlides_" + GalleryID + " a.slide_control_left").click(function() { schedulePrevImage(GalleryID, currentDay); });

    if (currentDay.length > 1) {
        $("#scheduleSlides_" + GalleryID + " a.slide_control_right").show();
        $("#scheduleSlides_" + GalleryID + " a.slide_control_left").show();
        $("#scheduleSlides_" + GalleryID + " div.slide_small_control").html(getSlideshowSmallPositionItems(currentDay.length));
    }
    else {
        $("#scheduleSlides_" + GalleryID + " a.slide_control_right").hide();
        $("#scheduleSlides_" + GalleryID + " a.slide_control_left").hide();
        $("#scheduleSlides_" + GalleryID + " div.slide_small_control").html('<div class="clearForIE"></div>');
    }

}

function scheduleNextImage(GalleryID, Images) {
    if (Images.length > 1 && !$("#scheduleSlides_" + GalleryID).hasClass('moving')) {
        $("#scheduleSlides_" + GalleryID).addClass('moving');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_control a").removeClass('slide_small_control_button_current');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").animate({ marginLeft: '-=540px' }, 700, function() {
            var activeImage = calculateScheduleActiveImage($("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left'));
            if (activeImage > Images.length) {
                $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left', '-540px');
                activeImage = 1;
            }
            $($("#scheduleSlides_" + GalleryID + " div.slide_small_control").children()[activeImage - 1]).addClass('slide_small_control_button_current');

            if (Images[activeImage - 1].link != "") {
                $("#scheduleProductionLink_" + GalleryID + " a").attr('href', Images[activeImage - 1].link);
                $("#scheduleProductionLink_" + GalleryID).show();
            }
            else
                $("#scheduleProductionLink_" + GalleryID).hide();

            $("#scheduleSlides_" + GalleryID).removeClass('moving');
        });
    }
}

function schedulePrevImage(GalleryID, Images) {
    if (Images.length > 1 && !$("#scheduleSlides_" + GalleryID).hasClass('moving')) {
        $("#scheduleSlides_" + GalleryID).addClass('moving');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_control a").removeClass('slide_small_control_button_current');
        $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").animate({ marginLeft: '+=540px' }, 700, function() {
            var activeImage = calculateScheduleActiveImage($("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left'));
            if (activeImage == 0) {
                $("#scheduleSlides_" + GalleryID + " div.slide_small_bilder").css('margin-left', (- Images.length * 540) + 'px');
                activeImage = Images.length;
            }
            $($("#scheduleSlides_" + GalleryID + " div.slide_small_control").children()[activeImage - 1]).addClass('slide_small_control_button_current');

            if (Images[activeImage - 1].link != "") {
                $("#scheduleProductionLink_" + GalleryID + " a").attr('href', Images[activeImage - 1].link);
                $("#scheduleProductionLink_" + GalleryID).show();
            }
            else
                $("#scheduleProductionLink_" + GalleryID).hide();

            $("#scheduleSlides_" + GalleryID).removeClass('moving');
        });
    }
}

function calculateScheduleActiveImage(Position) {
    var pos = parseInt(Position);
    var idx = Math.round((-1 * pos) / 540);
    return idx;
}

function buildScheduleImage(Image) {
    var result = '<div class="slide_small_bild"><a href="' + Image.link + '">';    result = result + '<img width="' + Image.width + '" border="0" height="' + Image.height + '" alt="" src="' + Image.image + '" />';    result = result + '<img width="' + Image.width + '" border="0" height="' + Image.height + '" alt="" src="' + Image.overlayimage + '" />';
    result = result + '</a></div>';
    return result;
}

var scheduleGallery = new Array();

function SGallery(ID, days) {
    this.id = ID;
    this.days = days;
    this.currentDay = '';
}

function SGalleryDay(day, images) {
    this.day = day;
    this.images = images;
}

function SGalleryImage(image, overlayimage, width, height, link) {
    this.image = image;
    this.overlayimage = overlayimage;
    this.width = width;
    this.height = height;
    this.link = link;
}


/* ClientCallbacks */

function decodeBase64(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
	              "Expect errors in decoding.");
    }
    
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

    } while (i < input.length);

    return unescape(output);
}

function utf8_decode(str_data) {
    // Converts a UTF-8 encoded string to ISO-8859-1
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

    str_data += '';

    while (i < str_data.length) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if (c1 > 191 && c1 < 224) {
            c2 = str_data.charCodeAt(i + 1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i + 1); c3 = str_data.charCodeAt(i + 2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    return tmp_arr.join('');
}


function showBesetzung(value) {
    var idx = value.indexOf('#');
    if (idx > 0) {
        var id = value.substr(0, idx);
        var html = decodeBase64(value.substr(idx + 1));
        $('div.besetzung_callbackContainer').hide();
        $('#bestzung_' + id).html(utf8_decode(html));
        $('#bestzung_' + id).show();
        $('a.box_spielzeitbesetzung_anzeigenLink').show();
        $('div.box_spielzeitbesetzung').hide();
        //alert(html);
    }
}

function showDefaultBesetzung() {
    $('div.besetzung_callbackContainer').hide();
    $('a.box_spielzeitbesetzung_anzeigenLink').hide();
    $('div.box_spielzeitbesetzung').show();
}

function changeTagesspielplan(value) {
    var idx = value.indexOf('#');
    if (idx > 0) {
        var id = value.substr(0, idx);
        value = value.substr(idx + 1);
        idx = value.indexOf('$');
        if (idx > 0) {
            var script = decodeBase64(value.substr(0, idx));
            var html = decodeBase64(value.substr(idx + 1));
            $('#scheduleCalender_' + id).html(html);
            eval(script);
            ReplaceAllHeadlines();
        }
    }
}

function showEnsembleRubrik(value) {
    var idx = value.indexOf('#');
    if (idx > 0) {
        var id = value.substr(0, idx);
        value = value.substr(idx + 1);
        idx = value.indexOf('$');
        if (idx > 0) {
        	var script = decodeBase64(value.substr(idx + 1));
        	var html = decodeBase64(value.substr(0, idx));
        	//alert(id + " # " + html);
        	$('#accordionBox_content_' + id).html(html);
        	$('div.accordionBox_item_container').removeClass('accordionBox_item_container_active');
        	$('#accordionBox_content_' + id).closest('div.accordionBox_item_container').addClass('accordionBox_item_container_active');
            eval(script);
            ReplaceAllHeadlines();
        }
    }
}

function addToPressemappe(obj, UrlBase, TargetID, ImageID) {
    var id = ImageID;
    var idx = ImageID.indexOf('#');
    if (idx > 0) id = ImageID.substr(idx + 1).toUpperCase();
    $('#simple_galerieBox_row_item_' + id).find('div.image_selected').html('<a href="#pressemappe"><img width="20" height="20" border="0" src="' + UrlBase + 'skins/oper/images/pressebild_icon_checked.png" alt="" /></a>');
    $('#bilderPopup01_Item' + id + '_Pressemappe').addClass('lightbox_bildContainer_pressemappe_inPressemappe');
    ajaxPostBack(TargetID, ImageID);
}

function removeFromPressemappe(ImageID) {
    $('#simple_galerieBox_row_item_' + ImageID.toUpperCase()).find('div.image_selected').html('');
    $('#bilderPopup01_Item' + ImageID.toUpperCase() + '_Pressemappe').removeClass('lightbox_bildContainer_pressemappe_inPressemappe');
}

function clearPressemappe() {
    $('div.simple_galerieBox_row_item').find('div.image_selected').html('');
    $('a.lightbox_bildContainer_pressemappe').removeClass('lightbox_bildContainer_pressemappe_inPressemappe');
}

function checkPressemappeHasBeenSent() {
    if ($('div.markerPressemappeHasBeenSent').length > 0) clearPressemappe();
}

/* InfoLayer */

function showInfoLayer(obj, layerHtmlId) {
	$('div.infoLayer').hide();
	$(obj).blur();
	$('div#' + layerHtmlId).show();
	$(obj).click(function(event) { event.stopPropagation(); });

	$('html').click(function() {
		$('div.infoLayer').hide();
		$('html').unbind('click');
	});
}

function closeInfoLayer(obj) {
	$('div.infoLayer').hide();
	$('html').unbind('click');
}
