$(document).ready(function(){
    $('body').addClass('js');

    $.nyroModalSettings({
			bgColor: '#ffffff',
			processHandler: function(settings) {
				var url = settings.url;
        			var from = settings.from;
				if (url && (url.substring((url.length-4)).toLowerCase() == '.flv')) {
					$.nyroModalSettings({
						type: 'swf',
						forceType: 'swf',
						height: '400',
						width: '500',
						url: 'fileadmin/common/swf/videoplayer.swf?file='+url
					});
				}

                //check, if it is a modal dialog
                if ($(from).hasClass('lightbox-modal')) {
                    $.nyroModalSettings({
                    		closeButton: '<a href="#" class="nyroModalClose" id="closeBut">Close</a>',
                        resizable: false,
                        autoSizable: false,
                        wrap: { // Wrapper div used to style the modal regarding the content type
                            div: '<div id="wrapperModal"></div>'
                        }
                    });
                }
			},

			hideContent : function(elts,settings,callback){
			    $('#nyroModalTitle').hide();
			    $('#imagecaption').hide();
			    $('#nyroModalWrapper').fadeOut(400, function(){
            callback();
          });
			}
		});


    $('#content-area a.lightbox-link').nyroModal();
    $('#content-area a.lightbox-modal').nyroModal();

    //set links for google maps popups
    $('#main-navigation-191').click(function(event){
      var w = window.open(this.href, 'Map', 'width=1000, height=700, toolbar=no');
			w.focus();
			event.preventDefault();
		});

    $('.toggle').click(function(){
        var selfOpen = false;
        if($(this).hasClass('toggle-act')) {
            selfOpen = true;
        }

        //hide all open elements
        //$('.toggle').removeClass('toggle-act').next().hide();
        $('.toggle').removeClass('toggle-act').next().animate({height:'hide'}, 'fast');
        if(selfOpen == false) {
            //$(this).addClass('toggle-act').next().show();
            $(this).addClass('toggle-act').next().animate({height:'show'}, 'fast');
        }
       return false;
    })

    // Elemente ausblenden (Start)
    $('.toggle + .element').each(function(){
        $(this).css('height', $(this).height());
        $(this).hide();
    });

    // Reset Search-Input
    $('#searchword').focus(function(){
        if(!$(this).hasClass('activated') && !$(this).attr('savedvalue')) {
            $(this).attr('savedvalue', $(this).val());
            $(this).attr('value', '');
        }
    });
    $('#searchword').blur(function(){
        if(!$(this).hasClass('activated') && $(this).val() == '') {
            $(this).val($(this).attr('savedvalue'));
        }
    });

    //modaler dialog
    $('#submitRefuseCopyright').click(function(e){
			$.nyroModalRemove();
			e.preventDefault();
		});
    $('#submitAcceptCopyright').click(function(e){
    	e.preventDefault();
    	window.open(lastClickedDownload.attr('savedhref'), '_blank');

			if($('#acceptCopyright').attr('checked') == true) {
				//re-transform download links to not show the modal dialogue
		    $('#main-content p.download-link a').each(function(){
		        $(this).attr('href',  $(this).attr('savedhref')).removeClass('lightbox-modal');
		        $(this).removeAttr('savedhref').removeAttr('rel').attr('target', '_blank').unbind('click.nyroModal');
		        $.cookies.set('acceptCopyright', 'true', {hoursToLive: 720} );

		    });
			}
			$.nyroModalRemove();


		});

});


// News-Ticker Startseite (#newsTab)
jQuery(document).ready(function(){
		/*newsticker on home page*/
		setInterval( "showHideNews()", 7000 );
		jQuery('#newsTab').each(function(){

			var newsList = $(this).find('.footerContentIn');
			var prevNews = jQuery('#footNavi').find('.prev-news')
			var nextNews = jQuery('#footNavi').find('.next-news');
			var newsItem = jQuery('#footNavi').find('.news-item');
			var newsTotal = jQuery('#footNavi').find('.news-total');

			/*setting the first termin to active*/
			jQuery(newsList).css('display', 'none');
			jQuery(newsList[0]).addClass('active').css('display', 'block');
			jQuery(newsList).each(function(i){
				$(this).attr('index', (i+1));
			});
			newsTotal.text(newsList.length);

			nextNews.click(function(){
				var activeNews = newsList.filter('.active');
				activeNews.removeClass('active').css('display', 'none');
				var next = jQuery(activeNews.next('.footerContentIn')[0] ? activeNews.next('.footerContentIn')[0] : newsList[0]);
				//next.addClass('active').css('display', 'block');
				//newsItem.text(next.attr('index'));
				newsList.css({'display':'none', 'opacity':1});
				next.addClass('active');
				next.css({'display':'block', 'opacity':1});
				newsItem.text(next.attr('index'));
			});

			prevNews.click(function(){
				var activeNews = newsList.filter('.active');
				activeNews.removeClass('active');
				var prev = jQuery(activeNews.prev('.footerContentIn')[0] ? activeNews.prev('.footerContentIn')[0] : newsList[newsList.length - 1]);
				//prev.addClass('active');
				//newsItem.text(prev.attr('index'));
				newsList.css({'display':'none', 'opacity':1});
				prev.addClass('active');
				prev.css({'display':'block', 'opacity':1});
				newsItem.text(prev.attr('index'));
			});
		});
});

