$(document).ready(function() {
	if ($("a.inline").fancybox){
		$("a.inline").fancybox();
	}

	if ($('#SearchText').length > 0) showFieldTitle('#SearchText');

	if ($('#PressDate').length > 0) $('#PressDate').change(function() {
		if (this.value.length > 0) document.location = '/element-in-the-news/' + this.value.substr(5, 2) + '/' + this.value.substring(0, 4);
	});

	$('.fileDownloads').change(function(){
		
		var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
		
		if (!is_chrome)
		{
			if ($(this).val() != 'Select a Fund Sheet to view' && $(this).val() != 'Select a newsletter to view') {
				window.open($(this).val());
			}
		}
		else
		{
			if ($(this).val() != 'Select a Fund Sheet to view' && $(this).val() != 'Select a newsletter to view') {
				location.href = $(this).val();
			}
		}		
	});

	$('li.pdfIcon a, a.blank').attr('target', '_blank');

	$('.voteCompanies').change(function(){
		if (this.value != '') {
			document.location = '/responsible-investment/voting-record/archive/view/' + this.value;
		}
	});

	if ($(".videoColorbox").length > 0)
	{
		$(".videoColorbox").colorbox({iframe:true, innerWidth:425, innerHeight:344});
	}
	
	$(".hiddenFlow").click(function(){
		var podId = $(this).attr('rel'),
			htmlBox = "#hidden" + podId;		
		
		$(".hiddenFlow").colorbox({width:"492px", inline:true, href:htmlBox});	
	});

	newsletterSignup();
});

function newsletterSignup()
{
	if ($('form#NewsletterSignup').length > 0)
	{
		$('form#NewsletterSignup').submit(function()
		{
			var errorMsg = '';

			if ($('#NewsletterSignupFirstName').val() == '') errorMsg += 'Please enter your name\n';

			if ($('#NewsletterSignupLastName').val() == '') errorMsg += 'Please enter your surname\n';

			if (!validateEmail(($('#NewsletterSignupEmail').val()))) errorMsg += 'Please enter a valid email address\n';

			if (errorMsg.length > 0)
			{
				alert('Please correct:\n\n' + errorMsg);

				return false;
			}
		});
	}
}

function validateEmail(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;

	return true;
}

function showFieldTitle(fieldId)
{
	var title = $(fieldId).attr('title');

	$(fieldId).val(title);

	$(fieldId).focus(function() {
		if ($(fieldId).val() == title) $(fieldId).val('');
	});

	$(fieldId).blur(function() {
		if ($(fieldId).val().length == 0) $(fieldId).val(title);
	});
}
