$(document).ready(function() {
	/*
		create home carrousel
	*/

	website.home.carrousel = function(readmoreUrls) {

		// Check if carrousel html is present. If not, quit.
		if($('#home-carrousel').length == 0)
			return;

		var justHadVimeo = false;
		var justHadVimeoId = '';
        var bVimeoIsPlaying = false;
        var nTimerInterval = 4600;
        var nMapTimerInterval = 9200;

		var pub = {};


        /*
            Vimeo implementation code
         */

        /**
         * Utility function for adding an event. Handles the inconsistencies
         * between the W3C method for adding events (addEventListener) and
         * IE's (attachEvent).
         */
        var addEvent = function(element, eventName, callback) {
            if (element.addEventListener) {
                element.addEventListener(eventName, callback, false);
            }
            else {
                element.attachEvent('on' + eventName, callback);
            }
        };

        var vimeoPlayerReady = function() {
            //console.log('vimeo player ready!');

        };

        var vimeoPlayerOnPlay = function() {
            //console.log('vimeo player: play!');

            // set boolean for timer checks
            bVimeoIsPlaying = true;

            // pause the countdown while playing
            getFlashMovie("carrousel-flash-element").pauseCountdown();
        };

        /*
            /Vimeo implementation code
        */

		/*
			constructor
		*/

		init = function() {



            /*/(// Listen for the ready event for any vimeo video players on the page
            var vimeoPlayers = document.querySelectorAll('iframe'), player;

            for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
                player = vimeoPlayers[i];
                $f(player).addEvent('ready', ready);
            }*/







			// setup swfobject properties
			var flashvars = {
				timeCountdown : nTimerInterval,
				mapCountdown : nMapTimerInterval,
				amount : 4
			};

			var params = {
				scale : "noscale",
				menu  : "false",
				wmode : "transparent",
				allowscriptaccess : "samedomain"
			};

			// add class on successful embed to check if flash is present
			attributes  = {
				styleclass : "swfobject_present"
			};

			// trigger the swf embed
			window.swfobject.embedSWF("/swf/countdown.swf", "carrousel-flash-element", "100%", "100%", "9", "false", flashvars, params, attributes, function(){

				$("#home-carrousel").bind('mouseover', showNavigation);
				$("#home-carrousel").bind('mouseleave', hideNavigation);
			});

			// trigger the embed-check
			setTimeout(function() { embedCheck(); }, 1500);

			// initial vimeo embeds (gets redone in the scrollTo)
			// includes a rather quick n dirty parser for multiple video's

			for(var y=0; y<$('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel > .video').length; y++) {

				$($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel > .video')[y]).html('<iframe src="http://player.vimeo.com/video/'+($($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel > .video')[y])).attr('vimeoId')+'?api=1&color=00ab4e&title=0&amp;byline=0&amp;portrait=0&amp;autoplay=0&amp;loop=1" width="559" height="314" frameborder="0" style="display: block; background-color: #000;"></iframe>');
			};

			// trigger initial scrolling
			scrollTo(0);

		}


		/*
			private methods
		*/

		var getFlashMovie = function(flashId) {

			if (navigator.appName.indexOf("Microsoft") != -1) {
				return window[flashId];
			} else {
				return document[flashId];
			}
		};

		// check to see if flash has been embedded (= class has been set by swfobject), if not trigger the no_flash
		var embedCheck = function() {

			if(!$("#carrousel-flash-element.swfobject_present").length) {

				//console.log("carrousel: no flash embed detected. triggering fallback");

				// fallback dom update
                $('#carrousel-flash-element').css('padding', '1px 0px 0px 1px');
                $('#carrousel-flash-element').append('<img class="button1" src="' + website.sDomain + 'img/home/carrousel/menu-fallback-item-1.gif" />');
                $('#carrousel-flash-element').append('<img class="button2" src="' + website.sDomain + 'img/home/carrousel/menu-fallback-item-2.gif" />');
                $('#carrousel-flash-element').append('<img class="button3" src="' + website.sDomain + 'img/home/carrousel/menu-fallback-item-3.gif" />');
                $('#carrousel-flash-element').append('<img class="button4" src="' + website.sDomain + 'img/home/carrousel/menu-fallback-item-4.gif" />');

                // fallback dom eventHandlers
                var fallbackMenuItems = $('#carrousel-flash-element').children();

                $.each(fallbackMenuItems, function(i) {

                    $(this).css('cursor', 'pointer');

                    $(this).bind('click', function() {

                        clearInterval(timer);
                        scrollTo(i);
                    });
                });

				// setinterval to trigger auto scrolling
                var currentItemId = 0;
                var itemListLength = $('#carrousel-flash-element').children().length;

                var timer = setInterval(function() {

                    if (currentItemId < itemListLength-1) {
                        currentItemId += 1;
                        scrollTo(currentItemId)

                    } else if (currentItemId == itemListLength-1) {

                        currentItemId = 0;
                        scrollTo(0)
                    };

                }, nTimerInterval);

			}
		};

		var scrollTo = function(nId) {

			// check on title width to expand and contract
			var currentTitle = $('.title-carrousel > .title')[nId];
			var currentTitleWidth = $.textMetrics($(currentTitle)).width;

			// properties for the call to update the read more button
			var bExpand = false;

			if (currentTitleWidth > 195) {

				// trigger the second line mask element
				$('#home-carrousel > .carrousel-header > .title-carrousel > .title > .second-line-mask').css('visibility', 'hidden');

				// tween the title container
				$('#home-carrousel > .carrousel-header > .title-carrousel').animate( {
				   'height' : 110
				},{'queue': false, 'duration': 350, 'easing': 'easeOutExpo'});

				bExpand = true;

			} else {

				// trigger the second line mask element
				$('#home-carrousel > .carrousel-header > .title-carrousel > .title > .second-line-mask').css('visibility', 'visible');

				// tween the title container
				$('#home-carrousel > .carrousel-header > .title-carrousel').animate( {
				   'height' : 70
				},{'queue': false, 'duration': 350, 'easing': 'easeOutExpo'});

				bExpand = false;

			}

			carrouselWidth = 577;
			imageWidth = 559;

			$('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').animate( {
				'margin-left' : -(imageWidth * (nId))
			}, {'queue' : false, 'duration' : 400, 'easing' : 'easeOutExpo', 'complete' : function() {

				// current & previous item was a vimeo
				if ($($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[nId]).attr('vimeoid') && justHadVimeo == true) {

					$($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[justHadVimeoId]).html('<iframe src="http://player.vimeo.com/video/'+($($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[justHadVimeoId])).attr('vimeoId')+'?api=1&color=00ab4e&title=0&amp;byline=0&amp;portrait=0&amp;autoplay=0&amp;loop=1" width="559" height="314" frameborder="0" style="display: block; background-color: #000;"></iframe>');



				    // $f(player).addEvent('ready', ready);
				}
				// if only current is vimeo
				if ($($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[nId]).attr('vimeoid')) {

				  // set the boolean
				  justHadVimeo = true;
				  justHadVimeoId = nId;

				} else {

				  if (justHadVimeo == true) {

					// re-do the vimeo embeds (also don initially in the constructor)
					// includes a rather quick n dirty parser for multiple video's

						$($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[justHadVimeoId]).html('<iframe src="http://player.vimeo.com/video/'+($($('#home-carrousel > .carrousel-header > .image-carrousel-border > .image-carrousel').children()[justHadVimeoId])).attr('vimeoId')+'?api=1&color=00ab4e&title=0&amp;byline=0&amp;portrait=0&amp;autoplay=0&amp;loop=1" width="559" height="314" frameborder="0" style="display: block; background-color: #000;"></iframe>');

					// reset the boolean
					justHadVimeo = false;
				    }
				}

                /*
                    Bind Vimeo listeners
                 */

                // bind the vimeo ready event to the iframe(s)
                var vimeoPlayers = $('.video').children();

                for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
                   player = vimeoPlayers[i];
                   //$f(player).addEvent('ready', vimeoPlayerReady);
                   $f(player).addEvent('play', vimeoPlayerOnPlay);
                };

                // reset the vimeo boolean
                bVimeoIsPlaying = false;

			}});

			$('#home-carrousel > .carrousel-header > .title-carrousel').animate( {
				'margin-left' : -(carrouselWidth * (nId))
			},{'queue': false, 'duration': 500, 'easing': 'easeOutExpo'});

			$('#home-carrousel > .carrousel-content > .info-carrousel').animate( {
				'right' : 1731-(carrouselWidth * (nId - 1))
			},{'queue': false, 'duration': 600, 'easing': 'easeOutExpo'});

			$('#home-carrousel > .carrousel-content > .footer-carrousel').animate( {
			  'right' : 1731-(carrouselWidth * (nId - 1))
			},{'queue': false, 'duration': 700, 'easing': 'easeOutExpo'});

			// update the read more button
			updateReadMoreBtn(nId, bExpand);

		};

		var updateReadMoreBtn = function(nId, bExpand) {

			// update href attr
			$('#home-carrousel a.readMoreBanner').attr('href', readmoreUrls[nId]);

			// update position
			if (bExpand == true) {

				$('#home-carrousel a.readMoreBanner').animate( {
					'margin-top' : 514
				},{'queue': false, 'duration': 350, 'easing': 'easeOutExpo'});

			} else if (bExpand == false) {
				$('#home-carrousel a.readMoreBanner').animate( {
					'margin-top' : 474
				},{'queue': false, 'duration': 350, 'easing': 'easeOutExpo'});
			};
		};

		var showNavigation = function() {
			if($("#carrousel-flash-element.swfobject_present").length) {

				getFlashMovie("carrousel-flash-element").pauseCountdown();
				//$('#home-carrousel > .image-carrousel > .video > .play-button').attr('src', website.sDomain + 'img/home/carrousel/play_button_hover.png');
			}
		};

		var hideNavigation = function() {

			if($("#carrousel-flash-element.swfobject_present").length) {

                if(bVimeoIsPlaying === false) {
				    getFlashMovie("carrousel-flash-element").resumeCountdown();
                }
				//$('#home-carrousel > .image-carrousel > .video > .play-button').attr('src', website.sDomain + 'img/home/carrousel/play_button.png');
			}
		};


		/*
			public methods
		*/

		// 'dirty' workaround to be able to instantiate the carrousel elsewhere and keep this public method available
		// won't work for multiple instances (!) (the bind to pub but to the website.home.carrousel object.

		website.home.carrousel.navigateTo = function(nId) {
			// scrolle the carrousel
			scrollTo(nId);

			// renew the stored id
			storedId = nId;

			//console.log('hit+')
		}

		// call constructor
		init();

		// expose public methods / objects
		return pub;

	};

});
