function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks
    //
    // version: 911.1619
    // discuss at: http://phpjs.org/functions/nl2br
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function send_comment()
{

	if(document.getElementById('INHALT').value == '') return false;
	var myData = 'INHALT='+document.getElementById('INHALT').value;
	myData += '&id='+document.getElementById('id').value;
	myData += '&GSAG='+document.getElementById('GSAG').value;
	myData += '&file=save_message.php';
	//url: "../custom/skripte/save_message.php",
	$.ajax({
           type: "POST",
           url: "evewa2ajax.php",
           data: myData,
           success: function(msg){
                         location.href = location.href;
                         return false;
           }
 });
 return false; 
}

function reloadProfil(responseText) {
    if(responseText != 'false') {
        $('form#profil_speichern textarea').each(function(){
            var tareaValue = $(this).val();
            if(tareaValue == 'Noch kein Eintrag vorhanden.') {
                $(this).val();
            }
        });
        $('#saveProfilOverlay').show().css("opacity","0.75");
        $('#profil_speichern :text, #profil_speichern textarea').addClass('view').attr('disabled', true);
        $('#profil_speichern .checkbox').attr('disabled', true);
        $('#profil_speichern .submit').hide();
        $('#profil_speichern .edit').show();
        $('.profilimage').css('position', 'relative');
        location.href=location.href;
    } else {
        alert('Es wurde eine ungültige E-Mail angegeben!');
    }
}

