﻿jQuery.fn.extend(
{
    element: function ()
    {
        return (this.length == 1) ? this[0] : null;
    },

    exists: function ()
    {
        return this.length > 0;
    },

    checked: function (isChecked) {
        if (isChecked === true || isChecked === 'true' || isChecked === 1) {
            $(this).attr('checked', 'checked');
        }
        else if (isChecked === false || isChecked === 'false' || isChecked === 0) {
            $(this).removeAttr('checked');
        }

        return $(this).attr('checked');
    },

    id: function ()
    {
        return $(this).attr('id');
    }

});


$(document).ready(function ()
{
    var activeSection = getActiveSection();

    initMainNavigation(activeSection);

    initSideNavigation();

    initLiveChat(activeSection);

    initTabs();

    initAccordions();

    initPopups();

    initSlideshows();

    initSearchBoxText();

    initToolTips();

    initClickTracking();

    // standard formatting stuff
    $('.hidden-submit').hide();

    // toggle map disclaimers
    $('.disclaimerlink').colorbox({ inline: true, href: "#disclaimer", width: "300px" });

    // default datepicker
    $('.date').datepicker({

        showOn: "button",
        buttonImageOnly: true,
        buttonImage: "/Content/images/bullet_dates.png",
        dateFormat: 'd M yy'
    });
});


// uses the current location to determine which section is active
function getActiveSection()
{
    var sections = new Array();

    sections['PlanYourTrip'] =   { waid: 48, waIconOnline: 31368, waIconOffline: 31369, nav: 'nav-pyt' };
    sections['Avalon'] =         { waid: 50, waIconOnline: 31320, waIconOffline: 31321, nav: 'nav-ptg' };
    sections['Eastern'] =        { waid: 51, waIconOnline: 31355, waIconOffline: 31356, nav: 'nav-ptg' };
    sections['Central'] =        { waid: 52, waIconOnline: 31352, waIconOffline: 31354, nav: 'nav-ptg' };
    sections['Western'] =        { waid: 53, waIconOnline: 31372, waIconOffline: 31373, nav: 'nav-ptg' };
    sections['Labrador'] =       { waid: 54, waIconOnline: 31357, waIconOffline: 31361, nav: 'nav-ptg' };
    sections['AboutThisPlace'] = { waid:  0, waIconOnline: 31005, waIconOffline: 31383, nav: 'nav-atp' };
    sections['ThingsToDo'] =     { waid: 45, waIconOnline: 31370, waIconOffline: 31371, nav: 'nav-ttd' };
    sections['PlacesToGo'] =     { waid: 46, waIconOnline: 31366, waIconOffline: 31367, nav: 'nav-ptg' };
    sections['WhereToStay'] =    { waid: 47, waIconOnline: 31374, waIconOffline: 31375, nav: 'nav-wts' };
    sections['TheLatest'] =      { waid: 49, waIconOnline: 31364, waIconOffline: 31365, nav: 'nav-tl' };
    sections['Home'] =           { waid: 55, nav: 'nav-homeresting' };

    var loc = document.location.pathname;

    for (var p in sections)
    {
        if (loc.toLowerCase().indexOf(p.toLowerCase()) > -1) {       
            return sections[p];
        }
    }

    return sections['Home'];
}

// styles the top navigation bar and adds menu dropdown effects
function initMainNavigation(activeSection)
{
    function navFadeQueue(id, code, delay)
    {
        window['navTimer' + id] = setTimeout(code, delay);
        window['resetDefaultStyleTimer'] = setTimeout(navDefaultStyle, delay);
    }

    function navFadeCancel(id)
    {
        clearTimeout(window['navTimer' + id]);
        clearTimeout(window['resetDefaultStyleTimer']);
    }

    function navFade(subnav)
    {
        if (subnav) $(subnav).fadeOut('fast');
    }

    function navDefaultStyle() {
        $('#topnav').attr('class', activeSection.nav);
        $('#topnav>li>a').attr('class', 'section-link');
        $('#' + activeSection.nav + '>a').attr('class', 'section-link-active');
    }

    $('#topnav>li').bind('mouseenter', function ()
    {
        navFadeCancel($(this).id());

        $('#topnav').attr('class', $(this).id());
        $('#topnav>li>a').attr('class', 'section-link');
        $(this).children('a').attr('class', 'section-link-active');

        var subnav = $(this).children('.subnav').first();
        if (subnav.exists())
        {
            $(subnav).slideDown('fast');
        }
    });

    $('#topnav>li').bind('mouseleave', function ()
    {
        var subnav = $(this).children('.subnav').first();

        navFadeQueue($(this).id(), function () { navFade(subnav); }, 150);
    });

    navDefaultStyle();
}

