jQuery.noConflict();

    var fancyboxSettings = {
        'transitionIn'   : 'none',
        'transitionOut'  : 'none',
        'cyclic'         : true,
        'padding'        : '20',
        'overlayOpacity' : '0.7',
        'overlayColor'   : '#000',
        'titlePosition'  : 'inside',
        'scrolling'      : 'no',
        'autoDimensions' : true,

        'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
            var title  = '<span id="imagePager">' + (currentIndex + 1) + ' ' + fancyCountSep + ' ' + currentArray.length + '</span>'
                       + '<span id="imageTitle">' + title + '</span>';
            return title;
        }
    };


/*
 * get image width from css-bg-images
 */
    function getImgWidth(img) {
      // IE's need to have the image inside the body/display block to get with
      var imgWidth =
        img.css({visibility:'hidden', display:'block'}).appendTo('body').attr('width');
      img.remove();

      return imgWidth;
    }


    /*
     * add extra images to header-slide
     * */
    function addImages(imgArr){
      	var divPre  = '<div id="fadingImage';
      	var divMid1 = '" class="';
      	var divMid2 = '" style="background-image: url(';
      	var divApp  = ')"></div>';

    	jQuery.each(imgArr, function(i, value) {
            var bgImage = value;

            if (value != '') {
//console.log(bgImage);
    			var bgImageW = getImgWidth(jQuery(bgImage));//jQuery(bgImage).attr('width');
//alert("bgImageW: " + bgImageW);
    			var addClass = 'fadingImage';
    			if (i === 0) addClass += ' active';
    			if (bgImageW >= 1300) addClass += ' large';
//console.log(bgImageW);
                var bgImageSrc = jQuery(bgImage).attr('src');

                // to add new bg-divs
                var headerBgsDiv = jQuery('.fadingImage:last');

                // build new bg-div
                var newBgDiv = divPre + i + divMid1 + addClass + divMid2 + bgImageSrc + divApp;

                // add new bg div to the dom
                headerBgsDiv.after(newBgDiv);

                // if it's the first remove the first original div
                if (i === 0) jQuery('.fadingImage:first').remove();

                jQuery('#fadingImage' + i).data('width', bgImageW);
                // hide new one for later use

                if (i != 0) jQuery('#fadingImage' + i).hide();

                i++;
            }
        });
    }


    /*
     * get image width from css-bg-images
     */
    function getImgWidth(img) {
    	// IE's need to have the image inside the body/display block to get with
        var imgWidth =
        	img.css({visibility:'hidden', display:'block'}).appendTo('body').attr('width');
        img.remove();

        return imgWidth;
    }
/**
********************************************************************************
* language vars
********************************************************************************
*/

/**
* fancybox *********************************************************************
*/
    var fancyCountSep;
    var fancyClose;

    var fancyCountSep_de = 'von';
    var fancyClose_de = 'schliessen';
    var fancyCountSep_en = 'from';
    var fancyClose_en = 'close';

/**
* rzgooglemaps *****************************************************************
*/
    var linkGoogleMaps;

    var linkGoogleMaps_de = 'Link zu Google Maps';
    var linkGoogleMaps_en = 'Link to Google Maps';


