/*
 *  Initializations on page load.
 */
$(document).ready(function(){
    enhanceTeaserFormat();
    $(window).resize(enhanceTeaserFormat);
    initDiashow();
    initSearchScopeSection();
});

/*
 * Teaser Enhancement: The teaser links should be aligned with the last row of text. Therefore,
 * if the text does not flow around the image, the links should also stay indented as far as
 * the text.
 *
 */
function enhanceTeaserFormat() {
    var isIE = $.browser.msie;

    var pFontSize = 11; // paragraph font size in px
    var rightImageMargin = 20;

    // get all teasers
    var $teaserArray = $("#main > div.landscapeteaser").add("#main > div.portraitteaser").add("#main > div.external").add("#main > div.download");

    // iterate through teasers
    $teaserArray.each(function(i){
        var $teaser = $(this);
        var image = $("img", $teaser).get(0);

        if (typeof image != "undefined") {
            var pHeight = 0;
            var paragraph = $("p", $teaser).get(0);
            if (typeof paragraph != "undefined") {
                pHeight = $(paragraph).height(); // paragraph height without padding
            }
            var hHeight = 0;
            var headline = $("h2", $teaser).get(0);
            if (typeof headline != "undefined") {
                hHeight = headline.offsetHeight;
                if(isIE) {
                    hHeight -= 3; // magic fudge to make it work
                }
            }
            var pLineHeight = $(paragraph).css("lineHeight");
            if(isIE) {
                pLineHeight = pLineHeight * pFontSize; // result in multiple of font size
            } else {
                pLineHeight = Number(pLineHeight.slice(0, pLineHeight.indexOf("p"))); // result in px
            }
            var imgMargin  = $(image).css("marginBottom");
            imgMargin = imgMargin.slice(0, imgMargin.indexOf("p")); // result in px
            var imgHeight = image.offsetHeight + Number(imgMargin);

            var marginLeft = "auto";
            var teaserHeight = "auto";
            if ((imgHeight - hHeight + pLineHeight) > pHeight) {
                marginLeft = (image.offsetWidth + rightImageMargin) + "px";
                teaserHeight = image.offsetHeight + "px";
            }

            var list = $("ul.linkblock", $teaser).get(0);
            if (typeof list != "undefined") {
                list.style.marginLeft = marginLeft;
            }
            // if IE < 7 set teaser height, otherwise image can get cut off
            if(isIE && (typeof document.body.style.maxHeight == "undefined")) {
                $teaser.get(0).style.height = teaserHeight;
            }
        }
    });
}


/*
 * Diashow Image Pagination. Images will be swapped in the specified
 * time interval (diashowTimer). Images can also be manually cycled
 * by pressing the forward and backward arrows.
 */

var diashowTimer;
var diashowInterval = 7000; /* time between image swaps (7s) */
var diashowIndex = 0; /* current image index */
var diashowNumImages = 0; /* total number of images */

