Tui.MediaPanel.panelWidth = 410;
Tui.MediaPanel.panelHeight = 307;

/******************Gallerriffic specific to thomson***************************************/

jQuery(document).ready(function() {
	// We only want these styles applied when javascript is enabled
	jQuery('div.navigation').css({'width' : '300px', 'float' : 'left'});
	jQuery('div.content').css('display', 'block');

	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	if(jQuery.fn.opacityrollover) {
		jQuery('#thumbs ul.thumbs li').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'fast',
			exemptionSelector: '.selected'
		});
	}
	
	// Initialize Advanced Galleriffic Gallery
	if(jQuery.fn.galleriffic) {
		var gallery = jQuery('#thumbs').galleriffic({
			delay:                     4500,
			numThumbs:                 7,
			preloadAhead:              10,
			enableTopPager:            true,
			enableBottomPager:         false,
			maxPagesToShow:            100,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          false,
			renderNavControls:         false,
			playLinkText:              'Play slideshow',
			pauseLinkText:             'Pause slideshow',
			prevLinkText:              'Previous',
			nextLinkText:              'Next',
			nextPageLinkText:          'Next',
			prevPageLinkText:          'Prev',
			enableHistory:             false,
			autoStart:                 false,
			syncTransitions:           true,
			defaultTransitionDuration: 1000,
			enableKeyboardNavigation:  false,
			onSlideChange:             function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of jQuery('#thumbs')
				this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
			}
			
		});
		setTimeout(function() {gallery.gotoIndex(0,false,true);}, 1000); // Hack for IE8. Main image not displaying on Live.
	}
});

jQuery(window).load(function() {
    if(jQuery.fn.resizeThumbs) {
        jQuery('#page #content ul.searchResults li .bodyPanel .image .insideImage img').resizeThumbs(225, 167); // EndecaSearchResultsPage
		jQuery('#page.homePage #recentlyViewed div.image img').resizeThumbs(130, 97); // RecentlyViewedAccommodationsPanel
		jQuery('#page.searchResults #recentlyViewed div.image img').resizeThumbs(46, 34); // RecentlyViewedAccommodationsPanel
		jQuery('#page ul.whosGoingList li.youSelected .image .insideImage img').resizeThumbs(235, 176); // DealsSearchPage
		jQuery('#page #content .mediaPanelHolder .insideMediaPanel ul.mediaPanelContent li.photo .detailsArea .galleryContent img').resizeThumbs(410, 307); // PhotoMediaPanel
		jQuery('.mediaPanelHolder .slideshow img.singleImage').resizeThumbs(410, 403); // PhotoMediaPanel_mootools
		jQuery('#bookingSummary ul.customisingList li.accommodation li.image .insideImage img').resizeThumbs(171, 126); // Booking summary
		jQuery('#page.bookingPage .inside #content .bookingBody ul.confirmationList li.yourAccommodation .image .insideImage img').resizeThumbs(363, 272); // Confirmation page
		jQuery('#content div.locationImageHolder div.locationImage img').resizeThumbs(171, 126); // CountryListPanel
		jQuery('#contentNavigation div.insideContentNavigation div.image img').resizeThumbs(120, 90); // CountryPanel
		jQuery('#content ul.destinationPageList  div.locationImage img').resizeThumbs(171, 126); // ResortListPanel
    }
});

function Slideshow()
{
    // Temporary stub to stop Slideshow error on accommodation page
}

