/*
 * jQuery Plugin: externalInterface
 * Version 1.0
 *
 * Copyright (c) 2010 David Comeau (http://www.davecomeau.net)
 * Licensed jointly under the GPL and MIT licenses.
 *
 */
(function($)
{
	$.fn.externalInterface = function(args)
	{
		this.each(function()
		{
			if(typeof(args.method) != 'undefined')
			{
				try
				{
					if(typeof(args.args) != 'undefined')
					{
						var data = this[args.method](args.args);
					}
					else
					{
						var data = this[args.method]();
					}
					
					if(typeof(args.success) != 'undefined')
					{
						args.success(data);
					}
				}
				catch(error)
				{
					if(typeof(args.error) != 'undefined')
					{
						args.error(error);
					}
				}
			}
		});
	
		return this;
	};
})(jQuery);

/**
 * Animate the big teaser for the homepage
 */
// we put everything into one function to not pollute the namespace
function mr_t(){
    // show only on pages with mrT!
    if (!$('#startseite_mrt').length) {
        return;
    }

    // toggle automatic scrolling between elements on/off
    var enableAutoForward = true;
    // animation automation pause length in ms
    var autoForwardEvery = 10000;
	// fade duration in ms
	var fadeDuration = 800;
	
	var slideChange = 7;

    // animation automation timer
    var ourTimeoutHandle;

    // find relevant DOM Elements
    var nextBtn = $("#mrt_controls a#slideNext");
    var prevBtn = $("#mrt_controls a#slidePrev");
    var stopBtn = $("#mrt_controls a#slideStop");
    var startBtn = $("#mrt_controls a#slideStart");
    
    var navBtns = $("#startseite_mrt table td");

    // the <li>s containing the different slides
    var slides = $("#startseite_mrt #mrt_container li");

    var allFlashSlides = $("#startseite_mrt #mrt_container li.isFlash div");

    // the big slider in which all slides reside
    var allSlidesContainer = $("#startseite_mrt #mrt_container ul");

    // find the slide width - all slides have to be of the same width
    var slidesWidth = $(slides[0]).width();

    // find the one to start with
    var currentSlide = navBtns.index(navBtns.filter(".active"));
    //var currentSlide = 3;
	
	if (-1 == currentSlide) {
		currentSlide = 0;
		$(navBtns[currentSlide]).addClass("active");
	}

    // a safeguard used to prevent multiple animations or events
    // running at the same time
    var currentlySliding = false;
	
	var currentlyHighestZ = 100;

    // actually slide to a specified slide
    // and update the mr_t controls state afterwards
    function slideTo(slideNo) {
        // no multiple slide actions at once!
        if (currentlySliding) {
            return;
        }
        currentlySliding = true;
		
        // perform + animate sliding
		
		currentlyHighestZ += 1;

		$(slides[slideNo]).css({
			'display': 'none',
			'z-index': currentlyHighestZ
		});
		
		
		//$(slides[slideNo]).fadeIn(fadeDuration);
		
        $(slides[slideNo]).fadeIn( fadeDuration, function() {
                // after sliding do

                // send stop - event to all flashes
                stopAllFlashTeasers();
                if ($(slides[slideNo]).hasClass("isFlash")) {
                    sendEventToFlashTeaser($(slides[slideNo]).children('div'), 'start');
                }

                // update display
                // updateControls(slideNo);
                // set new current slide no
                currentSlide = slideNo;
                if (enableAutoForward) {
                    // re-set timeout duration
                    stopAutoPlay();
                    startAutoPlay();
                }

                currentlySliding = false;
            }
        );
    }

    function stopAllFlashTeasers() {
        $.each(allFlashSlides, function(indexInArray, flashContainer){
            sendEventToFlashTeaser($(flashContainer), 'stop');
        });
    }

    function sendEventToFlashTeaser(flashContainer, msg) {
        var containerId = $(flashContainer)[0].id;
        $('#'+containerId+'_flash').externalInterface({
            method:'callMovie',
            args:msg,
            success: function(response)
            {
                // console.log('success' + msg);
            },
            error: function(error)
            {
                // console.log('error' , error);
            }
        });
    }
    
    // slide to the next slide, slide to first if we're on the last slide
    function autoForward() {
        var nextSlide = currentSlide + 1;

        if ( nextSlide > slides.length - 1) {
            nextSlide = 0;
        }
        slideTo(nextSlide);
    }

    // update the controls to reflect the new current slide
    function updateControls(setTo) {
        // remove 'active' - class from previously active
        // numbered button

        $(navBtns[currentSlide]).removeClass('active');

        // add active class to new active button
        $(navBtns[setTo]).addClass('active');

         // update previous - button
        if (setTo <= 0) {
            prevBtn.addClass('disabled');
        } else {
            prevBtn.removeClass('disabled');
        }
        // update next - button
        if (setTo >= slides.length - 1) {
            nextBtn.addClass('disabled');
        } else {
            nextBtn.removeClass('disabled');
        } 
    }

    // register events on the navigation page buttons 1...n
    // navBtns.each(function(z0, elem){
    //     $(elem).click(function(event){
    //         event.preventDefault();
    //         slideTo(z0);
    //     });
    // });

     // register event for next button click
    nextBtn.click(function(event){
        event.preventDefault();
        if (currentlySliding) {
            return;
        }
        // this shouldn't actually happen
        if (currentSlide >= slides.length - 1) {
            slideTo(0);
            // return;
        } else {
            slideTo(currentSlide + 1);
        }
    }); 

     // register event for previous button click
    prevBtn.click(function(event){
        event.preventDefault();
        if (currentlySliding) {
            return;
        }
        // this shouldn't actually happen
        if (currentSlide <= 0) {
            slideTo(slides.length - 1);
        } else {
            slideTo(currentSlide - 1);
        }
    });
    
     // register event for stop button click
    stopBtn.click(function(event){
        stopAutoPlay();
        return false;
    });

     // register event for start button click
    startBtn.click(function(event){
        startAutoPlay();
        return false;
    });

    if (enableAutoForward) {
        startAutoPlay();

        // register event for cancelling autoplaying if the user hovers over mt t
        // $('#startseite_mrt').bind(
        //     'mousemove',
        //     stopAutoPlay
        // );

        // register event for starting autoplay again if the user leaces mr t
        // $('#startseite_mrt').bind(
        //     'mouseleave',
        //     startAutoPlay
        // );
    }

    // register timeout for autoskipping every n seconds
    function startAutoPlay() {
        stopBtn.css('display', 'block');
        startBtn.css('display', 'none');
        ourTimeoutHandle = setTimeout(function(){
            autoForward();
            startAutoPlay();
        }, slideChange * 1000);
    }

    // cancel skipping every n seconds
    function stopAutoPlay() {
        stopBtn.css('display', 'none');
        startBtn.css('display', 'block');
        clearTimeout(ourTimeoutHandle);
    }

}