// "smooth" show and hide (News)
function showHideNews() {
	var newsList = $('#newsTab').find('.footerContentIn');
	var activeNews = newsList.filter('.active');
	var next = $(activeNews.next('div')[0] ? activeNews.next('div')[0] : newsList[0]);
	var newsItem = $('#footNavi').find('.news-item');
	newsItem.text(next.attr('index'));

	$('.news-wrapper').css({'position':'relative'});
	$('.news-wrapper .footerContentIn').css({'position':'absolute'});
	var $alt = $('.news-wrapper div.active');

	if($alt.next('div').length) var $neu = $alt.next('div');
	else var $neu = $('.news-wrapper div:first');

	$alt.addClass('middle');
	$alt.css({'display':'block'});
	$alt.animate({'opacity': 0}, 600);
	$alt.removeClass('active');

	$neu.css({'opacity': 0, 'display' : 'block'});
	$neu.addClass('active');
	$neu.animate({'opacity': 1}, 600, function(){
		$alt.removeClass('middle');
		$alt.css({'opacity': 0, 'display':'none'});
	});
};


// Termin-Ticker Startseite (#termineTab)
jQuery(document).ready(function(){
		/*terminticker on home page*/

		jQuery('#termineTab').each(function(){

			var terminList = $(this).find('.footerContentIn');
			var prevTermin = jQuery('#footNavi2').find('.prev-termin')
			var nextTermin = jQuery('#footNavi2').find('.next-termin');
			var terminItem = jQuery('#footNavi2').find('.termin-item');
			var terminTotal = jQuery('#footNavi2').find('.termin-total');

			if(terminList.length > 1) {
			    jQuery(this).find('#footNavi2').css({'display': 'block'});
			    setInterval( "showHideEvents()", 7000 );
			    /*setting the first news to active*/
			    jQuery(terminList).css('display', 'none');
			    jQuery(terminList[0]).addClass('active').css('display', 'block');
			    jQuery(terminList).each(function(i){
				    $(this).attr('index', (i+1));
			    });
			    terminTotal.text(terminList.length);

			    nextTermin.click(function(){
				    var activeTermin = terminList.filter('.active');
				    activeTermin.removeClass('active').css('display', 'none');
				    var next = jQuery(activeTermin.next('.footerContentIn')[0] ? activeTermin.next('.footerContentIn')[0] : terminList[0]);
				    //next.addClass('active').css('display', 'block');
				    //terminItem.text(next.attr('index'));
				    terminList.css({'display':'none', 'opacity':1});
				    next.addClass('active');
				    next.css({'display':'block', 'opacity':1});
				    terminItem.text(next.attr('index'));
			    });

			    prevTermin.click(function(){
				    var activeTermin = terminList.filter('.active');
				    activeTermin.removeClass('active');
				    var prev = jQuery(activeTermin.prev('.footerContentIn')[0] ? activeTermin.prev('.footerContentIn')[0] : terminList[terminList.length - 1]);
				    //prev.addClass('active');
				    //terminItem.text(prev.attr('index'));
				    terminList.css({'display':'none', 'opacity':1});
				    prev.addClass('active');
				    prev.css({'display':'block', 'opacity':1});
				    terminItem.text(prev.attr('index'));
			    });
			}
			else {
			    jQuery(this).find('#footNavi2').css({'display': 'none'});
			}
		});
});

// "smooth" show and hide (Events)
function showHideEvents() {
	var terminList = $('#termineTab').find('.footerContentIn');
	var activeTermin = terminList.filter('.active');
	var next = $(activeTermin.next('div')[0] ? activeTermin.next('div')[0] : terminList[0]);
	var terminItem = $('#footNavi2').find('.termin-item');
	terminItem.text(next.attr('index'));

	$('.termin-wrapper').css({'position':'relative'});
	$('.termin-wrapper .footerContentIn').css({'position':'absolute'});
	var $alt = $('.termin-wrapper div.active');

	if($alt.next('div').length) var $neu = $alt.next('div');
	else var $neu = $('.termin-wrapper div:first');

	$alt.addClass('middle');
	$alt.css({'display':'block'});
	$alt.animate({'opacity': 0}, 600);
	$alt.removeClass('active');

	$neu.css({'opacity': 0, 'display' : 'block'});
	$neu.addClass('active');
	$neu.animate({'opacity': 1}, 600, function(){
		$alt.removeClass('middle');
		$alt.css({'opacity': 0, 'display':'none'});
	});
};


