/*
Blakedown javascript

Designed and built by Jonathan Brain
http://jonathanbrain.com
*/


//global variables
var slide_width = 564;
var slide_current = 0;
var slide_total = 0;
var slide_moving = false;
var slide_images = [];
var slide_titles = [];

var page_total = 0;
var page_this = 0;
var page_items_per_page = 0;


//set up page and events
$(document).ready( function() {
	//paginate();
	gallery_clicks();
	smooth_scroll();
	home_banners();
	home_featured_work();
	home_columns_align();
	add_work_filter();
	nav_pop_out();
});


function paginate() {
	
	//get number of items to be paginated
	var paginate_items = $('.paginate-this .project-item').length;
	
	
	//can this page be paginated?
	if ( paginate_items > 0 ) {
	
		//get number of items to show on the page
		page_items_per_page = $('#pagination-items-per-page').val();
	
		if ( parseInt( page_items_per_page ) > 0 ) {
			page_items_per_page = parseInt( page_items_per_page );
		}
		else {
			page_items_per_page = 5;
		}
		
		
		//set this page data
		page_this = 1;
		page_total = Math.round(paginate_items / page_items_per_page);
			
		if ( page_total * page_items_per_page < paginate_items ) {
			page_total++;
		}

		
		//so, does pagination apply to this page?
		if ( page_total > 1 ) {
		
			//show items on page 1
			$('.paginate-this .project-item').each( function(index) {
				if ( index >= page_items_per_page ) {
					$(this).hide();
				}
			});
	
			
			//build pager
			show_pager(1);
		}
	}
}


function show_page( page ) {
	
	//remove pager
	$('#pager-note').remove();
	$('#pager').remove();
	
	//show items on this page
	$('.paginate-this .project-item').each( function(index) {
		if ( index >= ( page_items_per_page * (page-1) ) && index < ( page_items_per_page * page ) ) {
			$(this).slideDown(800);
			//$(this).fadeIn(500);
		}
		else {
			$(this).slideUp(400);
			//$(this).hide()
		}
	});
	
	//set this page data
	page_this = page;
	
	//re-build pager
	show_pager( page );
}


function show_pager( page ) {
	//build pager
	pager = '<ul id="pager">';
	
	//add a 'previous' arrow to the pager
	if ( page_this == 1 ) {
		//if this is the first page, grey-out the arrow
		pager += '<li><span><img src="/images/arrow_pager_left_off.gif" alt="" /></span></li>';
	}
	else {
		pager += '<li><a href="#" onclick="show_page('+(page_this-1)+');"><img src="/images/arrow_pager_left.gif" alt="" /></a></li>';
	}
		
		
	for ( var i = 1; i <= page_total; i++ ) {
		if ( page_this == i ) {
			//this is the current page
			pager += '<li class="on"><span>'+i+'</span></li>';
		}
		else {
			pager += '<li><a href="#" onclick="show_page('+i+');">'+i+'</a></li>';
		}
	}
	
	//add a 'next' arrow to the pager
	if ( page_this == page_total ) {
		//if this is the last page, grey-out the arrow
		pager += '<li><span><img src="/images/arrow_pager_right_off.gif" alt="" /></span></li>';
	}
	else {
		pager += '<li><a href="#" onclick="show_page('+(page_this+1)+');"><img src="/images/arrow_pager_right.gif" alt="" /></a></li>';
	}
	
	pager += '</ul>';
	
	
	//build pager note
	var pager_note = '<p id="pager-note">' + $('.paginate-this .project-item').length + ' items found: showing page ' + page + ' of ' + page_total + '</p>';
	
	//display the pager
	$('.paginate-this').after( pager ).after( pager_note );
}


function gallery_clicks() {

	//set up gallery links to show slides
	$('.gallery a').click( function() {
		//get slide data in raw form
		slide_images = [];
		slide_titles = [];
		var slide_current_src = strip_thumbnail( $(this).find('img').attr('src') );
		slide_total = 0;
		
		$(this).parent().parent().find('li').each( function(index) {
			slide_images[slide_total] = strip_thumbnail( $(this).find('img').attr('src') );
			slide_titles[slide_total] = $(this).find('img').attr('alt');
			
			if ( slide_images[slide_total] == slide_current_src ) {
				slide_current = index;
			}
			
			slide_total ++;
		});
		
		if ( slide_images[0] != '' ) {
		
			//initiate slide show
			show_slides( slide_current );
		}
		
		return false;
	});
}


