/**
*  Homepage v4 Stuff
*
*  hs - Home slideshow
*  ad - arrivals & departures
*  sop - Sense of Place
*
*  Last modified: 2011-09-30 {id}
*
*/
////////////////////////////////////////////////////////////////////////////////////

// Create global home slideshow slides, thumbs, set, previous arrow and next arrow, current slide, 
var $hsSlides, // slides ref
    $hsSlidesCopy, // html inside .text for each slide
    $hsSlidesWrap, // reference to jquery created blue background
    $hsSlideWidth, // width of one slide (including padding and margin)
    $hsThumbs, // thumbs ref
    $hsThumbWidth, // width of one thumb
    $hsSetNum, // Number of thumbs in set
    $hsPrevious, // previous arrow
    $hsNext,    // next arrow
    $hsCurrent, // current slide
    $hsInt, // interval reference
    $hsWrap; // wraparound version?

// how fast should the slides move, in seconds
var $HSSPEED = 7;

// Moves the slides one forward
function hsDoNextSlide() {
    var next = ($hsCurrent != ($hsSlides.length - 1)) ? $hsCurrent + 1 : 0;
    hsGoToSlide(next);
}

// go to designated slide
//      params:
//          i = index of slide
function hsGoToSlide(i) {
    $hsCurrent = i;
    // what left margin should this slide get then?
    var ml = parseInt('-' + (i * $hsSlideWidth), 10);
    // if wrap version
    if ($hsWrap) {
        // fade out copy in the box.
        $hsSlidesWrap.children().animate(
            { opacity: 0.001 },
            400
        );
    }
    $hsSlides.parent().animate(
            { marginLeft: ml },
            800,
            function() {
                if ($hsWrap) {
                    // replace old copy with new copy and set to fully opaque
                    $hsSlidesWrap.children().replaceWith($hsSlidesCopy[i]);
                    $hsSlidesWrap.children().css('opacity', '1');
                } else {
                    return false;
                }
            }
        );
    // update thumb position 
    hsHighlightThumb();
    // move thumb set
    // are we on the last slide?
    var last = ($hsCurrent != ($hsSlides.length - 1)) ? false : true;
    hsMoveSet();
}

// Highlight appropriate thumb
function hsHighlightThumb() {
    $hsThumbs.each(function() {
        $(this).removeClass('selected');
    });
    $($hsThumbs[$hsCurrent]).addClass('selected');
}

// Move set of thumbs
function hsMoveSet(dir) {
    // check we should be moving thumbs at all
    var move = ($hsSetNum < $hsThumbs.length) ? true : false;
    var ml = 0;
    if (move) {
        if (dir == undefined) {
            // check we're not on the penultimate slide of the last set
            var lastSet = ($hsCurrent >= ($hsThumbs.length - 2)) ? true : false;
            // check we're not on the first two slides of the first set
            var firstSet = ($hsCurrent < ($hsSetNum - 1)) ? true : false;
            ml = 0;
            if (!lastSet && !firstSet) {
                ml = -(($hsCurrent - 1) * $hsThumbWidth);
            } else if (lastSet) {
                ml = -(($hsThumbs.length - $hsSetNum) * $hsThumbWidth);
            }
        } else {
            var oldMl = parseInt($hsThumbs.parent().css('marginLeft'), 10);
            if (dir == 'next') {
                ml = oldMl - ($hsSetNum * $hsThumbWidth);
            } else if (dir == 'previous') {
                ml = oldMl + ($hsSetNum * $hsThumbWidth);
            }
            if (ml > 0) { ml = 0; }
            var w = ($hsThumbs.length - $hsSetNum) * $hsThumbWidth;
            if (Math.abs(ml) > w) { ml = parseInt('-' + w, 10); }
        }
        $hsThumbs.parent().animate(
            { marginLeft: ml },
            { queue: false, duration: 800 }
        );
        // update CSS for last thumb in set
        hsUpdateLastThumb(ml);
    }
}

// every time the set moves, the last thumb in the set needs to get class 'last'
function hsUpdateLastThumb(ml) {
    // work out how many thumbs are hidden
    var s = (ml != 0) ? Math.abs(parseInt(ml, 10) / $hsThumbWidth) : 0;
    // from that work out which thumb is the last in the shown set
    var l = (s + $hsSetNum - 1);
    $hsThumbs.each(function() {
        $(this).removeClass('last');
    });
    $($hsThumbs[l]).addClass('last');
}

