$(document).ready(function() {

$("body").addClass("jscript");
extLinks();
$("input, textarea, select, button").uniform();


$('h1,h2').html(function(index, oldhtml) {
  return '<span>&#047;&#032;</span>' + oldhtml;
});

$('h2.project').html('<span>&#047;&#032;</span>Project latest');

//$('.rawContent a:not(.CGBlogSummary a)').html(function(index, oldhtml) {
//  return '<span>&#093;&#032;</span>' + oldhtml + '<span>&#032;&#091;</span>';
//});

$("a[rel='colorbox']").colorbox();

// dim portfolio thumbnails that are not matched
$('div.thumbnails div:not(.shown)').stop().animate({"opacity": "0.2"}, "slow");


// add onclick behaviour to portfolio thumbnails
$('.portfolio div.thumbnails img').hover(
function() {
$(this).stop().animate({"opacity": "0.5"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});

$(".funder_logos img").css({ opacity: 0.3 });
   
// add hover behaviour to funder logos
$('.funder_logos img').hover(
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "0.3"}, "slow");
});


//grayscale.prepare( $('.funder_logos img') );
//grayscale( $('.funder_logos img') );


//$('.funder_logos img').hover(function() {
//		grayscale.reset( $(this) );
//	}, function() {
 //       grayscale( $(this) );	});




$('div.thumbnails div h3').hover(
function() {
$( this ).addClass( 'hover' );
$( this ).attr( 'title', 'View project in more detail' );
$( 'div.thumbnails div' ).css( 'cursor', 'pointer' );
},
function() {
$( this ).removeClass( 'hover' );
});


// add onclick behaviour to portfolio thumbnails
 $( 'div.thumbnails div ' ).click(function(){
    window.location=$(this).find("a:first").attr("href");
    return false;
});


// does tabs wrapper exist ?
if ($('#tabsWrapper').length != 0 ) {

// add controls
$('#tabsWrapper').prepend('<ul id="controls">');

var filternav = '<li class="Chronological"><a href="#" class="chronological" title="Sort projects chronologically">Chronological</a></li><li class="Alphabetical"><a href="#" class="alphabetical" title="Sort projects alphabetically">Alphabetical</a></li>';
var filternavextra = '<li class="allprojects"><a href="/portfolio" class="allprojects" title="View all projects">All projects</a></li>';


$('#tabsWrapper.portfoliopage:not(.allprojects) ul').html(filternav);
$('#tabsWrapper.portfoliopage.allprojects ul').html(filternav + filternavextra);

$( '#controls li.Chronological a, #controls li.Alphabetical a' ).click( function(e) {
e.preventDefault();
});

// change view order ids to numbers
$( 'div.thumbnails div' ).each(function () {
$(this).attr("id", $(this).attr("id").substring(5) );
});


$( '#controls li.Chronological' ).click( function() {
$(this).toggleClass( 'activeSlide');
$('#controls li.Alphabetical').removeClass( 'activeSlide');
$( 'div.thumbnails' ).css("backgroundPosition", '-5950px -143px');
$('div.thumbnails div').sortElements(function(a, b){

a = $(a).attr('id');
b = $(b).attr('id');

 return +a > +b ? 1 : -1;
});
});

$("#controls li.Chronological").trigger("click");





//sort alphabetical toggle /reverse
$( '#controls li.Alphabetical').click(function(){
$(this).toggleClass( 'activeSlide');
$('#controls li.Chronological').removeClass( 'activeSlide');
$( 'div.thumbnails' ).css("backgroundPosition", '-4950px -143px');
$( 'div.thumbnails div h3' ).sortElements(function(a, b){
a = $(a).text();
b = $(b).text();
return a > b ? 1 : -1;
}, function(){
return this.parentNode;
});
});


// if tabs exists
if ($('#tabs').length != 0 ) {

// find number of elements
var kids = $("#tabs").children();
var len = kids.length;

// add class of first elemnt name to controls container
$('#controls').addClass( kids.attr('id'));
}


// if there is only one element in the slideshow, create title without link
if (len == 1 ) {

$('#controls').html('<li class="'+ kids.attr('id') + '">' + kids.attr('id') + '</li>');
$('#controls li').addClass( 'activeSlide' );

// if the element is images or video... add caption containers
if (kids.attr('id') == 'Image' || 'Video' ) {
addCaptions();

// if there is only one video or image, manually populate captions
if (  $('#videoSlideshow a').length == 1 || $('#imageSlideshow a').length == 1 )  {
populateCaptions();
}

}





// else generate links for the other elements
} else {

$('#tabs').cycle({
                fx: 'fade',
                speed:  'slow',
                timeout: 0,
                pager:  '#controls',  
                pagerAnchorBuilder: function(idx, slide) { 
                return '<li class="'+ $(slide).attr('id') +'"><a href="#"' + 'class="' + $(slide).attr('id') + '">' + $(slide).attr('id') + '</a></li>';
        }
});

addCaptions();


// set onclick actions for the other elements

$( '#controls li.Image a, #controls li.Documents a, #controls li.Sound a, #controls li.Video a' ).click( function(e) {
e.preventDefault();
});

$( '#controls li.Image'  ).click( function() {
$( '#controls' ).css("backgroundPosition", '-712px 7px');
$('#vidCaption').hide();
$('#caption').show();
$('#imageSlideshow').cycle(resume);
});

$('#controls li.Documents'  ).click( function() {
$('#controls' ).css("backgroundPosition", '-962px 7px');
$('#caption').hide();
$('#vidCaption').hide();
$('#imageSlideshow').cycle(pause);
});

$('#controls li.Sound'  ).click( function() {
$('#controls' ).css("backgroundPosition", '-1212px 7px');
$('#caption').hide();
$('#vidCaption').hide();
$('#imageSlideshow').cycle(pause);
});
  
$('#controls li.Video'  ).click( function() {
$('#controls' ).css("backgroundPosition", '-1462px 7px');
$('#vidCaption').show();
$('#caption').hide();
$('#imageSlideshow').cycle(pause);
}); 

}
}


// if there are more than one video, setup video transport for slideshow
if ($('#videoSlideshow a').length != 1 ) {

$('#videoSlideshow').after('<ul id="vidNav" class="nav"><li id="vidPrev"><a id="videoPrev" href="#">Prev</a></li></li><li id="vidNext"><a id="videoNext" href="#">Next</a></li><li id="vidCount"></li></ul>').cycle({ 
    fx:     'fade', 
    speed:  'fast', 
    timeout: 0, 
    next:   '#videoNext', 
    prev:   '#videoPrev',
    after:     vidOnAfter
});

}

else if ($('#videoSlideshow a').length == 1 ){
populateCaptions();
}


// if there are more than one image, setup image transport for slideshow
if ($('#imageSlideshow a').length != 1 ) {

$('#imageSlideshow').after('<ul id="imgNav" class="nav"><li id="imgPrev"><a id="imagePrev" href="#">Prev</a></li><li id="imgPause"><a id="imagePause" href="#">Pause</a></li><li id="imgNext"><a id="imageNext" "href="#">Next</a></li><li id="count"></li></ul>').cycle({ 
    fx:     'fade', 
    speed:  'fast', 
    timeout: 10000, 
    next:   '#imageNext', 
    prev:   '#imagePrev',
    after:     onAfter
 
});
}

else if ($('#imageSlideshow a').length == 1 ){
populateCaptions();
}


function onAfter(curr,next,opts) {
		$('#caption').html('<p>' + this.title + '</p>');
        var count = (opts.currSlide + 1) + '/' + opts.slideCount;
	    $('#count').html(count);
	    $('#imgPause a').removeClass("paused");
	    $('#imageSlideshow').cycle('resume'); // if paused
}

function vidOnAfter(curr,next,opts) {
	$('#vidCaption').html('<p>' + $(this).find("a:first").attr("title") + '</p>');
    var count = (opts.currSlide + 1) + '/' + opts.slideCount;
	$('#vidCount').html(count);
	
	
}


// pause button
$('#imgPause a').click(function(e) { 
e.preventDefault();
$('#imageSlideshow').cycle('toggle');
$(this).toggleClass("paused") 
}); 


 // end onload
});


// external links
function extLinks() {

    $("a[rel='external']").click( function(){
        window.open( this.href );
        return false;
    });
    
};

function addCaptions() {

if ($('#controls li.Video').length != 0) { $('#tabsWrapper').prepend('<div id="vidCaption">'); }
if ($('#controls li.Image').length != 0) {
$('#tabsWrapper').prepend('<div id="caption">');
$('#vidCaption').hide();
}

}

function populateCaptions() {
if ($('#caption').length != 0) { $('#caption').html('<p>' + $('#imageSlideshow').find("a:first").attr("title") + '</p>'); }
if ($('#vidCaption').length != 0) {$('#vidCaption').html('<p>' + $('#videoSlideshow').find("a:first").attr("title") + '</p>'); }
}



jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

