/*--------------------------------------------------------------------------------------
    fadeIn() and fadeTo(speed, 1) now removes filter attribute in IE to resolve
    clearType issues in IE6 and IE7. Addresses tickets #2457, #3230, #4779 and others.
  ---------------------------------------------------------------------------------------*/
(function(){
    var _fadeIn = $.fn.fadeIn;
    var _fadeTo = $.fn.fadeTo;

    $.fn.fadeIn = function(easing, callback) {
        return _fadeIn.call(this, easing, function(){
            if( jQuery.browser.msie ) this.style.removeAttribute('filter');
            if( $.isFunction(callback) ) callback();
        });
    };
  
    $.fn.fadeTo = function(speed, to, callback) {
        return _fadeTo.call(this, speed, to, function() {
            if( jQuery.browser.msie && to == 1 ) this.style.removeAttribute('filter');
            if( $.isFunction(callback) ) callback();
        });
    };
})();

(function() {
    // Configuration for the Headerimages
    var conf = {
        fancybox: {
            url: 'fileadmin/templates/js/jquery.fancybox-1.3.1.pack.js',
            config_lightbox: {
                hideOnContentClick: true,
                hideOnOverlayClick: true,
                overlayShow: true,
                overlayOpacity: 0.7,
                speedIn: 200,
                speedOut: 200,
                changeSpeed: 200,
                titlePosition: 'inside',
                titleFormat: titleFormatter
            },
            config_small: {
                hideOnContentClick: true,
                overlayShow: false,
                speedIn: 200,
                speedOut: 200,
                changeSpeed: 200,
                titlePosition: 'inside',
                titleFormat: titleFormatter
            }
        },
        preload: [
        'fileadmin/templates/images/ui/imgHeader_lg.jpg',
        'fileadmin/templates/images/ui/imgHeader_bz.jpg',
        'fileadmin/templates/images/ui/imgHeader_sm.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_02.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_03.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_04.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_05.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_06.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_07.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_08.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_09.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_10.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_11.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_12.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_13.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_14.jpg',
        'fileadmin/templates/images/ui/slideshow/slide_15.jpg',
        'fileadmin/templates/images/ui/imgLogo_lg.png',
        'fileadmin/templates/images/ui/imgLogo_bz.png',
        'fileadmin/templates/images/ui/imgLogo_sm.png'
        ],
        hoverImages: { 
            lg: {
                src: 'fileadmin/templates/images/ui/imgHeader_lg.jpg', 
                alt: '###lg', 
                text: 'Das Museum für moderne und zeitgenössische Kunst'
            },
            bz: {
                src: 'fileadmin/templates/images/ui/imgHeader_bz.jpg', 
                alt: '###bz', 
                text: 'Wissen sammeln<br /> Natur vermitteln'
            },
            sm: {
                src: 'fileadmin/templates/images/ui/imgHeader_sm.jpg', 
                alt: '###sm', 
                text: 'Größtes Universalmuseum Österreichs an einem Ort'
            }
        },
        headerLogos: {
            lg: {
                src: 'fileadmin/templates/images/ui/imgLogo_lg.png', 
                alt: 'Landesgalerien'
            },
            bz: {
                src: 'fileadmin/templates/images/ui/imgLogo_bz.png', 
                alt: 'Biologiezentrum'
            },
            sm: {
                src: 'fileadmin/templates/images/ui/imgLogo_sm.png', 
                alt: 'Schlossmuseum'
            }
        },
        slideshow: {
            FADE_TIME: 1800,
            SHOW_TIME: 6000,
            EASING: 'easeInOutCubic'
        },
        slideshowImages: [
        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_02.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_03.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_04.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_05.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_06.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_07.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_08.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_09.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_10.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_11.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_12.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_13.jpg', 
            alt: '###slideshow3'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_14.jpg', 
            alt: '###slideshow2'
        },

        {
            src: 'fileadmin/templates/images/ui/slideshow/slide_15.jpg', 
            alt: '###slideshow3'
        }
        ]
    };
  
    // The DOM is ready, yaiks!
    jQuery(function($) {
        // Make the searchfield handle its focus
        $('#searchterm').blurFocus('Suche');
    
        // Let's initialize the Header slideshow 
        $('#headerMain.start').headerSlideshow();
    
        // Let's initialze the header hover handling
        $('#headerMain').headerHover();
    
        // Initialize a gallery
        $('#content .gallery').gallery();
    
        // Initialize the event filter
        $('#eventfilter').eventFilter();
    
        // enhance all forms in the content
        $('#content form').enhanceForm();
    
        // enlarge clickarea for event lists
        $('#eventlist li.event').enlargeClickarea();
    
        // preloadImages when everything is finised loading
        $(window).load(preloadImages(conf.preload));
    
        // IE6 doesn't understand :first-child, so let's
        // do that here
        if ( $.browser.msie && $.browser.version == 6 ) {
            $('#content .contentHeader h1:first-child').addClass('firstChild');
        }
    
        // handle The Billing-Address Bindings    
        $('#addresses_the_same').toggleBillingAddress();
        
        // Binding Links with a new window 
        $('a[rel=extern]').bindExternalLinks();
        
        $('#shop_categorys_wrap li.hasSub').handleSubCategorys();
        $('#shopCategoryOpen').handleCategoryWrap();
        $('#itemlist').handleShopDetails();
        
        $('#itemlist h2 a').unbindClicks();
        
        $('#shop_categorys_wrap, #shop_categorys_wrap li.hasSub ul').hide();
        $('#content form').handleCheckboxErrors();
    });
  
  
    $.fn.extend({   
        
        // unbind the Click-Event
        unbindClicks: function() {
            return this.each(function() {
                $(this).bind('click.unbind', function(event) {                    
                   event.preventDefault(); 
                }).mouseover(function() {
                    $(this).css( {'text-decoration' : 'none' , 'cursor' : 'text'} );
                });
            });
        },
        
        // handleDetails
        handleShopDetails: function() {
          return this.each(function() {
              var $element = $(this),
                  $links = $element.find('a.details');
                  
                  $links.bind('click.toggle' , function(event) {
                      var $this = $(this);
                      
                      $this.parent().parent().find('div.details').slideToggle(200);
                      event.preventDefault();
                      
                  });
          });  
        },        
        
        // shop category handler
        handleCategoryWrap: function() {
            return this.each(function() {
                var $element = $(this),
                    $toggleElement = $('#shop_categorys_wrap'),
                    init_text = $element.text();
                                
                $element.bind('click.cattoggle', function(event) {
                   if($element.hasClass('open')) {
                        $element.removeClass('open').attr('id' , 'shopCategoryOpen').text(init_text);
                        $toggleElement.stop(true, true).slideUp(400);                      
                   } else {                       
                       $element.addClass('open').attr('id' , 'eventfilterClose').text('Filter schließen');
                       $toggleElement.stop(true, true).slideDown(400);
                       
                   }                   
                   event.preventDefault();
                    
                });                
                
            });
        },
        
        //shop submenues
        handleSubCategorys: function() {
            return this.each(function() {
                var $element = $(this),
                $sublist = $element.find('ul'),
                $link = $element.find('a:first');
                  
                // Look for Submenues
                $link.bind('click.toggle', function(event) {
                    if($sublist.length > 0) {                      
                        if($element.hasClass('open')) {
                            $sublist.slideUp(200);
                            $element.removeClass('open');
                        } else {
                            $sublist.slideDown(200);
                            $element.addClass('open');
                        }                    
                    }                     
                    event.preventDefault();                     
                });
                
                
                // Unbind Links
                $link.bind('click.toggle', function(event) {
                    event.preventDefault();
                });
                
                
            });  
        },
        
        // any enhancements for the forms
        handleCheckboxErrors: function() {
            
            return this.each(function() {
                var $form = $(this),
                $cb = $form.find('input.required:checkbox'),
                $submit = $form.find('input[type=submit], button[type=submit]'),
                $error = $('<div id="agb_error" class="errorBubble"><div><p role="alert" class="required_error">Sie müssen die AGB akzeptieren.</p></div></div>').css( { 'bottom' : '2.9em' , 'left' : '0em' });
                
                $cb.bind('click', function() {
                    if($(this).parent().hasClass('wrong')) {
                       if($(this).attr('checked')) {
                           $error.remove();
                           $(this).parent('span').removeClass('wrong');
                       }
                    }      
                });                
                
                $submit.bind('click', function() {
                    $.each($cb, function() {
                        if(!$(this).attr('checked')) {
                            $(this).parent('span').addClass('wrong');
                            $error.appendTo($(this).parent('span'));
                        } else {
                            $(this).parent('span').removeClass('wrong');
                            $error.remove();
                        }
                    }); 
                }); 
            });                           
        },
        
        // toggle the billing-Address
        toggleBillingAddress: function() {
            return this.each(function() {               
                var $element = $(this),
                $toggleElement = $('#billing_address_wrap');
                
                $element.click(function() {
                    var checked  =  $element.attr('checked');                    
                    if(checked) {
                        $toggleElement.stop(true, true).hide(400);
                        $toggleElement.find('input').removeClass('required');
                    } else {
                        $toggleElement.stop(true, true).show(400);
                        $toggleElement.find('input').addClass('required');
                    }
                });
               
            });
        },
        
        bindExternalLinks: function() {
            return this.each(function() {
                $(this).attr('target','_blank');             
            });
        },
      
        // Delete word from inputfield on focus
        // Put word in inputfield on blur
        blurFocus: function(word) {
            var word = word || 'Suche';
          
            return this.each(function() {
                var field = $(this);            
            
                field
                .focus(function() {
                    if ( field.val() == word ) field.val('');
                })
                .blur(function() {
                    if ( field.val() == '' ) field.val(word);
                })
            ;
            });
        },
    
        // enlarge clickarea function
        // will try to find the <a> element inside the element
        // and put the location to it
        enlargeClickarea: function() {
            var baseurl = $('base').attr('href') || '';
      
            return this.each(function() {
                var link = $(this).find('a').eq(0);
                if ( !link.length ) {
                    $(this).addClass('nolink');
                    return;
                }
                $(this).click(function(event) {
                    if ( $(event.target).is('a') ) return true;
          
                    var href = link.attr('href');

                    window.location = href.indexOf('http') == 0 ? href : baseurl + href;
                });
            });
        },

        eventFilter: function(initial) {
      return this.each(function() {
	  
	  
        var filters = $(this),
            contentCol = $('#contentCol'),
            dates = $('#datesDatepicker').empty(),
            close = $('<a id="eventfilterClose" href="#">Filter schließen</a>').appendTo(filters),
            open = $('<a id="eventfilterOpen" href="#">nach Datum, Ort und Thema filtern</a>').prependTo('#content'),
            requestUrl = contentCol.data("url"),
            // extract the params if there are any
            params = ( requestUrl && requestUrl.indexOf('?') !=-1 ) ? requestUrl.split('?')[1] : '',
			rex_date_init = /\[selectDateFilter\]\=(\d{4})\/(\d{1,2})\/(\d{1,2})/;
        ;
		
		var date_month = 0;
		var date_year = 0;
		var date_day = 0;
        
        // if initial exists add it as classname to the contentCol
        if ( initial ) { contentCol.addClass(initial); }
        
        // bind the open and close
        close.click(toggleHandler);
        open.click(toggleHandler);
        
        // bind changeHandler to lists
        filters.find('ul').delegate('a', 'click', function() { return changeHandler(false, $(this) ); } );
		
		// initialze the datepicker
		dates.datepicker({
			dateFormat: 'yy/mm/dd',
			onSelect: function(dateText, inst) { 
				setDate( dateText );
			}			
		});
		
		if( requestUrl ) {
			var start_date =  requestUrl.match(rex_date_init);
			if( start_date ) 
				{ dates.datepicker("setDate", new Date(start_date[1],start_date[2]-1,start_date[3]) ); }
			
		}
		
		
        // Add Ajax Eventhandlers
        contentCol
          .ajaxSend(function() {  $(this).addClass('loading'); })
          .ajaxComplete(function() { $(this).removeClass('loading'); })
        ;
        
		function setDate( date ) {
							
			var _prefix = contentCol.data("url");
			
			if(window.location.pathname=='/' || window.location.pathname=='/biologiezentrum/' || window.location.pathname=='/landesgalerie/' || window.location.pathname=='/schlossmuseum/'  ) {
				
				var pathname = window.location.pathname.toString();
				
				if(pathname.match(/\/nc\/1\/?/) ) { _prefix = '?tx_ooemuseenevents_pi4'; }
				else { _prefix = 'nc/1/?tx_ooemuseenevents_pi4'; }
				
				
			 }
			else {
			
			var pathname = window.location.pathname.toString();
			if(pathname.match(/\/nc\/1\/?/) ) { if(!_prefix) { _prefix = window.location.pathname+'?tx_ooemuseenevents_pi1'; } }
				else { if(!_prefix) { _prefix = window.location.pathname+'nc/1/?tx_ooemuseenevents_pi1'; } }
			
			}
			
			var rex_date = /\[selectDateFilter\]\=\d{4}\/\d{1,2}\/\d{1,2}/;
			
			if( _prefix.match( rex_date ) ) {
				_prefix = _prefix.replace(rex_date, "[selectDateFilter]="+date);
			} else {			
				if( _prefix.indexOf(']') !=-1 || _prefix.indexOf('%5D') !=-1 ) 
					{ _prefix = _prefix + "&tx_ooemuseenevents_pi1[selectDateFilter]="+date; }
				else 
					{ _prefix = _prefix + "[selectDateFilter]="+date; }
			}
			changeHandler( _prefix , false );
		
		}
				
        // handle clicks on filters
        function changeHandler (data, $element) {	
		
			if(data) { loadContent(data); }
			else { loadContent( $element.attr('href') ); }			
		   return false; }
        
        // load content via ajax insteas of page reload
        function loadContent (url) {	
		  if(url && ( contentCol.data('url', url) != url ) ) {
			  contentCol.load(url + ' #content', function() {
					contentCol.data('url', url);
					$('#eventfilter').eventFilter('ajax');					
				});				  
		  }  }
        
        // handle showing and hiding of filters
        function toggleHandler (event) {
          if ( $(event.target).is('#eventfilterClose') ) {
            // IE is stupid
            if ( $.browser.msie ) dates.add(close).hide();
            filters.fadeTo(300, 0).slideUp(600, 'easeInOutQuint');
            open.fadeIn(600);
          } else {
            // IE is stupid
            if ( $.browser.msie ) dates.add(close).hide();
            filters.slideDown(600, 'easeInOutQuint').fadeTo(300,1, function() {
              // IE is stupid
              if ( $.browser.msie ) dates.add(close).show();
            });
            open.delay(600).fadeOut(300);
          }
          return false;
        }
      });
    },
	
        // Initialise gallery
        gallery: function() {
            return this.each(function() {
                var gallery = $(this),
                links = gallery.find('a:not(.download)'),
                imgs = gallery.find('img'),
                // get the url of the big versions of the images from the links href
                preloadImgs = links.map(function() {
                    return $(this).attr('href');
                }).get();
            
                // preload the big versions when everything is finised loading
                $(window).load(preloadImages(preloadImgs));
        
                // get the fancybox javascript and initalize it when it's here
                $.getScript(conf.fancybox.url, initFancybox);
        
                function initFancybox () {
                    var configuration = gallery.hasClass('lightbox') ? conf.fancybox.config_lightbox : conf.fancybox.config_small;
                    links.fancybox(configuration);
                }
            });
        },
    
        // Initialise slideshow (insert other slidehowimages, start slideshow)
        headerSlideshow: function() {
            return this.each(function() {
                var container = $(this),
                slideshow = container.find('#slideshow'),
                fadeTime = conf.slideshow.FADE_TIME,
                showTime = conf.slideshow.SHOW_TIME,
                easing = conf.slideshow.EASING;
        
                // insert rest of slides
                $.each(conf.slideshowImages, function() {
                    $('<img src="'+this.src+'" alt="'+this.alt+'" width="768" height="300" />').appendTo(slideshow);
                });
        
                var slides = slideshow.children('img');
                // if there is only one image we don't want a slideshow
                if ( slides.length <= 1 ) return;
                slides.hide();
                var current = slides.eq(0).show();
                // Add Play / Pause Buttons and hide the play button
                slideshow.prepend('<a id="slideshowPlay" href="#"><span class="hidden">Play</span></a> <a id="slideshowPause" href="#"><span class="hidden">Pause</span></a>');
                var slidePause = $('#slideshowPause').click(pause);
                var slidePlay = $('#slideshowPlay').hide().click(play);
                // Start the slideshow in an interval
                var interval = setInterval(changeSlide, showTime);
        
                // Find out the next slide, animate the change
                // and then make the next slide the current one
                function changeSlide () {
                    var next = current.next();
                    if (! next.length ) {
                        next = slideshow.children('img:first');
                    }
                    animateChange(current, next);
                    current = next;
                }
        
                // fadeOut first element, fadeIn second element
                function animateChange (currentSlide, nextSlide, speed) {
                    var animSpeed = speed || fadeTime;
                    currentSlide.fadeOut({
                        duration: animSpeed, 
                        easing: easing
                    });
                    nextSlide.fadeIn({
                        duration: animSpeed, 
                        easing: easing
                    });
                }
        
                // Stop Playing and change the buttons
                function pause () {
                    clearInterval(interval);
                    animateChange(slidePause, slidePlay, 300);
                    return false;
                }
        
                // Start Playing immediately and in interval and change the buttons
                function play () {
                    changeSlide();
                    interval = setInterval(changeSlide, showTime);
                    animateChange(slidePlay, slidePause, 300);
                    return false;
                }
            });
        },
    
        // Insert hover images
        // React to hovers on the headerlinks
        headerHover: function() {
            return this.each(function() {
                var container = $(this),
                list = container.find('ul'),
                headerLogo = container.find('#headerLogo img'),
                headerLogoInfo = {
                    src: headerLogo.attr('src'), 
                    alt: headerLogo.attr('alt')
                },
                hoverImg = $('<img id="hoverImg" src="" alt="" width="768" height="300" />').insertBefore(list),
                hoverTxt = $('#hoverTxt').length ? $('#hoverTxt') : $('<div id="hoverTxt"></div>').insertAfter(hoverImg),
                hoverTxt_text = hoverTxt.html();
            
                // Revert to slidehow when we leave the list
                list.mouseleave(revert)
                .find('a, span')
                // When we enter a link change the image
                .bind('mouseenter focus', change)
                // Revert to startimage when we blur a link
                .blur(revert);
        
                function revert (event) {
                    container.removeClass('hover');
                    headerLogo.attr(headerLogoInfo);
                    hoverTxt.html(hoverTxt_text);
                }
        
                function change (event) {
                    var klass = $(this).attr('class'),
                    imgInfo = conf.hoverImages[klass],
                    logoInfo = conf.headerLogos[klass];
                    container.addClass('hover');
                    hoverTxt.html(imgInfo.text);
                    hoverImg.attr({
                        src: imgInfo.src,
                        alt: imgInfo.alt
                    });
                    headerLogo.attr({
                        src: logoInfo.src,
                        alt: logoInfo.alt
                    });
                }
            });
        }
    });
  
    // preloadImages
    function preloadImages (images) {
        return function() {
            for ( var i = images.length; i--; ) {
                (new Image()).src = images[i];
            }
        };
    }
  
    // fancybox titleFormatter
    function titleFormatter () {
        var url = this.orig.closest('li').find('a.download').attr('href');
        if ( url ) {
            return '<span class="title">'+this.title+'</span><a class="imgDownload" href="'+url+'">Download</a>';
        } else {
            return this.title;
        }
    }
  
})();