function hsStopSlideShow() {
    clearInterval($hsInt);
}

// go to slide when clicking on a thumb
function hsOnThumbClicked(t) {
    hsStopSlideShow();
    // find the index of the thumb that was clicked
    var i = parseInt($(t).attr('id').replace('thumb', ''));
    // weird stuff happens if you click on thumb for the selected slide.
    // Avoid this thus.
    if ($hsCurrent != i) {
        hsGoToSlide(i);
    }
}

// Show the next set of thumbs
function hsDoNextSet() {
    hsStopSlideShow();
}

// Show the previous set of thumbs
function hsDoPreviousSet() {
    hsStopSlideShow();
}

// initialize home slideshow
$(function() {
    $hsSlides = $('#slidesContainer').find('.slides li');
    $hsThumbs = $('#homeSlideshow').find('.controls .thumbs .set li');
    // Need to calculate this when I adjust this for the wide version
    $hsPrevious = $('#homeSlideshow').find('.controls .prev');
    $hsNext = $('#homeSlideshow').find('.controls .next');
    $hsCurrent = 0;
    $hsSlideWidth = parseInt($hsSlides.width(), 10); // + parseInt($hsSlides.css('paddingLeft'),10) + parseInt($hsSlides.css('marginLeft'),10);
    $hsThumbWidth = parseInt($hsThumbs.width(), 10);
    $hsWrap = $('#homeSlideshow').parent().hasClass('wrap');
    // Calculate how many thumbs in a set. thumbs div width / width of one thumb
    $hsSetNum = Math.round($('#homeSlideshow').find('.thumbs').width() / $hsThumbWidth);
    // Set appropriate width for slides ul
    $hsSlides.parent().width($hsSlides.length * $hsSlideWidth);
    // Set appropriate width for set ul
    $hsThumbs.parent().width($hsThumbs.length * $hsThumbWidth);

    // start slideshow, but only if css is enabled
    // I know the slides are floated left, when css disabled, jquery reports none.
    if ($hsSlides.css("float") != "none") {
        // if it's the wrap around version
        if ($hsWrap) {
            // Set up DOM for transitions
            $hsSlidesCopy = new Array();
            $hsSlides.each(function(i) {
                $hsSlidesCopy[i] = $($hsSlides[i]).find('.copy .text').children();
                $($hsSlides[i]).find('.copy').remove();
            });
            // create new blue background to sit on top of all slides
            $('#slidesContainer').prepend('<div id="copy2"><div id="text2"></div></div>');
            $hsSlidesWrap = $('#text2');
            // add wrapjs class to style elements just prepended
            $('#homeSlideshow').parent().addClass('wrapjs');
            // insert copy of first slide
            $hsSlidesWrap.append($hsSlidesCopy[0]);
        }

        $hsInt = setInterval(hsDoNextSlide, ($HSSPEED * 1000));

        $hsNext.click(function(ev) {
            hsMoveSet('next');
            hsStopSlideShow();
            ev.preventDefault();
        });

        $hsPrevious.click(function(ev) {
            hsMoveSet('previous');
            hsStopSlideShow();
            ev.preventDefault();
        });

        $hsThumbs.click(function(ev) {
            hsOnThumbClicked(this);
            ev.preventDefault();
        });
    }
});

// Create global arrivals & departures li's, a's that will be clicked on and divs that need to be shown and hidden
var $adLi, $adA, $adDiv;

function adSwitchBoards(o) {
    var clicked = $adA.index(o);
    var other = (clicked == 0) ? 1 : 0;
    // switch button on states    
    $($($adLi)[clicked]).addClass('active');
    $($($adLi)[other]).removeClass('active');
    // switch flightboards shown
    $($($adDiv)[clicked]).fadeIn('slow');
    $($($adDiv)[other]).hide();
}

// Initialize Arrivals & Departures
$(function() {
    $adLi = $('#flightBoardSummary').find('.inner ul li');
    $adA = $('h2 a', $adLi);
    $adDiv = $('.flightBoardDetails', $adLi);
    $adA.click(function(ev) {
        adSwitchBoards(this);
        ev.preventDefault();
    });
});

