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


var mr_t_currentSlide = null;
var mr_t_resetAutoPlay = null;

var mr_t_isReady = false;

/**
 * Animate the big teaser for the real,- 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;

    // animation automation timer
    var ourTimeoutHandle;

    // find relevant DOM Elements
    /* var nextBtn = $("#mrt a.vor");

    var prevBtn = $("#mrt a.zurueck"); */
    
    var navBtns = $("#startseite_mrt td.navbuttons");

    // 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
    mr_t_currentSlide = navBtns.index(navBtns.filter(".active"));

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

    // 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
        allSlidesContainer.animate(
            {'left': -slidesWidth * slideNo},
            700,
            'swing',
            function() {
                // after sliding do

                // send stop - event to all flashes
                stopAllFlashTeasers();
				
                // update display
                updateControls(slideNo);
                // set new current slide no
                mr_t_currentSlide = slideNo;
                if (enableAutoForward) {
                    // re-set timeout duration
                    mr_t_resetAutoPlay();
                }
				
				// send start - event to current slide if it contains a flash movie
                if ($(slides[slideNo]).hasClass("isFlash")) {
                    sendEventToFlashTeaser($(slides[slideNo]).children('div'), 'start');
                }
				
                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 = mr_t_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[mr_t_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 (mr_t_currentSlide >= slides.length - 1) {
            return;
        }
        slideTo(mr_t_currentSlide + 1);
    }); */

    /* // register event for previous button click
    prevBtn.click(function(event){
        event.preventDefault();
        if (currentlySliding) {
            return;
        }
        // this shouldn't actually happen
        if (mr_t_currentSlide <= 0) {
            return;
        }
        slideTo(mr_t_currentSlide - 1);
    }); */

    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
        );
    }
	
	// send start - event to current slide if it contains a flash movie
	// we need to poll & wait for mt. t to get loaded
	if ($(slides[mr_t_currentSlide]).hasClass("isFlash")) {
		var myFlashLoadedPollingThreadReference = window.setInterval(
			function() {
				if (!mr_t_isReady) {
					return;
				}
				window.clearInterval(myFlashLoadedPollingThreadReference);
				sendEventToFlashTeaser($(slides[mr_t_currentSlide]).children('div'), 'start');
			},
			100
		);
	}

    // register timeout for autoskipping every n seconds
    function startAutoPlay() {
        if (!teaserDurations[mr_t_currentSlide]) {
            return;
        }
        
        ourTimeoutHandle = setTimeout(function(){
            autoForward();
            startAutoPlay();
        }, teaserDurations[mr_t_currentSlide] * 1000);
    }

    // cancel skipping every n seconds
    function stopAutoPlay() {
        clearTimeout(ourTimeoutHandle);
    }
    
    mr_t_resetAutoPlay = function() {
        stopAutoPlay();
        startAutoPlay();
    }

}

/**
 * This is called by Mr. T to update the waiting time
 * after which the currently active tab should be advanced automatically.
 *
 * the time is given in milliseconds, a 0 disbles the switching completely (until a new timeoput is set).
 */
function mrt_duration(millis) {
    teaserDurations[mr_t_currentSlide] = millis / 1000;
    // re-set timeout duration
    mr_t_resetAutoPlay();
};

/**
 * This is called by Mr. T to indicate his readiness to receive events.
 */
function mrt_isready() {
	mr_t_isReady = true;
}