function strip_thumbnail( src ) {
	var url_start = src.indexOf( '/perch' );
	
	if ( url_start > 0 ) {
		return src.substr( url_start );
	}
	else {
		return src;
	}
}
		
		
function show_slides( slide_this ) {
	
	//add lightbox elements to document
	if ( document.getElementById( 'lightbox' ) === null ) {
		
		//get slide list
		var slide_list = '';
		for ( var i = 0; i < slide_total; i++ ) {
			slide_list += '<div class="slide-image-container"><img class="slide-image-' + i + '" src="' + slide_images[i] + '" alt="' + slide_titles[i] + '" onload="show_slideshow_image(\'' + i + '\');" /></div>';
		}		
		
		//slide show
		$('body').append('<div id="lightbox-overlay" onclick="lightbox_close();"></div><div id="lightbox"><div id="lightbox-outer"><div id="lightbox-inner">' + slide_list + '</div><a id="lightbox-previous" class="invisible" href="#" onclick="slide_previous(); return false;"><span>Previous</span></a><a id="lightbox-next" class="invisible" href="#" onclick="slide_next(); return false;"><span>Next</span></a></div><div id="lightbox-title"><h2>' + slide_titles[slide_this] + '</h2><a id="lightbox-close" onclick="lightbox_close(); return false;" href="#"><span>Close</span></a></div></div>');
		
		//show it
		$('#lightbox-overlay').hide().height( $(document).height() ).show();
		$('#lightbox').hide().fadeIn(200);
		$('#lightbox-inner').css({ width: (slide_total * slide_width) + 'px' });
		$('#lightbox-inner').css({ marginLeft: '-' + (slide_this * slide_width) + 'px' });
		
		//set global variables
		slide_current = slide_this;	
		slide_moving = false;
		
	
		//bind events to buttons
		$('#lightbox-outer').hover( function() {
			slide_buttons();
			$('#lightbox-outer a').fadeIn(200);
		}, function() {
			$('#lightbox-outer a').fadeOut(200);
		});
		
		//show buttons initially
		slide_buttons();
	}
}


function show_slideshow_image( slide_this ) {
	//show slide image
	$('#lightbox-inner img.slide-image-' + slide_this).fadeIn(200);
}


function lightbox_close() {
	//remove the lightbox
	$('#lightbox').fadeOut(200, function() { 
		$(this).remove(); 
	});
	$('#lightbox-overlay').remove(); 
}


function slide_previous() {
	//show previous slide
	if ( !slide_moving ) {
		slide_moving = true;
		
		if ( slide_current > 0 ) {
			slide_current--;
			show_slide( slide_current );
			
			//tidy up buttons
			slide_buttons();
		}
	
		slide_moving = false;
	}
}


function slide_next() {
	//show next slide
	if ( !slide_moving ) {
		slide_moving = true;
		
		if ( slide_current < slide_total-1 ) {
			slide_current++;
			show_slide( slide_current );
			
			//tidy up buttons
			slide_buttons();
		}
	
		slide_moving = false;
	}
}


function show_slide( slide ) {
	//animate slideshow
	$('#lightbox-inner').animate({ marginLeft: '-' + (slide * slide_width) + 'px' }, 400);
	
	if ( $.browser.msie && $.browser.version == "6.0" ) {
		$('#lightbox-title h2').empty().hide().text(slide_titles[slide]).show();
	}
	else {
		$('#lightbox-title h2').empty().hide().text(slide_titles[slide]).fadeIn(200);
	}
}