// Create global sense of place children, clickable headings and expanding/contracting sections
var $sop, $sopA, $sopInnerDiv;

function doSopExpand(o) {
    var i = $sopA.index(o);
    var innerDiv = $($sopInnerDiv)[i];
    // If not already expanded
    if ($(innerDiv).css("display") == "none") {
        doSopShow(innerDiv)
        $sopInnerDiv.each(function(j) {
            if (j != i) {
                doSopHide(this);
            }
        });
        // if already expanded
    } else {
        doSopHide(innerDiv);
    }
}

function doSopHide(sop) {
    $(sop).slideUp();
    $(sop).parent().removeClass("active");
}

function doSopShow(sop) {
    $(sop).slideDown();
    $(sop).parent().addClass("active");

}

// Initialize Sense of Place
$(function() {
    $sop = $('#senseOfPlace').find('ul li');
    $sopA = $('#senseOfPlace').find('ul li p.heading a');
    $sopInnerDiv = $('#senseOfPlace').find('ul li div.inner');
    // bind click event if more than 1
    if ($sop.length > 1) {
        $sopA.click(function(ev) {
            doSopExpand(this);
            ev.preventDefault();
        });
    }
});


/**
*  Destination Hero Setup
*  Last modified: 2011-03-03 {pf}
*/

//  Create globals
var $heroes, $hero, $buttonsLI, $buttonsA;

