$(function(){

	//ui radio buttons
	//$('.uiradio').buttonset();
				
	//view schedule benefits
	if ($('.benefitsLink').length)
	{
		$('.benefitsLink').click(function(e){
			schemeID = $(this).attr('rel');
			e.preventDefault();
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=ScheduleBenefits&c='+schemeID,
				success: function (html){
					$('#ScheduleOfBenefitsDialog').html(html);
					$('#ScheduleOfBenefitsDialog').dialog({
						bgiframe: true,	autoOpen: false, modal: false, width: 800, height: 500,	resizable: true,
						buttons: {
							'Close': function(){
								$(this).dialog('close');
							}
						}
					});

					$('#ScheduleOfBenefitsDialog').dialog('open');
				}
			});
		});
	}

	
	//stop double click
	$('form').submit(function() {
		if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
		  jQuery.data(this, "disabledOnSubmit", { submited: true });
		  $('input[type=submit], input[type=button]', this).each(function() {
			$(this).attr("disabled", "disabled");
		  });
		  return true;
		}
		else
		{
		  return false;
		}
    });

	//ajax method to get option description
	if ($('a.optionDesc').length)
	{
		$('#container').after('<div id="optionDescDialog" title="Description"></div>');
		
		$('#optionDescDialog').dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, height: 250, resizable: true,
			buttons: {
				'Close': function(){
					$(this).dialog('close');
				}
			}
		});

		$('a.optionDesc').click(function(){
			var optionID = $(this).attr('name');
			
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=OptionDesc&c=' + optionID,
				success: function (html){
					$('#optionDescDialog').html(html);
					$('#optionDescDialog').dialog('open');
				}
			});
			//$('#optionDescDialog').html(optionID);
			//$('#optionDescDialog').dialog('open');


			return false;
		
		});


	}
	
	//option description
	if ($('.definitionLink3').length)
	{
		$('.dialogpol').dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
			buttons: {
				'OK': function(){
					$(this).dialog('close');
				}
			}
		});

		$('.definitionLink3').click(function(){
			var SchemeID = $(this).attr('rel');
			//$('#PolicyDialog' + SchemeID).attr('title', $('#HiddenName' + SchemeID).val());

			$('#PolicyDialog' + SchemeID).dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
			buttons: {
				'OK': function(){
					$(this).dialog('close');
				}
			}
			});
			$('#PolicyDialog' + SchemeID).dialog({title:$('#HiddenName' + SchemeID).val()});;
			$('#PolicyDialog' + SchemeID).dialog('open');

			return false;

		});

	}
	
	//impaired declaation question terminal
	$('#TerminalRow').hide();
	$('#Med6').change(function(){
		$('#Med6 option:selected').each(function(){
			if ($(this).text() == 'Yes')
				$('#TerminalRow').show();
			else
				$('#TerminalRow').hide();
		});
	});

	// hide submit buttons after click
	if (('#PaymentSubmit').length)
	{
		$('input[type="submit"], input[type="image"]').click(function(){
			if ($('#PaymentPage').val() == 1)
			{
				$(this).hide();
				$('<div class="ajaxloader" />').appendTo('#PaymentSubmit');
				
				$('#PaymentForm').submit();
			}
		});
	}
	
	//impaired declaration page
	$('#DialogNonDeclaration').dialog({
		bgiframe: true,	autoOpen: false, modal: true, width: 500, resizable: false,
		buttons: {
			'Yes': function(){
				$(this).dialog('close');
			},
			'No': function(){
				window.location = SITEPATH;
			}
		}
	});
	$('#LinkNonDeclaration').click(function(e){
		e.preventDefault();
		$('#DialogNonDeclaration').html('<p>Unfortunately you cannot proceed with issuing this policy unless the declaration is agreed.</p><p>Do you wish to continue?</p>');
		$('#DialogNonDeclaration').dialog('open');
	});

	
	
	// set links with a rel value of external to target a new frame
	$('a[rel="external"][href]').each(function(){
		$(this).attr('target', '_blank');
	});

	//claims dialogs
	$('#CancellationDialog').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkCancellationDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#CancellationDialog').html('<embed src="' + SITEPATH + 'templates/sm_cancellation.pdf" href="' + SITEPATH + 'templates/sm_cancellation.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#CancellationDialog').dialog('open');
	});

	$('#PersonalEffectsDialog').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkBaggageDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#PersonalEffectsDialog').html('<embed src="' + SITEPATH + 'templates/sm_personaleffects.pdf" href="' + SITEPATH + 'templates/sm_personaleffects.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#PersonalEffectsDialog').dialog('open');
	});

	$('#MedicalExpensesDialog').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkMedicalDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#MedicalExpensesDialog').html('<embed src="' + SITEPATH + 'templates/sm_medicalexpenses.pdf" href="' + SITEPATH + 'templates/sm_medicalexpenses.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#MedicalExpensesDialog').dialog('open');
	});

	$('#TravelDelayDialog').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkDelayDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#TravelDelayDialog').html('<embed src="' + SITEPATH + 'templates/sm_traveldelay.pdf" href="' + SITEPATH + 'templates/sm_traveldelay.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#TravelDelayDialog').dialog('open');
	});

	// put policy wording and key facts into dialogs
	$('#DialogWordingDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('#DialogWordingDocSmall').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 300, height: 300, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('#DialogQuotePackDoc').dialog({
		bgiframe: true, autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkQuotePackDoc').click(function(e){
		e.preventDefault();
		$('#DialogQuotePackDoc').html('<embed src="' + SITEPATH + 'temp/quotepack' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/quotepack' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogQuotePackDoc').dialog('open');
	});
	$('#DialogQuotePackLetterheadDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkQuotePackLetterheadDoc').click(function(e){
		e.preventDefault();
		$('#DialogQuotePackLetterheadDoc').html('<embed src="' + SITEPATH + 'temp/quotepackletterhead' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/quotepackletterhead' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogQuotePackLetterheadDoc').dialog('open');
	});
	$('#DialogPolicyPackDoc').dialog({
		bgiframe: true, autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkPolicyPackDoc').click(function(e){
		e.preventDefault();
		$('#DialogPolicyPackDoc').html('<embed src="' + SITEPATH + 'temp/policypack' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/policypack' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogPolicyPackDoc').dialog('open');
	});
	$('#DialogPolicyPackLetterheadDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('#SendDocsLink').click(function(){
		$('#DialogSendDocs').html('<form id="FormSend" action="' + SITEPATH + 'index.php?a=Internal&amp;b=Policies&amp;QuoteID=' + $('#QuoteID').val() + '&amp;SendCert=1" method="POST"><table><tr><td style="width:100px">Email:</td><td><input type="text" id="Email" name="Email" value="' + $('#Email').val() + '" /></td></tr></table></form>');
		$('#DialogSendDocs').dialog({
			bgiframe: true,	autoOpen: true,	modal: false, width: 400, resizable: false,
			buttons: {
				'Send': function(){
					$(this).dialog('close');
					$('#FormSend').submit();
				}
			}
		});

		return false;
	});
	
	$('.ShowWordingImpaired').click(function(e){
		e.preventDefault();
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchPlatinum2011.pdf" href="' + SITEPATH + 'templates/TopNotchPlatinum2011.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingDoc').dialog('open');
	});

	$('.ShowWordingList').click(function(e){
		e.preventDefault();
		$('#DialogWordingDocSmall').html('<p><a href="' + SITEPATH + '/templates/TopNotchBronze2011.pdf" target="_blank" class="linkWordingDoc">Bronze Policy Wording</a><br /><a href="' + SITEPATH + '/templates/TopNotchSilver2011.pdf" target="_blank" class="linkWordingDoc">Silver Policy Wording</a><br /><a href="' + SITEPATH + '/templates/TopNotchGold2011.pdf" target="_blank" class="linkWordingDoc">Gold Policy Wording</a></p>');
		$('#DialogWordingDocSmall').dialog('open');
	});
	$('.ShowKeyFactsList').click(function(e){
		e.preventDefault();
		$('#DialogKeyFactsDocSmall').html('<p><a href="' + SITEPATH + '/templates/TopNotchBronzeKF.pdf" target="_blank" class="linkKeyFactsDoc">Bronze Key Facts</a><br /><a href="' + SITEPATH + '/templates/TopNotchSilverKF.pdf" target="_blank" class="linkKeyFactsDoc">Silver Key Facts</a><br /><a href="' + SITEPATH + '/templates/TopNotchGoldKF.pdf" target="_blank" class="linkKeyFactsDoc">Gold Key Facts</a></p>');
		$('#DialogKeyFactsDocSmall').dialog('open');
	});

	$('.linkBronzeWordingDoc').click(function(e){
		e.preventDefault();
		$('#DialogWordingDocSmall').dialog('close');
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchBronze2011.pdf" href="' + SITEPATH + '/templatesTopNotchBronze2011.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingDoc').dialog('open');
	});
	$('.linkSilverWordingDoc').click(function(e){
		e.preventDefault();
		$('#DialogWordingDocSmall').dialog('close');
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchSilver2011.pdf" href="' + SITEPATH + 'templates/TopNotchSilver2011.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingDoc').dialog('open');
	});
	$('.linkGoldWordingDoc').click(function(e){
		e.preventDefault();
		$('#DialogWordingDocSmall').dialog('close');
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchGold2011.pdf" href="' + SITEPATH + 'templates/TopNotchGold2011.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingDoc').dialog('open');
	});
	$('.linkPlatinumWordingDoc').click(function(e){
		e.preventDefault();
		$('#DialogWordingDocSmall').dialog('close');
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchPlatinum2011.pdf" href="' + SITEPATH + 'templates/TopNotchPlatinum2011.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingDoc').dialog('open');
	});

	$('#DialogKeyFactsDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('#DialogKeyFactsDocSmall').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 300, height: 300,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	
	$('.ShowKeyFactsImpaired').click(function(e){
		e.preventDefault();
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchPlatinumKF.pdf" href="' + SITEPATH + 'templates/TopNotchPlatinumKF.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsDoc').dialog('open');
	});

	$('.linkBronzeKeyFactsDoc').click(function(e){
		e.preventDefault();
		
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchBronzeKF.pdf" href="' + SITEPATH + 'templates/TopNotchBronzeKF.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		
		$('#DialogKeyFactsDoc').dialog('open');
	});
	$('.linkSilverKeyFactsDoc').click(function(e){
		e.preventDefault();
		$('#DialogKeyFactsDocSmall').dialog('close');
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchSilverKF.pdf" href="' + SITEPATH + 'templates/TopNotchSilverKF.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsDoc').dialog('open');
	});
	$('.linkGoldKeyFactsDoc').click(function(e){
		e.preventDefault();
		$('#DialogKeyFactsDocSmall').dialog('close');
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchGoldKF.pdf" href="' + SITEPATH + 'templates/TopNotchGoldKF.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsDoc').dialog('open');
	});
	$('.linkPlatinumKeyFactsDoc').click(function(e){
		e.preventDefault();
		$('#DialogKeyFactsDocSmall').dialog('close');
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + 'templates/TopNotchPlatinumKF.pdf" href="' + SITEPATH + 'templates/TopNotchPlatinumKF.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsDoc').dialog('open');
	});


	$('#DialogWordingBackpackerDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkWordingBackpackerDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#DialogWordingBackpackerDoc').html('<embed src="' + SITEPATH + 'templates/' + affiliate + 'wording' + $(this).attr('rel') + '_2.pdf" href="' + SITEPATH + 'templates/' + affiliate + 'wording' + $(this).attr('rel') + '_2.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogWordingBackpackerDoc').dialog('open');
	});

	$('#DialogKeyFactsBackpackerDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkKeyFactsBackpackerDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#DialogKeyFactsBackpackerDoc').html('<embed src="' + SITEPATH + 'templates/' + affiliate + 'keyfacts' + $(this).attr('rel') + '_2.pdf" href="' + SITEPATH + 'templates/' + affiliate + 'keyfacts' + $(this).attr('rel') + '_2.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsBackpackerDoc').dialog('open');
	});


	//quote landing page
	// auto set end date for annual policies
	if ($('#TripType').length)
	{
		$('#TripType option:selected').each(function(){
			if ($(this).text() == 'Annual multi-trip')
			{
				$('#DivEndDate').hide();
				$('#MultipleInfo').show();
				$('#FamilyGroup option:contains(Single Parent Family)').show();
				$('#FamilyGroup option:contains(Couple)').show();
				$('#FamilyGroup option:contains(Family)').show();
				$('#FamilyGroup option:contains(Individual)').show();
				$('#FamilyGroup option:contains(Group)').hide();
				$('#DestinationRowAnnual').show();
				$('#DestinationRowSingle').hide();
				$('#DestinationRowBackpacker').hide();
				$('#TripAge').text('(at the date the cover commences)');
			}
			else if ($(this).text() == 'Backpacker')
			{
				$('#DivEndDate').show();
				$('#MultipleInfo').show();
				$('#FamilyGroup option:contains(Single Parent Family)').hide();
				$('#FamilyGroup option:contains(Couple)').hide();
				$('#FamilyGroup option:contains(Family)').hide();
				$('#FamilyGroup option:contains(Individual)').show();
				$('#FamilyGroup option:contains(Group)').show();
				$('#DestinationRowAnnual').hide();
				$('#DestinationRowSingle').hide();
				$('#DestinationRowBackpacker').show();
				$('#TripAge').text('(at the date the trip commences)');
			}
			else 
			{
				$('#MultipleInfo').hide();
				$('#DivEndDate').show();
				$('#FamilyGroup option:contains(Single Parent Family)').show();
				$('#FamilyGroup option:contains(Couple)').show();
				$('#FamilyGroup option:contains(Family)').show();
				$('#FamilyGroup option:contains(Individual)').show();
				$('#FamilyGroup option:contains(Group)').show();
				$('#DestinationRowAnnual').hide();
				$('#DestinationRowSingle').show();
				$('#DestinationRowBackpacker').hide();
				$('#TripAge').text('(at the date the trip commences)');
			}
		});
									//alert('hello');

		$('#TripType').change(function(){
				$('#TripType option:selected').each(function(){
				if ($(this).text() == 'Annual multi-trip')
				{
					
					//$('#RowTripLength').hide();
					if ($('#StartDate').val() == '')
					{
						var d = new Date();
						var day = String(d.getDate());
						if (day.length == 1)
							day = '0' + day;
						day += '/';
						var month = String(d.getMonth() + 1);
						if (month.length == 1)
							month = '0' + month;
						month += '/';
						$('#StartDate').val(day + month + String(d.getFullYear()));
					}
					$('#DivEndDate').hide();
					$('#MultipleInfo').show();
					$('#TravellingText').text('When do you need the cover to start?');
					$('#FamilyGroup option:contains(Single Parent Family)').show();
					$('#FamilyGroup option:contains(Couple)').show();
					$('#FamilyGroup option:contains(Family)').show();
					$('#FamilyGroup option:contains(Individual)').show();
					$('#FamilyGroup option:contains(Group)').hide();
					$('#DestinationRowAnnual').show();
					$('#DestinationRowSingle').hide();
					$('#DestinationRowBackpacker').hide();
					$('#TripAge').text('(at the date the cover commences)');
				}
				else if ($(this).text() == 'Backpacker')
				{
					$('#MultipleInfo').hide();
					$('#DivEndDate').show();
					$('#TravellingText').text('Tell us the dates of your holiday');
					$('#FamilyGroup option:contains(Single Parent Family)').hide();
					$('#FamilyGroup option:contains(Couple)').hide();
					$('#FamilyGroup option:contains(Family)').hide();
					$('#FamilyGroup option:contains(Individual)').show();
					$('#FamilyGroup option:contains(Group)').show();

					$('#DestinationRowAnnual').hide();
					$('#DestinationRowSingle').hide();
					$('#DestinationRowBackpacker').show();
					$('#TripAge').text('(at the date the trip commences)');

				}
				else
				{
					//$('#RowTripLength').show();
					$('#MultipleInfo').hide();
					$('#DivEndDate').show();
					$('#TravellingText').text('Tell us the dates of your holiday');
					$('#FamilyGroup option:contains(Single Parent Family)').show();
					$('#FamilyGroup option:contains(Couple)').show();
					$('#FamilyGroup option:contains(Family)').show();
					$('#FamilyGroup option:contains(Individual)').show();
					$('#FamilyGroup option:contains(Group)').show();
					$('#DestinationRowAnnual').hide();
					$('#DestinationRowSingle').show();
					$('#DestinationRowBackpacker').hide();
					$('#TripAge').text('(at the date the trip commences)');
				}
			});
		});

		

		$('#DialogDestinationError').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: true,
			buttons: {
				'Continue': function() {
					$('#AltDestination').val($('#DestinationOverride').val());
					$('#DestinationName').val('');
					$('#FormStart').submit();
				}
			}
		});

		$('#DialogDestinationError').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: true,
			buttons: {
				'Continue': function() {
					$('#AltDestination').val($('#DestinationOverride').val());
					$('#DestinationName').val('');
					$('#FormStart').submit();
				}
			}
		});

	}

	// show age rows for the number of people travelling
	if ($('#RowAges').length)
	{
		if ($('#Age0').val() == '')
			$('#RowAges').hide();
		for (i = 0; i < MAXTRAVELLERS; i++)
		{
			if ($('#Age' + i).val() == '')
				$('#AgeRow' + i).hide();
		}

		$('#NumberTravellers').keyup(function(){
			var num = parseInt($('#NumberTravellers').val());
			if (isNaN(num)){num = '';}
			if (num < 0){num = 0;}
			if (num > MAXTRAVELLERS)
			{
				$('#DialogMaxTravellers').text('The maximum number of travellers you can have is ' + MAXTRAVELLERS); 
				$('#DialogMaxTravellers').dialog('open');
				num = MAXTRAVELLERS;
			}
			$('#NumberTravellers').val(num);

			for (i = 0; i < MAXTRAVELLERS; i++)
			{
				if (i < num)
				{
					$('#AgeRow' + i).show();
				}
				else
				{
					$('#Age' + i).val('');
					$('#Months' + i).val('');
					$('#AgeRow' + i).hide();
				}
			}
			$('#RowAges').show();
		});

		$('#DialogMaxTravellers').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 200, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
	}


	// auto set number of travellers for different family group types
	if ($('#FamilyGroup').length)
	{
		$('#RowNumPeople').hide();

		$('#FamilyGroup').change(function(){
			$('#FamilyGroup option:selected').each(function(){
				if ($(this).text() == 'Individual')
				{
					$('#NumberTravellers').val(1);
					$('#RowNumPeople').hide();
				}
				else if ($(this).text() == 'Couple')
				{
					$('#NumberTravellers').val(2);
					$('#RowNumPeople').hide();
				}
				else if ($(this).text() == 'Single Parent Family')
				{
					$('#NumberTravellers').val(2);
					$('#RowNumPeople').show();
				}
				else if ($(this).text() == 'Family')
				{
					$('#NumberTravellers').val(3);
					$('#RowNumPeople').show();
				}
				else if ($(this).text() == 'Group')
				{
					$('#NumberTravellers').val(3);
					$('#RowNumPeople').show();
				}
				else
					$('#RowNumPeople').show();
				$('#NumberTravellers').keyup();
			});
		}).change();
	}

	// destination autocomplete
	if ($('#DestinationName').length)
	{
		$('#DestinationName').autocomplete({
			source: SITEPATH + 'index.php?a=Ajax&b=AutoComplete&c=Destinations',
			minLength: 2
		});
	}

	// condition autocomplete
	if ($('#ConditionSearch').length)
	{
		$('#ConditionSearch').autocomplete({
			source: SITEPATH + 'index.php?a=Ajax&b=AutoComplete&c=Conditions',
			minLength: 3
		});
	}

	//date picker
	if ($('#StartDate').length || $('#EndDate').length)
	{
		$('#StartDate').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			minDate: '+0d',
			maxDate: '+1y',
			hideIfNoPrevNext: true,
			onSelect: function(dateText, inst){
				
				$('#EndDate').datepicker('option', 'defaultDate', dateText);
			}
		});
		$('#EndDate').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			minDate: '+1d',
			maxDate: '+2y',
			hideIfNoPrevNext: true,
			onSelect: function(){
			}
		});
	}
	
	//faqs
	if ($('.answer').length)
	{
		$('.answer').hide();
		$('.question').click(function(){
			$(this).next('.answer').animate({opacity:'toggle',height:'toggle'},{duration:200});


		});
	}
	
	/* NEEDS CHANGING WHEN CONNTECT TO TOP NOTCH */
	//scheme page 
	if ($('.checkBoxSilver').length)
	{
		checkBox1 = $('.checkBoxSilver');
		checkBox1.addClass('checked');

		$('#PremiumChoice').html($('#PremiumSilver').html());
	}
	
	//highlight selected fields
	$('.Bronze,.Bronze1').click(function(){
		$('.checkBox').removeClass('checked');
		$('.checkBoxBronze').addClass('checked');
		$('table td').each(function() {
			if ($(this).hasClass('highlight'))
			{
				$(this).removeClass('highlight');
			}
				
		});
		
		$('.Bronze,.Bronze1').each(function(){
			$(this).addClass('highlight');
		});
		$('#SchemeID').val($('#Bronze').val());
		$('#PremiumChoice').html($('#PremiumBronze').html());
	});
	$('.Silver,.Silver1').click(function(){
		$('.checkBox').removeClass('checked');
		$('.checkBoxSilver').addClass('checked');
		$('table td').each(function() {
			if ($(this).hasClass('highlight'))
			{
				$(this).removeClass('highlight');
			}
				
		});
		$('.Silver,.Silver1').each(function(){
			$(this).addClass('highlight');
		});
		$('#SchemeID').val($('#Silver').val());
		$('#PremiumChoice').html($('#PremiumSilver').html());
	});
	$('.Gold,.Gold1').click(function(){
		$('.checkBox').removeClass('checked');
		$('.checkBoxGold').addClass('checked');
		$('table td').each(function() {
			if ($(this).hasClass('highlight'))
			{
				$(this).removeClass('highlight');
			}
				
		});
		$('.Gold,.Gold1').each(function(){
			$(this).addClass('highlight');
		});
		$('#SchemeID').val($('#Gold').val());
		$('#PremiumChoice').html($('#PremiumGold').html());
	});
	
	///options page
	if ($('.optionChange').length)
	{
		$('.optionChange').click(function() {
			var name = $(this).attr('name');
			if (name == 'Hazardous-Activities-Category-B' || name == 'Hazardous-Activities-Category-C' || name == 'Hazardous-Activities-Category-D')
			{
				$('input[name=Hazardous-Activities-Category-B]').attr('checked',false);
				$('input[name=Hazardous-Activities-Category-C]').attr('checked',false);
				$('input[name=Hazardous-Activities-Category-D]').attr('checked',false);

				$('input[name='+name+']').attr('checked',true);
				
				if ($(this).attr('checked') == true)
				{
					$('input[name=Hazardous-Activities-Category-A]').attr('checked',false);
				}
				else
				{
					$('input[name=Hazardous-Activities-Category-A]').attr('checked',true);
				}

			}
			if (name == 'Hazardous-Activities-Category-A')
			{
				$('input[name=Hazardous-Activities-Category-B]').attr('checked',false);
				$('input[name=Hazardous-Activities-Category-C]').attr('checked',false);
				$('input[name=Hazardous-Activities-Category-D]').attr('checked',false);

			}
			premiumCalculate();

		});

		function premiumCalculate()
		{
			var originalPolicy = parseFloat($('#BasePremium').val());
	
			var total = parseFloat(0);
			$('.optionChange').each(function(){
				if ($(this).attr('checked') == true)
				{
					var temp = parseFloat($(this).val());
					total += temp;
				}
			});

			$('#SidePremium').html(premiumFormatHTML(total+originalPolicy));

			/*$('#PolicyCost').text((Total+OriginalPolicy).toFixed(2));
			$('#OptionCost').text(Total.toFixed(2));*/

		}
	}
	
	//scheme page for impaired
	//function to calculate premium on scheme page
	function calculatePremium() 
	{
		var base = parseFloat($('#BasePremium').val());

		$('.ConditionTraveller').each(function(){
			if ($(this).val() == 1)
			{
				base += parseFloat($(this).attr('data-premium'));
			}
		});

		$('.JSPremium').html(premiumFormatHTML(parseFloat(base)));

	}

	calculatePremium();

	//add / remove traveller medical condition
	$('.RemoveCover').click(function() {

		//note change text

		var TravID = $(this).attr('id');
		
		if ($('#ConditionTraveller' + TravID).val() == 1)
		{
			$('#Sprite' + TravID).removeClass('tick').addClass('cross');
			$('#ConditionTraveller' + TravID).val(0);
			$(this).text('Add Cover');
		}
		else
		{
			$('#Sprite' + TravID).removeClass('cross').addClass('tick');
			$('#ConditionTraveller' + TravID).val(1);
			$(this).text('Remove Cover');
			
		}
		
		calculatePremium();
		return false;
	});


	///options page
	if ($('.MedicalRadio').length)
	{
		$('.MedicalRadio').click(function() {
			
			premiumCalculate2();

		});

		function premiumCalculate2()
		{
			var originalPolicy = parseFloat($('#OriginalPolicy').val());
	
			var total = parseFloat(0);
			$('.MedicalRadio').each(function(){
				if ($(this).attr('checked') == true)
				{
					var temp = parseFloat($(this).val());
					total += temp;
				}
			});

			$('#SidePremium').html(premiumFormatHTML(total+originalPolicy));

		}
		premiumCalculate2();
	}
	
	function optionPremiumUpdate() {
		var basePremium = parseFloat($('#HiddenPremium').val());
		
		$('.radioOptions').each(function() {

			if ($(this).val() == 1 && $(this).attr('checked') == true)
			{
				var rel = $(this).attr('rel');
				
				basePremium += parseFloat($('#HiddenPrice'+rel).val());
			}

			$('#DivFinalPremium2 span').html(premiumFormatHTML(basePremium));

		});

	}

	// attach on click event to radio button
	$('.radioOptions').click(function() {
			optionPremiumUpdate();

	});
	
	$('.radioYes').click(function(){
		var thisRadio = $(this);
		$('.radioYes').each(function(){
			$(this).attr('checked',false);
		});
		$('.radioNo').each(function(){
			$(this).attr('checked','checked');
		});
		
		thisRadio.attr('checked','checked');
		optionPremiumUpdate();
	});

	$('.radioNo').click(function(){
	

		$('.radioNo').each(function(){
			$(this).attr('checked','checked');
		});
		$('.radioYes').each(function(){
			$(this).attr('checked',false);
		});
		
		$('.radioYes').first().attr('checked',true);
		optionPremiumUpdate();
	});



	//show hide password text
	if ($('#Username').length)
	{
		if ($('#Username').val() != '')
		{
			$('#Username').removeClass('emailBG');
		}
		else
		{
			$('#Username').addClass('emailBG');
		}

		$('#Username').focus(function() {
			if ($(this).hasClass('emailBG'))
			{
				$(this).removeClass('emailBG');
			}
			
		});
		$('#Username').blur(function() {
			if ($(this).val() == '')
			{
				$(this).addClass('emailBG');
			}
			else
			{
				if ($(this).hasClass('emailBG'))
				{
					$(this).removeClass('emailBG');
				}
			}
		});

	}

	if ($('#RetrievePassword').length)
	{
		if ($('#RetrievePassword').val() != '')
		{
			$('#RetrievePassword').removeClass('passwordBG');
		}
		else
		{
			$('#RetrievePassword').addClass('passwordBG');
		}

		$('#RetrievePassword').focus(function() {
			if ($(this).hasClass('passwordBG'))
			{
				$(this).removeClass('passwordBG');
			}
		});
		$('#RetrievePassword').blur(function() {
			if ($(this).val() == '')
			{
				$(this).addClass('passwordBG');
			}
			else
			{
				if ($(this).hasClass('passwordBG'))
				{
					$(this).removeClass('passwordBG');
				}
			}
			
		});

	}



	//postcode lookup

	$('#PostcodeLookup').each(function(){
		
		$(this).append('<img id="PostcodeLookupTrigger" src="' + SITEPATH + 'images/buttonFindAddress.png" alt="Find Address" style="cursor:pointer;" />');
		$('#container').after('<div id="DialogPostcodeLookup" title="Postcode Search"></div>');

		if ($('#Address1').val() == '')
		{
			$('#RowAddress').hide();
		}
		

		$('#DialogPostcodeLookup').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 400, height: 600, resizable: false,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
		$('#PostcodeLookupTrigger').click(function(){
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=PostcodeSearch&c=CheckPostcode',
				data: $('#FormCoverDetails').serialize(),
				success: function (html){
					$('#DialogPostcodeLookup').html(html);
					$('#DialogPostcodeLookup').dialog('open');

					$('.pickAddress').click(function(){
						$.ajax({
							url: SITEPATH + 'index.php?a=Ajax&b=PostcodeSearch&c=CheckAddress&id=' + $(this).attr('rel'),
							dataType: 'json',
							success: function (data){
								$.each(data, function(i,item){
									$('#' + i).val(item);
								});
								$('#RowAddress').show();
								$('#DialogPostcodeLookup').dialog('close');
							}
						});
					});
					$('#RowAddress').show();
				}
			});

			return false;
		});
	});

	// medical condition warning
	$('#MedFormSubmit').click(function(event){
		if ($('#NumConditions').val() == 0)
		{
			$('#BuyDiv').after('<div id="DialogMedCheck" title="Medical Conditions"><p>To confirm you have not added a medical condition. By clicking continue a full previous disability exclusion will apply.</p></div>');
			$('#DialogMedCheck').dialog({
				bgiframe: true,	autoOpen: true,	modal: true, width: 400, resizable: false,
				buttons: {
					'Continue': function(){
						$('#MedForm').submit();
					},
					'Add Condition': function(){
						$('#MedFormSubmit').show();
						$('.ajaxloader2').each(function(){
							$(this).hide();
						});
						$(this).dialog('close');
					}
				}
			});
			event.preventDefault();
		}
		else
		{
			$('#MedForm').submit();
		}
	});

	// dialog for policy options description
	if ($('.dialogpol').length)
	{
		$('.dialogpol').dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
			buttons: {
				'OK': function(){
					$(this).dialog('close');
				}
			}
		});

		$('.policyoptionstrigger').click(function(){
			var SchemeID = $(this).attr('rel');

			$('#PolicyDialog' + SchemeID).dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
			buttons: {
				'OK': function(){
					$(this).dialog('close');
				}
			}
			});

			$('#PolicyDialog' + SchemeID).dialog('open');

			return false;

		});

		$('.schemeoptionstrigger').click(function(){
			var SchemeID = $(this).attr('rel');

			$('#SchemeDialog' + SchemeID).dialog({
			bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
			buttons: {
				'OK': function(){
					$(this).dialog('close');
				}
			}
			});

			$('#SchemeDialog' + SchemeID).dialog('open');

			return false;

		});

	}

	// change card number fields on maestro selection
	if ($('#CardNumber5').length)
	{
		$('#RowCardMaestro').hide();
		$('#CardType').change(function(){
			$('#CardType option:selected').each(function(){
				if ($(this).text() == 'Maestro')
				{
					$('#RowCardNormal').hide();
					$('#RowCardMaestro').show();
				}
				else
				{
					$('#RowCardNormal').show();
					$('#RowCardMaestro').hide();
				}
			});
		});
	}
	//payment page dialogs
	$('#DialogDeclarationDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkDeclarationDoc').click(function(e){
		e.preventDefault();
		$('#DialogDeclarationDoc').html('<embed src="' + SITEPATH + 'temp/declaration' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/declaration' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogDeclarationDoc').dialog('open');
	});
	$('#DialogCertificateDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkCertificateDoc').click(function(e){
		e.preventDefault();
		$('#DialogCertificateDoc').html('<embed src="' + SITEPATH + 'temp/cert' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/cert' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogCertificateDoc').dialog('open');
	});

	// save button
	if ($('#SubmitSave').length)
	{
		//$('#SaveText').text('Save your quote and come back to it later');
		$('#SubmitSave').html('<a href="#" id="SubmitSaveBtn"><img src="' + SITEPATH + 'images/buttonSave.png" alt="Save" title="Save" /></a>');

		
		$('#container').after('<div id="DialogEmail" title="Save Quote"><p id="text">To save your quote, please enter your email address, a password and your current postcode.</p><p>If you have already saved a previous quotation, simply enter the same details as before and it will add this quote to your quote list when you log in.</p><table><tr><td class="caption strong"><label for="Email">Email address</label></td><td><input type="text" id="Email" name="Email" maxlength="80" class="short text" /></td></tr><tr><td class="caption strong"><label for="Password">Password<br /><span class="italic">(at least 6 characters)</span></label></td><td><input type="password" id="Password" name="Password" maxlength="20" class="short text" /></td></tr><tr><td class="caption strong"><label for="Password2">Retype Password<br /><span class="italic"></span></label></td><td><input type="password" id="Password2" name="Password2" maxlength="20" class="short text" /></td></tr><tr><td class="caption strong"><label for="Postcode">Postcode</label></td><td><input type="text" name="Postcode" id="Postcode" maxlength="20" class="short text" /></td></tr></table><br /><p style="margin-top:10px;">We will use your email address in accordance with our <a href="'+SITEPATH+'privacy-policy" title="privacy policy" target="_blank">privacy policy</a></p></div>');
		
		$('#DialogEmail').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 400, resizable: false,
			buttons: {
				'Continue': function(){

					//$('#FormCoverDetails').preventDefault();

					var emailval = $('#Email').val();
					var emailindex = emailval.indexOf("@");
					var emailindex2 = emailval.indexOf(".");
					var emailindex3 = emailval.indexOf(".couk");
					var passval1 = $('#Password').val();
					var passval2 = $('#Password2').val();
					var postval = $('#Postcode').val();

					if (postval == '')
					{
						$('#DialogEmail #text').html('<span style="color:red;font-weight:bold;">Please enter a postcode</span>');
						$('#Postcode').focus();
					}
					else
					{

						if (emailval != '' && emailindex != -1 && emailindex2 != -1 && emailindex3 == -1)
						{
							if (passval1 != '' && passval1.length > 5 && passval2 != '' && passval2.length > 5 && passval1==passval2)
							{
								$.ajax({
									url: SITEPATH + 'index.php?a=Ajax&b=SaveQuote',
									data: {email:emailval,password:passval1},
									success: function (data){
										//console.log(data);
										$('#HiddenPassword').val('');
										$('#HiddenEmail').val('');
										
										if (data == 'OK')
										{
											$('#HiddenPassword').val(passval1);
											$('#HiddenEmail').val(emailval);
											$('#HiddenPostcode').val(postval);
											$('#SaveNew').val(1);
											sendform();
										}
										else if (data == 'Match')
										{
											$('#HiddenPassword').val(passval1);
											$('#HiddenEmail').val(emailval);
											$('#HiddenPostcode').val(postval);
											$('#SaveNew').val(0);
											sendform();
										}
										else if (data == 'Taken')
										{
											$('#DialogEmail #text').html('<span style="color:red;font-weight:bold;">Your email address has already been taken OR does not match a password given. If you have forgotten you password, please visit our <a href="'+SITEPATH+'reset-password" target="_blank">reset password page</a>.</span>');

										}
									}
								});

							}
							else
							{
								$('#DialogEmail #text').html('<span style="color:red;font-weight:bold;">Please check your passwords are at least 6 characters long and they match</span>');
								$('#Password').focus();

							}
						}
						else 
						{
							$('#DialogEmail #text').html('<span style="color:red;font-weight:bold;">You have entered an invalid email address</span>');
							$('#Email').focus();
						}
					}

					
					
					
					
					function sendform()
					{
						if ($('#HiddenPassword').val().length && $('#HiddenEmail').val().length)
						{
							$('form').submit();
						}
					}

				}
			}
		});

		$('#SubmitSaveBtn').click(function(e){
			
			e.preventDefault();
			$('#DialogEmail').dialog('open');
		});
	}
	
	//save page
	$('.linkQuotationDoc').click(function(e){
		e.preventDefault();
		$('#DialogQuotationDoc').html('<embed src="' + SITEPATH + 'temp/quote' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'temp/quote' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogQuotationDoc').dialog('open');
	});
	$('#DialogQuotationDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('#DialogLetterDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkLetterDoc').click(function(e){
		e.preventDefault();
		$('#DialogLetterDoc').html('<embed src="' + SITEPATH + '/temp/purchaseletter' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/temp/purchaseletter' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogLetterDoc').dialog('open');
	});

	//internal get quote
	if ($('#DestinationRowCountry').length)
	{
		$('#DestinationRowArea').hide();
		if ($('#TripTypeInternal').val() == 2 || $('#TripTypeInternal').val() == 4)
			setInternalAnnual();

		$('#TripTypeInternal').change(function(){
			$('#TripTypeInternal option:selected').each(function(){
				if ($(this).text() == 'Annual Multi-Trip' || $(this).text() == 'Annual Winter Sports')
				{
					setInternalAnnual();
				}
				else
				{
					setInternalSingle();
				}
			});
		});

		function setInternalAnnual()
		{
			$('#DestinationRowArea').show();
			$('#DestinationRowCountry').hide();
			$('#DivEndDate').hide();
			$('#TravellingText').text('Start Date');
			if ($('#StartDate').val() == '')
			{
				var d = new Date();
				var day = String(d.getDate());
				if (day.length == 1)
					day = '0' + day;
				day += '/';
				var month = String(d.getMonth() + 1);
				if (month.length == 1)
					month = '0' + month;
				month += '/';
				$('#StartDate').val(day + month + String(d.getFullYear()));
			}
		}
		function setInternalSingle()
		{
			$('#DestinationRowArea').hide();
			$('#DestinationRowCountry').show();
			$('#DivEndDate').show();
			$('#TravellingText').text('Dates of Cover');
		}
		
	}

	$('#Page0Submit').click(function(e){
			// check the destination
			if ($('#DestinationName').length)
			{
				e.preventDefault();
				$.ajax({
					url: SITEPATH + 'index.php?a=Ajax&b=DestinationCheck&DestinationName=' + $('#DestinationName').val(),
					success: function (result){
						if (result == 'Failure')
						{
							$('#DialogDestinationError').html('<p></p><p>Please indicate the region you will be travelling to based on the definitions below.</p><p><select name="DestinationOverride" id="DestinationOverride" style="width:450px"><option value="16">United Kingdom:</option><option value="21">Europe 1</option><option value="22">Europe 2</option><option value="27">Worldwide 1</option><option value="28">Worldwide 2</option></select></p><p><strong>United Kingdom:</strong> Is United Kingdom, and Isle of Man</p><p><strong>Europe 1:</strong> means the continent of Europe west of the Ural Mountains including the Republic of Ireland and the Channel Islands all Countries bordering the Mediterranean Sea, Madeira, The Azores and Commonwealth of Independent States (west of the Ural Mountains) <span class="highlight">Excluding</span> Spain, Egypt, Turkey, Cyprus and Bulgaria.</p><p><strong>Europe 2:</strong> means the continent of Europe west of the Ural Mountains including the Republic of Ireland and the Channel Islands all Countries bordering the Mediterranean Sea, Madeira, The Azores and Commonwealth of Independent States (west of the Ural Mountains) <span class="highlight">including</span> Spain, Egypt, Turkey, Cyprus and Bulgaria.</p><p><strong>Worldwide 1:</strong> means anywhere in the world <span class="highlight">excluding</span> the USA, Canada and The Caribbean, Spain, Egypt, Turkey, Cyprus and Bulgaria.</p><p><strong>Worldwide 2</strong> means anywhere in the world.</p>');
							$('#DialogDestinationError').dialog('open');
						}
						else
						{
							$('#FormStart').submit();
						}
					}
				});
			}
		});

	$('#DialogDestinationError').dialog({
		bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: true,
		buttons: {
			'Continue': function() {
				$('#AltDestination').val($('#DestinationOverride').val());
				$('#DestinationName').val('');
				$('#FormStart').submit();
			}
		}
	});

	// help buttons
	$('.help').each(function(){
		var helpText = '';
		var target = $(this);
		var id = $(this).attr('rel');
		if ($(this).attr('name'))
		{
			var quoteID = $(this).attr('name');
			var urlDest = SITEPATH + 'index.php?a=Ajax&b=Help&c=' + id + '&d=' + quoteID;
		}
		else
		{
			var urlDest = SITEPATH + 'index.php?a=Ajax&b=Help&c=' + id;
		}
		
		$.ajax({
			url: urlDest,
			success: function (html){
				helpText = html;
				//alert(helpText);
				id = id.replace('&', '');
				id = id.replace('=', '');
				target.append('<span class="ui-icon ui-icon-info clickableHelp HelpTrigger' + id + '"  rel="' + id + '" style="float:right;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><div class="clearer"></div>');
				$('<div class="DialogHelp' + id + '" title="More Information">' + helpText + '</div>').appendTo('#container');

				$('.DialogHelp' + id).dialog({
					bgiframe: true,	autoOpen: false, modal: true, width: 650, resizable: false,
					buttons: {
						'Close': function() {
							$(this).dialog('close');
						}
					}
				});
				$('.HelpTrigger' + id).unbind('click');
				$('.HelpTrigger' + id).click(function(e){
					$('.DialogHelp' + $(this).attr('rel') + ':first').dialog('open');
				});
			}
		});
	});

	// date fields on policy list
	if ($('#ListStartDate').length || $('#ListEndDate').length)
	{
		$('#ListStartDate').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			minDate: '-1y',
			maxDate: '+1d',
			hideIfNoPrevNext: true
		});
		$('#ListEndDate').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			minDate: '-1y',
			maxDate: '+1d',
			hideIfNoPrevNext: true
		});
	}

	//internal resend quote
	$('.ResendQuote').click(function(event){
		var QuoteID = $(this).attr('name');
		var ResendEmail = $('#ResendEmail_'+QuoteID).val();
		$('#DialogEmailQuote').html('<p id="text">Enter the email address to send this quote to:</p><form method="POST" id="ResendQuote" action="' + SITEPATH + 'Internal/Quotes"><input type="hidden" name="ResendQuote" value="1" /><input type="hidden" name="QuoteID" id="QuoteID" value="'+QuoteID+'" /><table><tr><td class="caption"><label for="Email">Email address</label></td><td><input type="email" id="Email" name="Email" maxlength="80" class="short text" value="'+ResendEmail+'" required="required"/></td></tr></table></form>');
		$('#DialogEmailQuote').dialog('open');
		event.preventDefault();
	});

	$('#DialogEmailQuote').dialog({
		bgiframe: true,	autoOpen: false, modal: true, width: 400, resizable: false,
		buttons: {
			'Continue': function(){

				var emailval = $('#Email').val();
				var emailindex = emailval.indexOf("@");
				var emailindex2 = emailval.indexOf(".");
				var emailindex3 = emailval.indexOf(".couk");

				if (emailval != '' && emailindex != -1 && emailindex2 != -1 && emailindex3 == -1)
				{
					$('#ResendQuote').submit();
				}
				else 
				{
					$('#DialogEmailQuote #text').html('<span style="color:red;font-weight:bold;">You have entered an invalid email address:</span>');
				}
			}
		}
	});

	//page content links

	if ($('#ParaLinkP').length)
	{

		$('#BreadLink').live('click', function() {
			$('#LinkPreviewDialog2').dialog('open');
			return false;
		});

		$('a.linkselect2').click(function() {

				var linkName = $(this).attr('title');

				if ($('#Breadcrumbs').val() == '')
				{
					$('#Breadcrumbs').val(linkName);
				}
				else
				{
					$('#Breadcrumbs').val($('#Breadcrumbs').val() + ',' + linkName);
				}
				
				$('#Breadcrumbs').focus();
				$('#LinkPreviewDialog2').dialog('close');

				return false;
		});

		
		$('#LinkPreviewDialog2').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#IntLink').live('click', function() {
			$('#LinkPreviewDialog').dialog('open');
			return false;
		});

		$('a.linkselect').click(function() {

				var linkName = $(this).attr('title');
				
				$('#Content').text($('#Content').text() + '[[Link:'+linkName+']]');
				$('#Content').focus();
				$('#LinkPreviewDialog').dialog('close');
		});

		
		$('#LinkPreviewDialog').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#ExtLink').live('click', function() {
			$('#Content').text($('#Content').text() + '<a href="http://www.google.co.uk" rel="external">Google</a>');
			$('#Content').focus();
			return false;
		});

		$('#BannerLink').live('click', function() {
			$('#Content').text($('#Content').text() + '[[SideBanner]]');
			$('#Content').focus();
			return false;
		});

		$('#ParaLinkP').live('click', function() {
			$('#Content').text($('#Content').text() + '<p></p>');
			$('#Content').focus();
			return false;
		});

		$('#ListLinkP').live('click', function() {
			$('#Content').text($('#Content').text() + '<ul><li>item 1</li><li>item 2</li></ul>');
			$('#Content').focus();
			return false;
		});

		$('#PreviewLinkP').live('click', function() {
			// escape any html

			
			$('#Content').text($('#Content').text().replace('/ & /g'," &amp; "));
			//$('#Content').text($('#Content').text().replace(/ > /g," &gt; "));
			//$('#Content').text($('#Content').text().replace(/ < /g," &lt; "));
			//$('#Content').text($('#Content').text().replace(/\"/g,"&quot;"));
			$('#Content').text($('#Content').text().replace('/£/g',"&pound;"));

			var htmlval = $('#Content').text();

			$('#PreviewDialog').dialog('open');
			$('#PreviewDialog').html('<div style="height:500px;overflow:auto;">' + $('#Content').text() + '</div>');

			return false;
			
		});

		$('#PreviewDialog').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
	}
	
	//internal reports
	if ($('#StartDate2').length || $('#EndDate2').length)
	{
		$('#StartDate2').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			hideIfNoPrevNext: true,
			onSelect: function(dateText, inst){
				$('#EndDate2').datepicker('option', 'defaultDate', dateText);
			}
		});
		$('#EndDate2').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			hideIfNoPrevNext: true
		});
	}

	//policy list
	$('.moreDetails').click(function(e){
		var divid = $(this).attr('rel');
		e.preventDefault();
		$('#InternalQuote'+divid).dialog('open');
	});
	$('.InternalDialogue').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	if ($('#DialogCancel').length)
	{
		$('#DialogCancel').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 440, resizable: false,
			buttons: {
				'OK': function(){
					$('#FormCancel').submit();
				},
				'Back': function(){
					$(this).dialog('close');
				}
			}
		});
		$('#CancelLink').click(function(){
			$('#DialogCancel').dialog('open');
		});
	}
	
	//delete endorsements
	$('#DialogDeleteEndorsement').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 300, resizable: false,
		buttons: {
			'No': function(){
				$(this).dialog('close');
			},
			'Yes': function(){
				window.location = SITEPATH + 'index.php?a=Internal&b=Endorsements&c=DeleteEndorsement&EndorsementID=' + $('#SelectedID').val();
			}
		}
	});
	$('.linkDeleteEndorsement').click(function(e){
		e.preventDefault();
		$('#SelectedID').val($(this).attr('rel'));
		$('#DialogDeleteEndorsement').dialog('open');
	});
	

	

});

function premiumFormatHTML(pAmount)
{
	pAmount = parseFloat(pAmount);
	if (!isNaN(pAmount))
		return '&pound;' + commaFormat(pAmount.toFixed(2));
	else
		return '';
}

function commaFormat(pAmount)
{
	var delimiter = ","; // replace comma if desired
	var a = pAmount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { pAmount = n; }
	else { pAmount = n + '.' + d; }
	pAmount = minus + pAmount;
	return pAmount;
}