// Funktion zum leeren des Login-Formulars
function clearLoginForm () {
	document.getElementById('login').value='';
	document.getElementById('password').value='';
}


/*
if you need to display the path to user, you need to write some JavaScript like these.
*/


 var FileUploadUI =  function(dUploadButtonEl){
     this.init.apply(this,arguments);
 }

 FileUploadUI.prototype = {

     init:function(dUploadButtonEl){

             var dEl = this.getEl(dUploadButtonEl);
             var pathElementName = dEl.id+'-path';
             if( !dEl.type || dEl.type!='file' || !dEl.form ) return null;

             this._uploadButtonEl = dEl;
             this._uploadPathEl =   dEl.form.elements.namedItem(pathElementName);

             if( this._uploadPathEl ){
                 this._eventListeners = [];
                 this.addEvent(dEl,'change',this.syncFilePath);
                 this.addEvent(dEl.form,'submit',this.destruct);
                 this.makeAccessible();
             }
     },


     getEl:function(el){
           if( typeof(el) === 'string') el = document.getElementById(el);
           return el;
     },

     //simple addEvent, buggy and better replace it with your own Event Library
     addEvent:function(el,type,fn){

            el = this.getEl(el);

            var sOn = el.attachEvent ? 'on' : '';
            var oThis = this ;

            //let scope always be this (FileUploadUI)
            var wfn =  function(e){
                fn.call(oThis  ,e || window.event , el );
            };
            this._eventListeners.push( [el,type,wfn ]   );

            if(sOn){
               el.attachEvent( sOn + type , wfn  );
            }else if(el.addEventListener){
               el.addEventListener(type , wfn , false);
            };

            return wfn;
      },

      removeEvent:function(el,type,wfn){
            el = this.getEl(el);

            var sOn = el.attachEvent ? 'on' : '';
            if(sOn){
               el.dettachEvent( sOn + type , wfn  );
            }else if(el.addEventListener){
               el.removeEventListener(type , wfn , false);
            };
      },

    //you need to sync the value when user select a new file path;
    syncFilePath:function(){
         var dPath = this._uploadPathEl;
         var dBtn =  this._uploadButtonEl;
         dPath.value = dBtn.value.split('/').pop().split('\\').pop();
         if(  typeof(this.onChange) === 'function' ){
              this.onChange.call( this, dPath.value );
         }
    },

    onChange:function(){
    },

    makeAccessible:function(){
            var dPath = this._uploadPathEl;
            var dBtn =  this._uploadButtonEl;
            dPath.tabIndex = -1;
            this.addEvent( dPath ,'focus' , this._onPathFocus );
            this.addEvent( dBtn  ,'focus' , this._onBtnFocus );
            this.addEvent( dBtn  ,'blur' , this._onBtnBlur );
            this.addEvent( dBtn ,'keydown' , this._onBtnKeyDown );
            this.makeAccessible = function(){};
    },

    _onPathFocus:function(){
            var dBtn =  this._uploadButtonEl;
            dBtn.focus();
            return false;
    },

    _onBtnFocus:function(){
            var dPath = this._uploadPathEl;
                //dPath.style.backgroundColor = '#ffffcc';

    },

    _onBtnKeyDown:function(e){

        if(e.keyCode != 13) return ;
        var dBtn =  this._uploadButtonEl;
        if( dBtn.click ) dBtn.click();
    },

    _onBtnBlur:function(e){
        var dPath = this._uploadPathEl;
        //dPath.style.backgroundColor = '#fff';
    },

    destruct : function (){
          var dPath = this._uploadPathEl;
          var dBtn =  this._uploadButtonEl;
              dPath.disabled = true ;
              dBtn.style.display = 'none';//focus-not-allowed

          for( var i,arg;arg=this._eventListeners[i];i++){
               this.removeEvent.call(this,arg);
          }
          this._eventListeners = null;

    }
}



//instantiate all UI
$(document).ready(function(){
	var aUploadFileBtns = [];
	aUploadFileBtns[0] = document.getElementById('mailformplusplus-cv1');
	aUploadFileBtns[1] = document.getElementById('mailformplusplus-cv2');
	aUploadFileBtns[2] = document.getElementById('mailformplusplus-cv3');
	for(var i=0,dBtn;dBtn = aUploadFileBtns[i];i++){
	    new FileUploadUI(dBtn);
	};
})