var $j = jQuery.noConflict();

$j(window).load(function () { //Start code ******************************************
	var prefix = window.location.protocol;
	var imageServer = "http://images.golfbreaks.com/customimage.aspx?format=";
	if (prefix == "https:") {
		imageServer = "https://images.golfbreaks.com/customimage.aspx?format=";
	}

	var elements = $j(".customBackground");

	$j(elements).each(function () {
		var element = $j(this);
		var classNames = $j(element).attr("class").split(" ");

		var customBackground = "";
		for (j = 0; j < classNames.length; j++) {
			if (classNames[j] == "customBackground" && (j + 1) < classNames.length) {
				customBackground = classNames[j + 1];
				break;
			}
		}

		if (customBackground !== "") {
			// Get the height and width of the element
			var width = $j(this).attr("offsetWidth");
			var height = $j(this).attr("offsetHeight");

			// Set the custom background image of the element
			var backgroundImage = imageServer + customBackground + "&width=" + width + "&height=" + height;
			$j(element).css("backgroundImage", "url(" + backgroundImage + ")");
		}

	});

	// Date picker
	$j('input.datepicker:not(.dateOfBirthContainer input.datepicker)').datepicker({
		dateFormat: 'dd/mm/yy',
		minDate: 0,
		showOn: 'button',
		buttonImage: '/Themes/Golfbreaks/Images/calendar-dropdown.gif',
		buttonImageOnly: true
	});

	$j(".dateOfBirthContainer input.datepicker").datepicker({
		buttonImage: '/Themes/Golfbreaks/Images/calendar-dropdown.gif',
		buttonImageOnly: true,
		changeYear: true,
		dateFormat: 'dd/mm/yy',
		maxDate: 0,
		showOn: 'button',
		yearRange: '-100:+0',
		onClose: function () { $j(".dateOfBirthContainer input.datepicker").focus(); }
	});

	$j(".ui-datepicker-trigger")
        .attr("alt", "Calendar")
        .attr("title", "Open calendar");

	// Decorative .last class
	$j("#[id$=crossSellingVenues] li:last, #[id*=SpecialOffersList] li:last-child, #[id*=CategorySpecialOfferList] li:last-child, div.availableFacets ul:last-child").addClass("last");

	/*	Watermarked inputs */
	$j('input.hasDefaultText, textarea.hasDefaultText').watermark();

	/*	Floyout nav	*/
	$j('ul.sf-menu').superfish({
		animation: { opacity: 'show', height: 'show' },
		autoArrows: false,
		delay: 1000,
		dropShadows: true,
		onBeforeShow: function () { $j('#ui-datepicker-div').hide(); $j(this).css('top', $j(this).parent('li').outerHeight()); },
		speed: 'fast'
	}).find('ul').bgIframe({ opacity: false });
});

//	SKYSCANNER
// Amend some of the skyscanner code.
// Add a theme, set the heading and additional content, if any set
function amendSkyscannerCode(skyScannerTheme, skyScannerHeading, skyScannerContent) {

	jQuery('#snippet_searchpanel').addClass(skyScannerTheme);
	jQuery('#snippet_searchpanel div.ss_sp_header').html('<h1>' + skyScannerHeading + '</h1>');
	jQuery('#snippet_searchpanel div.ss_sp_header').after(skyScannerContent);

	// Remove all the cruft
	jQuery('#snippet_searchpanel span.ss_sp_rtc, ' +
		'#snippet_searchpanel span.ss_sp_lbc, ' +
		'#snippet_searchpanel span.ss_sp_rbc, ' +
		'#snippet_searchpanel div.ss_sp_header_txt, ' +
		'#snippet_searchpanel a.sp_logo, ' +
		'#snippet_searchpanel div.ss_sp_rc, ' +
		'#snippet_searchpanel div.ss_sp_pass_desc, ' +
		'#snippet_searchpanel div.ss_sp_best_label, ' +
		'#snippet_searchpanel table.ss_sp_dates div.ss_datesel_icon, ' +
		'#snippet_searchpanel table.ss_sp_dates div.ss_datesel_inp_right_corner, ' +
		'#snippet_searchpanel div.ss_subt_box, ' +
		'#snippet_searchpanel span[style*=clear]').remove();

	// The div with inline clear is removed separately - IE will not select this (or the span but the span is fairly harmless right now) using the *= selector
	jQuery('#snippet_searchpanel div.ss_sp_sc').next('div').remove();

	// We're going to float the form, the marquee and the submit "button" so need a clearfix on the containers
	jQuery('#snippet_searchpanel div.ss_sp_content_in, #snippet_searchpanel div.ss_sp_bottom').addClass('clearfix');

	// Shift the to / from labels to get around the table structure
	jQuery('#snippet_searchpanel table.ss_sp_as div.ss_sp_as_container').each(function () {
		var labelText = jQuery(this).parents('tr').find('td.ss_label').html();
		jQuery(this).before(labelText);
		jQuery(this).parents('tr').find('td.ss_label').html('');
	});

	// Add labels for the adult / child / infant fields
	jQuery('#snippet_searchpanel input.ss_sp_pass_adult').before('<span id="ssAdultHdg">Adult</span>');
	jQuery('#snippet_searchpanel input.ss_sp_pass_child').before('<span id="ssChildHdg">Under 12</span>');
	jQuery('#snippet_searchpanel input.ss_sp_pass_inf').before('<span id="ssInfantHdg">Under 2</span>');

	// Add datepickers
	jQuery('#snippet_searchpanel table.ss_sp_dates tr.ss_sp_sc_to td input').datepicker({
		dateFormat: 'dd/mm/yy',
		minDate: 0,
		showOn: 'button',
		buttonImage: '/Themes/Golfbreaks/Images/calendar-dropdown.gif',
		buttonImageOnly: true
	});

	jQuery('.ui-datepicker-trigger')
		.attr('alt', 'Calendar')
		.attr('title', 'Open calendar');

	// Get rid of the inline styles on the marquee
	jQuery('#snippet_searchpanel div.ss_sp_offer_list_content').attr('style', '');

	// Add a heading for the marquee
	jQuery('#snippet_searchpanel div.ss_sp_offers_in').before('<h2 id="ssOffersHdg">Best Offers</h2>');

} // Close amendSkyscannerCode()