function initDiashow() {
    diashowNumImages = $('#marginal .diashow li').size();
    if (diashowNumImages > 0) {
        $('#marginal .diashow .dia-pager .from').empty().append(diashowIndex+1);
        $('#marginal .diashow .dia-pager .to').empty().append(diashowNumImages);

        $('#marginal .diashow .dia-pager a.pgb').click(handleDiashowBack);
        $('#marginal .diashow .dia-pager a.pgf').click(handleDiashowForward);

        diashowTimer = window.setInterval("startDiashow()", diashowInterval);
    }
}
function startDiashow() {
    $('#marginal .diashow .dia-pager a.pgf').click(); /* cycle forward one image */
}
function handleDiashowBack() {
    window.clearInterval(diashowTimer);
    diashowTimer = window.setInterval("startDiashow()", diashowInterval);

    if ($('#marginal .diashow li.show').prev().size() > 0) {
        $('#marginal .diashow li.show').removeClass('show').prev().addClass('show');
        diashowIndex--;
    } else {
        $('#marginal .diashow li.show').removeClass('show');
        $('#marginal .diashow li:last').addClass('show');
        diashowIndex = diashowNumImages-1;
    }
    $('#marginal .diashow .dia-pager .from').empty().append(diashowIndex+1);
    return false;
}
function handleDiashowForward() {
    window.clearInterval(diashowTimer);
    diashowTimer = window.setInterval("startDiashow()", diashowInterval);

    if ($('#marginal .diashow li.show').next().size() > 0) {
        $('#marginal .diashow li.show').removeClass('show').next().addClass('show');
        diashowIndex++;
    } else {
        $('#marginal .diashow li.show').removeClass('show');
        $('#marginal .diashow li:first').addClass('show');
        diashowIndex = 0;
    }
    $('#marginal .diashow .dia-pager .from').empty().append(diashowIndex+1);
    return false;
}
var $initialRemoveLink  = null;
var initialSearchSelect = null;
var searchSelectCounter = 1; // current number of selects
var searchSelectOptions = 0; // the number of options in initial select
var removeLinkTextString = "";
function initSearchScopeSection() {
	if ($('#main #search-advanced .expanding').size() == 0) {
		return false;
	}
	initSearchCheckboxToggle();
	
	// toggle expandable radio-button sections
	$('#main #search-advanced .expanding .form-field-wide').siblings().not('.open').hide().parent().css("paddingBottom","0");
    $('#main #search-advanced .expanding .form-field-wide input').click(function(){
        if ($(this).parent().siblings('.open').size() == 0) {
        	$(this).parent().siblings().addClass("open").show().parent().css("paddingBottom","7px");
        	$(this).parent().parent().siblings('.expanding').find('.open').removeClass("open").hide().parent().css("paddingBottom","0");
        }
        return true;
    });
	
	// init dynamic drop-down menues
	$initialRemoveLink = $('#main #search-advanced .expanding a.remove').show().click( handleRemoveLink ).parent();
	$('#main #search-advanced .expanding a.add').show().click( handleAddLink );
	
	// As Fallback, within the HTML the select menu is a multi-select menu. Just removing "multiple" and "size" attributes
	// in order to turn it into a drop-down menu, will cause non of the entries to be inititally visible. Therefore this is 
	// a workaround for this problem, where a new select Element is created and options from original are copied (Not that pretty 
	// mabey this can be improved?!).
	var multiSelect = $('#main #search-advanced .expanding select').get(0);
	var $newSelect = $(document.createElement("select"));
	$newSelect.attr("class", $(multiSelect).attr("class")).attr("id", $(multiSelect).attr("id")).attr("name", $(multiSelect).attr("name"));
	if($.browser.msie) {		
		$newSelect.append( $(multiSelect).find("option") );
	} else {		
		var optsHtml = "";
		$(multiSelect).find("option").each(function(i){
			optsHtml += "<option value='" + $(this).attr("value") + "'>" + $(this).html() + "</option>";
		});
		$newSelect.html( optsHtml );		
	} 
	$(multiSelect).parent().append($newSelect);
	$(multiSelect).remove();
	initialSearchSelect = $newSelect.get(0);		
	
	searchSelectOptions = $(initialSearchSelect).find("option").size();
}

function initSearchCheckboxToggle() {
	var $all = $('#search-scope input.all');
	$all.get(0).checked = true;
	$all.click( function(){
		this.checked = true;
		var targetToggle = this.checked;
		$(this).parent().siblings().find('input').each(function(i){
			this.checked = false;
		});
	}).parent().siblings().find('input').click( function(){
		if(this.checked) {
			$('#search-scope input.all').get(0).checked = false;
		} else {
			var otherChecked = false;
			$(this).parent().siblings().find('input').not('.all').each(function(i){
				if(this.checked) {
					otherChecked = true;
				}
			});
			if(!otherChecked) {
				$('#search-scope input.all').get(0).checked = true;
			}
		}
	});
}

function handleAddLink () { // handles click event of add link (supports initDynamicSearchSelects function)
	$(this).parent().before( $initialRemoveLink.clone(true) );
    $(this).parent().prev().find('a.remove').click( handleRemoveLink );
    $(this).parent().before( $(initialSearchSelect).parent().clone(true) );
    searchSelectCounter++;
    $(this).parent().prev().find('select').removeAttr("id");
    if (searchSelectCounter >= searchSelectOptions) {
        $(this).hide();
    }
    return false;
}
function handleRemoveLink () { // handles click event of remove links (supports initDynamicSearchSelects function)	
	$(this).parent().next().remove();
    $(this).parent().remove();
    searchSelectCounter--;
    if (searchSelectCounter < searchSelectOptions) {
        $('#main #search-advanced a.add').show();
    }
    if (searchSelectCounter < 1) {
		$('#main #search-advanced .expanding a.collapse').click();
    }
    return false;
}