// highlights the link for the current page in the side navigation panel
function initSideNavigation() {
    var loc = window.location.pathname;

    if (loc.indexOf("AboutThisPlace/Videos") > -1 || loc.indexOf("AboutThisPlace/Photos") > -1) {
        $('#sidenav a:contains("Multimedia")').closest('li').addClass('current');
    }
    else {

        $('#sidenav a').each(function () {
            var href = $(this).attr('href');

            if (loc.indexOf(href) > -1) {
                $(this).closest('li').addClass('current');
            }
        });
    }
}

function initLiveChat(activeSection)
{
    // click handling for the live chat
    $('.livechat').bind('click', function ()
    {
        var url =
            'http://a5.websitealive.com/447/rRouter.asp' +
            '?groupid=447' +
            '&departmentid=6490' +
            '&dl=' + encodeURIComponent(document.location.href) +
            '&websiteid=' + activeSection.waid;

        window.open(url, 'livechat', 'width=650,height=470', true);
        window._gaq.push(['_trackEvent', 'livechat', 'open' ]);
        return false;
    });

    // load background images for the live chat
    if (activeSection.waIconOnline && activeSection.waIconOffline)
    {
        $('#livechat').css('background-image', 'url(' +
            'http://a5.websitealive.com/447/Visitor/vButton_v3.asp' +
            '?groupid=447' +
            '&departmentid=6490' +
            '&w=400&h=400' +
            '&icon_online=https%3A%2F%2Fimages%2Ewebsitealive%2Ecom%2Fimages%2Fhosted%2Fupload%2F' + activeSection.waIconOnline + '%2Epng' +
            '&icon_offline=https%3A%2F%2Fimages%2Ewebsitealive%2Ecom%2Fimages%2Fhosted%2Fupload%2F' + activeSection.waIconOffline + '%2Epng' +
            ')');
    }
}

// tab handling
function initTabs()
{
    checkTab('offers');
    checkTab('itineraries');
    checkTab('routes');
    checkTab('photos');
    checkTab('videos');

    function checkTab(tabName) {
        var tabId = '#' + tabName + '-tab';
        var titleId = tabId + '-title';

        if (!$(tabId).exists() || !$(tabId).children().length>0) {
            $(titleId).remove();            
        }
    }

    $('#tabs a').live('click', function ()
    {
        if ($(this).is('.externalLink, .popupImage, .video-player, .forceNewPage'))
        {
            return true;
        }

        $(this).closest('.ui-tabs-panel').load(this.href);
        return false;
    });

    $("#tabs li a").bind('click', function () {
        $("#tabs li").removeAttr("title");
        $(this).parent("li").attr("title", "selected");
        menuSlider.init('slider', 'slide');
        window._gaq.push(['_trackEvent', 'tabclicked', $(this).children("span").text()]);
    });

    $('#tabs').tabs({
        load: function (event, ui) {
            $('a.popupImage', ui.panel).colorbox({ photo: true });
            $('a.video-player', ui.panel).colorbox(
            {
                iframe: true,
                innerWidth: 640,
                innerHeight: 390,
                onLoad: function () { $("#cboxTitle").remove(); }               
            });
        }
    });

    // slider for the tabs
    // TODO: this needs refactoring
    var menuSlider = function ()
    {
        var m, g, s, w, p;
        var e = [];
        var q = 8;
        var i = 8;
        return {
            init: function (j, k)
            {
                m = document.getElementById(j);
                if (m)
                {
                    var e = m.getElementsByTagName('li');
                    s = e[0];
                    w = s.offsetWidth;
                    p = s.offsetLeft;

                    for (var i = 0; i < e.length; i++)
                    {
                        var c = e[i];
                        if (c.title == "selected")
                        {
                            s = c;
                            w = s.offsetWidth;
                            p = s.offsetLeft;
                        }
                        c.onmouseover = function () { menuSlider.mo(this) };
                        c.onmouseout = function () { menuSlider.mo(s) };
                    }

                    g = document.getElementById(k);
                    g.style.width = w + 'px';
                    g.style.left = p + 'px';
                }
            },
            mo: function (d)
            {
                clearInterval(m.tm);
                var el = parseInt(d.offsetLeft);
                var ew = parseInt(d.offsetWidth);
                m.tm = setInterval(function () { menuSlider.mv(el, ew) }, i);
            },
            mv: function (el, ew)
            {
                var l = parseInt(g.offsetLeft);
                var w = parseInt(g.offsetWidth);
                if (l != el || w != ew)
                {
                    if (l != el) { var ld, lr, li; ld = (l > el) ? -1 : 1; lr = Math.abs(el - l); li = (lr < q) ? ld * lr : ld * q; g.style.left = (l + li) + 'px' }
                    if (w != ew) { var wd, wr, wi; wd = (w > ew) ? -1 : 1; wr = Math.abs(ew - w); wi = (wr < q) ? wd * wr : wd * q; g.style.width = (w + wi) + 'px' }
                }
                else
                {
                    clearInterval(m.tm);
                }
            }
        };
    } ();

    menuSlider.init('slider', 'slide');
}

