$(document).ready(function() {

    var i;

    //VideoJS.setup();
    
    /* -------------------------------------------------------------- 

		GLOBAL
   
	-------------------------------------------------------------- */

	// Set the fade speed to be used throughout the site (and multiples of)
	var fadeSpeed = 95;

	// Preload various images
	jQuery.preLoadImages(
		"/static/css/images/overlay.png"
	);

	// Apply hints to text inputs
    $('input.text').hint();
    
    $('#featured-items video').each(function () {
        //if ($(this).parents('#featured-items')) {
            $(this).jwplayer({
                flashplayer: '/static/js/player.swf',
                skin: '/static/js/five/five.xml',
                autostart: true,
                controlbar: 'none',
                displayheight: 263
            });
        /*} else {
            $(this).jwplayer({
                flashplayer: '/static/js/player.swf',
                skin: '/static/js/five/five.xml',
                displayheight: 432,
                controlbar: 'bottom'
            });
        }*/
    });
    
    
    
    
    
    /* Page build
	-------------------------------------------------------------- */
	
	var contentContainer = $('#content');
	var whiteOverlays = $('#main-overlay, #header-overlay');
	
	// Fade the content in if not a slideshow
	if ($("body[not='.slideshow']").size()==0) {
	
		whiteOverlays.delay(150).fadeOut(fadeSpeed*4);
	
	}
	
	// We only want to try to animate the logo if the browser is not MSIE
	if (!$.browser.msie) {
	

		// Animate logo 1's first two segments
		$('body.logo-1 #logo-a').animate({
			backgroundPosition: "233px 0",
			opacity: "1"
		}, fadeSpeed*4);
		
		$('body.logo-1 #logo-b').delay(fadeSpeed*4).animate({
			backgroundPosition: "219px 0",
			opacity: "1"
		}, fadeSpeed*4);
		
		// Animate logo 2's first two segments
		$('body.logo-2 #logo-a').animate({
			backgroundPosition: "79px 0",
			opacity: "1"
		}, fadeSpeed*4);
		
		$('body.logo-2 #logo-b').delay(fadeSpeed*4).animate({
			backgroundPosition: "66px 0",
			opacity: "1"
		}, fadeSpeed*4);
		
		// Animate logo 3's first two segments
		$('body.logo-3 #logo-a').animate({
			backgroundPosition: "164px 0px",
			opacity: "1"
		}, fadeSpeed*4);
		
		$('body.logo-3 #logo-b').delay(fadeSpeed*4).animate({
			backgroundPosition: "151px 0px",
			opacity: "1"
		}, fadeSpeed*4);
		
		
		// Animate logo 2 and 3's last segments
		$('body #logo-c').delay(fadeSpeed*8).animate({
			backgroundPosition: "0px 0px",
			opacity: "1"
		}, fadeSpeed*4);
		
		// This is only for logo 1
		$('body #logo-d').delay(fadeSpeed*12).animate({
			backgroundPosition: "0px 0px",
			opacity: "1"
		}, fadeSpeed*4);
	
	}
	
	
	/* // If an anchor is clicked, capture the url and redirect
	var redirectURL;
	
	$('a:not(.no-transition)').click(function(){
	
		redirectURL = $(this).attr('href');
	
		// Fade out the content		
		whiteOverlays.fadeIn(fadeSpeed*4, function(){
			 document.location.href = redirectURL;
		});
		
		return false;

	}); */

	
	

    /* Search form
	-------------------------------------------------------------- */

    var searchForm = $("section#search");

	// Initialise the search form dialog
    searchForm.dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        position: [67,'center'],
        dialogClass: 'search-form',
        draggable: false,
        closeOnEscape: true,
        width: 800,
		open: function(event, ui) {
			// The overlay should fade in along with the text inputs
			$('.ui-widget-overlay').hide();
			$('form', searchForm).hide();
			$('.ui-widget-overlay').fadeIn(fadeSpeed*2);
			$('form', searchForm).fadeIn(fadeSpeed*2);
		}
    });
    
    // A hack for dialog to close the modal when anything else on the screen is selected
    $('.ui-widget-overlay').live('click', function(){
		if (searchForm.dialog("isOpen")) {
			$('form', searchForm).fadeOut(fadeSpeed*2, 
				function(){ 
					searchForm.fadeOut(fadeSpeed,
						function(){ 
							$('.ui-widget-overlay').fadeOut(fadeSpeed*2, function(){
								searchForm.dialog("close");
								
							});
						});
					});	
		}
    });
	
	// Open the search form when search is clicked from the main menu
    $('nav#first ul li.search a').click(function() {
        searchForm.dialog('open');
        return false;
    });


    /* Login form
	-------------------------------------------------------------- */

    var loginForm = $("section#login");
    var loginFormTop = 0;

	// Initialise the login form dialog
    loginForm.dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        position: [67,'center'],
        dialogClass: 'login-form',
        draggable: false,
        width: 800,
        closeOnEscape: true,
        open: function(event, ui) {
			$('.ui-widget-overlay').hide();
			$('form', loginForm).hide();
			$('.ui-widget-overlay').fadeIn(fadeSpeed*2);
			$('form', loginForm).fadeIn(fadeSpeed*2);
        }
    });
    
	// A hack for dialog to close the modal when anything else on the screen is selected: same as search one; possibility to combine
    $('.ui-widget-overlay').live('click', function(){
		if (loginForm.dialog("isOpen")) {
			$('form', loginForm).fadeOut(fadeSpeed*2, 
				function(){ 
					loginForm.fadeOut(fadeSpeed,
						function(){ 
							$('.ui-widget-overlay').fadeOut(fadeSpeed*2, function(){
								loginForm.dialog("close");
							});
						});
					});	
		}
    });

	// Open the search form when search is clicked from the main menu
    $('nav#first ul li.login a').click(function() {
        loginForm.dialog('open');
        if (loginFormTop==0) {
        	loginFormTop = $('.login-form').css('top');
        } else {
        	$('.login-form').css('top', loginFormTop);
        }
        return false;
    });

	if (window.location.href.indexOf('loginform=true') > -1) {
		$('nav#first ul li.login a').trigger('click');
	}

	// This is to switch the password input from a normal text input (hinted) to a password text input
    $("input.password, form.password.new-account input.text").focus(function() {
    
        var inputName = $(this).attr('name'); // grab name of original
        var inputValue = $(this).attr('value'); // grab value of original
        var inputClass = $(this).attr('class'); // grab value of original
        
        /* create new password input */
        var html = '<input type="password" class="' + inputClass + '" name="' + inputName + '" value="' + inputValue + '" />';
        
        $(this).after(html).remove(); // add new, then remove original input
        
        $("input[type='password']").focus();

    });
    
    


    /* Handle image caption rollovers
	-------------------------------------------------------------- */

    var imagesWithCaptions = $('div.image');
    var currentCaption;
    var targetOpacity = (jQuery.browser.msie) ? 0.7 : 1;

    imagesWithCaptions.hover(

    function() {
    
    	$(this).find('img').fadeTo(0.7);
    
        currentCaption = $(this).find('.caption');
        
        if (currentCaption.length > 0) {
            currentCaption.stop().fadeTo(fadeSpeed, targetOpacity, function(){
            
            	if (jQuery.browser.msie) { 
            		$('div', this).each(function(){
            			$(this).get(0).style.removeAttribute('filter');
            		});            		
            	}
            
            });
        }
        
    },
    function() {
    	
    	$(this).find('img').fadeTo(0.8);
    
        if (currentCaption.length > 0) {
            currentCaption.stop().fadeTo(fadeSpeed, 0);
        }
    }

    );
    
	/* -------------------------------------------------------------- 

		HOME
   
	-------------------------------------------------------------- */

	var featuredItems = $('#featured-items');
	var featuredItemImages = $('.image img', featuredItems);
	
	// If we have featured items, fade them in when the page is ready
	if (featuredItems.size()>0) {	
	
		featuredItemImages.hide().randomFadeIn(fadeSpeed*10, fadeSpeed*2);
	
	}

	// If there is a slideshow, apply cycle to it
	var homepageSlideshow = $('body#home .slideshow');
	var homepageSlideshowFirstSlide = $('img:first', homepageSlideshow);
	
	
	if (homepageSlideshow.size()>0) {
	
		homepageSlideshow.cycle({
			timeout: 4000,
			continuous: 0,
			speed: 1000,
			fx: 'fade'
		});
		
		/* Removed load event - too unreliable.
		homepageSlideshow.cycle('pause').hide();
		
		homepageSlideshowFirstSlide.load(function(){
		
			homepageSlideshow.fadeIn(fadeSpeed*4).cycle('resume');
			
		});
		*/
	
	}
	
		

    /* -------------------------------------------------------------- 

		PROJECTS
   
	-------------------------------------------------------------- */

    /* Handle category dropdown
	-------------------------------------------------------------- */

    var catDropdown = $('nav ul.categories');
    
    
	if (catDropdown) {
	
		var catDropdownActive = false;
		var catDropdownToggle = $('li a', catDropdown).eq(0);

	    $(catDropdownToggle).click(function() {
	
	        if (!catDropdownActive) {
	
	            $(this).addClass('active');
	
	            catDropdownActive = true;
	
	            $('ul', catDropdown).slideDown();
	
	        } else {
	
	            $(this).removeClass('active');
	
	            catDropdownActive = false;
	
	            $('ul', catDropdown).slideUp();
	
	        }
	
	        return false;
	
	    });
    
    }

    /* Project thumbnail grid
	-------------------------------------------------------------- */

    var projectGrid = $('#project-grid');
    var selectedCategory;
    
    if (projectGrid.length>0) {
    
		// Remove the right margin from the item at the end of a row
	    $('article:nth-child(5n)', projectGrid).css('margin-right', 0);
    
	 
		// Apply masonry to the grid
		projectGrid.masonry({
		    single: true, 
		    animate: true,
			itemSelector: 'article:not(.invis)',
			animationOptions: {
		        duration: fadeSpeed*4,
		        queue: false
		    }
		});
		
		// Handle the grid behaviour
		var projectItems = $('article', projectGrid);
		var projectImages = $('a img', projectItems);
		
		projectImages.hide().randomFadeIn(fadeSpeed*4, fadeSpeed/4);		
	
	    // Now handle the grid when a category is selected
	    $('a', catDropdown).not(':first').click(function() {
	
	        // Get the selected category from the li class
	        selectedCategory = '.'+$(this).parent().attr('class');
	        
	        if (selectedCategory=='.all') {
	        
				// Show hidden thumbnails
		        $('article.invis', projectGrid).toggleClass('invis').show().animate({ opacity: 1 }, fadeSpeed*4);
	        
	        } else {
	        
		        // Hide visible thumbnails
		        $('article', projectGrid).not('.invis').not(selectedCategory).toggleClass('invis').animate({ opacity: 0 }, fadeSpeed*4).hide();
		        
		        // Show hidden thumbnails
		        $('article' + selectedCategory + '.invis', projectGrid).toggleClass('invis').show().animate({ opacity: 1 }, fadeSpeed*4);
	        
	        }
	        
			projectGrid.masonry();
		
			$(this).addClass('active').parent().siblings().find('a').removeClass('active');
	
	        return false;
	
	    });
	    
	    
    
    }


    /* Project list
	-------------------------------------------------------------- */

    var projectList = $('#project-list');

    // Now handle the grid when a category is selected
    $('a', catDropdown).not(':first').click(function() {

		// Make sure all the list items are visible
        $('ul > li > ul > li', projectList).show();
        
        
        // Get the selected category from the li class
        selectedCategory = $(this).parent().attr('class');
        
        // Fade out the items that are not of that class
        $('ul > li > ul > li:not(.' + selectedCategory + ')', projectList).hide();

        
        if (selectedCategory=="all") {
        	$('ul > li > ul > li', projectList).show();
        }


        
        $(this).addClass('active').parent().siblings().find('a').removeClass('active');

        return false;

    });

    /* Project map
	-------------------------------------------------------------- */

    var projectMap = $('#project-map');

	// Now handle the grid when a category is selected
    $('a', catDropdown).not(':first').click(function() {

        // Get the selected category from the li class
        selectedCategory = '.'+$(this).parent().attr('class');
        
        if (selectedCategory=='.all') {
        
			// Show hidden items
	        $('.info-box.invis', projectMap).toggleClass('invis').animate({ opacity: 1 }, fadeSpeed*4);
        
        } else {
        
	        // Hide visible items
	        $('.info-box', projectMap).not('.invis').not(selectedCategory).toggleClass('invis').animate({ opacity: 0 }, fadeSpeed*4);
	        
	        // Show hidden items
	        $('.info-box' + selectedCategory + '.invis', projectMap).toggleClass('invis').animate({ opacity: 1 }, fadeSpeed*4);
        
        }
	
		$(this).addClass('active').parent().siblings().find('a').removeClass('active');

        return false;

    });


    /* Project detail toggle
	-------------------------------------------------------------- */

    var projectDetailMenu = $('body#projects.detail nav#detail-nav');
    var projectInfo = $('ul li.info', projectDetailMenu);
    var projectInfoClose = $('a.close', projectInfo);
    var projectInfoOpen = $('a.open', projectInfo);
    var projectInfoContent = $('div.content', projectInfo);
    var minimumProjectInfoContentHeight =  168; // to ensure it covers the logo completely
    var projectInfoContentHeight = (projectInfoContent.outerHeight()>minimumProjectInfoContentHeight) ? projectInfoContent.outerHeight() : minimumProjectInfoContentHeight;

    // projectInfo.height(projectInfoContentHeight);
    
    projectInfo.addClass('closed');
	
	projectInfoClose.click(function(){
	
		projectInfoContent.fadeOut(fadeSpeed);
		
		projectInfoClose.fadeOut(fadeSpeed);
		
		projectInfo.addClass('closed').delay(fadeSpeed*2).animate({
			height: "18px"
		}).parent().parent().delay(fadeSpeed*2).animate({
			width: "146px"
		}, function(){
			projectInfoOpen.css('display', 'block');
		});
		
		
		projectInfoOpen.delay(fadeSpeed*4).fadeIn(fadeSpeed, function(){ if(jQuery.browser.msie) { $(this).get(0).style.removeAttribute('filter'); } });
	
		return false;
	});
	
	projectInfoOpen.click(function(){
	
		projectInfoOpen.fadeOut(fadeSpeed);
		
		projectInfo.removeClass('closed').delay(fadeSpeed).animate({
			height: projectInfoContentHeight+"px"
		}).parent().parent().delay(fadeSpeed).animate({
			width: "301px"
		});
		
		projectInfoContent.delay(fadeSpeed*4).fadeIn(fadeSpeed, function(){ if(jQuery.browser.msie) { $(this).get(0).style.removeAttribute('filter'); } });
		
		projectInfoClose.delay(fadeSpeed*4).fadeIn(fadeSpeed, function(){ if(jQuery.browser.msie) { $(this).get(0).style.removeAttribute('filter'); } });
	
		return false;
	
	});
	
	$('body#projects.detail nav#detail-nav ul li.info a.open').hover(
		function(){	$(this).parent().addClass('hover')	},
		function(){	$(this).parent().removeClass('hover');	}
	);
	
	
	/* Add this - REMOVED
	-------------------------------------------------------------- */
	
	/*
	var projectAddThisToolbox = $('.addthis_toolbox');
	
	$('li.share a').click(function(){
	
		if ($(this).hasClass('selected')) {
		
			$(this).removeClass('selected');
		
			projectAddThisToolbox.stop().fadeTo(300, 0);
			
			$(this).css('border-top', '1px solid #BDBDBD');
		
		} else {
		
			$(this).addClass('selected');
		
			projectAddThisToolbox.stop().fadeTo(300, 1);
			
			$(this).css('border-top', '1px solid #0f0');
			
		}
		
		return false;
	
	});
	*/
	
	
	
	/* Show in slideshow hover
	-------------------------------------------------------------- */
	
	var projectDetailImages = $('body#projects.detail .images');
	
	$('p.image', projectDetailImages).stop().hover(
		function(){	$('span.open-slideshow', this).stop().fadeTo(fadeSpeed, 1);	},
		function(){	$('span.open-slideshow', this).stop().fadeTo(fadeSpeed, 0);	}
	);
	
	/* Apply lazy loading to project pages - REMOVED
	-------------------------------------------------------------- */
	/*
	var projectImages = $("body#projects.detail img");
	
	projectImages.hide();
	
	projectImages.bind("load", function () { 
		$(this).fadeIn(fadeSpeed*4);
	});
	*/
	

	/* -------------------------------------------------------------- 

		CONTACT
   
	-------------------------------------------------------------- */

	$('body#contact p.pdf a').hover(
		function(){	$('.content').css('border-bottom-color', '#00FF00');	},
		function(){	$('.content').css('border-bottom-color', '#747679');	}
	);
	

    /* -------------------------------------------------------------- 

		BLOG
   
	-------------------------------------------------------------- */

    var archiveGrid = $('#archive-grid');

    // Remove the right margin from the item at the end of a row
    $('article:nth-child(5n)', archiveGrid).css('margin-right', 0);



	if (archiveGrid.length>0) {
    
		// Remove the right margin from the item at the end of a row
	    $('article:nth-child(5n)', archiveGrid).css('margin-right', 0);
    
		// Apply masonry to the grid
		archiveGrid.masonry({
		    single: true
		});
		
		// Handle the grid behaviour
		var archiveItems = $('article', archiveGrid);
		var archiveImages = $('a img', archiveItems);
		
		archiveImages.hide().randomFadeIn(fadeSpeed*4, fadeSpeed);
	    
    
    }
    
    
    var toolbox;
	var content;
	
	$('p.share a').click(function(){
	
		toolbox = $(this).parent().parent().find('.addthis_toolbox');
		content = $(this).parent().parent().find('.content');
	
		if ($(this).hasClass('selected')) {
		
			$(this).removeClass('selected')
		
			toolbox.stop().fadeTo(300, 0);
			
			content.css('border-bottom', '1px solid #747679');
		
		} else {
		
			$(this).addClass('selected');
		
			toolbox.stop().fadeTo(300, 1);
			
			content.css('border-bottom', '1px solid #0f0');
			
		}
		
		return false;
	
	});



    /* -------------------------------------------------------------- 

		STUDIO
   
	-------------------------------------------------------------- */

    /* Approach
	-------------------------------------------------------------- */

    var approachSections = $('body#studio.approach div.section');
    var approachMenu = $('body#studio.approach nav#third ul li');
    var approachHref;

    // show the first section
    approachSections.first().show();
    approachMenu.first().addClass('selected');

    // now handle the show and hide when a menu item is selected
    $('a', approachMenu).click(function() {

        approachMenu.removeClass('selected');

        $(this).parent().addClass('selected');

        approachHref = $(this).attr('href');

        approachSections.hide();

        $('body#studio.approach div' + approachHref).show();

        return false;

    });

    /* People
	-------------------------------------------------------------- */

    var peopleGrid = $('#people-grid');
    var peopleItems = $('.person', peopleGrid);
    var currentInformation;
    var personClicked = false;
    var initialOpacity = 0.7;
    
    // Handle the grid behaviour
	var peopleImages = $('a img', peopleItems);
	
	peopleImages.hide();
    
    // Random fade in    
    peopleImages.randomFadeIn(fadeSpeed*4, fadeSpeed, initialOpacity);
    
    // Hover
    peopleImages.hover(
    	function(){	if (!personClicked)	{	$(this).fadeTo(fadeSpeed, 1); }	},
    	function(){	if (!personClicked)	{	$(this).fadeTo(fadeSpeed, initialOpacity);	}	}
    );

    // Remove the right margin from the item at the end of a row
    $('div.person:nth-child(5n)', peopleGrid).css('margin-right', 0);

    $('div.person', peopleGrid).click(function() {
    
    	if (!personClicked) {
    
	    	personClicked = true;
	   
			// Get the info panel for this person
			currentInformation = $('.information', this);
	
			// Fade all the other people
			peopleImages.not($('.image a img', this)).each(function(){
			
				$(this).stop().fadeTo(fadeSpeed*4, 0.1, function(){
					$(this).addClass('invis');
					$('.information', this).stop().fadeTo(fadeSpeed*4, 0, function(){ $(this).hide() });
				});
			
			});
			
			// Fade in clicked person
			$('.image a img', this).fadeTo(fadeSpeed*4, 1, function(){
				$(this).removeClass('invis');
				currentInformation.stop().fadeTo(fadeSpeed*4, 1, function(){ $(this).show(); if(jQuery.browser.msie) { $(this).get(0).style.removeAttribute('filter'); } }).position({
				    my: 'left top',
				    of: this,
				    offset: '10 0',
				    at: 'right top',
				    collision: 'flip none'
				});
			});
		
		} else {
		
			$('.image a img', peopleItems).stop().fadeTo(fadeSpeed*4, initialOpacity).removeClass('invis');
			
			$('.information', peopleGrid).stop().fadeTo(fadeSpeed*4, 0, function(){ $(this).hide() });
			
			personClicked = false;
		
		}
		
		return false;
		
	});
	
	// If anywhere else is clicked show all people
	$(window).click(function(){
	
		if (personClicked) {
		
			peopleImages.stop().fadeTo(fadeSpeed*4, initialOpacity).removeClass('invis');
			
			$('.information', peopleGrid).stop().fadeTo(fadeSpeed*4, 0, function(){ $(this).hide() });
			
			personClicked = false;
		
		}
	
	});
	
	

	
	
    /* -------------------------------------------------------------- 

		DOWNLOADS
   
	-------------------------------------------------------------- */

    var currentBucket;
    var downloadCategory;
    var filterStatus;

	$.tablesorter.addParser({ 
		// set a unique id 
		id: 'dd.mm.yy', 
		is: function(s) { 
			// return false so this parser is not auto detected 
			return false; 
		}, 
		format: function(s) { 
			// format your data for normalization 
			return s.substr(7, 9) + s.substr(3, 5) + s.substr(0, 2);
		}, 
		// set type, either numeric or text 
		type: 'numeric' 
	});

    // apply table sorter to all the downloads tables
	$("body#downloads table").tablesorter({
		headers: { 
			0: { 
				sorter: false 
			},
			5: {
				sorter: 'dd.mm.yy'
			}
		} 
	});
    


    
    // Highlight the table row on hover
    $("body#downloads table").not(".uploadtable").find("tbody tr").hover(
		function(){	$(this).find('th, td').animate({ backgroundColor: "#d9ffd9"	}, fadeSpeed);	},
		function(){	$(this).find('th, td').animate({ backgroundColor: "#ffffff"	}, fadeSpeed);	}    
    );

	// Show/hide files.
    $("body#downloads .bucket header a.toggle").click(function() {

        currentBucket = $(this).parent().parent();

        if (currentBucket.hasClass('expanded')) {

            currentBucket.removeClass('expanded');
            // currentBucket.find('.controls').fadeOut(fadeSpeed);
            $('.downloads, .uploads, .filter-status, .controls', currentBucket).slideUp(fadeSpeed);
            
        } else {
            currentBucket.addClass('expanded');
            $('.downloads, .controls', currentBucket).show();
            $.scrollTo(currentBucket, 300);
        }

        return false;

    });
    
    $("body#downloads .success").each(function () {
        var self = this;
        setTimeout(function () {
            $(self).slideUp(500);
        }, 4000);
    })
    
    var t = window.location.search.match(/bucket=(\d+)/)
    if (t && t.length >= 2) {
        var bucket = $("body#downloads .bucket[data-bucket='" + t[1] + "']");
        bucket.addClass('expanded');
        $('.downloads, .controls', bucket).show();
    }
    
    $("body#downloads .bucket").each(function () {
        var bucket = $(this);
        $(this).find("thead .first input").click(function () {
            
            if ($(this).is(':checked')) {
                bucket.find('tbody tr:visible .first:visible input').attr('checked', 'checked');
            } else {
                bucket.find('tbody .first input').attr('checked', '');
            }
            
        });
    })
    
    
    var downloadCategoryLabel, tableRows;

    // filter the downloads according to what has been selected in dropdown
    $('body#downloads .bucket .filter-form').each(function () {
        
        var selects = $(this).find('select');
        var currentBucket = $(this).parents('.bucket').get(0);
        var rows = $(currentBucket).find('table:last tbody tr');
        var filterStatus = $(currentBucket).find('.filter-status');
        
        selects.change(function () {
            
            var map = [];
            selects.each(function () {
                var s = $(this).find('option:selected').val();
                var d = $(this).attr('class');
                var t = $(this).find('option:selected').text();
                
                if (s !== "") {
                    map.push([d, s, t]);
                }
            });
            
            
            $(rows).each(function () {
                var show = true;
                for (var i = 0, len = map.length; i < len; i++) {
                    if ($(this).data(map[i][0]) != map[i][1]) {
                        show = false;
                    }
                }
                
                if (show) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
            
            if (map.length > 0) {
                filterStatus.find('span').html($.map(map, function (m) {
                    return m[2];
                }).join(', '));
                filterStatus.show();
            } else {
                filterStatus.hide();
            }
            
        });
    });
    

    // Show all the rows and reset the filter dropdown if remove is clicked
    $('body#downloads .bucket .filter-status .remove a').click(function() {

        currentBucket = $(this).parent().parent().parent();

        tableRows = $('table tbody tr', currentBucket);

        tableRows.show();

        $('.filter-form select', currentBucket).val('');

        $(this).parent().parent().hide();

        return false;

    });
    
    $('body#downloads .bucket .uploads .toggle').click(function () {
        $(this).parent().slideUp(500);
        return false;
    })

	$('body#downloads .bucket .uploads').submit(function () {
		var go = true;
		$(this).find('tbody tr').each(function () {
			if ($(this).find('input[name="description[]"]').val() != "" && $(this).find('select[name="category[]"] option:selected').val() == "") {
				alert('Please select a category');
				go = false;
			}
		});
		return go;
	});
	
	$('.addmorefiles').each(function () {
		var table = $(this).prev();
		var lastrow = table.find('tbody tr:last');
		var clone = lastrow.clone()
		
		$(this).click(function () {
			table.find('tbody').append(clone.clone());
			return false;
		});
	});
	
	$('.upload_new_files').click(function () {
		var form = $(this).parent().parent().find('form.uploads');
		$(form).slideDown(500);
		return false;
	});
	
	$('.download_files').click(function () {
        var form = $(this).parent().parent().find('form.downloads');
		form.submit();
		return false;
	});
	
    $('form.uploads .submit a.notify_users').click(function () {
        $(this).parent().next().slideToggle(500);
        return false;
    });
	

});


