function replaceFormat(source, format) {
      var protocol='';
      if(source.indexOf('http://')>-1) {
            protocol='http://';
            source=source.replace('http://','');
      }else if(source.indexOf('https://')>-1) {
            protocol='https://';
            source=source.replace('https://','');
      }
      source=source.split('/');
      source[3]=format;
      return protocol+source.join('/');  
};

$(function() {
	
	// Set up frontpage cycle
	var cycle = $('#banner .element');
	if(cycle.length) {
		cycle.cycle({
			keep : true,
			previous : false,
			navigation : true,
			navigationKeep : true,
			next : false
		});
	};
	
	// Set up project images cycle
	var cycle = $('#project .images img');
	if(cycle.length) {
		cycle.cycle({
			previous : false,
			navigation : true,
			next : false,
			interval : 8000
		});		
	};
	
	// Seperate authors
	var authors = $('.authors');
	if(authors.length) {
		authors.each(function() {
			$(this).find('span').slice(0, -1).append(',');
		});
	};
	
	
	// Set up localization
	$('#lc').css('display', 'none');
	
	var lc = $('.lc');
	if(lc.length && $('.lc-title').eq(1).text().length) {

		var labels = [
			'Read this article in the original language',
			'Read this article in English',
		];
		
		var step = 0;
		$('#lc-button').show().append($('<a />', {
			href : '',
			text : labels[step],
			click : function(event) {
				$(this).text(labels[step = step == 0 ? 1 : 0]);
				lc.each(function() {
					var el = $(this),
						html = el.html(),
						tar = $('.' + el.attr('class').split(' ')[1]).not(el);
					el.html(tar.html());
					tar.html(html);
				});
				event.preventDefault();
			}
		}));
	
	};
	
	// Set up related projects cycle
	var cycle = $('#projects-view .element');
	if(cycle.length) {
	
		var oHeight = 110;
		
		cycle.cycle({
			interval : 8000,
			navigation : true,
			numbers : false,
			keep : true
		});
		
		cycle.each(function() {
			
			var el = $(this),
				title = el.attr('title');
				
			var overlay = $('<span />', {
				className : 'overlay',
				css : {
					'display' : 'block',
					'padding-top' : '5',
					'opacity' : '0'
				}
			});
			overlay.appendTo(el);
			
			var overlayInner = $('<span />', {
				className : 'overlay-inner',
				text : title
			});
			overlayInner.appendTo(overlay);
			
			el.removeAttr('title');
			
			el.bind({
				'mouseover' : function() {
					overlay.stop();
					overlay.animate({
						'opacity' : '1',
						'padding-top' : '20',
						'height' : oHeight - 20
					}, 150);
				},
				'mouseout' : function() {
					overlay.stop();
					overlay.animate({
						'opacity' : '0',
						'padding-top' : '5',
						'height' : oHeight - 5
					}, 100)
				}
			});
			
		});
		
	};
	
	// Set up the main navigation
	$('#main-nav').menu({
		effect : 'fade',
		hide : 'slideVertical',
		maxWidth : 960
	});
	
	// Hide sub nav when empty
	var subnav = $('#sub-nav');
	if(subnav.length) {
		if(!subnav.find('a').length) {
			subnav.remove();
		};
	};
	
	// More links shizzle
	var moreLinks = $('.view-more');
	if(moreLinks.length) {
		moreLinks.each(function() {
			
			var el = $(this),
				id = el.attr('id'),
				container = $('#' + id.substring(0, id.lastIndexOf('-')));
				
			if(container.children().length) {
				el.appendTo(container);
			} else {
				el.css('display', 'none');
			};
			
		});
	};
	
	// Set up tabs
	var tabs = $('#tabs');
	if(tabs.length) {
	
		// Move the publication order form to the tabs container
		var form = $('#order-form');
		if(form.length && $('.publication-form-1').length) {
			form.css('display', 'block');
			form.appendTo(tabs);
		};
		
		// Move the more links to the appropriate tabs
		var moreLinks = $('.tab-more');
		if(moreLinks.length) {
			moreLinks.each(function() {
				
				var el = $(this),
					id = el.attr('id'),
					container = $('#' + id.substring(0, id.lastIndexOf('-')));
					
				if(container.children().length) {
					el.appendTo(container);
				} else {
					el.css('display', 'none');
				};
				
			});
		};
		
		// Move the documents to the publications tab
		var documents = $('#documents-view'),
			publications = $('#publications-view');
			
		if(documents.length) {
			if(publications.length) {
				documents.appendTo(publications);
			} else {
				documents.addClass('tab');
				documents.children('h2').addClass('tab-title');
			};
		};
	
		// Run tabs script
		function show(index) {
			
			$.each(liNodes, function(i) {
				if(index == i) {
					$(this).addClass('active');
				} else {
					$(this).removeClass('active');
				};
			});
			
			pages.hide();
			pages.eq(index).show();
			
		};
		
		var pages = tabs.find('.tab');
		if(pages.length) {
			
			// Custom addition -- remove pages which contain no elements with the class element
			pages.find('.tab').each(function() {
				var page = $(this);
				if(!page.find('.element').length) {
					page.remove();
				};
			});
		
			var titles = tabs.find('.tab-title'),
				liNodes = [];
		
			var ulNode = $('<ul class="navigation" />');
			ulNode.prependTo(tabs);
			
			titles.each(function(i) {
			
				var title = $(this);
				
				var liNode = $('<li />');
				liNode.appendTo(ulNode);
				liNodes.push(liNode);
				
				var aNode = $('<a />', {
					click : function(event) {
						show(i);
						event.preventDefault();
					},
					href : '#'
				});
				aNode.appendTo(liNode);
				
				$('<span>' + title.text() + '</span>').appendTo(aNode);
				
			});
			
			titles.remove();
			
			show(0);
			
		} else {
		
			tabs.remove();
		
		};
			
	};
	 
	// Set up search box
	var search = $('#search');
	if(search.length) {
		
		var input = search.find('input'),
			params = window.location.search,
			searchParam = 'search=',
			searchParamPos = params.indexOf(searchParam),
			searchKeyPos = params.indexOf('search_key='),
			nextParamPos = params.indexOf('&', searchParamPos),
			oVal;

		if(params && searchParamPos >= 0 && searchKeyPos == -1) {
			if(nextParamPos > 0) {
				oVal = params.substring(searchParamPos + searchParam.length, nextParamPos);
			} else {
				oVal = params.substring(searchParamPos + searchParam.length);
			};
			oVal = oVal.replace('+', ' ');
			oVal = unescape(oVal);
		} else {
			oVal = 'Click here to search';
		};
		
		search.bind('submit', function(event) {
			var val = input.val();
			if(val == '' || val == oVal) {
				return event.preventDefault();
			};
		});
		
		input.val(oVal);
		
		input.bind({
			'focus' : function() {
				if(input.val() == oVal) {
					input.val('');
				};
			},
			'blur' : function() {
				if(input.val() == '') {
					input.val(oVal);
				};
			}
		});
		
	};
	
	// Set up print button
	var print = $('#print');
	if(print.length) {
		print.bind('click', function(event) {
			window.print();
			event.preventDefault();
		});
	};
	
	var filter = $('#filter');
	if(filter.length) {
		
		// Set up filter results	
		var results = filter.find('.total-results'),
			resultsCount = results.find('span').text(),
			reset = filter.find('.reset'),
			selects = filter.find('select');
	
		if(resultsCount == 1){
			results.text(resultsCount + ' result is found');
		};
		
		results.appendTo('#filter');
		
		var loading = $('<img />', {
			alt : 'Loading',
			css : {
				display : 'none'	
			},
			src : '/style/tropenbos2/img/loading.gif'
		});
		loading.appendTo(filter);
		
		selects.bind('change', function(){
			results.hide();
			loading.show();
		});
		
		selects.each(function(){
			if($(this).val()){
				reset.show();
				return false;
			};
		});
		
		// Reverse sort in year select
		var yearSelect = $('select[name=output_year]');
		if(yearSelect.length) {
			
			var options = yearSelect.children('option');
			//console.log(options);
			//yearSelect.remove();
			
			var optionsLength = options.length;
			options.each(function(i) {
				yearSelect.append(options.eq(optionsLength - i));
			});
			
		};
		
	};
	
	// Hide overview links
	$('#right #country-projects-view').children('.overview:not(:last)').remove();
	$('#right #news-articles-view').children('.overview:not(:last)').remove();
	$('#right #country-publications-view').find('.overview:not(:last)').remove();
	
	// Document icons
	if($('#documents-view').find('li').length){
		
		$('#documents-view').find('li').each(function(){
			
			var link = $(this).find('a').attr('href'),
				ext = link.substring(link.lastIndexOf('.'));
			
			if(ext == '.doc' || ext == '.docx'){
				
				$(this).addClass('word');
				
			}else if(ext == '.pdf'){
				
				$(this).addClass('pdf');
				
			}
			
		});
		
	}
	
	// Publication image highlight
	$('#publications .element.highlight').each(function(){
		
		$(this).find('.image').addClass('large');
		
		var image = $(this).find('img').attr('src'),
			newImage = replaceFormat(image, 'publication_image');
		
		$(this).find('img').attr('src', newImage);
		
	});
	
	// Hide order form on publications page -- not needed, should be hidden by CSS by default
	/* if($('#publications').length){
		$('#tabs').hide();
	} */
	
});
