/**
 * Boolean isAnimatedLogo - Flag whether the animation is running or not
 */
var isAnimatedLogo;

/**
 * Fade the logo
 */
function fadeInOutLogo() {
    $('#homepage #logo img').fadeTo(1000, 0.5, function(){
    	$(this).fadeTo(1000, 1);
    });
}

function loadVideo(playerUrl, autoplay) {
	// Lets Flash from another domain call JavaScript
	var params = {allowScriptAccess: 'always', allowfullscreen: 'true'};

	// The element id of the Flash embed
	var attributes = {id: 'video-player'};

	swfobject.embedSWF(playerUrl + '&amp;enablejsapi=1&amp;rel=1&amp;border=0&amp;fs=1&amp;autoplay=' + (autoplay ? 1 : 0), 'video-player', '504', '378', '9.0.0', null, null, params, attributes);
}

function showMyVideos(data) {
	var feed = data.feed;
	var entries = feed.entry || [];
	var totalResults = feed.openSearch$totalResults.$t;
	var itemsPerPage = feed.openSearch$itemsPerPage.$t;
	var startIndex = feed.openSearch$startIndex.$t;
	// Compute the number of pages (it's safer not to round it)
	var numPages = Math.floor(totalResults / itemsPerPage) + (totalResults % itemsPerPage == 0 ? 0 : 1);

	// Construct the video list
	var html = ['<ul id="video-list" class="videos">'];
	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];
		var title = entry.title.$t.substr(0, 15).trim();
		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
		var playerUrl = entries[i].media$group.media$content[0].url;
		html.push('<li title="', entry.title.$t, '" onclick="loadVideo(\'', playerUrl, '\', true)">', '<img src="', thumbnailUrl, '" width="120" height="90"/>', '</span></li>');
	}
	html.push('</ul><span id="scroll-lt" class="scroll left">&lsaquo;</span><span id="scroll-rt" class="scroll right">&rsaquo;</span>');
	$('#video-container').append(html.join(''));

	// Construct the page list
	var htmlPages = ['<ul id="video-pages">'];
    if (numPages > 1) {
		for (var i = 1; i <= numPages; i++) {
			htmlPages.push('<li><a href="#page-', i, '">', i, '</a></li>');
		}
	}
	htmlPages.push('</ul>');
	$('#video-container').append(htmlPages.join(''));

	// Select the first page
	$('#video-pages li:first a').addClass('selected');

    if (entries.length > 0) {
		loadVideo(entries[0].media$group.media$content[0].url, false);
		$('#video-list li:first-child').addClass('selected');
	}
}

var ksVideoPlayer = {
	playerContainer: null,
	currentPage: 0,
	currentItem: 0,
	startIndex: 1,
	itemsPerPage: 15,
	totalItems: 0,
	totalPages: 0,
	defaultUrl: 'http://gdata.youtube.com/feeds/api/videos?orderby=published&amp;v=2&amp;alt=jsonc&amp;author=stephanekonan&amp;callback=ksVideoPlayer.loadVideos',
	loadVideos: function(response) {
		totalResults = response.data.totalItems;


		// We have results
		if (totalResults > 0) {
			//alert(totalResults);
			// Compute the number of pages (it's safer not to round it)
			totalPages = parseInt(totalResults / itemsPerPage) + (totalResults % itemsPerPage == 0 ? 0 : 1);
			//alert(totalPages);


			if (totalPages > 1) {
				//alert(totalPages);
				// Construct the page list
				//alert(totalResults);
				var htmlPages = ['<ul id="video-pages">'];
				for (var i = 1; i <= totalPages; i++) {
					htmlPages.push('<li><span>', i, '</span></li>');
				}
				htmlPages.push('</ul>');
				$('#video-container').append(htmlPages.join(''));
				// Show the pager
				$('#video-pages').width(20 * totalPages).fadeIn('slow');

				// Select the first page
				$('#video-pages li:first span').addClass('selected');

				var items = response.data.items || [];

				// Construct the video list
				var htmlClips = ['<ul id="video-list" class="videos">'];
				for (var i = 0; i < items.length; i++) {
					var item = items[i];
					var title = item.title.trim();
					var thumbnail = item.thumbnail.sqDefault;
					var player = item.content['5'];
					//console.log(player);
					htmlClips.push('<li title="', title, '" onclick="loadVideo(\'', player, '\', true)">', '<img src="', thumbnail, '" width="120" height="90"/>', '</span></li>');
				}
				htmlClips.push('</ul><span id="scroll-lt" class="scroll left">&lsaquo;</span><span id="scroll-rt" class="scroll right">&rsaquo;</span>');
				$('#video-container').prepend(htmlClips.join(''));
				$('#video-list').fadeIn('slow');
			}
		}
	}
};

