function calendarLinks() {
	if($('a.calNav').size() > 0) {
		$('a.calNav').click(function(){
			ajaxCalendar();
			return false;
		});
	}
	toolTips();
}

function ajaxCalendar() {
	var target = $(this).attr('href');
	target = target.replace('calendar','ajax_calendar/'+$('body').attr('class'));
	console.log(target);
	$('#calendar').load(target,'',calendarLinks);
}

function toolTips() {
	if($('td.events a').size() > 0) {
		$('td.events a').tooltip({
			track: true, 
			delay: 0,
			showBody: ' | ',
			showURL: false,
			opacity: 0.5
		});		
	}
}

function printPage() {
    var link_text = "";
	
	if($('#socialLinks').size() > 0) {
		if($("html").attr("Lang") == "en")
        {
            link_text = "Print this page";
        }
        else
        {
            link_text = "Argraffwch y dudalen hon";
        }

        $('#socialLinks').prepend('<li><a href="#printPage" id="printPage" title="' + link_text + '">' + link_text + '</a></li>');		
	}

	if($('#page-tools').size() > 0) {
		if($("html").attr("Lang") == "en")
        {
            link_text = "Print this page";
        }
        else
        {
            link_text = "Argraffwch y dudalen hon";
        }

//        $('#page-tools').prepend('<a href="#printPage" id="printPage"><img src="/assets/v2/images/icon-print.gif" alt="' + link_text + '" width="14" height="11"/> ' + link_text + '</a>');
	      $('#page-tools').prepend('<a href="#printPage" id="printPage">' + link_text + '</a>'); 
	}

	$('#printPage').click(function(){
		window.print();
		return false;
	});
}

function matchHeight() {
	if($('.basicJS').size() == 0) {
		if($('.matchHeight').size() > 0) {
			var maxHeight = '0';
			$('.matchHeight').each(function(){
				maxHeight = ($(this).height() > maxHeight) ? $(this).height() : maxHeight;
			});
			$('.matchHeight').height(maxHeight);
		}
	}
}

function leadImage() {
	if($('.featured-intro').size() > 0 && $('img#leadImage').size() > 0) {
			$('.featured-intro').css('padding-right','254px');
			var bottomPadding = $('.featured-intro:first').css('padding-bottom');
			var topPadding = $('.featured-intro:first').css('padding-top');
			var minHeight = $('.featured-intro:first').height();
			var maxHeight = $('img#leadImage').height() - parseInt(bottomPadding) - parseInt(topPadding);
			if(maxHeight < minHeight) maxHeight = minHeight;
			$('.featured-intro').css('padding-right','0').height(maxHeight);
		} else if($('.intro').size() > 0 && $('img#leadImage').size() > 0) {
			$('.intro').css('padding-right','254px');
			var bottomPadding = $('.intro:first').css('padding-bottom');
			var topPadding = $('.intro:first').css('padding-top');
			var minHeight = $('.intro:first').height();
			var maxHeight = $('img#leadImage').height() - parseInt(bottomPadding) - parseInt(topPadding);
			if(maxHeight < minHeight) { maxHeight = minHeight; }
			$('.intro').css('padding-right','0').height(maxHeight);
		}
	
}