function destinationsHero() {
    $buttonsLI.css('display', 'block');
    $heroes.hide();
    $hero.hide();
    $buttonsA.each(function() {
        var $this = $(this);
        if ($this.hasClass('current')) {
            $this.removeClass('current');
            window.setTimeout(function() { $this.trigger('click') }, 1750, true);
        }
    });
}
function destinationsToolbar(map) {
    $buttonsA.click(function() {
        if (!$(this).hasClass('current')) {
            var target = '#' + $(this).attr('href').split('#')[1];
            if ($('#destinationsToolbar .heroes:hidden').length > 0) {
                $('#destinationsToolbar .heroes').slideDown();
            }
            $('#destinationsHero .hero').hide();
            $(target).fadeIn('fast', function() {
                google.maps.event.trigger(map, 'resize');
            });
            $('#destinationsToolbar .buttons a').removeClass('current');
            $(this).addClass('current');
        }
        else if ($(this).hasClass('current')) {
            $('#destinationsToolbar .heroes').slideUp(function() {
                $('#destinationsToolbar .buttons a.current').removeClass('current');
            });
        }
        $('#pinWindow').fadeOut(150);
        return false;
    });
}
function destinationsMap() {
    $('#destinationsMap div.map').fadeOut(0);
    $('#destinationsMap div.default').fadeIn(0);
    $('#destinationsMap div.menu a, #destinationsMap a.region').click(function() {
        if ($(this).parent('li').hasClass('current')) {
            return false;
        }
        $('#destinationsMap div.menu li.current').removeClass('current');
        var region = $(this).attr('href');
        if ($(this).parent('li').length > 0) {
            $(this).parent('li').addClass('current');
        }
        else if ($(this).parent('#mapWorld').length > 0) {
            $('#destinationsMap div.menu a').each(function(i) {
                if ($(this).attr('href') == region) {
                    $(this).parent('li').addClass('current');
                }
            });
        }
        changeRegion(region);
        return false;
    });
}
function changeRegion(incoming) {
    var maps = '#destinationsMap div.map';
    var outgoing = visibleWithin(maps);
    $(maps).stop(true, true).fadeOut(function() {
        $('#pinWindow').fadeOut(0);
        $('#destinationsMap div.pin').fadeOut('fast');
    });
    $(incoming).fadeIn(function() {
        plotPins(incoming);
    });
}
function pinWindow(pinID) {
    var offset = $(pinID).offset();
    var title = $(pinID + ' a').attr('title');
    var url = $(pinID + ' a').attr('rel');
    var photo = $(pinID + ' img.photo').attr('src');
    var pinWindow = $('#pinWindow'); // caches ref if already created
    if ($('#pinWindow').length == 0) {
        $('body').append('<div id="pinWindow"><div class="title"></div><a href="#"><img src="" alt="" class="photo" /></a></div>');
        pinWindow = $('#pinWindow'); // caches ref after creation
        $(pinWindow).fadeOut(0);
    }
    var linkedTitle = '<a href="#">' + title.split(',')[0] + '</a>,' + title.split(',')[1];
    $('div.title', pinWindow).html(linkedTitle);
    $('a', pinWindow).attr('href', url);
    $('img.photo', pinWindow).attr('src', photo);
    $(pinWindow).stop(true, true).fadeOut(0).css({ left: offset.left, top: offset.top }).fadeIn('fast');
}
function plotPins(regionID) {
    var regionName = regionID.split('#')[1];
    var found = $(regionID).find('div.pin');
    if (found.length == 0) {
        //var jsonPath = '/json/' + regionName.toLowerCase() + '.json';
        var jsonPath = '/services/brs-airport/brs.handler.destinations.regionmapcoords.ashx?region=' + regionName.toLowerCase();
        var pins = [];
        $.getJSON(jsonPath, function(data) {
            $.each(data, function(i, pin) {
                var pinID = regionName + 'Pin' + i;
                var pinType = pin.connecting ? 'connecting' : 'direct';
                var pinImg = '<img src="/img/v4/pins/' + pinType + '.png" alt="" />';
                var pinURL = pin.url;
                $(regionID).append('<div class="pin" style="left:' + pin.x + 'px; top:' + pin.y + 'px;" id="' + pinID + '">' + pinImg + '<a href="#' + pinID + '" rel="' + pinURL + '" title="' + pin.destination + ', ' + pin.country + '" style="z-index:' + (100 + i) + '"></a><img src="' + pin.img + '" alt="" class="photo" /></div>');
            });
            $(regionID).find('div.pin').each(function() {
                var pinInPage = $(this);
                $(pinInPage).fadeOut(0, function() {
                    $(pinInPage).fadeIn(100);
                });
            });
            $(regionID).find('div.pin a').each(function() {
                $(this).click(function() {
                    // IE7 passes the *whole* relative URL as the HREF, so we need to split and recombine manually
                    var pinHREF = $(this).attr('href').split('#');
                    var pinID = '#' + pinHREF[1];
                    pinWindow(pinID);
                    return false;
                });
            });
        });
    }
    else if (found.length >= 1) {
        found.each(function() {
            $(this).fadeIn('fast');
        });
    }
}
function inspirationModal(page, title) {
    $('#inspirationModal').html(''); // strip out existing/previous gallery
    var target = page + '?' + Math.floor(Math.random() * 10001) + ' #inspirationGallery'; //random number helps prevent over-zealous caching
    $('#inspirationModal').load(target, function() {
        setupGallery('#inspirationModal #inspirationGallery');
        slideQuote($('#inspirationModal div.miniGallery div.slides div.default'));
        $('#inspirationModal p.quotation').show();
        $('#inspirationModal div.slides img').each(function() {
            var src = $(this).attr('src');
            var big = src.split('?')[0];
            $(this).attr('src', big);
        });
    });
    $('#inspirationModal').dialog({
        open: function(event, ui) {
            $('#inspirationModal').dialog({ title: 'Photos of ' + title + ':' });
        }
    });
    $('#inspirationModal').dialog('open');
}