jQuery(document).ready( function($) {
	/*
	 * JQuery Random Plugin
	 *
	 * Adds two random number functions to jQuery -
	 * one to find a random number and one to find a random number between a max and min limit.
	 *
	 * Version 1.0
	 *
	 * by Christian Bruun - 23. jan 2009
	 *
	 * Like it/use it? Send me an e-mail: rockechris@rockechris.com
	 *
	 * License: None. Use and abuse. Comes with no warranty, of course!
	 *
	 *
	 * Usage:
	 * $.random(int);
	 * $.randomBetween(min, max);
	 *
	 * Code found at:
	 * http://www.merlyn.demon.co.uk/js-randm.htm
	 *
	 */
    $.extend({
        random: function(X){
            return Math.floor(X * (Math.random() % 1));
        },
        randomBetween: function(MinV, MaxV){
            return MinV + $.random(MaxV - MinV + 1);
        }
    });

    /**
     * Open external links in new windows
     */
    $("a[rel='external']").attr('target', '_new');

    /**
     * Fix email addresses for Contact page (also changes the HTML for the A element)
     */
    $("address a.email").each(function(){
        var $this = $(this);
        var email = $this.html().replace(' (at) ', '@');
        $this.html(email);
        $this.attr('href', 'mailto:' + email);
    });

    /**
     * Fix email addresses in the Resources page
     */
    $(".employee-list a.email").each(function(){
        var $this = $(this);
        var email = $this.attr('href').replace(' (at) ', '@');
        $this.attr('href', email);
    });

    /**
     * Split the people directory in two columns
     */
    $('#resources-page ul.employee-list li:nth-child(even)').addClass('even');

    /**
     * Add class 'last' on the last item in a content list (fix for IE)
     */
    var peopleItems = $('#resources-page ul.employee-list li');
    $('#resources-page ul.employee-list li:gt(' + (peopleItems.length - 3) + ')').addClass('last');

    //$('ul.content-list li:last-child,ul.services li:last-child').addClass('last');

    /**
     * Fixes for MSIE6
     */
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
        // Fix "View larger map" links
        $('a.map-link', $('#content')).hover(function(event){
            $('span', this).show();
        }, function(event){
            $('span', this).hide();
        });
    }

    /**
     * Clear the animation on hover on people items
     */
    $('li', $('#people')).hover(function(event){
        clearInterval(animatePeople);
    }, function(event){
    	isAnimatedLogo = setInterval('fadeInOutLogo()', 5000);
    });

    /**
     * Setup the animation
     */
    isAnimatedLogo = setInterval('fadeInOutLogo()', 5000);


	// Mark selection for the clicked item
	$('#video-container li').live('click', function(event) {
		$(this).addClass('selected').siblings().removeClass('selected');
	});

	//when user clicks the image for sliding right
	$('#scroll-rt').live('click', function() {
		//get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '
		var item_width = $('#video-list li').outerWidth() + 10;
		//calculate the new left indent of the unordered list
		var left_indent = parseInt($('#video-list').css('left')) - item_width;
		//make the sliding effect using jquery's anumate function '
		$('#video-list:not(:animated)').animate({
			'left': left_indent
		}, 250, 'swing', function() {
			//get the first list item and put it after the last list item (that's how the infinite effects is made) '
			$('#video-list li:last').after($('#video-list li:first'));
			//and get the left indent to the default -210px
			$('#video-list').css({
				'left': '-140px'
			});
		});
	});

	//when user clicks the image for sliding left
	$('#scroll-lt').live('click', function() {
		var item_width = $('#video-list li').outerWidth() + 10;
		/* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
		var left_indent = parseInt($('#video-list').css('left')) + item_width;
		$('#video-list:not(:animated)').animate({
			'left': left_indent
		}, 250, 'swing', function() {
			/* when sliding to left we are moving the last item before the first item */
			$('#video-list li:first').before($('#video-list li:last'));
			/* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */
			$('#video-list').css({
				'left': '-140px'
			});
		});
	});

	$('.scroll', $('#video-container')).live('mousedown mouseup', function() {
		$(this).toggleClass('mouse_dn');
	}).live('mouseover mouseout', function(){
		$(this).toggleClass('hover');
	});




	/*

	$('.scroll', $('#video-container')).live('mousedown mouseup', function() {
		$(this).toggleClass('mouse_dn');
	}).live('mouseover mouseout', function(){
		$(this).toggleClass('hover');
	}).live('click', function() {
		var item_width = $('#video-list li').outerWidth() + 10;
		var left_indent;
		if ($(this).hasClass('left')) {
			left_indent = parseInt($('#video-list').css('left')) + item_width;
		} else {
			left_indent = parseInt($('#video-list').css('left')) - item_width;
		}
		$('#video-list:not(:animated)').animate({
			'left': left_indent
		}, 250, 'swing', function() {
			if ($(this).hasClass('left')) {
				//* when sliding to left we are moving the last item before the first item
				$('#video-list li:first').before($('#video-list li:last'));
			} else {
				//get the first list item and put it after the last list item (that's how the infinite effects is made) '
				$('#video-list li:last').after($('#video-list li:first'));
			}
			//* and again, when we make that change we are setting the left indent of our unordered list to the default -210px
			$('#video-list').css({
				'left': '-148px'
			});
		});
	});


	 */

	var playerContainer = $('#player-container');
	if (playerContainer.length != 0) {
		var currentPage = 0;
		var currentItem = 0;
		var startIndex = 1;
		var itemsPerPage = 15;
		var totalItems = 0;
		var totalPages = 0;

		var defaultUrl = 'http://gdata.youtube.com/feeds/api/videos?orderby=published&v=2&alt=jsonc&author=stephanekonan&callback=?';
		$.ajax({
			dataType: 'jsonp',
			ifModified: true,
			scriptCharset: 'UTF-8',
			url: defaultUrl,
			error: function(xhr, textStatus, errorThrown) {

			},
			success: function(response, textStatus, xhr) {
				totalResults = response.data.totalItems;

				// We have results
				if (totalResults > 0) {
					// Compute the number of pages (it's safer not to round it)
					totalPages = parseInt(totalResults / itemsPerPage) + (totalResults % itemsPerPage == 0 ? 0 : 1);

					if (totalPages > 1) {
						// Construct the page list
						var htmlPages = ['<ul id="video-pages">'];
						for (var i = 1; i <= totalPages; i++) {
							htmlPages.push('<li><span>', i, '</span></li>');
						}
						htmlPages.push('</ul>');
						$('#video-container').append(htmlPages.join(''));
						// Show the pager
						$('#video-pages').width(20 * totalPages).fadeIn('slow');

						// Select the first page
						$('#video-pages li:first span').addClass('selected');

						var items = response.data.items || [];

						// Construct the video list
						var htmlClips = ['<ul id="video-list" class="videos">'];
						for (var i = 0; i < items.length; i++) {
							var item = items[i];
							var title = item.title;
							var thumbnail = item.thumbnail.sqDefault;
							var player = item.content['5'];
							//console.log(player);
							htmlClips.push('<li title="', title, '" onclick="loadVideo(\'', player, '\', true)">', '<img src="', thumbnail, '" width="120" height="90"/>', '</span></li>');
						}
						htmlClips.push('</ul><span id="scroll-lt" class="scroll left">&lsaquo;</span><span id="scroll-rt" class="scroll right">&rsaquo;</span>');
						$('#video-container').prepend(htmlClips.join(''));
						$('#video-list').fadeIn('slow');

						// Move the last list item before the first item. The purpose of this is if the user clicks previous he will be able to see the last item.
						$('#video-list li:first').click().before($('#video-list li:last'));

						//$('#video-list li:first');
					}
				}
			}
		});

	}
});