function highlightExternalLinks() {
    var extlink_text = "";
    var pdflink_text = "";

	if($("html").attr("Lang") == "en")
    {
        extlink_text = "This link points to an external website";
        pdflink_text = "This link will open in a new window";
    }
    else
    {
        extlink_text = "Mae'r ddolen hon yn cyfeirio at wefan allanol";
        pdflink_text = "Bydd y ddolen hon yn agor mewn ffenestr newydd";
    }

	var externalIcon = ' <img src="/assets/v1/images/external-link.gif" alt="'+extlink_text+'" title="'+extlink_text+'" class="externalLinkIcon" />';

	var thisDomain = window.location.hostname;
	var links = $('#content a, #main-content a').each(function(){
		if ($(this).attr('href') && $(this).attr('href').indexOf("http") > -1 && $(this).attr('href').indexOf(thisDomain) == -1) {
			//$(this).addClass('external');

			var oldTitle = $(this).attr('title');
			if(oldTitle != 'undefined' && oldTitle != '' && oldTitle != null) {
				oldTitle = oldTitle + ' - '
			} else {
				oldTitle = ''
			}

			$(this).append(externalIcon).attr('title',oldTitle+extlink_text);
		}

		//Make PDFs open in a new window
		if (
			(
				$(this).attr('href') 
				&& 
				$(this).attr('href').indexOf("http") != -1 
				&& 
				$(this).attr('href').indexOf(thisDomain) != -1 
				&& 
				$(this).attr('href').indexOf('.pdf') != -1
			) 
			|| 
			(
				$(this).attr('href') 
				&& 
				(
					$(this).attr('href').indexOf("http") == -1 
					|| 
					$(this).attr('href').indexOf(thisDomain) != -1
				) 
				&& 
				$(this).attr('href').indexOf('.pdf') != -1
			)
		) {
			var oldTitle = $(this).attr('title');
			if(oldTitle != 'undefined' && oldTitle != '' && oldTitle != null) {
				oldTitle = oldTitle + ' - '
			} else {
				oldTitle = ''
			}

			$(this).attr('title',oldTitle+pdflink_text).click(function() { window.open($(this).attr('href')); return false; });
		};
	});
}

function openPopup() {
	var targeturl = $(this).attr('href');
	$(this).blur();
	window.open(targeturl, 'popupwindow', 'width=800,height=600,scrollbars,resizable');
	return false;
}

function prepPopups() {
    var popuplink_text = "";

	if($("html").attr("Lang") == "en")
    {
        popuplink_text = "This link will open in a new window";
    }
    else
    {
        popuplink_text = "Bydd y ddolen hon yn agor mewn ffenestr newydd";
    }

	var popupIcon = ' <img src="/assets/v1/images/popup-link.gif" alt="'+popuplink_text+'" title="'+popuplink_text+'" class="popupLinkIcon" />';

	var originalTitle = $(this).attr('title');

	if(originalTitle != 'undefined' && originalTitle != '' && originalTitle != null) {
		originalTitle = originalTitle + ' - '
	} else {
		originalTitle = ''
	}

	$('a.popup').each(function(){
		$(this).attr('title',(originalTitle + popuplink_text)).append(popupIcon).bind('click',openPopup);
	});
}

function prepTablePagers() {
	var pager = '<div id="tablesorterid" class="pager">';
	pager += '<form class="tablesorterpager">';
	pager += '<img src="/assets/v1/js/_library/tablesorter/addons/pager/icons/first.png" class="first"/>';
	pager += '<img src="/assets/v1/js/_library/tablesorter/addons/pager/icons/prev.png" class="prev"/>';
	pager += '<input type="text" class="pagedisplay"/>';
	pager += '<img src="/assets/v1/js/_library/tablesorter/addons/pager/icons/next.png" class="next"/>';
	pager += '<img src="/assets/v1/js/_library/tablesorter/addons/pager/icons/last.png" class="last"/>';
	pager += '<select class="pagesize">';
	pager += '	<option selected="selected"  value="10">10</option>';
	pager += '	<option value="20">20</option>';
	pager += '	<option value="30">30</option>';
	pager += '	<option value="40">40</option>';
	pager += '</select>';
	pager += '</form>';
	pager += '</div>';

	$('.tablesorter').each(function(){
		if($(this).find('tbody > tr').length >= 10) {
			$(this).after(pager.replace('tablesorterid',$(this).attr('id')+'_pager'));
		}
	});
}

function tidySiteMap() {
	$('ul.site-map li.secondary:odd').addClass('rightMost');
}

function keep_alive() {
	var timelag = new Date();
	timelag = timelag - $.keep_alive_time;
	if( timelag > 2000 ) {
		$.ajax({
			url: "en/users/keep_alive",
			cache: false
		});
		$.keep_alive_time = new Date();
		return true;
	} else {
		return false;
	};
}