function slide_buttons() {
	//show only relevant buttons
	if ( slide_current == 0 ) {
		$('#lightbox-previous').addClass('invisible');
	}
	else { 
		$('#lightbox-previous').removeClass('invisible');
	}
	
	if ( slide_current == slide_total-1 ) {
		$('#lightbox-next').addClass('invisible');
	}
	else { 
		$('#lightbox-next').removeClass('invisible');
	}
}


//add smooth-scrolling to elements
function smooth_scroll() {
	$('.scroll-to').click( function() {
		var target = $(this).attr( 'href' );
		var destination = $("[name='" + target.substring( 1, target.length ) + "']").offset().top;
		$('html:not(:animated),body:not(:animated)').animate({ scrollTop: destination-10 }, 500 );
		return false;
	});
}


//initialise home page banners
function home_banners() {
	//hide all banners except first one
	$('#banner-home-inner li:not(:first)').hide();
	
	//set timer if this is the home page
	if ( $('#banner-home-inner li').size() > 0 ) {
		setTimeout( function() { show_next_banner(); }, 10000 );
	}
}


//show a specific banner
function show_banner( banner_number ) {
	//hide all banners
	$('#banner-home-inner li').hide(); 
	
	//show matching banner - tweaked so the fade works correctly in IE
	//$('#banner-home-inner #banner-' + banner_number).fadeIn(500);
	$('#banner-home-inner #banner-' + banner_number + ' img').hide();
	$('#banner-home-inner #banner-' + banner_number).show();
	$('#banner-home-inner #banner-' + banner_number + ' img').fadeIn(500);
}


//home page banner - show next
function show_next_banner() {
	
	//get number of banners
	var banners_total = $('#banner-home-inner li').size();
	
	//get number of this banner
	var home_banner_id = $('#banner-home-inner li:visible').attr('id');
	var home_banner = parseInt( home_banner_id.substr( 7 ) );
	
	//calculate number of next banner
	home_banner++;
	if ( home_banner > banners_total ) {
		home_banner = 1;
	}
	
	//display it
	show_banner( home_banner );
	
	//set timer
	setTimeout( function() { show_next_banner(); }, 10000 );
}


//home featured work
function home_featured_work() {
	$('#featured-work-list li:not(:first)').hide();
	
	var featured_work_index = 0;
	$('#featured-work-list li').each( function() {
		featured_work_index++;
		$(this).addClass('featured-work-index-' + featured_work_index);
	});
		
	home_featured_work_count = $('#featured-work-list li').length;
	home_featured_work_index = 1;

	//set timer
	setTimeout( function() { show_next_featured_work(); }, 5000 );
}


function show_next_featured_work() {
	
	//hide current featured work
	$('#featured-work-list .featured-work-index-' + home_featured_work_index).hide();
	
	//update index
	home_featured_work_index++;
	if ( home_featured_work_index > home_featured_work_count ) {
		home_featured_work_index = 1;
	}
	
	//display new featured work
	if ( $.browser.msie && $.browser.version == "6.0" ) {
		$('#featured-work-list .featured-work-index-' + home_featured_work_index).show();
	}
	else {
		$('#featured-work-list .featured-work-index-' + home_featured_work_index).fadeIn(500);
	}
	
	//set timer
	setTimeout( function() { show_next_featured_work(); }, 5000 );
}


//align the bottom of the three homepage columns
function home_columns_align() {
	
	var max_height = 0;
	$('#main-upper-content .column-single').each( function() {
		if ( $(this).height() > max_height ) {
			max_height = $(this).height();
		}
	});
	
	$('#main-upper-content .column-single').css({ height: max_height + 'px' });
}