// initializes any accordions on the page
function initAccordions()
{
    $("#accordion, #accordion1, #accordion2, #accordion3").accordion({
        collapsible: true,
        autoHeight: false,
        active: false
    });
}

// adds colorbox handling for popup images
function initPopups()
{
    $('a.popupImage').colorbox({
        photo: true,
        onComplete: function () { $("#cboxTitle").show(); }
    });

    $(".video-player").colorbox({
        iframe: true,
        innerWidth: 640,
        innerHeight: 390,        
        onComplete: function () { $("#cboxTitle").hide(); }        
    });

    $(".popupModalView").colorbox({
        iframe: true,
        scrolling: false,
        onComplete: function () { $("#cboxTitle").hide(); }
    });
    
}

// toggles the search text in and out of filter search boxes
function initSearchBoxText()
{
    // create the (nonstandard...) originalValue attribute
    // based on the value of the textbox on page load
    $('input:text.filter').each(function ()
    {
        $(this).attr('originalValue', $(this).val());
    });

    $('input:text.filter').bind('focus', function ()
    {
        toggleSearchTerm(this, true);
    });

    $('input:text.filter').bind('blur', function ()
    {
        toggleSearchTerm(this);
    });

    function toggleSearchTerm(el, active)
    {
        var orig = $(el).attr('originalValue');

        // If the user has entered something new, don't clear the
        // textbox.  If the user has not entered anything new, clear
        // the textbox.
        // If this requirement ever changes, suggest you use clear the
        // textbox only if the word 'search' is found in the value:
        // if (active && $(el).val().match(/search/i))
        if (active && (!orig || $(el).val() == orig))
        {
            $(el).val('');
        }
        else if (!$(el).val())
        {
            if (orig) $(el).val(orig);
        }
    }
}

// slideshow handler
function initSlideshows()
{
    $('.slideshow').each(function ()
    {
        if ($('.slide', this).size() > 1)
        {
            $(this).loopedCarousel({
                showPagination: false,
                items: 1
            });

            $('.next', this).bind('click', function ()
            {
                slideshowLabelActiveImage($(this).closest('.slideshow'), 1);
            });

            $('.previous', this).bind('click', function ()
            {
                slideshowLabelActiveImage($(this).closest('.slideshow'), -1);
            });

            slideshowLabelActiveImage(this, 0);
        }
        else
        {
            $('.next, .previous', this).remove();
        }
    });

    function slideshowLabelActiveImage(slideshow, offset)
    {
        var container = $('.container', slideshow).first();
        var slides = $('.slides', container).first();
        var pos = parseInt($(slides).css('left'));
        var viewport = parseInt($(container).css('width'));

        if (!isNaN(pos) && !isNaN(viewport))
        {
            var count = $('.slide', slides).size();
            var activeSlide = Math.floor((Math.abs(pos) + viewport) / viewport) + offset;
            if (activeSlide > count) activeSlide = 1;
            if (activeSlide <= 0) activeSlide = count;
            $('.totalLabel', slideshow).first().text(activeSlide + ' of ' + count);
        }
    }
}