function showhide_blogposts() {
    var link_text = "";
	
	if($('#blog-controls-button').size() > 0 && !$('#blog-controls-button').hasClass('noShow')) { 
		if($("html").attr("Lang") == "en")
        {
            link_text = "View all <br />posts";
            link_title = "View all posts";
        }
        else
        {
            link_text = "View all <br />posts[cy]";
            link_title = "View all posts [cy]";
        }

        $('#blog-controls-button').append('<a href="#blogsList" class="view blog-controls-showhide" title="' + link_title + '">' + link_text + '</a>');

		$('#blogsList>li:gt(0), div.pag').slideUp();

		$('#blog-container').append('<p class="view-full"><a href="#blogsList" class="view blog-controls-showhide" title="' + link_title + '">' + link_title + '</a></p>');

	}

	$('.blog-controls-showhide').click(function(){
		$('#blogsList li, div.pag').slideDown();
		$(this).blur();
		$('.blog-controls-showhide').fadeOut();
		return false;
	});
}

$(function() {
	$(".noJS").hide();

	calendarLinks();
	printPage();
	highlightExternalLinks();
	prepPopups();
	tidySiteMap();

	if( $( 'body.basicJS' ).size() == 0 ) {
		showhide_blogposts();
	}

	prepTablePagers();

	$(".tablesorter").each(function(){
		if($(this).find('tbody > tr').length >= 10) {
			$(this).tablesorter(
				{
					sortList: [[0,0]],
					headers: { 
		            // assign the sixth column (we start counting zero) 
		            	5: { 
		                // disable it by setting the property sorter to false 
		                	sorter: false
	 					},
						6: { 
		                // disable it by setting the property sorter to false 
		               		sorter: false
						}
		            }
		        }
			)
			.tablesorterPager({container: $("#"+$(this).attr('id')+"_pager")});
		} else {
			$(this).tablesorter(
				{
					sortList: [[0,0]],
					headers: { 
		            // assign the sixth column (we start counting zero) 
		            	5: { 
		                // disable it by setting the property sorter to false 
		               		sorter: false
						},
						6: { 
		                // disable it by setting the property sorter to false 
		               		sorter: false
						}
		            } 
		        }
			);
		}
	});


//FLIR
	if(makeFlir != undefined && makeFlir == true) {
		FLIR.init();
		$('.odd h2.flir').each( function() { FLIR.replace(this, new FLIRStyle({ cBackground:'DF0194' })); } );
		$('.even h2.flir').each( function() { FLIR.replace(this, new FLIRStyle({ cBackground:'E0E0E0' })); } );
		$('#discoverAges li.flir').each( function() { FLIR.replace(this, new FLIRStyle({ cBackground:'DF0194' })); } );
	};


//Hit areas
	$('.hitArea').hover(function(){
		if( (hitlink = $(this).find('a.hitLink:first').attr('href')) || $(this).find('a:first').attr('href') ) {
			$(this).css('cursor','pointer');
		}
	},function(){});
	$('.hitArea').click(function(){
		var hitlink = '';
		if(hitlink = $(this).find('a.hitLink:first').attr('href')){
			window.location = hitlink;
		}
		else{
			hitlink = $(this).find('a:first').attr('href');
			if(hitlink) {
				window.location = hitlink;
			}
		};
	});
    
    $('.hitArea_new_window').hover(function(){
		$(this).css('cursor','pointer');
	},function(){});
	$('.hitArea_new_window').click(function(){
		var hitlink = '';
		if(hitlink = $(this).find('a.hitLink:first').attr('href')){
			//window.location = hitlink;
            window.open(hitlink,'_blank','width=600,height=600,scollbars=1');
		}
		else{
			//window.location =
            window.open( $(this).find('a:first').attr('href'),'_blank','width=600,height=600,scollbara=1');
		};
        
	});
	
//Keep-alive for textareas

	if($('textarea').size() > 0) {
		jQuery.extend({
			keep_alive_time: new Date()
		});

		$('textarea').bind('keyup',function(){
			keep_alive();
			return false;
		});
	}

    

});

$(window).load(function () {
    matchHeight();
	leadImage();
});
