var nav = {
	normalCss: {backgroundImage:"url('/img/chrome/arrowRight.gif')"},
	selectedCss: {backgroundImage:"url('/img/chrome/arrowDown.gif')"}
}

var fundCount = 0;

$(document).ready( function(){
	// new accordion to replace the old content slider.
	if ($('.multiOpenAccordion').length > 0)
	{
		$('.multiOpenAccordion').multiAccordion();	
		
		$('.multiOpenAccordion h3 a').click(function(e){
			e.preventDefault();
		});
	}
	
	
	/* Fix for rel="nofollow" on fancybox elements */
	$('a[rel=nofollow]').each(function(i) {
		$(this).attr('rel', '');
	});

	$('#leftColumn>ul>li>a').click( function(e){
		var siblings = $(this).siblings('ul')
		if ( siblings.length ) {
			e.preventDefault()
			$('#leftColumn>ul>li>a').css(nav.normalCss)
			if ( $(siblings).css('display') == 'none' ) {
				$(this).css(nav.selectedCss)
			}
			$(siblings).toggle()
		}
	})
	if ( here ) {
		var found = false
		$('#leftColumn>ul>li').each( function(){
			if ( $('a',this).attr('href') == here ) {
				$(this).addClass('selected')
				found = true
			}
		})
		if ( !found ) {
			$('#leftColumn>ul>li>ul>li').each( function(){
				if ( $('a',this).attr('href') == here ) {
					var self = $(this)
					var parent = self.parent()
					self.addClass('selected')
					parent.show().siblings('a').css(nav.selectedCss)
				}
			})
		}
	}
	if ( $.browser.msie && $.browser.version < 7 ) {
		$('#leftColumn li, #rightColumn .linkList li').hover(
			function(){$(this).addClass('hover')},
			function(){$(this).removeClass('hover')}
		)
	}
	/*
	$('#subscribeLink').fancybox({frameWidth: 660})
	$('#launchLink').fancybox({frameWidth: 600})
	$('a.promotion').fancybox({frameWidth: 650})
	$('a.fancybox').fancybox({
	    'padding'           : 0,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'width'				: '864',
		'height'			: '687',
		'swf'				: {'wmode': 'opaque'}
	});
	*/

	$('#tabContainer2 ul.tabList a').click(function() {
		$('#tabContainer2 div.tab').hide();
		$('#tabContainer2 div.' + $(this).attr('rel')).show();

		return false;
	});

    //investor signup stuff
    investorSignup();

	//google analytics
	googleAnalytics();

	webcast();
})

function webcast()
{
	if ($('#play_vid').length > 0)
	{
		$('#play_vid').click(function()
		{
			var unitTrustId = $('#unitTrustId').val();

			$.colorbox({href : '/unit_trusts/video/' + unitTrustId + '/', scrolling: false});
		});
	}
	
	if ($('a.iframeWebcast').length > 0)
	{
		if ($.browser.msie)
		{
			$('a.iframeWebcast').colorbox({iframe: true, width:850, height:520});
		}
		else
		{
			$('a.iframeWebcast').colorbox({iframe: true, width:850, height:490});
		}
	}
}

$('#tabContainer1').ready(function() {
	$('#tabContainer1 ul.tabList a').click(function() {
		$('#tabContainer1 ul.tabList a').removeClass('active');

		var marginLeft = 0;

		switch ($(this).attr('rel')) {
			case 'tab2':
				marginLeft = '-560px';
				break;

			case 'tab3':
				marginLeft = '-1120px';
				break;
		}

		$(this).addClass('active');

		$('#tabContainer1 div.tabArea').animate({"marginLeft": marginLeft}, 'slow');
		$('#tabContainer1 div.' + $(this).attr('rel')).show();

		return false;
	});
});

$('#tabContainer2').ready(function() {
	$('#tabContainer2 div.tab:gt(0)').hide();

	$('#tabContainer2 ul.tabList a').click(function() {
		$('#tabContainer2 div.tab').hide();
		$('#tabContainer2 div.' + $(this).attr('rel')).show();

		return false;
	});
});