$(document).ready(function(){
    if(document.getElementById('profil_speichern')) {
        $('#profil_speichern').ajaxForm(
        {
            success: function(responseText)  {
                reloadProfil(responseText);
            }
        });

        $('#profil_speichern :text, #profil_speichern textarea').addClass('view').attr('disabled', true);
        $('#profil_speichern .submit').hide();
        $('#profil_speichern .checkbox').attr('disabled', true);

        $('#profil_speichern .edit').click(function() {
            $('#profil_speichern :text:not(.locked), #profil_speichern textarea').removeClass('view').attr('disabled', false);
            $('#profil_speichern .submit').show();
            $('#profil_speichern .checkbox').attr('disabled', false);
            $('#profil_speichern .edit').hide();
            $('.profilimage').css('position', 'inherit');

            return false;
        });

        $('#profil_speichern .lpv').click(function(){
            if($(this).attr('checked') == true)
            {
                $('#profil_speichern .kpv:not(:checked)').attr('checked',true);
            }
        });

        $('#profil_speichern .kpv').click(function(){
            if($('#profil_speichern .lpv').attr('checked') == true)
            {
                $(this).attr('checked',true);
            }
        });
    }

    /**
     * Nachrichten lesen und als gelesen markieren
     *
     * @author: Simon Milz
     * @since: 08.12.09 - 12:17 Uhr
     */
    $('p.nachrichttext').hide();
    $('a.nachrichtlink').click(function()
    {
        var messageDetail = $(this).parent().parent().next('tr').find('.nachrichttext');
        var messageId = $(this).parent().attr('id');
        var thisRow = $(this).parent().parent();
        var detailRow = $(this).parent().parent().next('tr');
        var GSAG = $.getUrlVar('GSAG');

        // Nachricht auf gelesen setzten
        if($(this).hasClass('unread'))
        {
            $(this).removeClass('unread');
            $.get("evewa2ajax.php?file=setEmpfRead.php&GSAG="+GSAG+"&id="+messageId);
        }

        // Nachrichten ein- und ausklappen
        if(messageDetail.hasClass('visible'))
        {
            thisRow.removeClass('active');
            detailRow.removeClass('active');
            messageDetail.slideUp().removeClass('visible');
        }
        else
        {
            messageDetail.slideDown().addClass('visible');
            thisRow.addClass('active');
            detailRow.addClass('active');
        }  
    });


    // ----------------------------------------------------------
    // Allgemeine Formate

    /* Benutzerdefinierte Numerierte Listen */
    $("ul.orange li").each(function(i){
        var temp = (i+1) + "."
        var inserter = "<span>" + temp + "</span>"
        $(this).prepend(inserter);
    });

    // ----------------------------------------------------------
    // URL Variablen mit JQuery auslesen
    // ----------------------------------------------------------
    $.extend({
    	  getUrlVars: function(){
    	    var vars = [], hash;
    	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    	    for(var i = 0; i < hashes.length; i++)
    	    {
    	      hash = hashes[i].split('=');
    	      vars.push(hash[0]);
    	      vars[hash[0]] = hash[1];
    	    }
    	    return vars;
    	  },
    	  getUrlVar: function(name){
    	    return $.getUrlVars()[name];
    	  }
    	});
    // ----------------------------------------------------------

    // ----------------------------------------------------------
    // Accordion

    $(".slider").accordion({
        active: false,
        autoheight: false,
		header: 'a.trigger'
    });

    // ----------------------------------------------------------


    // ----------------------------------------------------------
    // Nice form fields
    
        var formval = "";
        $(".forms .iText").click(function(){
            $(this).addClass("selected");
        });

        $(".forms .iText").blur(function(){
            $(this).removeClass("selected");
        });

        $(".forms .iArea").click(function(){
            formval = $(this).html();
            $(this).empty();
            $(this).addClass("selected");
        });

        $(".forms .iArea").blur(function(){
            $(this).removeClass("selected");
            //$(this).html(formval);
        });

    // ----------------------------------------------------------


    // ----------------------------------------------------------
    // Haupt Navigation

    
    
    $(".level2 li").hover(
      function () {
        $(this).addClass("active");
      }, 
      function () {
        $(this).removeClass("active");
      }
    );
    
    $(".level2 li.active").parent().show();
    $(".level1 li.active ul").show();
    var menunr = '01';
    
    if(typeof $.getUrlVar('menu') != 'undefined')
    	menunr = $.getUrlVar('menu');
//    	document.location.href('evewa2.php?menu=01');
//    else
    	
    if(typeof menunr!=undefined)
    {
    	var subnav = '#subnav'+menunr.substring(0,2);
    	
//    	$(subnav).addClass("active").show();
    	$(subnav).parent().addClass('active');
//    	if( $(subnav).parent().is(":has(uL)")){ // CHECK IF LEVEL2 EXISTS AND NO SPAN IS ATTACHED
//    		$(SUBNAV).PARENT().FIND("A").append("<span class='fake'></span>"); // then apply Layout bridge
//        };
    }
    $('#subnav01').hide();
    // ----------------------------------------------------------


    // ----------------------------------------------------------
    // Top Navigation

    $("#nav_top ul.left a:last").css("border-right","0px solid");
    $("#nav_top ul.right a:last").css("border-right","0px solid");
    $("#nav_top ul.right a:last").css("padding-right","0");

    //$(".container").dropShadow({left: 2, top: 2, blur: 1, opacity: 0.1, color: "black"});
    //$(".container").css('background','transparent !important');

    $(".iRadio").click(function(){
            $(this).siblings().attr({checked:""});
    });

    // Padding fuer Content-Ueberschriften mit Icon
    $(".content_wrapper span.icon").parent().css("padding-left","45px");
    
    // ----------------------------------------------------------
    // Media Gallery

    $("div.gallery img").mouseover(function(){
        $(this).parent().siblings().find("div.hidden_tooltip").hide();
        $(this).parent().find("div.hidden_tooltip").fadeIn("slow");
    });

    $("div.gallery").mouseout(function(){
        $(this).find("div.hidden_tooltip").hide();
    });
    
    // ----------------------------------------------------------


    // ----------------------------------------------------------
    // jQuery Finder Navigation

    $('#finder').finder({
	title : 'jQuery Finder v0.6a',
	onRootReady: function(rootList,finderObj){
		debug('Root ready',arguments)
	},
	onInit : function(finderObj) {
		debug('Finder initialised',arguments)
		$('.ui-finder-action-refresh').click(function() {
			$('[name="refresh"]').click();
		});
		$('.ui-finder-action-open').click(function(){
			$('[name="select"]').click();
		});
		$('.ui-finder-action-current').click(function(){
			$('[name="getCurrent"]').click();
		});
		$('.ui-finder-action-destroy').click(function(){
			$('[name="createFinder"]').click();
		});
	},
	onItemSelect : function(listItem,eventTarget,finderObject){
		var anchor = $('a',listItem),
			href = anchor.attr('rel');
	// Debug is a function specified in Finder script for debugging purposes
	// Remove it if unnecessary
		debug('onItemSelect - URL: ',href)
	// By returning false, the url specified is not fetched
	// ie. Do not display new column if selected item is not an image
		if(href.indexOf('.jpg') == -1) {return false;}
	},
	onFolderSelect : function(listItem,eventTarget,finderObject){
		var anchor = $('a',listItem),
			href = anchor.attr('rel');
		debug('onFolderSelect - URL: ',href)
	},
	onItemOpen : function(listItem,newColumn,finderObject){
		var anchor = $('a',listItem),
			href = anchor.attr('href');
		debug('onItemOpen - Column source: ',newColumn.attr('data-finder-list-source'))
	},
	onFolderOpen : function(listItem,newColumn,finderObject){
		var anchor = $('a',listItem),
			href = anchor.attr('href');
		debug('onFolderOpen - Column source: ',newColumn.attr('data-finder-list-source'))
	},
	toolbarActions : function() {
		return '\
		<div class="ui-finder-button ui-state-default ui-corner-left ui-finder-action-refresh" title="Refresh">\
			<span class="ui-icon ui-icon-refresh"/>\
		</div>\
		<div class="ui-finder-button ui-state-default ui-finder-action-open" title="Open ..">\
			>span class="ui-icon ui-icon-folder-open"/>\
		</div>\
		<div class="ui-finder-button ui-state-default ui-finder-action-current ui-corner-right" title="Get current">\
			>span class="ui-icon ui-icon-help"/>\
		</div>\
		<div class="ui-finder-button ui-state-default ui-finder-action-destroy ui-corner-all" title="Destroy">\
			>span class="ui-icon ui-icon-closethick"/>\
		</div>\
		';
	}
    });

    // ----------------------------------------------------------

    // ----------------------------------------------------------
    // Medien AJAX includes

    function load_content(my_content){
        $.ajax({
          url: my_content,
          cache: false,
          success: function(html){
            $("#kmag").replaceWith(html);
            $("a.trigger").click(function(){
                var temp = $(this).attr("rel");
                load_content(temp);
            });
          }
        });
    };


    // ----------------------------------------------------------

    // ----------------------------------------------------------
    // Leere Einträge in Profilen vorbelegen

    $('form#profil_speichern textarea').each(function(){
        var tareaValue = $(this).val();
        if(tareaValue == '') {
            $(this).val('Noch kein Eintrag vorhanden.');
        }
    });
    
    $('#loader').load(function tester(){
        load_content("includes/09-04_media_ausgabe.html");
        $(this).remove();
    });

    // Magazines
    $('.mag .mag_item:nth-child(1)').addClass('top');
    $('.mag .mag_item:nth-child(2)').addClass('top');
    $('.mag .mag_item:nth-child(3)').addClass('top');
    $('.mag .mag_item:nth-child(4)').addClass('top');
    $('.mag .mag_item:nth-child(4n)').addClass('last');

    // Mitglieder
    $('.mit .mit_item:nth-child(1)').addClass('top');
    $('.mit .mit_item:nth-child(2)').addClass('top');
    $('.mit .mit_item:nth-child(3)').addClass('top');
    $('.mit .mit_item:nth-child(3n)').addClass('last');

    // Mediathek
    $('.media .media_item:nth-child(1)').addClass('top');
    $('.media .media_item:nth-child(2)').addClass('top');
    $('.media .media_item:nth-child(3)').addClass('top');
    $('.media .media_item:nth-child(3n)').addClass('last');
    $('.media .media_item').hover(
        function(){
            $(this).addClass('active');
        },
        function(){
            $(this).removeClass('active');
        }
    );

    // ----------------------------------------------------------

    // ----------------------------------------------------------
    // Get some Sublayouts

    $('#get_microsite').parent().parent().addClass('is_microsite');

    // ----------------------------------------------------------    
    
    // Dynamischer Aufruf der Subnavigation

    // Nachrichten bereinigen //
    $('.termin img').click(function(){
        //$('#news-container').load("../custom/skripte/striptagsnews.php");
    });
    
    // ----------------------------------------------------------
    // Lade Kalender Events
    // ----------------------------------------------------------
    ladeKalenderEvents();
});
   