/*  Setup destinations toolbar and heroes (inc. GMaps) */
$(function() {
    if ($('#destinationsToolbar').length > 0) {

        //  Populate globals
        $heroes = $('#destinationsToolbar .heroes');
        $hero = $('#destinationsToolbar .hero');
        $buttonsLI = $('#destinationsToolbar .buttons li');
        $buttonsA = $('#destinationsToolbar .buttons a');

        //  Setup "Inspirations" Google Map
        var myOptions = {
            zoom: 2,
            center: new google.maps.LatLng(74, -151),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            scrollwheel: false,
            streetViewControl: false
        }

        map = new google.maps.Map(document.getElementById("insMap"), myOptions);

        destinationsToolbar(map);

        $('body').append('<div id="inspirationModal"></div>');
        $('#inspirationModal').dialog({
            modal: true,
            width: 800,
            height: 528,
            autoOpen: false,
            draggable: false,
            resizable: false
        });

        var pinIconSize = new google.maps.Size(33, 33);
        var pinIconOrig = new google.maps.Point(0, 0);
        var pinIconAnch = new google.maps.Point(16, 32);
        var pinIcon = new google.maps.MarkerImage('/img/v4/pins/inspiration.png', pinIconSize, pinIconOrig, pinIconAnch);

        var pinHotSpot = { coord: [1, 0, 31, 0, 31, 24, 1, 24], type: 'poly' };

        var pinShdwSize = new google.maps.Size(53, 36);
        var pinShdwOrig = new google.maps.Point(0, 0);
        var pinShdwAnch = new google.maps.Point(7, 20);
        var pinShdw = new google.maps.MarkerImage('/img/v4/pins/inspirationshadow.png', pinShdwSize, pinShdwOrig, pinShdwAnch);

        //$.getJSON( '/json/inspiration.json', function(data) {
        $.getJSON('/services/brs-airport/brs.handler.destinations.inspirationmap.ashx', function(data) {
            $.each(data, function(i, pin) {
                var pinLatLng = new google.maps.LatLng(pin.lat, pin.lng);
                var pinMarker = new google.maps.Marker({
                    position: pinLatLng,
                    map: map,
                    icon: pinIcon,
                    shadow: pinShdw,
                    shape: pinHotSpot,
                    title: pin.destination + ', ' + pin.country
                });
                google.maps.event.addListener(pinMarker, 'click', function() {
                    inspirationModal(pin.page, $(this).attr('title'));
                });
            });
        });

        destinationsMap();

        //  Hide #pinWindow if clicking anywhere other than on the window itself
        $(document).click(function(e) {
            if ($(e.target).is('#pinWindow') || $(e.target).parent('#pinWindow').length > 0) {
                // don't hide #pinWindow and carry on as a normal click
            }
            else if ($('#pinWindow').length > 0) {
                $('#pinWindow').fadeOut('fast');
                // ...and carry on as a normal click
            }
        });

        destinationsHero();

    }
});


/**
*  "Visible within..."
*  Simple ways of testing which item in a collection is currently
*  visible, using a jQuery selector path.
*  Last modified: 2011-02-16 {pf}
*/
function visibleWithin(collection, ref) {
    var visible = false;
    $(collection, ref).each(function() {
        var slide = $(this);
        if (slide.is(':visible')) {
            visible = slide;
        }
    });
    return visible;
}


/**
*  Mini gallery slideshow
*  Last modified: 2011-02-23 {pf}
*/
function slideNumber(ref, id) {
    var target = '#' + id;
    $(ref).find('a.number-active').removeClass('number-active');
    $(ref).find('li.number a').each(function() {
        if ($(this).attr('href') == target) {
            $(this).addClass('number-active');
        }
    });
}
function slideQuote(incoming) {
    if ($(incoming).find('q').length > 0) {
        $('#inspirationModal .copy q').text($(incoming).find('q').text());
    }
}
function nextSlide(ref) {
    //  Setup and clear
    var outgoing = $('div.slide:visible', ref);
    var quotation = $('p.quotation', ref);
    $('div.slide', ref).stop(true, true).fadeOut();
    $(quotation).stop(true, true).hide();
    //  Bring in new slide
    var incoming = outgoing.next().length ? outgoing.next() : $('div.slide:first', ref);
    var id = incoming.attr('id');
    slideNumber(ref, id);
    slideQuote(incoming);
    $(incoming).fadeIn();
    $(quotation).fadeIn();
    return false;
}
function prevSlide(ref) {
    //  Setup and clear
    var outgoing = $('div.slide:visible', ref);
    var quotation = $('p.quotation', ref);
    $('div.slide', ref).stop(true, true).fadeOut();
    $(quotation).stop(true, true).hide();
    //  Bring in new slide
    var incoming = outgoing.prev().length ? outgoing.prev() : $('div.slide:last', ref);
    var id = incoming.attr('id');
    slideNumber(ref, id);
    slideQuote(incoming);
    $(incoming).fadeIn();
    $(quotation).fadeIn();
    return false;
}
function setupGallery(ref) {
    //  Slideshow numbers
    $(ref).find('div.slide').fadeOut(0);
    $(ref).find('div.default').fadeIn(0);
    $(ref).find('li.number a').click(function() {
        if ($(this).hasClass('number-active')) {
            return false;
        }
        $('a.number-active').removeClass('number-active');
        var number = $(this);
        number.addClass('number-active');
        var target = number.attr('href');
        $(ref).find('div.slide:visible').fadeOut();
        $(ref).find(target).fadeIn();
        return false;
    });
    //  Slide links
    $(ref).find('div.slide a').click(function() {
        window.location.href = $(this).attr('href');
    });
    //  Slideshow paging
    $(ref).find('li.number-prev a').click(function() {
        return prevSlide(ref);
    });
    $(ref).find('li.number-next a').click(function() {
        return nextSlide(ref);
    });
}
//  Bind on page load (if at least one mini gallery is present on the current page)
$(function() {
    var $miniGalleries = $('div.miniGallery');
    if ($miniGalleries.length > 0) {
        $miniGalleries.each(function() {
            setupGallery($(this));
        });
    }
});