// Add in a cleanup function - basically, this removes anything we added in the amend...() function
// so if the user re-opens the overlay they don't get duplicated headings etc.
// It's fairly unlikely that the user will do this enough times that the overheads for undoing the whole lot is worthwhile
function unAmendSkyscannerCode() {
	jQuery('#snippet_searchpanel #ssExtraContent, ' +
		'#snippet_searchpanel #ssOffersHdg, ' +
		'#snippet_searchpanel #ssAdultHdg, ' +
		'#snippet_searchpanel #ssChildHdg, ' +
		'#snippet_searchpanel #ssInfantHdg').remove();
} // Close unAmendSkyscannerCode()

(function ($) {
	$.fn.enquiryForm = function(options) {
		
		var settings = {	
			$arrivalDates: $('#arrivalDates'),
			$groupSizeLabel: $('#uiLblGroupSize'),
			$groupSizeDropdown: $('#uiGroupDropDownList'),
			$nightsLabel: $('#uiLblNights'),
			$nightsDropdown: $('#uiNightsDropDownList'),
			$roundsLabel: $('#uiLblNumberRounds'),
			$roundsDropdown: $('#uiNumberRounds'),
			$furtherInfoLabel: $('#uiLblFurtherInfo'),
			$furtherInfoField: $('#uiTxtFurtherInfo')
		};

		if (options) { $.extend(settings, options); }
		var initialised = true;

		$destinationDropdown = $(this);

		function hideAll() {
			$.each(settings, function(index, value) { 
				settings[index].hide();
			});
		}

		$destinationDropdown.change(function(event){
			if ($($destinationDropdown).val() === '') {return;}
			
			hideAll();

			if ($($destinationDropdown).val().search('UK') > 0) {
				settings.$groupSizeLabel.show();
				settings.$groupSizeDropdown.show();
				settings.$furtherInfoLabel.show();
				settings.$furtherInfoField.show();
			} else {
				settings.$groupSizeLabel.show();
				settings.$groupSizeDropdown.show();
				settings.$nightsLabel.show();
				settings.$nightsDropdown.show();
				settings.$roundsLabel.show();
				settings.$roundsDropdown.show();
				settings.$furtherInfoLabel.show();
				settings.$furtherInfoField.show();
			}

		});

		if (initialised) {
			initialised = false;

			if ($($destinationDropdown).val() !== '') {
				$destinationDropdown.trigger('change');
			} else {
				hideAll();
			}
		}
	};
})(jQuery);

function initialiseGBOnlineDialog(enquiryLink) {
	jQuery('#onlineBookingContainer').append('<div id="dialogContent" style="display: none;">' +
		'<p>If you have any questions about booking your break please contact us for assistance and advice.</p>' +
		'<ul>' +
		'<li><a id="overlayEnquiryLink" class="excludeOverlay" href="' + enquiryLink.attr('href') + '">Send us an enquiry</a> and one of our experienced sales agents will call you back</li>' +
		'<li>Call us on <span class="phoneCta">0800 279 7988</span></li>' +
		'<li class="whosOnOverlayItem">Chat to us live now</li>' +
		'</ul>' +
		'We look forward to speaking to you soon.' +
		'</div>');

	jQuery('#enqQuickbarLink, #whoson_chat_link, #termsLink').addClass('excludeOverlay');
	enquiryLink.addClass('excludeOverlay');

	jQuery('#dialogContent').dialog({
		autoOpen: false,
		buttons: { 'No thanks': function () { window.location = jQuery(this).data('intendedDestination'); } },
		closeOnEscape: true,
		dialogClass: 'needHelpOverlay',
		modal: true,
		resizable: false,
		title: 'Need Help?',
		width: 500
	});
}

function triggerGBOnlineDialog(event, triggerLink) {
	if (triggerLink.hasClass('ui-datepicker-prev') || triggerLink.hasClass('ui-datepicker-next')) { return; }
	
	event.preventDefault();
	var intendedDestination = triggerLink.attr('href');

	if (triggerLink.hasClass('excludeOverlay') || triggerLink.parents('#ui-datepicker-div').length > 0) {
		window.location = intendedDestination;
	} else {
		jQuery('#dialogContent').dialog('open').data('intendedDestination', intendedDestination);
		jQuery('li.whosOnOverlayItem').live('click', function () { sWOStartChat(); });
	}
}
