var Tui = Tui || {};
Tui.MediaPanel = {
    resize: function(img) {
        jQuery(img).resizeThumbs(Tui.MediaPanel.panelWidth, Tui.MediaPanel.panelHeight);
    },
    panelWidth: 539,
    panelHeight: 401
};

jQuery.fn.extend({
    resizeThumbs: function(maxThumbWidth, maxThumbHeight ) {
        jQuery(this).each(function() {
			var maxWidth = maxThumbWidth; // Max width for the image
			var maxHeight = maxThumbHeight;    // Max height for the image
			var ratio = 0;  // Used for aspect ratio
            jQuery(this).width('auto').height('auto').css('margin', 0);
			var width = jQuery(this).width();    // Current image width
			var height = jQuery(this).height();  // Current image height

			// Check if the current width is larger than the max
			if (width > maxWidth) {
				ratio = maxWidth / width;   // get ratio for scaling image
				jQuery(this).css("width", maxWidth); // Set new width
				jQuery(this).css("height", height * ratio);  // Scale height based on ratio
				height = height * ratio;    // Reset height to match scaled image
				width = maxWidth;
			}

			// Check if current height is larger than max
			if (height > maxHeight) {
				ratio = maxHeight / height; // get ratio for scaling image
				jQuery(this).css("height", maxHeight);   // Set new height
				jQuery(this).css("width", width * ratio);    // Scale width based on ratio
				height = maxHeight;
			}

			// Set margin top!
			if (height < maxHeight) {
				jQuery(this).css("margin-top", Math.ceil((maxHeight - height) / 2)); // Set new margin top
			}
		});
	},
	resultsGallery: function()
	{
		jQuery(this).each(function() {
			var container = jQuery(this), // Container element
				image = jQuery('img', container), // Image element
				links = jQuery('ul li a', container); // List of links containing urls for images
			var imgContainer = jQuery('.insideImage', container); // Image container element
			var imgContainer = image.parent();
				
			if(links.length <= 1) return; // If link list contains 1 or less links there is no need to use gallery
			var currentIndex = 0, numImages = links.length; 
			
			// Create elements for gallery controls
			var controls = jQuery('<ul class="imagesCounter"></ul>'), // control container
			prev = jQuery('<li class="previous"><a class="prev" href="#">Previous</a></li>'),
			counter = jQuery('<li class="number"><span>1</span> of <span>' + numImages + '</span></li>'),
			next = jQuery('<li class="next"><a class="next" href="#">Next</a></li>');
			
			controls.append(prev).append(counter).append(next); // Add control elements to control container
			container.append(controls); // Add controls to the image container
			prev.css('visibility', 'hidden'); // Hide "prev" control as the gallery starts on image 1

			// Event handler for the image loading
			image.load(function() {
				image.width('auto').height('auto').css('margin', '0') // Width, height and margin need to be reset for each new image otherwise they interfere with the resizing function.
				.resizeThumbs(imgContainer.width(), imgContainer.height()); // Call resize function on the newly loaded image
				counter.text(currentIndex+1 + ' of ' + numImages);
				if(currentIndex==0) 
				{
					prev.css('visibility', 'hidden');
				}
				else
				{
					prev.css('visibility', 'visible');
				}
				if(currentIndex==(numImages-1))
				{
					next.css('visibility', 'hidden');
				}
				else
				{
					next.css('visibility', 'visible');
				}
			});
			
			// Event handlers for next and prev links
			jQuery('a.prev', controls).click(function() {
				if(currentIndex>0) currentIndex--;
				image.attr('src', links.eq(currentIndex).attr('href')); // Triggers the image load event handler
				return false;
			});
			jQuery('a.next', controls).click(function() {
				if(currentIndex<numImages-1) currentIndex++;
				image.attr('src', links.eq(currentIndex).attr('href')); // Triggers the image load event handler
				return false;
			});
		});
	}
});


function ourInsuranceDetails() {
	if(jQuery('#page.bookingPage ul.extrasList li .ownInsurance .iHaveInsurance input[type=checkbox]').is(':checked')){}
	else{
		jQuery('#page.bookingPage ul.extrasList li .ownInsurance .myInsuranceProvider').hide(); // Hide my own insurance input box - Extras page
	}
}

function insuranceDeclaration(extrasSelected) {
	if(extrasSelected){
		if(jQuery("#page.bookingPage ul.bookingFlowList .insuranceExtras .checkBoxList").is(':visible'))
		{}else{
			jQuery('#page.bookingPage ul.bookingFlowList .insuranceExtras .checkBoxList').show(); // Show my own insurance input box - Extras page
		}
	}else{
		jQuery('#page.bookingPage ul.bookingFlowList .insuranceExtras .checkBoxList').hide(); // Hide my own insurance input box - Extras page
	}
}