function ladeKalender(monat, jahr, element_id, menunr, session_id)
{
    var url = 'evewa2.php?cal_month='+monat+'&cal_year='+jahr+'&menu='+menunr+'&GSAG='+session_id;
    $(".calendar").load(url +" .calendar", function() {
        $('.thickbox').each(function(i) {
            $(this).unbind('click');
        });
        tb_init('.calendar a.thickbox');
        ladeKalenderEvents();    
    });
}

// ----------------------------------------------------------
// Kalender
// ----------------------------------------------------------
function ladeKalenderEvents() {    
    $('td.termin').each(function () {
    
        var abstand = 5;
        var time = 250;
        var hideDelay = 500;
        var hideDelayTimer = null;

        // tracker
        var beingShown = false;
        var shown = false;

        var trigger = $(this);
        var popup = $('.events ul', this).css('opacity', 0);

        // mouseover und mouseout auf beiden elementen
        $([trigger.get(0), popup.get(0)]).mouseover(function () {
            // stoppt das hide event wenn mouseover auf popup
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // keine animation wenn bereits sichtbar
            if (beingShown || shown) { return;} 
            else {
                beingShown = true;

                // reset popup
                popup.css({
                    bottom: 20,
                    left: -76,
                    display: 'block'
                })

                // animieren
                .animate({
                    bottom: '+=' + abstand + 'px',
                    opacity: 1
                }, time, 'swing', function() {
                    beingShown = false;
                    shown = true;
                });
            }
        }).mouseout(function () {
            // timer reset
            if (hideDelayTimer) clearTimeout(hideDelayTimer);

            // speichert timer
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                popup.animate({
                    bottom: '-=' + abstand + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    popup.css('display', 'none');
                });
            }, hideDelay);
        });
    });

    // Behebt den FCK-Edior Mozilla BR_MOZ Bug
    // Simon Milz (29.10.09 - 19:52 Uhr)
    $("br[type='_moz']").each(function(){
        var parent_html = $(this).parent().html();
        if(parent_html == '<br>')
        {
            $(this).parent().remove();
        }

    });

    // Entfernt leere 'p'-Tags
    // Simon Milz (29.10.09 - 19:52 Uhr)
    $("p").each(function(){
        var this_html = $(this).html();
        if(this_html == '')
        {
            $(this).remove();
        }

    });

    // Shop extern öffnen
    // Simon Milz (30.10.09 - 17:54 Uhr)
    
    $("#subnav45").prev("a").click(function(){
        var shop_link = "http://www.kolping-shop.eu";
        window.open(shop_link);
        return false;
    });
    

    // ----------------------------------------------------------
    // Image Limits
    // ----------------------------------------------------------

    // Bildgröße für rechte SPalte auf 207px begrenzen
    $('#col_r img').each(function(){
       if($(this).width() > 207){
          $(this).css('width','207');
       } ;
    });

    $('#col_r .container.aktion:first:has(h2)').css('margin-top','-7px')

    $('#medienblog h3').text('Medienblog');
    $('#medienblog div.clearfix a').text('Medienblog');

    // ----------------------------------------------------------
    // eCard Funktion
    // ----------------------------------------------------------

    $('img.ecard_thumb').click(function(){
        $('img.ecard_thumb').removeClass('active');
        $(this).addClass('active');
        $('div#ecard_view_big').css('background-image', 'url('+$(this).attr('src')+')');
        $('#ecard_bild').val($(this).attr('src'));
    });

    $('#ecard_text').keyup(function(){
        $('#ecard_view_text').text($(this).val());
    });

    $('form#pinnwand_liste table.messages tr.noborder td:first').css('width','55px');
    $('form#pinnwand_liste table.messages tr.noborder td:first img.gallery').css('margin-right','0px');
	
    // ----------------------------------------------------------
    // eShop Produktteaser
    // ----------------------------------------------------------
	
    $('.eShop_product_cols:last').addClass('no_margin');

    // ----------------------------------------------------------
    // Chat
    // ----------------------------------------------------------

    $('#chat_send input[type=submit]').remove();
}