function initToolTips()
{
    if ($('.tooltip, .regionlinks').exists())
    {
        // preload background image
        var img = new Image();
        img.src = '/Content/images/tooltipbg.png';

        // preload the images required for regional tooltips
        var regions = ['avalon', 'central', 'eastern', 'labrador', 'western', 'multiregion'];
        for (var i = 0; i < regions.length; i++)
        {
            img = new Image();
            img.src = '/Content/images/th-' + regions[i] + '.png';
        }
        img = new Image();
        img.src = '/Content/images/tooltipbg.png';

        // keep track of all the visible tooltips and when they should fade out
        var toolTipTimers = new Array();

        $('.tooltip, .regionlinks').live('mouseenter', function (ev)
        {
            // kill any other tooltip windows that may still be around
            $('.tipwin').hide();

            // if this tooltip is already visible, stop it fading out
            if ($(this).hasClass('tipwin-visible'))
            {
                var idx = parseInt($(this).attr('toolTipIdx'));
                clearTimeout(toolTipTimers[idx]);
                toolTipTimers[idx] = null;
                return;
            }

            // reserve a spot for the fadeout timer
            $(this).attr('toolTipIdx', toolTipTimers.length);

            // create the tooltip for this link, if we haven't already
            var tipwin = $('.tipwin', this);
            if (!$(tipwin).exists())
            {
                // region tooltips should display the map
                if ($(this).hasClass('regionlinks'))
                {
                    var region = '';

                    for (var i = 0; i < regions.length; i++)
                    {
                        if ($(this).hasClass(regions[i]))
                        {
                            region = regions[i];
                        }
                    }

                    if (!region) return;

                    var title = (region == 'multiregion')
                        ? 'multi-region'
                        : 'visit our regional page';

                    $(this).append(
                        '<div class="tipwin">' +
                        '<div class="tipwin-content">' +
                        '<img src="/Content/images/th-' + region + '.png" alt="" width="130" height="115" />' +
                        '<p>' + title + '</p>' +
                        '</div></div>'
                    );

                    tipwin = $('.tipwin', this);
                }
                // regular tooltips should display the link title
                else
                {
                    var title = $(this).attr('title');
                    if (!title)
                    {
                        title = $(this).text();
                    }
                    title = $.trim(title);

                    $(this).append(
                        '<div class="tipwin">' +
                        '<div class="tipwin-content">' +
                        '<h4>' + title + '</h4><p>visit this site</p>' +
                        '</div></div>'
                    );

                    tipwin = $('.tipwin', this);

                    // if the tooltip is wider than 120 pixels,
                    // see if we can make it a bit narrower by adding
                    // line breaks to any spaces in the middle of the text
                    if ($(tipwin).width() > 120)
                    {
                        var midpoint = Math.floor(title.length / 2);
                        var limit = 4;

                        if (midpoint > limit + 1)
                        {
                            var from = midpoint - limit;
                            var to = midpoint + limit;

                            var splitter = new RegExp('(.{' + from + ',' + to + '})\\s+', 'g');
                            $('h4', tipwin).html(title.replace(splitter, "$1<br />"));
                        }
                    }
                }
            }

            // determine the coordinates at which to display the tooltip
            var top = $(this).position().top - $(tipwin).height() - 7;
            var left;

            // in tabs, use the element itself to position the tooltip
            if ($(this).closest('#tabs').exists())
            {
                left = $(this).position().left + $(this).width() - 20;
            }
            // outside tabs, use the mouse event to position the tooltip
            else
            {
                left = ev.pageX - 15;

                // check to see if the link spans multiple lines
                var line = parseInt($(this).css('line-height'));
                if (ev.pageY - $(this).position().top > line)
                {
                    top += $(this).height() / 2;
                }
            }

            // ok, we're ready to show that tooltip!
            $(this).addClass('tipwin-visible');

            tipwin.css('top', top);
            tipwin.css('left', left);
            tipwin.show();
        });

        $('.tooltip, .regionlinks').live('mouseleave', function ()
        {
            // fade out the tooltip after 500 milliseconds
            var parent = this;
            var idx = parseInt($(this).attr('toolTipIdx'));
            toolTipTimers[idx] = setTimeout(fadeOut, 500);

            function fadeOut()
            {
                $('.tipwin', parent).fadeOut(function ()
                {
                    $(parent).removeClass('tipwin-visible');
                    clearTimeout(toolTipTimers[idx]);
                    toolTipTimers[idx] = null;
                });
            }
        });
    }
}

// handles clicking on links that we want to track for analytics
function initClickTracking()
{
    // click tracking
    $('a.externalLink').live('click', function ()
    {
        return trackExternalLink(this, 'tdms');
    });

    $('a.packageLink').live('click', function ()
    {
        return trackExternalLink(this, 'package');
    });

    $('a.issuuLink').live('click', function () {
        return trackExternalLink(this, 'issuu');
    });

    $('a.socialLink').live('click', function () {
        return trackExternalLink(this, 'social');
    });

    $('a.printLink').live('click', function () {
        return trackPrintLink();
    });

    function trackExternalLink(link, category)
    {
        try
        {
            var action = $(link).attr('href')
                .replace('.', '_')
                .replace('http://', '');

            window._gaq.push(['_trackEvent', category, action]);
            setTimeout('document.location = "' + href + '"', 100);
            return false;
        }
        catch (err)
        {
        }

        // if analytics event tracking fails, allow the link to work normally
        return true;
    }
    function trackPrintLink() 
    {
        try 
        {
            window._gaq.push(['_trackEvent', 'print', 'print']);
            setTimeout('window.print()',100);
            return false;
        }
        catch (err) 
        {
        }

        // if analytics event tracking fails, allow the link to work normally
        return true;
    }
}

function printDirections()
{
    window.print();
}

// set up Google Analytics
var _gaq = _gaq || [];
_gaq.push(
    ['_setAccount', 'UA-1393970-1'],
    ['_trackPageview']
);

(function () {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();