(function($) {

    $.fn.randomFadeIn = function(fadeSpeed, delaySpeed, fadeToOpacity) {
    
		var item;
    
		if (!delaySpeed) {
			delaySpeed = 500;
		}

		if (!fadeSpeed) {
			fadeSpeed = 2000;
		}
		
		if (!fadeToOpacity) {
			fadeToOpacity = 1;
		}

		var orderArray = [];
		for (i=0; i<this.length; i++) {
			orderArray[i] = i;
		}
		
		$.shuffle(orderArray);
		
		i = 0;

		for (var key in orderArray) {
			if (key) {
				item = $(this).eq(orderArray[key]);
				item.delay(i * (delaySpeed)).fadeTo(fadeSpeed, fadeToOpacity).css('display', 'block');
				i++;
			}
		}
		
		return true;
        
    };

})(jQuery);


(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	};
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i, 10), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	};
	
})(jQuery);


(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  };
})(jQuery);


/* IE PNG fix multiple filters */
(function ($) {
    if (!$) { return; }
    $.fn.extend({
        fixPNG: function(sizingMethod, forceBG) {
                if (!($.browser.msie)) { return this; }
                var emptyimg = "/static/css/images/empty.gif"; //Path to empty 1x1px GIF goes here
                sizingMethod = sizingMethod || "scale"; //sizingMethod, defaults to scale (matches image dimensions)
                this.each(function() {
                        var isImg = (forceBG) ? false : jQuery.nodeName(this, "img"),
                                imgname = (isImg) ? this.src : this.currentStyle.backgroundImage,
                                src = (isImg) ? imgname : imgname.substring(5,imgname.length-2);
                        this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')";
                        if (isImg) { this.src = emptyimg; }
                        else { this.style.backgroundImage = "url(" + emptyimg + ")"; }
                });
                return this;
        }
    });
})(jQuery);



