﻿// IE fix for setTimeout/setInterval (Now you can include args like this in ie too: setTimeout(function,interval,arg1,arg2)
/*@cc_on
(function(f){
 window.setTimeout =f(window.setTimeout);
 window.setInterval =f(window.setInterval);
})(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c.apply(this,a)},t)}});
@*/

var pausableSlideShowInterval = null;

function slideShow($elm) {

	// Image-Slide
	if($elm.attr('class') == 'TellusMediaList')
	{
		var $active = $elm.find('div.active');
		
		if ( $active.length == 0 ) 
		{
			$active = $elm.find('div:last');
		}

		var $next = ($active.next().length)? $active.next() : $elm.find('div:first');

		$active.addClass('last-active');
		$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 1000, function() 
			{
				$active.removeClass('active last-active');
				$('#nav-wrapper').attr('title',$next.find('img').attr('title'));
		});		
	}
	else {
		var $active = $elm.find('img.active');
		
		if ( $active.length == 0 ) 
		{
			$active = $elm.find('img:last');
		}

		var $next = ($active.next().length)? $active.next() : $elm.find('img:first');

		$active.addClass('last-active');
		$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 1000, function() 
			{
				$active.removeClass('active last-active');
		});
	}
}

function loadYoutubeMovie(url) {
    var params = { allowScriptAccess: "always", wmode: "opaque" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF(url, "ytapiplayer", "508", "336", "8", null, null, params, atts);
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
    if (newState == 0) {
        $(".nav-button.right").click();
        pausableSlideShowInterval = setInterval(slideShow, 7000, $('.TellusMediaList'));
    }
    if (newState == 3) {
        clearInterval(pausableSlideShowInterval);
    }
}

function setTheme(color)
{
	$('body').addClass('theme-' + color);
	Cufon.replace('.large-banner h2');
}


/* Banner-SlideShow
------------------------------------------------------------------------------------------------*/
function slideNext($this) {
	$this.stop(true,false).animate({'left' : '-' + (Math.ceil($this.parent().outerWidth()/3) + Math.ceil($this.parent().outerWidth()/3)) + 'px'}, 300, function() {
		// Return the "left" CSS back to 0, and append the first child to the very end of the list.
		$this
		   .css('left', -Math.ceil($this.parent().outerWidth()/3))
		   .children(':first')
		   .appendTo($this); // move it to the end of the line.
	})
}
function slidePrev($this) {
	$this.stop(true,false).animate({'left' : 0}, 300, function() {
		// Return the "left" CSS back to 0, and append the first child to the very end of the list.
		$this
		   .css('left', -Math.ceil($this.parent().outerWidth()/3))
		   .children(':last')
		   .prependTo($this); // move it to the end of the line.
	})
}

function prepareSlide(selector) {
	
	var $this = $(selector);
	
	if ( $this.find('.item').length > 3 ) {
	    $this
		   .css('left', -Math.ceil($this.parent().outerWidth() / 3))
		   .children(':last')
		   .prependTo($this); // move it to the end of the line.
		// Wrap "this" in a div with a class of "slider-wrap."
		$this.wrap('<div class="slider-wrap" />');
		
		// Set the width to a really high number. Adjusting the "left" css values, so need to set positioning.
		$this.css({
			'width' : '99999px',
			'position' : 'relative',
			'padding' : 0,
			'left':	-Math.ceil($this.parent().outerWidth()/3) + 'px'
		});

		$this.children().css({
			'float' : 'left',
			'list-style' : 'none'
		});
			
		$('.slider-wrap').css({
			'width' : Math.ceil($this.children().outerWidth() * 3) + 19 + 'px',
			'overflow' : 'hidden'
		});	

		var sliderControls = $('<div id="hls-controls" class="clearfix" />').insertAfter('.slider-wrap');
		var prevButton = $('<div id="hls-prev">Prev</div>');
		var nextButton = $('<div id="hls-next">Next</div>');
		
		prevButton.bind('click', function(){
			slidePrev($this);
		});
		
		nextButton.bind('click', function(){
			slideNext($this);
		});
	
		prevButton.add(nextButton).appendTo(sliderControls);
	}
}


$(function () {
    prepareSlide('.important-highlights');
    $('body').addClass('js');

    /* Lang-Selector
    ------------------------------------------------------------------------------------------------*/
    //var $langButton = $('<a />').text($('#lang').attr('title')).appendTo('#elsewhere');
    //var $languages = $('<ul />').attr('id','js-lang').appendTo('#elsewhere');
    //var $currentLang = $('<a />').attr('class', 'lang-selected ' + $('#lang option:selected').val()).appendTo('#elsewhere');
    /*
    $('#lang, input','#elsewhere').hide();
	
    $('#lang option').each(function() {
    var $newLang = $('<li />')
    .attr('class',$(this).val())
    .appendTo($languages);
    });*/

    /*
    $langButton.add($currentLang).bind('click', function() {
    if ($languages.data('visible') == true) {
    $languages.data('visible', false).animate({ height: 0 }, 200, function() {
    $(this).css({ display: 'none' });
    });
    }
    else {
    $languages.data('visible', true).css({ height: 0, display: 'block' }).animate({ height: 18 + 'px' }, 200);
    }
    return false;
    });
    
    $languages.bind('mouseenter', function() {
    $(this).data('visible', true);
    });
    */
    /*
    $languages.bind('mouseleave', function() {
    $languages.data('visible', false).animate({ height: 18 + 'px' }, 500, function() {
    if($(this).data('visible') == false)
    {
    $(this).animate({ height: 0 }, 200, function() {
    $(this).css({ display: 'none' });
    });
    }
    });
    });
    */

    /*
    $languages.find('li').bind('click', function() {
    //$currentLang.attr('class', 'lang-selected ' + $(this).text());
    $('#lang option[value=' + $(this).text() + ']').attr('selected', 'selected');
    $('form:first').trigger('submit');
    });*/

    /* Main-Menu
    ------------------------------------------------------------------------------------------------*/
    $('#CustomCategoryMainMenuList li:last').css({
        marginRight: '0',
        background: 'none'
    });

    /* Puffar / Highlights
    ------------------------------------------------------------------------------------------------*/
    //$('.important-highlights .item').css('marginRight','9px');
    //$('.important-highlights .item:last, .important-highlights .item:nth-child(3n)').css('marginRight','0');

    var $cornerBL = $('<span />').addClass('corner bl').appendTo($('.important-highlights .image-wrapper'));
    var $cornerBR = $('<span />').addClass('corner br').appendTo($('.important-highlights .image-wrapper'));

    $('.highlights .item').css('marginRight', '10px');
    $('.highlights .item:last').css('marginRight', '0');


    /* Top-SlideShow (on startpage etc..)
    ------------------------------------------------------------------------------------------------*/
    if ($('.slideshow-images img').length > 1) {
        var slideShowInterval = null;
        $('.slideshow-images img:first').addClass('active');
        $('.flash').animate({ top: '0' }, 5000, function () {
            slideShowInterval = setInterval(slideShow, 5000, $('.slideshow-images'));
        });
    }


    /* Products / Product-SlideShow
    ------------------------------------------------------------------------------------------------*/
    if ($('#ProductList').length > 0 || $('#SearchList').length > 0) {
        $('.TellusProductList .clearfix .image').each(function () {
            if ($(this).html().length <= 1) {
                $(this).append('<img src="/assets/img/fallbacks/product_thumb.png" alt="" />');
            }
        });
    }

    $('tbody > tr:odd').addClass('odd');

    if ($('.TellusMediaList img').length > 1) {
        //var pausableSlideShowInterval = null;
        function navigate(e) {

            clearInterval(pausableSlideShowInterval);

            var $active = $('.TellusMediaList div.active');
            var direction = e.data.direction;

            if ($active.length == 0) {
                $active = $('.TellusMediaList div:last');
            }

            if (direction == 'back') {
                var $next = ($active.prev().length) ? $active.prev() : $('.TellusMediaList div:last');
            }
            else {
                var $next = ($active.next().length) ? $active.next() : $('.TellusMediaList div:first');
            }

            $active.addClass('last-active');
            $next.css({ opacity: 0.0 })
				.addClass('active')
				.animate({ opacity: 1.0 }, 200, function () {
				    $active.removeClass('active last-active');
				    $('#nav-wrapper').attr('title', $next.find('img').attr('title'));
				});
            return false;
        }

        var $wrapper = $('.product-images');
        var $navWrapper = $('<div />').attr('id', 'nav-wrapper').prependTo($wrapper).css('display', 'none');
        var $navLeft = $('<a />').attr('class', 'nav-button left').appendTo($navWrapper);
        var $navRight = $('<a />').attr('class', 'nav-button right').appendTo($navWrapper);

        $('.TellusMediaList img:first').addClass('active');
        $wrapper.attr('title', $('.TellusMediaList .active img').attr('title'));
        pausableSlideShowInterval = setInterval(slideShow, 7000, $('.TellusMediaList'));

        $wrapper.bind('mouseenter', function () {
            $navWrapper.css({ display: 'block' });
        });

        $wrapper.bind('mouseleave', function () {
            $navWrapper.css('display', 'none');
        });

        $navLeft.bind('click', { direction: 'back' }, navigate);
        $navRight.bind('click', { direction: 'forward' }, navigate);
    }
    else if ($('.TellusMediaList img').length < 1) {
        $('.product-images').remove();
    }


    /* Google-maps
    ------------------------------------------------------------------------------------------------*/
    if ($('#map').length > 0) {
        var $close = $('<span />').attr('id', 'close').appendTo($('#large-map'));
        var $largeMap = $('#large-map');

        $('#map a').bind('click', function () {
            $('#loader').show();
            $largeMap.css({
                display: 'block',
                zIndex: '1001'
            });
            initialize();
            return false;
        });

        $('#map-holder').bind('click', function (e) { return false; });

        $('.page-wrap').bind('click', function (e) {
            if (!$(e.target).is('#map-holder')) {
                if ($largeMap.css('display') == 'block') {
                    $largeMap.hide();
                    $('#loader').hide();
                    return false;
                }
            }
        });
        $close.bind('click', function (e) {
            $largeMap.hide();
            $('#loader').hide();
        });
    }


    /* External links
    ------------------------------------------------------------------------------------------------*/
    $('a[href^="http://"]').each(function (e) {
        if (!$(this).attr('target') == '_self')
            $(this).addClass('external').attr('target', '_blank');
    });


    /* Weather
    ------------------------------------------------------------------------------------------------*/
    function toggleWeather() {
        if ($('#weather #forecast').css('display') == 'none') {
            $('#more-weather').css('backgroundPosition', '0 -664px');
            $('#weather #forecast').css({
                height: '0',
                display: 'block'
            })
			.animate({ height: '310px' }, 400);
        }
        else {
            $('#more-weather').css('backgroundPosition', '2px -15px');
            $('#weather #forecast').animate({ height: '0' }, 400, function () {
                $(this).css('display', 'none');
            });
        }
        return false;
    }
    $('#more-weather').bind('click', toggleWeather);


    /* Meetingplanner
    ------------------------------------------------------------------------------------------------*/
    $('#media-links li:nth-child(2n)').css('margin-right', '0');


    /* Sidebar-Tabs
    ------------------------------------------------------------------------------------------------*/
    if ($('#popular').length >= 1) {
        $('#TopTips .item .image').each(function () {
            if ($(this).html().length <= 1) {
                $(this).append('<img src="/assets/img/fallbacks/sidebar_tip.png" alt="" />');
            }
        });

        $('#TopEvent').hide();

        $('.tab-header .tips').bind('click', function () {
            $('#TopEvent').hide();
            $('#TopTips').show();
            $('.tab-header a').removeClass('active');
            $(this).addClass('active');
            Cufon.refresh('#popular a.tab');
            return false;
        });
        $('.tab-header .events').bind('click', function () {
            $('#TopTips').hide();
            $('#TopEvent').show();
            $('.tab-header a').removeClass('active');
            $(this).addClass('active');
            Cufon.refresh('#popular a.tab');
            return false;
        });


        if ($('#TopTips').length >= 1) {
            var pageIndex = 0;

            var totalPages = Math.ceil(($('#TopTips .item').length / 3));
            var children = $('#TopTips .carousel-wrapper').children();
            var breaks = children.filter(':first, :nth-child(3n+1)').map(function () {
                return children.index(this);
            });

            $.each(breaks, function (i, v) {
                children.slice(v, (breaks[i + 1] || children.length)).wrapAll('<div class="page"></div>');
            });

            var pageLinks = '';

            for (var i = 0; i < totalPages; i++) {
                pageLinks += '<a title="Go to page ' + (i + 1) + '">' + (i + 1) + '</a>';
            }

            if (totalPages > 1) $('#TopTips').append('<div class="pageing">' + pageLinks + '</div>');

            $('#TopTips .pageing a:first').addClass('active');

            $('#TopTips .pageing a').bind('click', function () {
                $('#TopTips .pageing a').removeClass('active');
                $(this).addClass('active');

                var pageWidth = $('#TopTips .tab-content .page').width();
                var pageIndex = parseInt($(this).text()) - 1;

                $('#TopTips .carousel-wrapper').animate({
                    left: -pageWidth * pageIndex + 'px'
                },
					400);
                return false;
            });
        }

        if ($('#TopEvent').length >= 1) {
            var pageIndex = 0;

            var totalPages = Math.ceil(($('#TopEvent .item').length / 3));
            var children = $('#TopEvent .carousel-wrapper').children();
            var breaks = children.filter(':first, :nth-child(3n+1)').map(function () {
                return children.index(this);
            });

            $.each(breaks, function (i, v) {
                children.slice(v, (breaks[i + 1] || children.length)).wrapAll('<div class="page"></div>');
            });

            var pageLinks = '';

            for (var i = 0; i < totalPages; i++) {
                pageLinks += '<a title="Go to page ' + (i + 1) + '">' + (i + 1) + '</a>';
            }

            if (totalPages > 1) $('#TopEvent').append('<div class="pageing">' + pageLinks + '</div>');

            $('#TopEvent .pageing a:first').addClass('active');

            $('#TopEvent .pageing a').bind('click', function () {
                $('#TopEvent .pageing a').removeClass('active');
                $(this).addClass('active');

                var pageIndex = parseInt($(this).text()) - 1;
                var pageWidth = $('#TopEvent .tab-content .page').width();

                $('#TopEvent .carousel-wrapper').animate({
                    left: -pageWidth * pageIndex + 'px'
                },
					400);
                return false;
            });
        }

        $('#popular .TellusNoOfHits').remove();
        $('#popular .TellusPreviousNext').remove();
    }

    // Enhance Admin-Contentareas
    $('.edit-link, .delete-link').css({ display: 'none' });

    $('.newsitem').hover(
	function () {
	    $(this).find('.edit-link, .delete-link').css({ display: 'block' });
	},
	function () {
	    $(this).find('.edit-link, .delete-link').css({ display: 'none' });
	});

    $('.admin-image-area').hover(
	function () {
	    $(this).find('.edit-link').css({ display: 'block' });
	},
	function () {
	    $(this).find('.edit-link').css({ display: 'none' });
	});

    $('.admin-text-area').hover(
	function () {
	    $(this).find('.edit-link').css({ display: 'block' });
	},
	function () {
	    $(this).find('.edit-link').css({ display: 'none' });
	});
});
