$(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();
          });
			}
			
		    
		});
		
		jQuery('#location-finder input[name=zip]').attr('init', jQuery('#location-finder input[name=zip]').val());
		jQuery('#location-finder input[name=city]').attr('init', jQuery('#location-finder input[name=city]').val());
		jQuery('#location-finder input[name=city]').focus(function(){
      if($(this).val() == $(this).attr('init')){
        $(this).val("");
      }
    });
		jQuery('#location-finder input[name=city]').blur(function(){
      if($(this).val() == ''){
        $(this).val($(this).attr('init'));
      }
    });
		jQuery('#location-finder input[name=zip]').focus(function(){
      if($(this).val() == $(this).attr('init')){
        $(this).val("");
      }
    });
		jQuery('#location-finder input[name=zip]').blur(function(){
      if($(this).val() == ''){
        $(this).val($(this).attr('init'));
      }
    });
		
		$('#location-finder').submit(function(e){
		  e.preventDefault();
		  var searchString = '?';
      var zip   =  jQuery('#location-finder input[name=zip]');
		  var city    = jQuery('#location-finder input[name=city]');
		  var segment = jQuery('#location-finder select option:selected');
		  
		  if(zip.val() != zip.attr('init')) {
        searchString += '&zip='+escape(zip.val());
      }
      if(city.val() != city.attr('init')) {
        searchString += '&city='+escape(city.val());
      }
      searchString += '&segment='+segment.val();
		  
      window.open(this.action+searchString, 'Map', 'width=1000, height=700, toolbar=no');
      return false;
    });


    $('#content-area a.lightbox-link').nyroModal();
    $('#content-area a.lightbox-modal').nyroModal();
    
    //set links for google maps popups
    $('#main-navigation-47, #main-navigation-316').click(function(event){
			window.open(this.href, 'Map', 'width=1000, height=700, toolbar=no');
			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
jQuery(document).ready(function(){
		
	setInterval( "showHideNews()", 7000 );	
	jQuery('.newsticker').each(function(){

		var newsList = $(this).find('#single-ticker-wrap a');
		var prevNews = jQuery(this).find('.prev-news')
		var nextNews = jQuery(this).find('.next-news');
		var newsItem = jQuery(this).find('.news-item');
		var newsTotal = jQuery(this).find('.news-total');

		jQuery(newsList).css('display', 'none');
		jQuery(newsList[0]).addClass("active");
		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');
			var next = jQuery(activeNews.next('a')[0] ? activeNews.next('a')[0] : newsList[0]);
			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('a')[0] ? activeNews.prev('a')[0] : newsList[newsList.length - 1]);
			newsList.css({'display':'none', 'opacity':1});
			prev.addClass('active');
			prev.css({'display':'block', 'opacity':1});
			newsItem.text(prev.attr('index'));
		});
	});
});

// smooth show and hide
function showHideNews() {
	var newsList = $('#single-ticker-wrap').find('a');
	var activeNews = newsList.filter('.active');
	var next = $(activeNews.next('a')[0] ? activeNews.next('a')[0] : newsList[0]);
	var newsItem = $('.newsticker').find('.news-item');
	newsItem.text(next.attr('index'));
	
	$('#single-ticker-wrap').css({'position':'relative'});
	$('#single-ticker-wrap a').css({'position':'absolute'});
	var $alt = $('#single-ticker-wrap a.active');

	if($alt.next('a').length) var $neu = $alt.next('a');
	else var $neu = $('#single-ticker-wrap a:first');
	
	$alt.addClass('middle');
	$alt.css({'display':'block'});
	$alt.animate({'opacity': 0}, 600);
	$alt.removeClass('active');
	
	$neu.css({'opacity': 0});
	$neu.addClass('active');
	$neu.animate({'opacity': 1}, 600, function(){
		$alt.removeClass('middle');
		$alt.css({'opacity': 0, 'display':'none'});
	});
};


/*
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);
	};
})