jQuery(function($) {

/**
* check language ***************************************************************
*/
    var lang = jQuery('meta[name="language"]').attr('content');
    switch(lang) {
        case "de":
            fancyCountSep = fancyCountSep_de;
            fancyClose = fancyClose_de;
            linkGoogleMaps = linkGoogleMaps_de;
        break;
        case "en":
            fancyCountSep = fancyCountSep_en;
            fancyClose = fancyClose_en;
            linkGoogleMaps = linkGoogleMaps_en;
        break;
        case "fr":
            fancyCountSep = fancyCountSep_fr;
            fancyClose = fancyClose_fr;
            linkGoogleMaps = linkGoogleMaps_fr;
        break;
        default:
            fancyCountSep = fancyCountSep_de;
            fancyClose = fancyClose_de;
            linkGoogleMaps = linkGoogleMaps_de;
    }


/**
********************************************************************************
* link the whole teaser
********************************************************************************
*/
    // link a whole block (e.g. li)
    var linkAllItems = $("#col1 .teaserElement");
    linkAllItems.css("cursor","pointer");

    linkAllItems.click(function(e){
    	var $el = $('a:first', this);

        var newHref = $el.attr('href');
        var target =  $el.attr('target');

        if (target != '_blank') {
        	document.location = newHref;
        } else {
        	window.open(newHref);
	    }

        return false;
    });


/**
********************************************************************************
* genreal header animations
********************************************************************************
*/

    var headerBgsDiv;

    // IE8 needs this re-rendering of the site
    // hate these f*** IE's!
    $('body').css('padding','0');



	var Slider = function(ct, w) {
	     this.container = ct;
	     this.imgWidth = w;
	};

	Slider.prototype = {
		container : null,
		timer :     null,
		fps :       25,
		imgWidth :  null,

		startSlider: function() {
//console.log("slider start");
		    if(this.timer != null) {
		    	return;
		    }
		    this.timer = window.setInterval(jQuery.proxy(this.update, this), 1000/this.fps);
		},

		stopSlider: function() {
//console.log("slider stop");
		 	window.clearInterval(this.timer);
		    this.timer = null;
		},

		update: function() {
/**
 * get actual bg-position from active header-image,
 * calculate next position and change it
 */
			var bgPos = jQuery(this.container).css('backgroundPosition');
			/*
			 * FIX:
			 * IE doesn't like backgroundPosition, but jQuery could fix it. not in version 1.4.4 though
			 * so just make sure it works in every version, the hardcoded fix
			 *
			 *   FIXME:
			 *   check newer jQuery in the near future, maybe it'll work without this stupid fix
			 */
			if (bgPos == 'undefined' || bgPos == null) bgPos = jQuery(this.container).css('background-position-x');

			var bgPosNew = parseInt(bgPos);

	        if (-this.imgWidth < bgPosNew) {
	            bgPosNew = bgPosNew - 1;
	        } else {
	        	/*
	        	 * if panorama-image slided the whole length,
	        	 * stop sliding and fade to next image
	        	 */
	            bgPosNew = 0;
	            this.stopSlider();
	            s.update();
	        }

			bgPosNew = bgPosNew + 'px 0';
			$(this.container).css({
		    	backgroundPosition: bgPosNew
		    });
		}
	};

	var ImageSwitcher = function($imageDivs, interval) {
		this.imageContainers = $imageDivs;
		this.interval = interval;
	}

	ImageSwitcher.prototype = {
		firstRun: true,
		imageContainers: null,
		interval: 8000,

		update: function() {
			this.stopTimer();

			/**
			 * find active header-image and look for the next one
			 */
			var $active = jQuery('#fadingImages div.active');
	        if ( $active.length == 0 ) $active = jQuery('#fadingImages div:last');

	        var $nextImage = $active.next('div').length ?
	        		$active.next('div') : jQuery('#fadingImages div:first');

//bar = $nextImage.attr('id');
//console.log("update $next: " + bar);

			$active.removeClass('active').addClass('last-active');

			var self = this;
			$nextImage.addClass('active')
	            .fadeIn(2000, function() {
	            	/**
	            	 * fade the next one in and call the onAfterChange function
	            	 */
	            	self.onAfterChange($active);
	            });

			/**
			 * if the next one is a panorama-image,
			 * start the slider.
			 * if not, just start fading the the next image
			 */
		    if ($nextImage.hasClass('hasSlider')) {
//console.log("update $next: " + bar + " start slider");
	            var u = $nextImage.data('slider');
	            u.startSlider();
		    } else {
		    	this.startTimer();
		    }
		},

		startTimer: function() {
			/**
			 * if it's the first time running and the first image is a panorama-image,
			 * immediately start sliding, instead of waiting one interval of time
			 */
//console.log("starttimer");

//console.log("first active: " + $active.attr('id'));

			if (this.firstRun === true) {
//console.log("firstrun: " + this.firstRun);

				var $active = jQuery('#fadingImages div.active');
		        if ( $active.length === 0 ) $active = jQuery('#fadingImages div:last');

//foo = $active.attr('id');
//console.log("$active: " + foo);

		        if ($active.hasClass('hasSlider')) {
		            var u = $active.data('slider');
		            u.startSlider();
			    } else {
			    	window.setTimeout(jQuery.proxy(this.update, this), this.interval);
			    }
			} else {
				window.setTimeout(jQuery.proxy(this.update, this), this.interval);
			}
		},

	    stopTimer: function() {
//console.log("stoptimer");
	        window.clearTimeout(this.timer);
	        this.firstRun = false;
		},

	    onAfterChange: function($active) {
			/**
			 * after fading in the next image, change and remove the one before
			 */
			$active
				.removeClass('last-active')
				.hide();
	    }
	};




	if (headerBgs[1] != "") {
		/**
		 * if there are more images in the img-array,
		 * apply them to the main header-div
		 */
		addImages(headerBgs);

		/**
		 * large/slideable/panorama images get their own sliding-function.
		 * width is stored in the data-object of the div
		 */
		jQuery('#fadingImages .large').each(function() {
	        jQuery(this).addClass('hasSlider');
	        var thisWidth = jQuery(this).data('width');
	        jQuery(this).data('slider', new Slider(this, thisWidth));
		});

		$imageDivs = jQuery('.fadingImages');
		var s = new ImageSwitcher($imageDivs, 10000);
		s.startTimer();
	} else {
		addImages(headerBgs);

		jQuery('#fadingImages .large').each(function() {
	        jQuery(this).addClass('hasSlider');
	        var thisWidth = jQuery(this).data('width');
	        jQuery(this).data('slider', new Slider(this, thisWidth));
		});

		var isLarge = false;
		isLarge = jQuery('#fadingImage0').hasClass('large');

		if (isLarge === true) {
	        var u = jQuery('#fadingImage0').data('slider');
	        u.startSlider();
		}
	}







/**
********************************************************************************
* gallerys
********************************************************************************
*/

    $('#fancybox-close').text(fancyClose);

    function verticalAlign(images) {
        $.each(images, function(key, value) {
    //      console.log(key + ': ' + value);

            // get the get the height of the picture itself
            // and the height of its parent
            var imgHeight = $(this).height();
            var parentHeight = $(this).parent().height();

            // if the picture-height is smaller then the parent height, we have to calculate the top margin
            // and then add the top-margin to the picture
            if (parentHeight > imgHeight) {
                var marginTop = (parentHeight - imgHeight) / 2;
                marginTop = parseInt(marginTop);
                $(this).css('marginTop', marginTop);
            }
        });
    }

/**
* standard gallery *************************************************************
*/
    $(".gallery a").fancybox(fancyboxSettings);

    // only align pictures vertically
    var images = $('.gallery img');
    verticalAlign(images);


/**
* inline gallery ***************************************************************
*/
    var galInWrap = 'div.galleryInlineWrap';
    var galIn = $('ul.galleryInline');

    //for each inline-gallery
	$.each( galIn, function(i, l){

	    var galInLinks = $('a', this);
	    galInLinks.fancybox(fancyboxSettings);

	    // wrap for the inline-gallery
	    $(this).wrapAll('<div class="galleryInlineWrap" class="clearfix" />');

	    // change position of big images from list to wrap
	    $thisWrap = $(this).parent(galInWrap);
	    galInLinks.detach().prependTo($thisWrap);

	    // align all images
	    var images = $('img', $thisWrap);
	    verticalAlign(images);

	    // put the first big image on top
	    $('a:eq(0)', $thisWrap).css('z-index','1');

	    // find all the picture-pairs
	    var thumbLinks = $('li', this);

	    // function for the li's to show a associated big image
	    function changeThumbOver() {
	        var thisIndex = thumbLinks.index(this);
	        var $thisParentWrap = $(this).parents(galInWrap);
	        var bigImages = $('a', $thisParentWrap);
	        bigImages.css('z-index','0');
	        var assocBigImage = $('a:eq(' + thisIndex + ')', $thisParentWrap);
	        assocBigImage.css('z-index','1');

	    }
	    function changeThumbOut() {}

	    // set the funtion for the assoc image with indent
	    thumbLinks.hoverIntent(changeThumbOver, changeThumbOut);

	    // set mouseover for clickaction without intent
	    thumbLinks.mouseover(function() {
	        var thisIndex = thumbLinks.index(this);
	        var $thisParentWrap = $(this).parents(galInWrap);
	        $(this).css('cursor','pointer');
	        $(this).click(function() {
	            $('a:eq(' + thisIndex + ')', $thisParentWrap).trigger('click');
	            return false;
	        });
	    });

	}); //each


});