/**
*	Show Language Options [jQuery]
*	Changes the link behaviour of the header's 'Languages' hyperlink so
*	that it reveals the languages sub-menu on hover.
*	Last modified: 2011-03-03 {pf}
*/
$(function() {
    $('#languagesDrop').hover(
    //	Fade in language options on 'hover over'
		function() {
		    $('#languageOptions').fadeIn(175);
		},
    //	Null 'hover out' function
		function() { }
	);
    $('#languageOptions').hover(
    //	Null 'hover over' function
		function() { },
    //	Fade out language options on 'hover out'
		function() {
		    $('#languageOptions').fadeOut(500);
		}
	);
});


/**
*  Form Field Hinting
*  Last modified: 2011-03-03 {pf}
*/
function hinting($hints) {
    $hints.each(function() {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
            $(this).addClass('hinted'); // doesn't seem to work reliably chained
        }
        $(this).focus(function() {
            if ($(this).val() == '' || $(this).val() == $(this).attr('title')) {
                $(this).val('').removeClass('hinted'); ;
            }
        });
        $(this).blur(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr('title'));
                $(this).addClass('hinted'); // doesn't seem to work reliably chained
            }
        });
    });
}
$(function() {
    var $hints = $(':input.hint');
    if ($hints.length > 0) {
        hinting($hints);
    }
});


/**
*  Destinations jQuery UI Auto Complete
*  Last modified: 2011-03-03 {pf}
*/
$(function() {
    var $destinationSearch = $('.destinationSearchAutoComplete');
    if ($destinationSearch.length > 0) {
        $destinationSearch.autocomplete({
            delay: 0,
            source: '/services/brs-airport/brs.handler.destinations.autocomplete.ashx',
            minLength: 3,
            select: function(event, ui) {
                $(event.target).val(ui.item.label);
                window.location = ui.item.value;
                return false;
            },
            focus: function(event, ui) {
                $(event.target).val(ui.item.label);
                return false;
            }
        });
    }
});


/**
*  Destinations Flight Date Picker
*  Last modified: 2011-03-03 {pf}
*/
function flightPicker($flightPickers) {
    $flightPickers.each(function() {
        $(this).datepicker({
            dateFormat: 'dd/mm/yy',
            firstDay: 1,
            minDate: 0,
            maxDate: +365
        });
    });
}
$(function() {
    var $flightPickers = $(':input.flightPicker');
    if ($flightPickers.length > 0) {
        flightPicker($flightPickers);
    }
});


/**
*  Flight Timetable Tabs
*  Last modified: 2011-03-03 {pf}
*/
function fightTimetables($flightTabs) {
    $flightTabs.each(function() {
        if (!$(this).hasClass('active')) {
            var target = $(this).attr('href');
            $(target).hide();
        }
    });
    $flightTabs.click(function() {
        $flightTabs.removeClass('active');
        $(this).addClass('active');
        $flightTabs.each(function() {
            var target = $(this).attr('href');
            if ($(this).hasClass('active')) {
                $(target).show();
            }
            else if (!$(this).hasClass('active')) {
                $(target).hide();
            }
        });
        return false;
    });
}
$(function() {
    /* var $flightTabs = $('#flightTimetables a.tab');
    if ( $flightTabs.length > 0 ) {
    fightTimetables($flightTabs);
    } */
    // Functionality removed by PF & BW to reduce page weight.
});