//filter the Our Work section 
function add_work_filter() {
	//display work filter for our-work section	
	var work_type = get_work_filter_cookie();
	
	//display specific section if # variable available
	if ( window.location.hash != '' ) {
		work_type = window.location.hash.substring( 1 );
		if ( work_type != 'sports' && work_type != 'landscaping' ) {
			work_type = 'all';
		}
	}
	
	var filter_control = '<div id="work-filter"><span id="work-filter-title">Filter projects by type: </span><ul>';
	filter_control += '<li id="work-filter-all" class="'+work_filter_check( work_type, 'all' )+'"><a class="work-filter-button" href="#" onclick="filter_projects(\'all\'); return false;"><span>All projects</span></a></li>';
	filter_control += '<li id="work-filter-landscaping" class="'+work_filter_check( work_type, 'landscaping' )+'"><a class="work-filter-button" href="#" onclick="filter_projects(\'landscaping\'); return false;"><span>Landscaping projects</span></a></li>';
	filter_control += '<li id="work-filter-sports" class="'+work_filter_check( work_type, 'sports' )+'"><a class="work-filter-button" href="#" onclick="filter_projects(\'sports\'); return false;"><span>Sports facilities projects</span></a></li>';
	filter_control += '</ul></div>';
	
	$('.add-work-filter').prepend( filter_control );
	
	//apply filter
	apply_work_filter( work_type );
}

function work_filter_check( work_type, check ) {
	if ( work_type == check ) {
		return 'on';
	}
	else {
		return '';
	}
}

function get_work_filter_cookie() {
	
	//get work filter cookie
	var work_type = 'all';
	var work_type_cookie = get_cookie('work_filter');
	
	if ( work_type_cookie == 'sports' || work_type_cookie == 'landscaping' ) {
		work_type = work_type_cookie;
	}
	
	return work_type;
}

function apply_work_filter( filter ) {

	var speed = 250;
	
	//show items on this page
	if ( filter == 'landscaping' ) {
		$('.project-type-landscaping' ).hide().fadeIn(speed);
		$('.project-type-sports' ).hide();
	}
	else if ( filter == 'sports' ) {
		$('.project-type-landscaping' ).hide();
		$('.project-type-sports' ).hide().fadeIn(speed);
	}
	else {
		$('.project-type-landscaping' ).hide().fadeIn(speed);
		$('.project-type-sports' ).hide().fadeIn(speed);
	}
	
	if ( $('.add-work-filter').val() != undefined ) {
		window.location.hash = filter;
	}
	
}


function filter_projects( filter ) {
	set_cookie( 'work_filter', filter, '', '', '', '/', '', '' );
	set_work_filter_menu( filter );
	apply_work_filter( filter );
}

function set_work_filter_menu( filter ) {
	$('#work-filter li').removeClass('on');
	$('#work-filter-'+filter).addClass('on');
}


//cookie functions
function get_cookie( cookie_name ) {
	if ( document.cookie.length > 0 ) {
		var cookie_start = document.cookie.indexOf( cookie_name + "=" );
		if ( cookie_start != -1) {
			cookie_start = cookie_start + cookie_name.length+1;
			cookie_end = document.cookie.indexOf( ";", cookie_start );
			if ( cookie_end == -1 ) {
				cookie_end = document.cookie.length;
			}
			return unescape( document.cookie.substring( cookie_start, cookie_end ) );
		}
	}
	return '';
}

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}


function nav_pop_out() {
	//The gist of this code was heavily borrowed from grabaperch.com
	
	if ( $.browser.msie && ( $.browser.version == '6.0' || $.browser.version == '7.0' ) ) {
		//sorry IE users, but your z-index bug is too much for me today
	}
	else {
		var timer;
		
		$('#nav li').mouseenter( function() {
			clearTimeout(timer);
			this_item = $(this);
			$('#nav li').removeClass('pop-out-on');
			$(this).addClass('pop-out-on');
			$('#nav li:not(.pop-out-on) .nav-pop-out').fadeOut();
			this_item.find('.nav-pop-out').fadeIn();
		});
		
		$('#nav li').mouseleave( function() {
			clearTimeout(timer);
			var this_item = $(this);
			timer = window.setTimeout( function(){
				this_item.find('.nav-pop-out').fadeOut();
			}, 1000);
		});
		
		$('#nav li .nav-pop-out').mouseenter( function() {
			clearTimeout(timer);
			$(this).parents('li').addClass('pop-out-on');
			$(this).show();
		});
		
		$('#nav li .nav-pop-out').mouseleave( function() {
			clearTimeout(timer);
			var this_item = $(this);
			timer = window.setTimeout( function(){
				this_item.fadeOut();
			}, 1000);
		});
	}
}