/*
 * Oeffnen einer Sicht in einer Thickbox. Verwendung zb beim Bearbeiten von
 * Mirosites in der Verwaltungscommunity
 */
function openSichtInThickbox(gsag, gsa_lfdnr)
{
	tb_show("Microsite - Webseitenpflege", "skripte/micrositepflege.php?height=600&width=800&GSAG="+gsag+"&id="+gsa_lfdnr, false);
//	window.open("evewa2.php?menu=8020049901&GSAG="+gsag+"&mtable=EV_WEBSEITEN&showsingle="+gsa_lfdnr);
}


$(document).ready(function(){
	$('#TAB102_PAGE2').find('div').find('table').find('tr').each(function() {
	    var dbl = $(this).attr('ondblclick');
		var gsag = $('input[name=GSAG]').val();
	    if(dbl != null)
	    {
	    	$(this).attr('ondblclick', '');
	        var dbl1 = dbl.toString().split(',');
	        dbl1[1] = dbl1[1].replace(');\n}','');
	        dbl1[1] = dbl1[1].replace(' ','');
	    }		
	    $(this).dblclick(function() { openSichtInThickbox(gsag, dbl1[1]); });
	  
	});

	var gsag_id = $('input[name=GSAG]').val();
	var ds_id = $('input[name=fen_main_gsa_lfdnr]').val();
	var inhalt = '<a onclick="codeblock(\'codeblock.php?cbfile=EGW_MICROSITE_ADD&GSAG='+gsag_id+'&id='+ds_id+'\', \'gs_MGL_1_01_5317\');" href="#hier">';
	inhalt += '<img border="0px" alt="..." src="../standard/bilder/buttons/EGW_MICROSITE_ADD.gif"/>';
	inhalt += '</a>';
	$('#EGW_MICROSITE_ADD').html(inhalt);
	


});

function reanimateSession(sessionid)
{
	$.ajax({
		type: 'POST',
		url: 'evewa2ajax.php',
		data: {
			file: 'reanimate_session.php',
			GSAG: sessionid
		},
		cache: false,
		success: function(responseText) {
//			if (responseText == 'reconnect')
//				location.href = 'evewa2.php?menu=019910';
//			else
				setTimeout(function() { reanimateSession(sessionid); }, 600000);
		}
	});
}