function checkInsuranceDeclaration(){
	if(jQuery('.INSR .priceTrigger').filter(":checked").length > 0)
	{
		insuranceDeclaration(true);
	}else{
		insuranceDeclaration(false);
	}
}

function overlayClosed() {
	//alert('closed');
	var activeChildBoxes = jQuery('.travellers .children #childrenDropDownId').val();
	var formID = jQuery('#childrenDropDownId').closest('form').attr('id');
	
	for(var i = 0; i < activeChildBoxes; i++)
	{
		var counter=i+1;
		if(jQuery('.childAges #ChildAgeItem-'+counter+' select').val() == "")
		{
			jQuery('.travellers .children #childrenDropDownId').val(0);
			updateChildrenAgeBoxes();
			jQuery('#'+formID).submit(/*function(event) { event.preventDefault(); }*/);
			//event.preventDefault();
			break;
		}else{}
	}
}

function refreshSearchPanel() {
	jQuery('.searchPanel .dates .calendar .calendarChoices span.yui-skin-sam').show(); // Show search panel calendar icon for date selection - Home page
	updateChildrenAgeBoxes();
}

function updateChildrenAgeBoxes(){
	var numberOfChildBoxes = jQuery('.childAges .childOption').length; // Get number of children age selection boxes - Home page
	var activeChildBoxes = jQuery('.travellers .children #childrenDropDownId').val(); // Get number of selected children - Home page

	jQuery('.childAges .childOption select').slice(activeChildBoxes, numberOfChildBoxes).val(""); // Reset extra child age selection boxes
	//alert("break");
	jQuery('.childAges .childOption').slice(activeChildBoxes, numberOfChildBoxes).hide(); // Hide extra children age selection dropdowns
	
	/*if(activeChildBoxes == 0){
		//Reset ages if no children selected
		//alert("reset" + activeChildBoxes);
		//jQuery(".childAges .childOption #ChildAge-1").val("");
	}else{}*/
}

jQuery(document).ready(function() {
	refreshSearchPanel();
	
	
	
	jQuery('#page.bookingPage ul.extrasList li .ownInsurance .myInsuranceProvider').hide(); // Hide my own insurance input box - Extras page
	jQuery('#page.bookingPage ul.bookingFlowList .insuranceExtras .checkBoxList').hide(); // Hide insurance extras pdf checkboxes - Extras page
	jQuery('#page.travelPage .inside .sortByList #nonJSSortButton').hide(); // Hide sort button - Travel/Flight selection page
	jQuery('#page.bookingPage ul.passengerList li ul.formList li.lookUp').show(); // Show find address panel - Passenger page
	jQuery('#page.bookingPage ul.passengerList li ul.formList li#addressContainerId').hide(); // Hide manual address input boxes - Passenger page
	jQuery('#page.bookingPage .inside #content .bookingBody ul.paymentList .paymentDetails .chooseCard').hide(); // Hide ubdate buttons - Payment page

	//jQuery('#roomInformation').hide();
	//updateRoomDetails();

	jQuery('#page #content ul.searchResults li ul.imageList li a').css('display', 'none');
	jQuery('.resultsGallery, .summaryGallery').resultsGallery();
	jQuery('#page #content ul.searchResults li .bodyPanel .imageHolder').resultsGallery();
	if(jQuery('#bookingSummary').stickyfloat) jQuery('#bookingSummary').stickyfloat({duration: 500});
	
	checkInsuranceDeclaration();
});

function captureClickout(actId) {
var YWATracker = YWA.getTracker(ywaSiteId);
YWATracker.setAction(actId);
YWATracker.submit_action();

}

/*****************
*   Cluetip      *
*****************/
function updateRoomDetails(){
	jQuery('.bedBanks .load-local').cluetip({local:true, hideLocal: true, activation: 'click', cursor: 'pointer', cluetipClass: 'toolTip'});
}
/*****************/



/*****************
*   Group enquiry form children details input      *
*****************/

if ( jQuery(".enquiryform li.customerWho .children select").length > 0) {
var selected = jQuery(".enquiryform li.customerWho .children select").val();//find current value
if(selected > 0){jQuery(".enquiryform .childAgeDetails").show();}else {jQuery(".enquiryform .childAgeDetails").hide();}//hides input field on page load
jQuery(".enquiryform li.customerWho .children select").change(function() {
if (jQuery(this).val() > 0) { jQuery(".enquiryform .childAgeDetails").show();}//shows field if more than 1 child selected
else {jQuery(".enquiryform .childAgeDetails").hide();}//hides field if 0 are selected
});
} 