function googleAnalytics()
{	
	//invest now button on sub-pages
	if ($('#investNowCall2Action').length > 0)
	{
		$('#investNowCall2Action').click(function()
		{
			_gaq.push(['_trackEvent', 'Clicks', 'InvestOnlineNowButton-SP']);
		});
	}
	
	//application form for individual investors (invest now btn)
	if ($('a.btnInvestNow').length > 0)
	{
		$('a.btnInvestNow').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'Individuals']);
		});
	}
	
	//application form for individual investors (opportunity fund form download)
	if ($('a.pdfOppFund').length > 0)
	{
		$('a.pdfOppFund:not(.btnInvestNow)').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'OpportunityFund']);
		});
	}
	
	//opportunity fund downloads
	if ($('a.oppFundDownload').length > 0)
	{
		$('a.oppFundDownload').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'OppFundLit', $(this).attr('rel')]);
		});
	}
	
	//app form downloads
	if ($('a.appForm').length > 0)
	{
		$('a.appForm').click(function()
		{
			if (typeof($(this).attr('rel') != 'undefined'))
			{
				switch($(this).attr('rel'))
				{
					case 'investec_i_select_access_application_form':
						_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'iSelectAccess']);
						break;
						
					case 'investec_i_select_bond_application_form':
						_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'iSelectBond']);
						break;
						
					case 'investec_i_select_retirement_annuity_and_preservation_fund_application_form':
						_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'RetirementAnnuity']);
						break;
						
					case 'investec_i_select_retirement_annuity_and_preservation_fund_application_form':
						_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'PreservationFund']);
						break;
						
					case 'investec_i_select_living_annuity_application_form':
						_gaq.push(['_trackEvent', 'Downloads', 'AppForm', 'LivingAnnuity']);
						break;
						
					default:
						break;
				}
			}
		});
	}
	
	

	if ($('a.howToInvest').length > 0)
	{
		$('a.howToInvest').click(function()
		{
			_gaq.push(['_trackEvent', 'Clicks', 'HowToInvest']);
		});
	}

	if ($('a.individualAppForm').length > 0)
	{
		$('a.individualAppForm').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'PDF', 'ApplicationFormforIndividualInvestors']);
		})
	}

	if ($('a.pdfOppFund').length > 0)
	{
		$('a.pdfOppFund').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'PDF', 'ApplicationFormforIndividualInvestors-InvestecOpportunityFund']);
		});
	}

	if ($('a.pdfAllFunds').length > 0)
	{
		$('a.pdfAllFunds').click(function()
		{
			_gaq.push(['_trackEvent', 'Downloads', 'PDF', 'ApplicationFormforIndividualInvestors-AllForms']);
		});
	}
}