/**
*  Parking Hero
*  Last modified: 2011-06-20 {pf}
*/
$(function() {

    var $pSlideshow = $('#parkingSlideshow');
    var $pSlides = $('div.slides', $pSlideshow);
    $pSlides.fadeOut(0);
    $pSlides.filter(':first').fadeIn(0);
    var $pControls = $('div.controls', $pSlideshow);
    var $pThumbs = $('div.thumbs', $pSlideshow);
    var $pThumbLinks = $('a.thumb', $pThumbs);
    $pThumbLinks.filter(':first').addClass('selected');
    var $pSets = '-' + $('div.set', $pThumbs).length; /* negative to compare on division of total move */
    var $pSetWidth = 570;

    var $pPrev = $('a.prev', $pControls);
    $pPrev.click(function() {
        $pThumbs.stop(true, true);
        var current = $pThumbs.position();
        if (current.left < 0) {
            var destination = (current.left + $pSetWidth);
            $pThumbs.animate({ left: destination }, 350);
        }
        return false;
    });

    var $pNext = $('a.next', $pControls);
    $pNext.click(function() {
        $pThumbs.stop(true, true);
        var current = $pThumbs.position();
        //  Can we move another 'set' width and still have thumbs on-screen?
        if (((current.left - $pSetWidth) / $pSetWidth) > $pSets) {
            var destination = (current.left - $pSetWidth);
            $pThumbs.animate({ left: destination }, 350);
        }
        return false;
    });

    $pThumbLinks.click(function() {
        $clicked = $(this);
        $index = $pThumbLinks.index($clicked);
        if ($pSlides.eq($index).is(':hidden')) {
            $pSlides.fadeOut(350).eq($index).fadeIn(350);
        }
        $pThumbLinks.removeClass('selected');
        $clicked.addClass('selected');
        return false;
    });

});


/**
*  Parking Bump Modals
*  Last modified: 2011-06-21 {pf}
*/
$(function() {

    var $pModalBoxes = $('div.bump div.modal');
    $pModalBoxes.dialog({
        autoOpen: false,
        draggable: false,
        width: 640,
        height: 510,
        modal: true,
        resizable: false,
        open: function(event, ui) {
            $('a.youtubin', event.target).youtubin({
                swfWidth: '640',
                swfHeight: '480',
                autoplay: true
            });
        },
        close: function(event, ui) {
            $('.window').find('embed').stopVideo();
        }
    });

    var $pModalLinks = $('div.bump a.modal');
    $pModalLinks.click(function() {
        var $clicked = $(this);
        var $modal = $('#' + $clicked.attr('rel'));
        $modal.dialog('open');
        return false;
    });

});


/**
*  Parking Widget
*  Last modified: 2011-06-22 {pf}
*/
$(function() {

    //  Setup date pickers in general
    var $pDates = $('#airportParking input.datepicker');
    $pDates.datepicker({
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        minDate: 0,
        maxDate: +365
        //minDate: '+1',
        //maxDate: '+1y'
    });

});

/**
* Validate Field [jQuery]
*
* Intelligently checks a form field to make sure either a selection has
* been made or a value entered (as appropriate to the field type).
*
* Last modified: 2009-01-22 {pf}
*
*/

//  Warning to appear on form error
var reqWarnTitle = 'Sorry, there was a problem&hellip;';
var reqWarnBody = '<p>Please check the form fields highlighted below and try again.</p>';
var reqWarn = '<div class="message warning"><p class="heading">' + reqWarnTitle + '</p><div class="messageInner">' + reqWarnBody + '</div></div>';