Tui.Countdown = {
    /**
     * Create is called to create a countdown timer. Currently it only allows a single instance to
     * be created and stored as Tui.Countdown.Timer
     * @param   element     The target element to be turned into a countdown timer
     * @param   options     Either a string containing a date or an object literal containing a date and other options
     */
    Create: function(options) {
        var defaultOptions = {
            target: '.countdown',
            endDate: null,
            message: 'Sale ends in',
            days: true,
            hours: true,
            minutes: true,
            seconds: true
        }
        // Set up options and check for date entered as string
        if (typeof options === 'string') {
            var date = options,
                options = defaultOptions;
            options.endDate = date;
        }
        else {
            var options = jQuery.extend(defaultOptions, options);
        }

        // Create elements for countdown timer, including the elements to
        // contain the digits which will be updated by the timer.
        var container = jQuery(options.target).eq(0),
            timerDiv = jQuery('<div>').addClass('countdownContainer'),
            endDate = new Date(options.endDate),
            finalCountdownDate = options.finalCountdownDate ? new Date(options.finalCountdownDate) : null,
            days = jQuery('<span>').addClass('timerDigits'),
            hours = jQuery('<span>').addClass('timerDigits'),
            minutes = jQuery('<span>').addClass('timerDigits'),
            seconds = jQuery('<span>').addClass('timerDigits'),
            interval = null;

        // Check date is valid
        if(isNaN(endDate.valueOf())) {
            return;
        }

        /**
         * constructTimer creates most of the HTML elements required and inserts them into the DOM
         */
        function constructTimer() {
            var msgDiv = jQuery('<span>').addClass('countdownMessage').text(options.message),
                daysContainer = jQuery('<div>').addClass('timerElement'),
                hoursContainer = jQuery('<div>').addClass('timerElement'),
                minutesContainer = jQuery('<div>').addClass('timerElement'),
                secondsContainer = jQuery('<div>').addClass('timerElement');
            if(options.days) {
                daysContainer.append(days).append(jQuery('<span>').addClass('timerHeading').text('days'));
                timerDiv.append(daysContainer);
            }
            if(options.hours) {
                hoursContainer.append(hours).append(jQuery('<span>').addClass('timerHeading').text('hours'));
                timerDiv.append(hoursContainer);
            }
            if(options.minutes) {
                minutesContainer.append(minutes).append(jQuery('<span>').addClass('timerHeading').text('minutes'));
                timerDiv.append(minutesContainer);
            }
            if(options.seconds) {
                secondsContainer.append(seconds).append(jQuery('<span>').addClass('timerHeading').text('seconds'));
                timerDiv.append(secondsContainer);
            }
            // container.width(95 + 50 *(options.days + options.hours + options.minutes + options.seconds));
            container.empty().append(timerDiv).append(msgDiv);
            //container.width(container.width()); // Hack to persuade IE6 to display timer on some pages
        }

        /**
         * Calculates the time remaining and updates the countdown
         */
        function updateTimer() {
            var d,
                h,
                m,
                s,
                difference;
            today = new Date();
            difference = endDate - today;
            if(difference < 0) {
                clearInterval(Tui.Countdown.Interval);
                displayExpiredMessage();
                return;
            }
            d = Math.floor(difference/1000/60/60/24, 10);
            d = padLeftDigit(d);
            difference = difference - d * 24 * 60 * 60 * 1000;
            h = Math.floor(difference/1000/60/60, 10);
            h = padLeftDigit(h);
            difference = difference - h * 60 * 60 * 1000;
            m = Math.floor(difference/1000/60, 10);
            m = padLeftDigit(m);
            difference = difference - m * 60 * 1000;
            s = Math.floor(difference/1000, 10);
            s = padLeftDigit(s);
            days.text(d);
            hours.text(h);
            minutes.text(m);
            seconds.text(s);
            if(finalCountdownDate && finalCountdownDate <= today) {
                timerDiv.addClass('finalCountdown');
            }
            else {
                timerDiv.removeClass('finalCountdown');
            }
        }

        // Displays the message when the countdown finishes.
        function displayExpiredMessage() {
            container.empty();
            var expiredMessage = 'Ended at ' + getTimeString(endDate) + ' on ' + getDateString(endDate);
            options.expiredMessage = options.expiredMessage || expiredMessage;
            container.append(jQuery('<span>').addClass('expiredMessage').text(options.expiredMessage));
        }

        // Makes sure that the countdown digits are always 2 digits, even if less than 10
        function padLeftDigit(number) {
            if(number < 10) {
                number = '0' + number;
            }
            return number;
        }

        // Extracts the time in the format hh:mm from a date object
        function getTimeString(date) {
            return padLeftDigit(date.getHours()) + ':' + padLeftDigit(date.getMinutes());
        }

        // Extracts the date in the format dd/mm/yyyy from a date object
        function getDateString(date) {
            return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
        }

        // clearInterval(Tui.Countdown.Interval);
        constructTimer();
        Tui.Countdown.Interval = setInterval(function() {
            updateTimer();
        }, 100);


        Tui.Countdown.Timer = {
            stop: function() {
                clearInterval(Tui.Countdown.Interval);
            },
            start: function() {
                Tui.Countdown.Interval = setInterval(function() {
                    updateTimer();
                }, 400);
            },
            setDate: function(newDate) {
                endDate = new Date(newDate);
            },
            setFinalCountdownDate: function(finalDate)
            {
                finalCountdownDate = new Date(finalDate);
                if(isNaN(finalCountdownDate.valueOf())) {
                    finalCountdownDate = null;
                }
            },
            end: function() {
                clearInterval(Tui.Countdown.Interval);
                displayExpiredMessage();
            }
        }
    }
}
