$(function()
{

	//sortable list feedback internal
	$('#sortable').sortable({
		axis: 'y',
		cursor: 'pointer',
		distance: 5,
		opacity: 0.6,
		tolerance: 'pointer',
		update: function(event, ui){
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=Feedback',
				type: 'POST',
				data: $('#sortable').sortable('serialize')
			});
		}
	});

	$('#addanswer').click(function(e){
		records = $('#records').val();
		$('<li class="ui-state-default" style="list-style:none;" id="Feedback_'+records+'" ><input type="hidden" id="AnswerID'+records+'" name="AnswerID'+records+'" value="0" /><table width="100%"><tr><td style="width:250px;"><input type="text" name="Answer'+records+'" style="padding:0;margin:0;width:200px;"/></td><td>Live? <input type="checkbox" name="is_active'+records+'" style="width:20px;"</td></tr></table></li>').appendTo('#sortable2');
		$('#records').val(parseInt(records)+1);
		return false;
	});

	if ($('#Type').val() == '1')
	{
		$('#showhide').show();
		$('#link').show();
	}

	else if ($('#Type').val() == '2' || $('#Type').val() == '3')
	{
		$('#showhide').hide();
		$('#link').hide();
	}

	$('#answer_type').change(function(e){
		 if ($("option:selected", $(this)).attr("value")==1) 
		{
			$('#showhide').show();
			$('#link').show();
		}
		else 
		{
			$('#showhide').hide();
			$('#link').hide();
		}
	});
	$(".slider-range-max").each(function(){
		$(this).slider(
		{
			range: "max",
			min: 0,
			max: 10,
			value: $("#" + $(this).attr('rel')).val(),
			slide: function(event, ui) {
				$("#" + $(this).attr('rel')).val(ui.value);
			}
		});
	});


	
	// internal magenta page
	if ($('.linkCanxDetails').length)
	{
		$('.linkCanxDetails').click(function(){
			$('#DialogDetails').html('<table><tr><td class="captionShort">Affiliate:</td><td>' + $('#AffiliateName' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Premium:</td><td>' + $('#AffiliatePremium' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Cancellation Date:</td><td>' + $('#AffiliateCanxDate' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Notes:</td><td>' + $('#AffiliateNotes' + $(this).attr('rel')).val() + '</td></tr></table>');
			$('#DialogDetails').dialog('open');
		});

		$('.linkEndorsementDetails').click(function(){
			$('#DialogDetails').html('<table><tr><td class="captionShort">Reference:</td><td>' + $('#EndorsementName' + $(this).attr('rel')).val() + '</td></tr><td class="captionShort">Affiliate:</td><td>' + $('#EndorsementAffiliate' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">User:</td><td>' + $('#EndorsementUser' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Premium:</td><td>' + $('#EndorsementPremium' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Added Date:</td><td>' + $('#EndorsementDate' + $(this).attr('rel')).val() + '</td></tr><tr><td class="captionShort">Content:</td><td>' + $('#EndorsementNotes' + $(this).attr('rel')).val() + '</td></tr></table>');
			$('#DialogDetails').dialog('open');
		});


		$('#DialogDetails').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: false,
			buttons: {
				'Close': function(){
					$(this).dialog('close');
				}
			}
		});

		$('.linkSignOff').click(function(){
			$('#SelectedQuote').val($(this).attr('rel'));
			$('#DialogSignOffConfirmation').dialog('open');
		});
		$('.linkSignOffEndorsement').click(function(){
			$('#SelectedEndorsement').val($(this).attr('rel'));
			$('#DialogSignOffConfirmationEndorsement').dialog('open');
		});

		$('#DialogSignOffConfirmation').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: false,
			buttons: {
				'Cancel': function(){
					$(this).dialog('close');
				},
				'Confirm': function(){
					window.location = SITEPATH + 'index.php?a=Internal&b=Magenta&c=SignOff&QuoteID=' + $('#SelectedQuote').val();
				}
			}
		});
		$('#DialogSignOffConfirmationEndorsement').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: false,
			buttons: {
				'Cancel': function(){
					$(this).dialog('close');
				},
				'Confirm': function(){
					window.location = SITEPATH + 'index.php?a=Internal&b=Magenta&c=SignOff&EndorsementID=' + $('#SelectedEndorsement').val();
				}
			}
		});
	}

	// dialogs for affiliate home page
	if ($('#DialogInfo').length)
	{
		$('#DialogInfo').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 700, height: 500, resizable: true,
			buttons: {
				'Close': function(){
					$(this).dialog('close');
				}
			}
		});

		$('#LinkWording').click(function(){
			$('#DialogInfo').html('<embed src="' + SITEPATH + 'templates/affiliates/' + $('#AffiliateID').val() + '/wording' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'templates/affiliates/' + $('#AffiliateID').val() + '/wording' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
			$('#DialogInfo').dialog('open');
		});
		$('#LinkKeyfacts').click(function(){
			$('#DialogInfo').html('<embed src="' + SITEPATH + 'templates/affiliates/' + $('#AffiliateID').val() + '/keyfacts' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + 'templates/affiliates/' + $('#AffiliateID').val() + '/keyfacts' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
			$('#DialogInfo').dialog('open');
		});
		$('#LinkMedical').click(function(){
			$.ajax({
				url: SITEPATHU + 'index.php?a=Ajax&b=AffiliateMedicalText',
				success: function(data){
					$('#DialogInfo').html(data);
					$('#DialogInfo').dialog('open');
				}
			});
		});
		$('#LinkClaims').click(function(){
			$.ajax({
				url: SITEPATHU + 'index.php?a=Ajax&b=AffiliateClaimsText',
				success: function(data){
					$('#DialogInfo').html(data);
					$('a[rel="external"][href]').each(function(){
						$(this).attr('target', '_blank');
					});
					$('#DialogInfo').dialog('open');
				}
			});
		});
	}

	// set banner link on affiliate form
	$('.bannerLink').click(function(){
		var i = $(this).attr('rel');
		$('#Link').val('<a href="http://www.goodtogoinsurance.com/index.php?xyzid=' + $('#ArticleID').val() + '&utm_source=affiliate&utm_medium=Banner&utm_campaign=' + escape($('#Name').val()) + '" rel="canonical" target="_blank"><img src="http://www.goodtogoinsurance.com/images/banners/' + $('#Filename'+i).val() + '" alt="' + $('#Alt'+i).val() + '" width="' + $('#Width'+i).val() + '" height="' + $('#Height'+i).val() + '" /></a>');
		$('#BannerID').val(i);
		$('#DialogBanners').dialog('close');
	});

	if ($('#DialogBanners').length)
	{
		$('#DialogBanners').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: false,
			buttons: {
				'Close': function(){
					$(this).dialog('close');
				}
			}
		});
		$('#LinkBanners').click(function(){
			$('#DialogBanners').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
		});
	}

	// hide javascript warning
	$('#JavascriptWarning').hide();

	// details on ABTA and ATII
	$('#DialogABTA').dialog({
		bgiframe: true,	autoOpen: false, modal: true, width: 500, resizable: false,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('#LinkABTA').click(function(e){
		//e.preventDefault();
		$('#DialogABTA').html('<p>Goodtogoinsurance.com is an ABTA Travel Industry Partner. This helps us keep up to date with the latest in developments in the travel industry and the needs of UK holiday makers.</p>');
		$('#DialogABTA').dialog('open');
	});
	$('#DialogATII').dialog({
		bgiframe: true,	autoOpen: false, modal: true, width: 500, resizable: false,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('#LinkATII').click(function(e){
		//e.preventDefault();
		$('#DialogATII').html('<p>Goodtogoinsurance.com is a member of the Association of Travel Insurance Intermediaries, an industry body which encourages best practice in the selling of travel insurance to promote trust and consumer satisfaction within the industry.</p>');
		$('#DialogATII').dialog('open');
	});


	// news archive links
	$('.monthLink').hide();
	$('a.yearLink').click(function(){
		var year = $(this).attr('rel');
		$('.monthLink').each(function(){
			if ($(this).attr('rel') == year)
				$(this).show();
			else
				$(this).hide();
		});
	});

	// cancel policy
	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');
		});
	}

	//[[SitePath]]index.php?a=Internal&amp;b=Policies&amp;QuoteID=[[Var:Name=QuoteID:HTML]]&amp;SendCert=1

	$('#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();
				}
			}
		});
	});

	// create pdf from all unsent policy packs
	$('#MegaPDFLink').click(function(){
		$.ajax({
			url: SITEPATH + 'index.php?a=Ajax&b=MegaPDF',
			success: function(){
				$('#DialogMegaPDF').html('<embed src="' + SITEPATH + '/temp/unsent.pdf" href="' + SITEPATH + '/temp/unsent.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
				$('#DialogMegaPDF').dialog({
					bgiframe: true, autoOpen: true,	modal: false, width: 700, height: 500, resizable: true,
					buttons: {
						'Close': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	$('#MegaPDFLink2').click(function(){
		$.ajax({
			url: SITEPATH + 'index.php?a=Ajax&b=MegaPDF2',
			success: function(){
				$('#DialogMegaPDF2').html('<embed src="' + SITEPATH + '/temp/unsent2.pdf" href="' + SITEPATH + '/temp/unsent2.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
				$('#DialogMegaPDF2').dialog({
					bgiframe: true, autoOpen: true,	modal: false, width: 700, height: 500, resizable: true,
					buttons: {
						'Close': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});

	// quote end options
	$('#LinkReference').click(function(e){
		e.preventDefault();
		if ($('#NewReference').val())
		{
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=SaveNewReference', //&QuoteID=' + $('#QuoteID').val(),
				data: $('#FormSave').serialize(),
				success: function (html){
					$('#DialogReference').html('<p>Your new reference has been saved and emailed to you if you stated an email address. You can still use the original reference.</p>');
					$('#DialogReference').dialog({
						bgiframe: true,	autoOpen: true,	modal: true, width: 500, resizable: false,
						buttons: {
							'Close': function() {
								$(this).dialog('close');
							}
						}
					});
				}
			});
		}
	});
	$('#LinkSMS').click(function(e){
		e.preventDefault();
		if ($('#SMS').val())
		{
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=SendQuoteSMS', //&QuoteID=' + $('#QuoteID').val(),
				data: $('#FormSave').serialize(),
				success: function (html){
					$('#DialogSMS').html('<p>An SMS message has been sent.</p>');
					$('#DialogSMS').dialog({
						bgiframe: true, autoOpen: true,	modal: true, width: 500, resizable: false,
						buttons: {
							'Close': function() {
								$(this).dialog('close');
							}
						}
					});
				}
			});
		}
	});
	$('#LinkEmail').click(function(e){
		e.preventDefault();
		if ($('#Email').val())
		{
			$.ajax({
				url: SITEPATH + 'index.php?a=Ajax&b=SendQuoteEmail', //&QuoteID=' + $('#QuoteID').val(),
				data: $('#FormSave').serialize(),
				success: function (html){
					$('#DialogEmail').html('<p>The quotation email has been sent.</p>');
					$('#DialogEmail').dialog({
						bgiframe: true,	autoOpen: true,	modal: true, width: 500, resizable: false,
						buttons: {
							'Close': function() {
								$(this).dialog('close');
							}
						}
					});
				}
			});
		}
	});


	// traveller options dialogs
	if ($('#NumTravellers').length && $('#NumTravellers').val() > 1)
	{
		var optionArray = $('#OptionIDs').val().split(" ");
		for (i = 0; i < optionArray.length; i++)
		{
			if (optionArray[i] != ' ' && optionArray[i] != '')
			{
				for (j = 0; j < $('#NumTravellers').val(); j++)
				{
					$('#Option' + optionArray[i] + '_' + j).remove();
				}

				var optionText = '<p>Select which travellers require this option:</p><table>';
				for (j = 0; j < $('#NumTravellers').val(); j++)
				{
					optionText += '<tr><td><input type="checkbox" class="checkbox optionChange" name="Option' + optionArray[i] + '_' + j + '" rel="' + optionArray[i] + '" id="Option' + optionArray[i] + '_' + j + '" value="1"';
					if (optionArray[i] == 10000)
					{
						optionText += ' checked="checked"';
					}
					optionText += ' /></td><td style="width:150px">Traveller ' + (j + 1) + ' (age ' + $('#Age' + j).val() + ')</td><td>' + premiumFormatHTML($('#Gross' + optionArray[i]).val()) + '</td></tr>';
					//alert('added Option' + optionArray[i] + '_' + j);
				}
				optionText += '</table>';
				$('#DialogOptions' + optionArray[i]).html(optionText);
				$('#DialogOptions' + optionArray[i]).attr('rel', optionArray[i]);

				$('#DialogOptions' + optionArray[i]).dialog({
					bgiframe: true,	autoOpen: false, modal: false, width: 500, resizable: false,
					buttons: {
						'OK': function(){
							// reset parent checkbox if none selected
							var num = 0;
							var option = $(this).attr('rel');
							for (j = 0; j < $('#NumTravellers').val(); j++)
							{
								if ($('#Option' + option + '_' + j).attr('checked') == true)
								{
									$('#HiddenOption' + option + '_' + j).val(1);
									num++;
								}
								else
								{
									$('#HiddenOption' + option + '_' + j).val(0);
								}
							}
							if (num == 0)
							{
								$('#LinkOption' + option).attr('checked', '');
							}

							$(this).dialog('close');
						}
					}
				});

				var hiddenVars = '<input type="checkbox" class="checkbox" id="LinkOption' + optionArray[i] + '" rel="' + optionArray[i] + '"';
				if (optionArray[i] == 10000)
				{
					hiddenVars += ' checked="checked"';
				}
				hiddenVars += ' />';
				for (j = 0; j < $('#NumTravellers').val(); j++)
				{
					hiddenVars += '<input type="hidden" id="HiddenOption' + optionArray[i] + '_' + j + '" name="HiddenOption' + optionArray[i] + '_' + j + '" />';
				}
				$('#OptionCell' + optionArray[i]).html(hiddenVars);
				$('#LinkOption' + optionArray[i]).click(function(){
					if ($(this).attr('rel') != 10000)
					{
						$(this).attr('checked', 'checked');
						$('#DialogOptions' + $(this).attr('rel')).dialog('open');
					}
				});

			}
		}
	}

	//condition confirm exlusion dialog

	if ($('#TravellerIDs').length)
	{
		var travelArray = $('#TravellerIDs').val().split(",");
		for (i = 0; i < travelArray.length; i++)
		{
			if (travelArray[i] != '' && travelArray[i] != ',')
			{
				$('#Traveller'+ travelArray[i]).live("click",function() {

					var index = $(this).attr('rel');

					if ($('#TravPrem'+index).length && $('#TravPrem'+index).val() > 0.00 && $(this).attr("checked") == false)
					{
						$('#DialogMedical').html('<p>Are you sure you want to remove cover for this medical condition?</p><p>By unticking this box you are choosing to remove the insurance cover for this medical condition. If you do go ahead and remove the cover, any medical treatment resulting from or associated with the condition will be excluded from your policy.</p>');
						$('#DialogMedical').dialog('open');

						$('#DialogMedical').dialog({
							bgiframe: true,	autoOpen: true,	modal: false, width: 400, height: 200, resizable: true,
							buttons: {
								'No': function(){
									$(this).dialog('close');
									$('#Traveller'+index).attr("checked", 'checked');
								},
								'Yes': function(){
									$(this).dialog('close');
								}
								
							}
						});
					}
				});
			}
		}
	}

	//home internal page

	$('#InternalGoogle').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 400, height: 300, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('.openGoogle').click(function(e){
		e.preventDefault();
		$('#InternalGoogle').dialog('open');
	});

	$('#InternalQuotations').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 400, height: 300, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('.openQuotes').click(function(e){
		e.preventDefault();
		$('#InternalQuotations').dialog('open');
	});

	$('#InternalPolicies').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 400, height: 300, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});

	$('.openPolicies').click(function(e){
		e.preventDefault();
		$('#InternalPolicies').dialog('open');
	});


	// put the claims forms into dialog

	$('#DialogPersonalBelongingsDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkPersonalBelongingsDoc').click(function(e){
		e.preventDefault();
		$('#DialogPersonalBelongingsDoc').html('<embed src="' + SITEPATH + '/templates/personalbelongings' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/personalbelongings' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogPersonalBelongingsDoc').dialog('open');
	});

	$('#DialogCancellationDoc').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();
		$('#DialogCancellationDoc').html('<embed src="' + SITEPATH + '/templates/cancellation' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/cancellation' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogCancellationDoc').dialog('open');
	});

	$('#DialogCurtailmentDoc').dialog({
		bgiframe: true, autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkCurtailmentDoc').click(function(e){
		e.preventDefault();
		$('#DialogCurtailmentDoc').html('<embed src="' + SITEPATH + '/templates/curtailment' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/curtailment' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogCurtailmentDoc').dialog('open');
	});

	$('#DialogLuggageDelayDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkLuggageDelayDoc').click(function(e){
		e.preventDefault();
		$('#DialogLuggageDelayDoc').html('<embed src="' + SITEPATH + '/templates/luggagedelay' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/luggagedelay' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogLuggageDelayDoc').dialog('open');
	});

	$('#DialogTravelDelayDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkTravelDelayDoc').click(function(e){
		e.preventDefault();
		$('#DialogTravelDelayDoc').html('<embed src="' + SITEPATH + '/templates/traveldelay' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/traveldelay' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogTravelDelayDoc').dialog('open');
	});

	$('#DialogMedicalExpensesDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkMedicalExpensesDoc').click(function(e){
		e.preventDefault();
		$('#DialogMedicalExpensesDoc').html('<embed src="' + SITEPATH + '/templates/medicalexpenses' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/medicalexpenses' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogMedicalExpensesDoc').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');
			}
		}
	});
	$('.linkWordingDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#DialogWordingDoc').html('<embed src="' + SITEPATH + '/templates/' + affiliate + 'wording' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/' + affiliate + 'wording' + $(this).attr('rel') + '.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');
			}
		}
	});
	$('.linkKeyFactsDoc').click(function(e){
		e.preventDefault();
		var affiliate = '';
		if ($('#Affiliate').length)
			affiliate = 'affiliates/' + $('#Affiliate').val() + '/';
		$('#DialogKeyFactsDoc').html('<embed src="' + SITEPATH + '/templates/' + affiliate + 'keyfacts' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/templates/' + affiliate + 'keyfacts' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogKeyFactsDoc').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');
	});
	$('#DialogCertificateLetterheadDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500, resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkCertificateLetterheadDoc').click(function(e){
		e.preventDefault();
		$('#DialogCertificateLetterheadDoc').html('<embed src="' + SITEPATH + '/temp/certletterhead' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/temp/certletterhead' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogCertificateLetterheadDoc').dialog('open');
	});

	$('#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');
	});
	$('#DialogQuotationDoc').dialog({
		bgiframe: true, autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.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');
	});
	$('#DialogQuotationLetterheadDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkQuotationLetterheadDoc').click(function(e){
		e.preventDefault();
		$('#DialogQuotationLetterheadDoc').html('<embed src="' + SITEPATH + '/temp/quoteletterhead' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/temp/quoteletterhead' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogQuotationLetterheadDoc').dialog('open');
	});


	$('#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');
			}
		}
	});
	$('.linkPolicyPackLetterheadDoc').click(function(e){
		e.preventDefault();
		$('#DialogPolicyPackLetterheadDoc').html('<embed src="' + SITEPATH + '/temp/policypackletterhead' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/temp/policypackletterhead' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogPolicyPackLetterheadDoc').dialog('open');
	});
	
	$('#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');
	});
	$('#DialogDeclarationLetterheadDoc').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 700, height: 500,	resizable: true,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('.linkDeclarationLetterheadDoc').click(function(e){
		e.preventDefault();
		$('#DialogDeclarationLetterheadDoc').html('<embed src="' + SITEPATH + '/temp/declarationletterhead' + $(this).attr('rel') + '.pdf" href="' + SITEPATH + '/temp/declarationletterhead' + $(this).attr('rel') + '.pdf" style="width:100%; height:100%"><noembed>Your browser does not support embedded PDF files.</noembed></embed>');
		$('#DialogDeclarationLetterheadDoc').dialog('open');
	});

	$('.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');
			}
		}
	});




	// set links with a rel value of external to target a new frame
	$('a[rel="external"][href]').each(function(){
		$(this).attr('target', '_blank');
	});

	// hide faq answers until needed
	//$('.faqGroup').hide(); 
	$('.faqAnswer').hide();
	$('.faqSection').addClass('clickableHelp'); $('.faqQuestion').addClass('clickableHelp');
	$('.faqSection').click(function(){
		//$('.faqGroup').hide();
		$(this).next('.faqGroup').toggle();
	});
	$('.faqQuestion').click(function(){
		//$('.faqAnswer').hide();
		$(this).next('.faqAnswer').toggle();
	});


	// hide submit buttons after click
	$('input[type="submit"], input[type="image"]').click(function(){
		if ($('#PaymentPage').val() == 1)
		{
			$(this).hide();
			$('<div class="ajaxloader" />').appendTo('#PaymentSubmit');
			
			$('#PaymentForm').submit();
		}
	});

	// postcode search
	$('#PostcodeLookup').each(function(){
		if ($('#Affiliate').val() > 0)
			$(this).append('<img id="PostcodeLookupTrigger" src="' + SITEPATH + 'images/affiliates/' + $('#Affiliate').val() + '/button_findaddress.png" alt="Find Address" style="float:right;position:relative;right:52px;" />');
		else
			$(this).append('<img id="PostcodeLookupTrigger" src="' + SITEPATH + 'images/button_findaddress.png" alt="Find Address" style="float:right;position:relative;right:52px;" />');
		$('#leftWrapper').after('<div id="DialogPostcodeLookup" title="Postcode Search"></div>');
		$('#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').append(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();
				}
			});
		});
	});

	// save or buy button
	$('#SubmitBuyNow').each(function(){
		if ($('#Affiliate').val() > 0)
			$(this).after('<br /><br /><input type="image" id="SubmitSave" src="' + SITEPATH + 'images/affiliates/' + $('#Affiliate').val() + '/button_savequotation.png" style="height:39px; width:169px; background-color:transparent" class="submit" alt="Save Quotation" />');
		else
			$(this).after('<br /><br /><input type="image" id="SubmitSave" src="' + SITEPATH + 'images/button_savequotation.png" style="height:39px; width:169px; background-color:transparent" class="submit" alt="Save Quotation" />');

		$('#leftWrapper').after('<div id="DialogEmail" title="Email Address"><p id="text">To continue, enter your email address:</p><table><tr><td class="caption"><label for="Email">Email address</label></td><td><input type="text" id="Email" name="Email" maxlength="80" class="short" /></td></tr></table></div>');
		
		$('#DialogEmail').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)
					{
						$('#HiddenEmail').val($('#Email').val());
						$('#HiddenContactName').val('');
						$('#FormSchemes').submit();
					}
					else 
					{
						$('#DialogEmail #text').html('<span style="color:red;font-weight:bold;">You have entered an invalid email address:</span>');
					}
				},
				'I do not have an email address': function(){
					if ($('#Email').val() == '' || $('#Email').val() != '')
					{
						$('#DialogEmail').dialog('close');
						$('#DialogContactName').html('<p>In order to retrieve a quote in the future, please enter your contact name and use this when prompted:</p><table><tr><td class="caption"><label for="ContactName">Contact Name</label></td><td><input type="text" id="ContactName" name="ContactName" maxlength="80" class="short" /></td></tr></table>');
						$('#DialogContactName').dialog('open');
						$('#HiddenEmail').val('');
						//$('#FormSchemes').submit();
					}
				}
			}
		});
		

		$('#DialogContactName').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 400, resizable: false,
			buttons: {
				'Continue': function(){
					if ($('#ContactName').val() != '')
					{
						$('#HiddenContactName').val($('#ContactName').val());
						$('#FormSchemes').submit();
					}
				}
			}
		});
	});

	$('#SubmitBuyNow').click(function(event){
		$('#QuitNow').val(0);
		$('#DialogEmail').html('<p id="text">To continue, enter your email address:</p><table><tr><td class="caption"><label for="Email">Email address</label></td><td><input type="text" id="Email" name="Email" maxlength="80" class="short" /></td></tr></table>');
		$('#DialogEmail').dialog('open');
		event.preventDefault();
	});
	$('#SubmitSave').click(function(event){
		$('#QuitNow').val(1);
		$('#DialogEmail').html('<p id="text">To continue, enter your email address:</p><table><tr><td class="caption"><label for="Email">Email address</label></td><td><input type="text" id="Email" name="Email" maxlength="80" class="short" /></td></tr></table>');
		$('#DialogEmail').dialog('open');
		event.preventDefault();
	});

	// terminal months popout question
	$('#TerminalRow').hide();
	$('#Med4').change(function(){
		$('#Med4 option:selected').each(function(){
			if ($(this).text() == 'Yes')
				$('#TerminalRow').show();
			else
				$('#TerminalRow').hide();
		});
	});

	// made a mistake, return to beginning link
	$('#QuoteList').each(function(){
		$(this).after('<a href="#" id="MistakeTrigger">Made a mistake?</a>');
		$('#leftWrapper').after('<div id="DialogMistake" title="Made a mistake"><p>In order to correct a mistake in the quote you must start the process again.</p></div>');
		$('#DialogMistake').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 350, resizable: false,
			buttons: {
				'Restart': function(){
					window.location = SITEPATH + 'public/Quote,Page0';
				},
				'Continue': function(){
					$(this).dialog('close');
				}
			}			
		});
		$('#MistakeTrigger').click(function(){
			$('#DialogMistake').dialog('open');
		});
	});

	// medical condition warning
	$('#MedFormSubmit').click(function(event){
		if ($('#NumConditions').val() == 0)
		{
			$('#leftWrapper').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();
						$(this).dialog('close');
					}
				}
			});
			event.preventDefault();
		}
		else
		{
			$('#MedForm').submit();
		}
	});

	// help buttons
	$('.help').each(function(){
		var helpText = '';
		var target = $(this);
		var id = $(this).attr('rel');
		$.ajax({
			url: SITEPATH + 'Ajax/Help/' + id,
			success: function (html){
				helpText = html;
				id = id.replace('&', '');
				id = id.replace('=', '');
				target.append('<span class="ui-icon-info clickableHelp HelpTrigger' + id + '" style="background-image: url(' + SITEPATH + 'images/jqueryui/ui-icons_000000_256x240.png); width:16px;" rel="' + id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
				$('#leftWrapper').after('<div class="DialogHelp' + id + '" title="Help">' + helpText + '</div>');

				$('.DialogHelp' + id).dialog({
					bgiframe: true,	autoOpen: false, modal: true, width: 500, resizable: false,
					buttons: {
						'Close': function() {
							$(this).dialog('close');
						}
					}
				});
				$('.HelpTrigger' + id).unbind('click');
				$('.HelpTrigger' + id).click(function(e){
					$('.DialogHelp' + $(this).attr('rel') + ':first').dialog('open');
				});
			}
		});
	});
	$('.helpLink').each(function(){
		var helpText = '';
		var target = $(this);
		var id = $(this).attr('rel');
		$.ajax({
			url: SITEPATH + 'Ajax/Help/' + id,
			success: function (html){
				helpText = html;
				id = id.replace('&', '');
				id = id.replace('=', '');
				//target.append('<span class="ui-icon-info clickableHelp HelpTrigger' + id + '" style="background-image: url(' + SITEPATH + 'images/jqueryui/ui-icons_000000_256x240.png); width:16px;" rel="' + id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
				$('#leftWrapper').after('<div class="DialogHelp' + id + '" title="Help">' + helpText + '</div>');

				$('.DialogHelp' + id).dialog({
					bgiframe: true,	autoOpen: false, modal: true, width: 500, resizable: false,
					buttons: {
						'Close': function() {
							$(this).dialog('close');
						}
					}
				});
				$('.HelpTrigger' + id).unbind('click');
				$('.HelpTrigger' + id).click(function(e){
					$('.DialogHelp' + $(this).attr('rel') + ':first').dialog('open');
				});
			}
		});
	});
	$('.helpUnsecure').each(function(){
		var helpText = '';
		var target = $(this);
		var id = $(this).attr('rel');
		$.ajax({
			url: SITEPATHU + 'Ajax/Help/' + id,
			success: function (html){
				helpText = html;
				id = id.replace('&', '');
				id = id.replace('=', '');
				target.append('<span class="ui-icon-info clickableHelp HelpTrigger' + id + '" style="background-image: url(' + SITEPATH + 'images/jqueryui/ui-icons_000000_256x240.png); width:16px;" rel="' + id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
				$('#leftWrapper').after('<div class="DialogHelp' + id + '" title="Help">' + helpText + '</div>');

				$('.DialogHelp' + id).dialog({
					bgiframe: true, autoOpen: false, modal: true, width: 500, resizable: false,
					buttons: {
						'Close': function() {
							$(this).dialog('close');
						}
					}
				});
				$('.HelpTrigger' + id).unbind('click');
				$('.HelpTrigger' + id).click(function(e){
					$('.DialogHelp' + $(this).attr('rel') + ':first').dialog('open');
				});
			}
		});
	});	

	// auto set end date for annual policies
	if ($('#TripType').length)
	{
		$('#TripType option:selected').each(function(){
			if ($(this).text() == 'Annual')
			{
				$('#DivEndDate').hide();
				$('#MultipleInfo').show();
				$('#FamilyGroup option:last-child').hide();

			}
			else 
			{
				$('#MultipleInfo').hide();
				$('#DivEndDate').show();
				$('#FamilyGroup option:last-child').show();
			}
		});

		$('#TripType').change(function(){
			$('#TripType option:selected').each(function(){
				if ($(this).text() == 'Annual')
				{
					//$('#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:last-child').hide();
				}
				else
				{
					//$('#RowTripLength').show();
					$('#MultipleInfo').hide();
					$('#DivEndDate').show();
					$('#TravellingText').text('Tell us the dates of your holiday');
					$('#FamilyGroup option:last-child').show();
				}
			});
		});
	}

	// 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() == 'Family')
				{
					$('#NumberTravellers').val(3);
					$('#RowNumPeople').show();
				}
				else
					$('#RowNumPeople').show();
				$('#NumberTravellers').keyup();
			});
		}).change();
	}

	// condition autocomplete
	if ($('#ConditionSearch').length)
	{
		$('#ConditionSearch').autocomplete({
			source: SITEPATH + 'index.php?a=Ajax&b=AutoComplete&c=Conditions',
			minLength: 3
		});
	}

	// live premium update
	if ($('#DivFinalPremium').length || $('#DivFinalPremium2').length)
	{
		$('.schemeChange').click(function(){
			premiumCalculate();
		});
		$('.optionChange').click(function(){
			premiumCalculate();
		});
		$('.travellerChange').click(function(){
			premiumCalculate();
		});

		function premiumCalculate()
		{
			var premium = 0; //parseFloat($('#HiddenPremium').val());
			/*$('.schemeChange').each(function(){
				if ($(this).attr('checked'))
				{
					premium = parseFloat($('#Gross' + $(this).attr('rel')).val());
				}
			});*/
			$('.travellerChange').each(function(){
				if ($(this).attr('checked'))
					premium += parseFloat($('#TravPrem' + $(this).attr('rel') + 'Inc').val());
				else
					premium += parseFloat($('#TravPrem' + $(this).attr('rel') + 'Exc').val());
			});
			$('.hiddenTraveller').each(function(){
				premium += parseFloat($(this).val());
			});
			$('.optionChange').each(function(){
				if ($(this).attr('checked'))
				{
					premium += parseFloat($('#Gross' + $(this).attr('rel')).val());
				}
			});
			$('#DivFinalPremium').html('<h2>' + premiumFormatHTML(premium) + '</h2>');
			$('#DivFinalPremium2').html('Premium ' + premiumFormatHTML(premium));
		}
	}

	// trip dates
	if ($('#StartDate').length || $('#EndDate').length || $('#NewsDate').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
		});
		$('#NewsDate').datepicker({
			dateFormat: "dd/mm/yy",
			gotoCurrent: true,
			minDate: '-1y',
			maxDate: '+6m',
			hideIfNoPrevNext: true
		});
	}


	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
		});
	}

	// traveller date of birth
	if ($('.shortDob').length)
	{
		$('.shortDob').each(function(){
			var id = $(this).attr('rel');
			$('#DobDay' + id).keyup(function(){
				if ($(this).val().length == 2)
					$('#DobMonth' + id).focus();
			});
			$('#DobMonth' + id).keyup(function(){
				if ($(this).val().length == 2)
					$('#DobYear' + id).focus();
			});
		});
	}

	// adding time to news article
	if ($('#NewsTime1').length)
	{
		$('#NewsTime1').keyup(function(){
			if ($(this).val().length == 2)
				$('#NewsTime2').focus();
		});
	}

	// credit card number
	if ($('#CardNumber1').length)
	{
		$('#CardNumber1').keyup(function(){
			if ($(this).val().length == 4)
				$('#CardNumber2').focus();
		});
		$('#CardNumber2').keyup(function(){
			if ($(this).val().length == 4)
				$('#CardNumber3').focus();
		});
		$('#CardNumber3').keyup(function(){
			if ($(this).val().length == 4)
				$('#CardNumber4').focus();
		});

		$('#CardStartDate1').keyup(function(){
			if ($(this).val().length == 2)
				$('#CardStartDate2').focus();
		});
		$('#CardEndDate1').keyup(function(){
			if ($(this).val().length == 2)
				$('#CardEndDate2').focus();
		});
	}
	
	// facebook bookmark link
	if ($('#BookmarkFacebook').length)
	{
		$('#BookmarkFacebook').click(function(){
			window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(location.href) + '&amp;t=' + encodeURIComponent(document.title));
			return false;
		});
	}

	// news article content links
	if ($('#ImageLink').length)
	{

		$('#ImageLink').live('click', function() {
		  // Live handler called.
		//});
		//$('#ImageLink').click(function(){
			$('#ImagePreviewLeftDialog').dialog('open');
			return false;
		});

		$('a.imageLeft').click(function(e) {

				e.preventDefault();
				var imgID = $(this).attr('id');
				var alt = $(this).attr('title');
				var portrait = $(this).attr('href');

				if (portrait == 0)
				{
					$('#Content').text('<img src="' + SITEPATHU + 'images/news/'+ imgID+'.jpg" alt="'+ alt +'" style="margin:0 0 10px;" />' + $('#Content').text());
				}
				else 
				{
					$('#Content').text('<img src="' + SITEPATHU + 'images/news/'+ imgID+'.jpg" alt="'+ alt +'" style="margin:0 10px 10px 0;float:left;" />' + $('#Content').text());
				}

				$('#Content').focus();
				$('#ImagePreviewLeftDialog').dialog('close');

				
		});

		$('#ImageLink2').live('click', function() {
			$('#ImagePreviewRightDialog').dialog('open');

		});

		$('a.imageRight').click(function() {

				var imgID = $(this).attr('id');
				var alt = $(this).attr('title');
				
				$('#Content').text($('#Content').text() + '<img src="' + SITEPATHU + 'images/news/'+ imgID+'.jpg" alt="'+ alt +'" class="newsPhotoRight" />');
				$('#Content').focus();
				$('#ImagePreviewRightDialog').dialog('close');
			});
		
		$('#ImagePreviewLeftDialog').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#ImagePreviewRightDialog').dialog({
			bgiframe: true, autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});

		$('#LinkLink').live('click', function() {
			$('#Content').text($('#Content').text() + '<a href="http://www.google.co.uk" rel="external">Google</a>');
			$('#Content').focus();
		});
		$('#ParaLink').live('click', function() {
			$('#Content').text($('#Content').text() + '<p></p>');
			$('#Content').focus();
		});
		$('#ListLink').live('click', function() {
			$('#Content').text($('#Content').text() + '<ul><li>item 1</li><li>item 2</li></ul>');
			$('#Content').focus();
			
			return false;

		});

		$('#PreviewLink').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();

			//$('<div style="width:600px;background:red;position:absolute;top:500px;left:400px;" id="preview">'+htmlval+'</div>').appendTo('body');
			
			$('#PreviewDialog').dialog('open');
			$('#PreviewDialog').html('<div style="height:500px;overflow:auto;">' + $('#Content').text() + '</div>');
			
		});

		$('#PreviewDialog').dialog({
			bgiframe: true,	autoOpen: false, modal: true, width: 600, resizable: true,
			buttons: {
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
	}
	


	$('#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>Please call 0844 334 0160 is you have any queries.</p><p>Do you wish to continue?</p>');
		$('#DialogNonDeclaration').dialog('open');
	});

	$('#DialogPhone').dialog({
		bgiframe: true,	autoOpen: false, modal: false, width: 300, resizable: false,
		buttons: {
			'Close': function(){
				$(this).dialog('close');
			}
		}
	});
	$('#LinkPhone').click(function(e){
		$('#DialogPhone').dialog('open');
	});

	$('#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');
	});

	//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;
		});

		$('#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');
				}
			}
		});
	}
	

});

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;
}