function investorSignup()
{
    if ($('#InvestorSignupStep1AddForm'))
    {
        $('#InvestorSignupStep1AddForm').submit(function()
        {
            errorMsg = '';

            if ($('#InvestorSignupTitle').val() == '') errorMsg += 'Please enter a title\n';

            if ($('#InvestorSignupFirstname').val() == '') errorMsg += 'Please enter a first name\n';

            if ($('#InvestorSignupLastname').val() == '') errorMsg += 'Please enter a last name\n';

            if ($('#InvestorSignupEmail').val() == '' || !validateEmail($('#InvestorSignupEmail').val())) errorMsg += 'Please enter a valid email address\n';

            if ($('#InvestorSignupPhysicalAddress1').val() == '' || $('#InvestorSignupPhysicalAddressCity').val() == '' || $('#InvestorSignupPhysicalAddressCode').val() == '')
			{
				errorMsg += 'Please complete physical address details\n';
			}

            if ($('#InvestorSignupTelephoneWork').val() == '') errorMsg += 'Please enter a work telephone number\n';

			if (!$('#InvestorSignupCommOption').val() == '')
			{
				switch ($('#InvestorSignupCommOption').val())
				{
					case 'Home':
						if ($('#InvestorSignupTelephoneHome').val() == '') errorMsg += 'Please enter a home number (preferred communication)\n';
						break;

					case 'Cell':
						if ($('#InvestorSignupTelephoneCell').val() == '') errorMsg += 'Please enter a cell number (preferred communication)\n';
						break;

					case 'Fax':
						if ($('#InvestorSignupTelephoneFax').val() == '') errorMsg += 'Please enter a fax number (preferred communication)\n';
						break;
				}
			}

            if ($('#InvestorSignupIdPassportNumber').val() == '') errorMsg += 'Please enter an ID/Passport number\n';

            if ($('.dateOf .emigration').val() == '') errorMsg += 'Please select a date of birth\n';

            dateOk = true;

            $('.dateOf.birth').each(function()
            {
                if ($(this).val() == '') dateOk = false;
            });

            if (!dateOk) errorMsg += 'Please select a date of birth\n';

            if (!$('.onlineAccessChoice').is(':checked')) errorMsg += 'Please select an online access option\n';

            if (!$('.residenceOptions').is(':checked')) errorMsg += 'Please select a residency option\n';

            if ($('#InvestorSignupResidenceEmigrant').is(':checked'))
            {
                if ($('#ForexDetailName').val() == '') errorMsg += 'Please enter foreign exchange dealer name\n';

                if ($('#ForexDetailAddress').val() == '') errorMsg += 'Please enter forex physical address\n';

                if ($('#ForexDetailCountryId').val() == '') errorMsg += 'Please select a country of residence\n';

                if ($('#ForexDetailContactName').val() == '') errorMsg += 'Please enter a forex contact name\n';

                if ($('#ForexDetailContactTel').val() == '') errorMsg += 'Please enter a forex contact telephone number\n';

                dateOk = true;

                $('.dateOf.emigration').each(function()
                {
                    if ($(this).val() == '') dateOk = false;
                });

                if (!dateOk) errorMsg += 'Please select a date of emigration';
            }

            if (errorMsg.length > 0)
			{
				alert ('Please correct below:\n\n' + errorMsg);

				return false;
			}
        });

		if (!$('#InvestorSignupResidenceEmigrant').is(':checked'))
		{
			$('.forexDetails').hide();
		}

		$('.residenceOptions').click(function()
		{
            if ($('#InvestorSignupResidenceResident').is(':checked'))
            {
                $('.forexDetails').fadeOut();
            }
            else if ($('#InvestorSignupResidenceEmigrant').is(':checked'))
            {
                $('.forexDetails').fadeIn();
            }
		});

		$('#InvestorSignupIdPassportNumber').keyup(function()
		{
			if ($(this).val().length == 13)
			{
				var idDate = $(this).val().substring(0, 6);

				var date = new Date(idDate.substr(0, 2), idDate.substr(2, 2) - 1, idDate.substr(4, 2));

				$('#InvestorSignupDateOfBirthDay').val(pad(date.getDate(), 2));
				$('#InvestorSignupDateOfBirthMonth').val(pad(date.getMonth() + 1, 2));
				$('#InvestorSignupDateOfBirthYear').val(date.getFullYear());
			}
			else
			{
				$('#InvestorSignupDateOfBirthDay').val('');
				$('#InvestorSignupDateOfBirthMonth').val('');
				$('#InvestorSignupDateOfBirthYear').val('');
			}
		});
    }

    if ($('#InvestorSignupStep2AddForm').length > 0)
    {
		fundAccountNumbers = null;

		fundCount = $('.fundSelect').size();

		$.post('/unit_trusts/getFundAccountNumbers/', function(data)
		{
			fundAccountNumbers = data;
		}, 'json');

		$('.btnAdd').live('click', function()
		{
			html = '<ul class="investDetails">' +
			'<li><div class="input select"><label for="InvestmentDetail' + fundCount + 'FundId">Fund Name*</label><select id="InvestmentDetail' + fundCount + 'FundId" class="fundSelect newSelect" name="data[InvestmentDetail][' + fundCount + '][fund_id]">';

			html += $(this).parents('ul').find('select').html();

			html +=	'</select></div></li>' +
			'<li><div class="input text"><label for="InvestmentDetail' + fundCount + 'LumpSum">Lump Sum in ZAR</label><input type="text" id="InvestmentDetail' + fundCount + 'LumpSum" value="" class="lumpSumValue" maxlength="11" name="data[InvestmentDetail][' + fundCount + '][lump_sum]"></div></li>' +
			'<li><div class="input text"><label for="InvestmentDetail' + fundCount + 'MonthlyContribution">Monthly Contribution</label><input type="text" id="InvestmentDetail' + fundCount + 'MonthlyContribution" class="monthlyValue" value="" maxlength="11" name="data[InvestmentDetail][' + fundCount + '][monthly_contribution]"></div></li>' +
			'<li class="accNum"><div class="input text"><label for="InvestmentDetail' + fundCount + 'AccountNumber">Account Number</label><input type="text" id="InvestmentDetail' + fundCount + 'AccountNumber" value="" maxlength="45" disabled="disabled" name="data[InvestmentDetail][' + fundCount + '][account_number]"></div></li>' +
			'<li class="btn"><input type="image" class="btnAdd" src="/img/btn-add.png" name="btnAdd"></li>' +
			'<li class="btn"><input type="image" ismap="false" name="btnRemove" src="/img/btn-remove.png" class="btnRemove" />' +
			'</ul>';

			$(html).insertAfter($(this).parents('ul'));

			//make sure newly added has nothing selected
			$('ul.investDetails').last().find('.fundSelect').val('');

			if (jQuery.browser.msie)
			{
				{
					$('select.newSelect').customSelect();
					$('select.newSelect').removeClass('newSelect');
				}
			}

			//if more than one li exists, replace the add on the first with a remove
			if ($('ul.investDetails').size() > 1)
			{
				$('ul.investDetails').first().children('li.btn').children('input.btnAdd').replaceWith('<input type="image" ismap="false" name="btnRemove" src="/img/btn-remove.png" class="btnRemove" />');

				$(this).parent('li').remove();
			}

			fundCount++;

            $('ul.investDetails').last().hide().slideDown();

			return false;
		});

		$('.btnRemove').live('click', function()
		{
			$(this).parents('ul').slideUp(null, function()
			{
				$(this).remove();

				//if only one item is left, stick an add button back on the first li and remove btnRemove
				if ($('ul.investDetails').size() == 1)
				{
					$('ul.investDetails').first().children('li.btn').children('input.btnAdd').parent('li').remove();
					$('ul.investDetails').first().children('li.btn').children('input.btnRemove').replaceWith('<input type="image" class="btnAdd" src="/img/btn-add.png" name="btnAdd" />');
				}

				if ($('ul.investDetails').last().children('li.btn').children('input.btnAdd').length < 1)
				{
					$('ul.investDetails').last().children('li.btn').before('<li class="btn"><input type="image" class="btnAdd" src="/img/btn-add.png" name="btnAdd"></li>');
				}
			});

			return false;
		});

		$('.fundSelect').live('change', function()
		{
			if (!$(this).val() == '')
			{
				selectBox = $(this);

				$('.fundSelect').not(selectBox).each(function()
				{
					if ($(this).val() == selectBox.val())
					{
						alert('This fund has already been selected.');
						selectBox.val('');
						selectBox.parents('ul').children('li.accNum').find('input').val('');
						return false;
					}
				});

				$(this).parents('ul').children('li.accNum').find('input').val(fundAccountNumbers[$(this).val()]);
			}
			else
			{
				$(this).parents('ul').children('li.accNum').find('input').val('');
			}
		});

		$('#InvestorSignupStep2AddForm').submit(function()
		{
			errorMsg = '';

			allFundsOk = true;

			$('.fundSelect').each(function()
			{
				var fundId = $(this).val();
				var fundName = $(this).find('option:selected').text();

				var lumpSum = $(this).parents('ul').find('.lumpSumValue').val();
				var monthlyContribution = $(this).parents('ul').find('.monthlyValue').val();

				if (fundId == '')
				{
					allFundsOk = false;
					return;
				}
				else if (lumpSum == '' && monthlyContribution == '')
				{
					errorMsg += 'Investment Details: No lump sum or monthly contribution entered for ' + fundName + '\n';
					return;
				}
				else
				{
					if (lumpSum < 10000 && lumpSum != '')
					{
						errorMsg += 'Investment Details: Lump sum value for ' + fundName + ' less than minimum of R10000\n';
						return;
					}
					if (monthlyContribution < 500 && monthlyContribution != '')
					{
						errorMsg += 'Investment Details: Monthly contribution value for ' + fundName + ' less than minimum of R500\n';
						return;
					}
				}
			});

			if (!allFundsOk) errorMsg += 'Investment Details: One or more fund details are incomplete\n';

			if ($('#BankDetailBankName').val() == '') errorMsg += 'Investor Bank Details: Name of Bank\n';

			if ($('#BankDetailBranchName').val() == '') errorMsg += 'Investor Bank Details: Branch Name\n';

			if ($('#BankDetailBranchCode').val() == '') errorMsg += 'Investor Bank Details: Branch Code\n';

			if ($('#BankDetailAccountHolderName').val() == '') errorMsg += 'Investor Bank Details: Account Holder Name\n';

			if ($('#BankDetailAccountNumber').val() == '') errorMsg += 'Investor Bank Details: Account Number\n';

			if ($('#BankDetailAccountType').val() == '') errorMsg += 'Investor Bank Details: Account Type\n';

			if (!$('.redistributionChoiceRadio').is(':checked')) errorMsg += 'No Income Distribution choice\n';

			//if (!$('.startDayRadio').is(':checked')) errorMsg += 'Debit Order Instructions: Start Day selection\n';

			//if ($('#DebitOrderInstructionMonth').val() == '') errorMsg += 'Debit Order Instructions: Start Month selection\n';

			//if ($('#DebitOrderInstructionYear').val() == '') errorMsg += 'Debit Order Instructions: Start Year selection\n';

			//if ($('#DebitOrderInstructionMonthlyIncreaseAmount').val() == '' && $('#DebitOrderInstructionEscalationRate').val() == '') errorMsg += 'Debit Order Instructions: Monthly investment increase choice\n';

			if ($('#DebitOrderInstructionOnBehalf').is(':checked'))
			{
				if ($('#ThirdPartyBankDetailBankName').val() == '') errorMsg += 'Third Party Bank Details: Branch Name\n';

				if ($('#ThirdPartyBankDetailBranchName').val() == '') errorMsg += 'Third Party Bank Details: Branch Name\n';

				if ($('#ThirdPartyBankDetailBranchCode').val() == '') errorMsg += 'Third Party Bank Details: Branch Code\n';

				if ($('#ThirdPartyBankDetailAccountHolderName').val() == '') errorMsg += 'Third Party Bank Details: Account Holder Name\n';

				if ($('#ThirdPartyBankDetailAccountNumber').val() == '') errorMsg += 'Third Party Bank Details: Account Number\n';

				if ($('#ThirdPartyBankDetailAccountType').val() == '') errorMsg += 'Third Party Bank Details: Account Type\n';
			}

			if (!$('#InvestorSignupAcceptTerms').is(':checked')) errorMsg += 'Please accept the terms and conditions\n';

			if (errorMsg.length > 0)
			{
				alert ('Please correct below:\n\n' + errorMsg);

				return false;
			}
		});

		$('#DebitOrderInstructionEscalationRate').change(function()
		{
			if ($(this).val() != '')
			{
				$('#DebitOrderInstructionMonthlyIncreaseAmount').attr('disabled', 'disabled');
			}
			else
			{
				$('#DebitOrderInstructionMonthlyIncreaseAmount').removeAttr('disabled');
			}
		});

		/*if (!$('#InvestorSignupUsingAdviser').is(':checked'))
		{
			$('.adviserDetails').hide();
		}

        $('#InvestorSignupUsingAdviser').click(function()
        {
            if ($(this).is(':checked'))
            {
                $('.adviserDetails').slideDown();
            }
            else
            {
                $('.adviserDetails').slideUp();
            }
        });*/

		if (!$('#InvestorSignupOnBehalf').is(':checked'))
		{
			$('.thirdPartyBankDetails').hide();
		}

		$('#InvestorSignupOnBehalf').click(function()
		{
            if ($(this).is(':checked'))
            {
                $('.thirdPartyBankDetails').slideDown();
            }
            else
            {
                $('.thirdPartyBankDetails').slideUp();
            }
		});
    }
}

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 log(message)
{
	if(typeof console != "undefined")
	{
		console.log(message);
	}
}

function pad(number, length) {

    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }

    return str;
}