function validateField(field) {

    //console.log( field.attr('id') + ' value is ' + field.val() );

    switch (field.attr('type')) {

        case 'select':
        case 'select-one':
            if (!field.val()) {
                return false;
            }
            break;

        case 'checkbox':
        case 'radio':
            if (field.hasClass('requiredGroup')) {
                var groupChecked = false;
                var fieldset = $(field).parents('fieldset')[0];
                $('input.requiredGroup', fieldset).each(function() {
                    if ($(this).attr('checked')) {
                        groupChecked = true;
                    }
                });
                return groupChecked;
            }
            else if (!field.attr('checked')) {
                return false;
            }
            break;

        case 'password':
            // not currently testing or comparing passwords in JS, so treated as...
        default: // text
            if (field.hasClass('validateEmail')) {
                var emailPattern = new RegExp(/^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
                if (field.val() == field.attr("title") || field.val().match(emailPattern) === null) {
                    return false;
                }
            }
            else if (field.val() == field.attr("title") || !field.val()) {
                return false;
            }

    }

    return true;

}


/**
* Check Requireds [jQuery]
*
* Alerts the user to any 'required' inputs, in the target form, which
* have not been completed.
*
* Only displays confirmation message if a callback is used otherwise
* assumes server-side functionality.
*
* Last modified: 2009-01-22 {pf}
*/
function checkRequireds(thisForm, hasCallback) {

    var validated = false;

    //  Failure counter
    var failed = 0;

    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required', thisForm).each(function() {

        var fieldValid = validateField($(this));

        if (!fieldValid) {

            failed++;

            //  Highlight error and set row class for hint reveal
            if ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') {
                $(this).parent().addClass('error');
            }
            else if (!$(this).parent().hasClass('error')) {
                $(this).wrap('<div class="error"></div>');
            }

            $(this).parents('.row').addClass('errorRow');

        }
        else {

            //  Remove error highlight (if present)
            if ($(this).parents('.errorRow')) {
                $(this).unwrap();
            }

            //$(this).parents('.errorRow').removeClass('errorRow');
            //$(this).parent().removeClass('error');

        }

    });

    if (failed > 0) {

        if ($('div.warning', thisForm).length < 1) {
            //  Requires 'reqWarn' HTML string (top of this file)
            if (($(thisForm).attr('id')) != "joinRewardsForm") {
                $(reqWarn).prependTo(thisForm).slideDown(250);
            } else {
                $(reqWarn).insertBefore($(thisForm).find(".row")).slideDown(250);
            }

        }
        else {
            $('div.warning', thisForm).slideDown(250);
        }

    }
    else if (failed == 0) {

        if (hasCallback) {
            $('div.warning:visible', thisForm).slideUp(250);
            $('div.confirmation', thisForm).slideDown(250);
            $('fieldset', thisForm).slideUp(250);
        }

        validated = true;

    }

    return validated;

}

/**
* Find Requireds [jQuery]
*
* Automatically scans the page for elements with a class of 
* formWrapper. 
*
* formWrapper is the identifier for a individual
* form inside a page as the use of the .net form warpper 
* removes the ability to add multiple forms to a page.
*
* Then adds a click event to each submit button within 
* formWrapper to validate any element marked as 'required'.
*
* By specifying a formCallback class a callback function can
* called on successful validation. 
*
* See below (where callbackFunction is the function to 
* callback):
*
*      <div class="formWrapper formCallback(callbackFunction)">
*
* Last modified: 2009-08-14 {pf}
*/

function findRequireds() {

    $('.formWrapper').each(function() {
        var thisForm = $(this);
        var $callback;
        $class = thisForm.attr('class');
        $splitClass = $class.split(' ');
        if ($splitClass.length > 1) {
            for (i = 0; i < $splitClass.length; i++) {
                if ($splitClass[i].substring(0, 12) == 'formCallback') {
                    $callback = $splitClass[i].substring(13, $splitClass[i].length - 1);
                }
            }
        }

        if ($(':input.required', thisForm)) {
            $(':submit', thisForm).click(function() {
                if (checkRequireds(thisForm, $callback != null)) {
                    if ($callback != null) {
                        callFunction($callback, [thisForm]);
                    }

                    return true;
                } else {
                    return false;
                }
            });
        }
    });

}

/**
* Call Function
*
* Takes a function name in a string format and calls the named 
* function along with any arguments passed in as an array.
*
* Last modified: 2010-02-24 {dn}
*/

function callFunction(name, arguments) {
    var fn = window[name];
    if (typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}

// Bind form validation when DOM ready [uses jQuery]
$(function() {
    if ($(':input.required').length > 0) {
        findRequireds();
    }
});

