var tabArray = [];

function initJS() {

    if ($('#slideshow').length) {
        theScroller = new slideshow('slideshow'); //global variable 
    };

    if ($('#membersList').length) {
        new membersList('membersList');
    };

    fixEventsCalendar();
    tabArray.push(new tabs('featurePanel'));

    $('.tabPanel, .topTabPanel').each(function() {
        var t = $(this);
        if (!t.attr('id')) t.attr('id', makeid());
        tabArray.push(new tabs(t.attr('id')));
    });

    if ($('.monthView').length) {
        new monthView();
    };

    if ($('.weekView').length) {
        new weekView();
    };

    if ($('.dayView').length) {
        new dayView();
    };

    fix2ndNav();
    fixTip();
    hideReleases();
    shrinkSitemap();
    hideModal();

    $('#searchTerm').defaultText('Search...');
    $('#txtMembersSearch').defaultText('Search');
    $('#podSearchTerm').defaultText('Search');

    new HSlider('clubSlider');
}


//$(function () {
//$(window).load(function () { 
    //new HSlider('clubSlider');
//})

function jsCalendarReformat() {
    new monthView();
    new weekView();
    new dayView();
}

function fixTip() {
    $('.tip').each(function() {
        var offset = $(this).prev().position();
        $(this).css({ left: offset.left + 20, top: offset.top - 3 });
    });
}

// fix background dots (if not private homepage)
$(function() {

    var theBg = $('#bg-dots');
    if (!$('#col0').length) {
        theBg.css("height", $(document).height());
    }

    $(window).bind('resize', function() {
        theBg.css("height", $(document).height());
    });

});
$(function() {
    $('a.help').toggle(
        function() {
            $(this).next().css('visibility', 'visible');
        },
        function() {
            $(this).next().css('visibility', 'hidden');
        });
});


function reCufon() {
    Cufon.replace('#PopUp h2', { hover: true, fontFamily: 'HelveticaNeue' });
}

;

$(function() {
    for (var i = 0, len = tabArray.length; i < len; i++)
        tabArray[i].resetContentDimensions();
});

$(function() {
    if ($('.timeOfMonth').length) {
        $('.timeOfMonth').datetimepicker({
                showOn: "button",
                buttonImage: "/images/calendar.gif",
                buttonImageOnly: true,
                dateFormat: "yy-mm-dd",
                timeFormat: "hh:mm",
                closeText: "Close"
            });
    }
});

$(window).load(function() { //start animation on page load
    if ($('#slideshow').length) {
        //theScroller.autoScroll();
        setTimeout(function() { theScroller.autoScroll(); }, 10000);
    }
});

function fix2ndNav() {
    $('.navColumn li.active span').each(function() {
        var t = $(this);
        t.css({ height: t.parent().height() - 2 });
    });
}

function hideReleases() {
    if ($('.mediaPod').length) {
        $('.mediaPod li').filter(function(index) {
            return index > 3;
        }).hide();
    }
}

;

function fixEventsCalendar() {
    if ($('.eventsCalender').length) {
        $('.eventsCalender li').height($('.eventsWrapper').height());
    }
}

;

function makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    for (var i = 0; i < 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

function printpage() {
    setTimeout('window.print()', 1000);
}


/***** CLASSES *******/

/** Month View **/

function monthView() {

    $('.lnkNoJsFallbackBtn').hide();

    var mv = this;
    mv.container = $('.monthView');
    mv.td = mv.container.find('td');
    mv.td.mouseenter(function() {
        var t = $(this);
        if (t.hasClass('active') || t.hasClass('otherMonth')) {
            return;
        } else {
            t.addClass('dayHover');
        }
    });
    mv.td.mouseleave(function() {
        var t = $(this);
        if (t.hasClass('dayHover')) {
            t.removeClass('dayHover');
        }
    });
    mv.td.click(function() {
        /* do nothing if it's otherMonth, to avoid month skip error from ticket #320 */
        var t = $(this);
        if (t.hasClass('otherMonth'))
            return;
        mv.td.removeClass('active');
        $(this).addClass('active');
        mv.td.theDate = t.find('input').val();
        window.__doPostBack('upEventDetails', mv.td.theDate);
    });
}


/** Week View **/

function weekView() {
    var wv = this;
    wv.container = $('.weekView');
    //wv.li = wv.container.find('li');
    wv.li = $('.weekView ul').not('.weekView ul ul').children('li');
    wv.li.mouseenter(function() {
        var t = $(this);
        if (t.hasClass('active')) {
            return;
        } else {
            t.addClass('dayHover');
        }
    });
    wv.li.mouseleave(function() {
        var t = $(this);
        if (t.hasClass('dayHover')) {
            t.removeClass('dayHover');
        }
    });
    wv.li.click(function() {
        var t = $(this);
        wv.li.removeClass('active');
        $(this).addClass('active');
        wv.li.theDate = t.find('input').val();
        window.__doPostBack('upEventDetails', wv.li.theDate);
    });

}


/** Day View **/

function dayView() {

    if (!$('.durations').length) {

        var dv = this;
        dv.container = $('.dayView');
        dv.eventContainer = dv.container.find('.events').css({ position: 'absolute', top: 80 });
        dv.events = dv.eventContainer.find('li').css({ position: 'absolute' });
        dv.durations = $('<ul class="durations"></ul>').insertBefore(dv.eventContainer);
        dv.timeout = [];
        dv.h = dv.container.find('.hours li').show().height();
        for (var i = 0, len = dv.events.length; i < len; i++) {
            var e = dv.events.eq(i);
            var rel = e.find('a').attr('rel').split('-');
            var t = (rel[0] * dv.h) + (dv.h / 2);
            //var h = rel[1] * dv.h;
            var endTime = rel[1];
            if (endTime == 0) endTime = 24;
            //var h = (rel[1] - rel[0]) * dv.h;
            var h = (endTime - rel[0]) * dv.h;
            var dur = $('<li class="' + e.attr('class') + '" rel="' + i + '"></li>').css({ marginTop: t, height: h });
            dv.durations.append(dur);

            e.css({
                    top: t + (h / 2) - (e.outerHeight() / 2),
                    left: (i + 1) * 23,
                    zIndex: 100,
                    opacity: 0.1
                }).attr('index', i);

            dur.mouseenter(function() {
                var index = $(this).attr('rel');
                clearTimeout(dv.timeout[index]);
                dv.events.eq(index).stop(true, true).css({ zIndex: 101 }).animate({ opacity: 1 });
            });
            dur.mouseleave(function() {
                var index = $(this).attr('rel');
                dv.events.eq(index).css({ zIndex: 100 });
                dv.timeout[index] = setTimeout(function() { dv.events.eq(index).stop(true, true).css({ zIndex: 100 }).animate({ opacity: 0.1 }); }, 2000);
            });
            e.mouseenter(function() {
                var index = $(this).attr('index');
                clearTimeout(dv.timeout[index]);
                dv.events.eq(index).stop(true, true).css({ zIndex: 101 }).animate({ opacity: 1 });
            });
            e.mouseleave(function() {
                var index = $(this).attr('index');
                dv.events.eq(index).css({ zIndex: 100 });
                dv.timeout[index] = setTimeout(function() { dv.events.eq(index).stop(true, true).css({ zIndex: 100 }).animate({ opacity: 0.1 }); }, 2000);
            });
        }


        dv.li = $('ul.events').children('li');

        dv.li.find('a').click(function(event) {
            event.preventDefault();
        });

        dv.li.click(function() {
            var t = $(this);
            dv.li.theDate = t.find('input').val();
            window.__doPostBack('upEventDetails', dv.li.theDate);
        });
    }

    function clearFilters() {
        $('.filterEvents').find('input:checkbox').each(function(o, i) {
            $(this).removeAttr('checked');
        });

    }
}

/** Members list **/

function membersList(id) {
    var ml = this;
    ml.timeout = null;
    ml.container = $('#' + id + '>dl').addClass('js');
    ml.dd = ml.container.find('dd dd').hide();
    ml.dt = ml.container.find('dd dt').append('<span></span>');

    ml.container.find('>dt').each(function() { $(this).css({ height: $(this).next().innerHeight() }); });
    ml.dd.each(function() {
        var t = $(this);
        var p = t.prev();
        t.css({ top: p.position().top + p.height() + 1, left: p.position().left });
    });

    ml.dt.click(function() {
        clearTimeout(ml.timeout);
        var t = $(this);
        if (t.hasClass('active')) {
            t.removeClass('active').next().stop(true, true).slideUp();
            return;
        }
        ml.dd.filter(':visible').stop(true, true).css({ zIndex: 9 }).slideUp().prev().removeClass('active');
        t.addClass('active').next().stop(true, true).css({ zIndex: 10 }).slideDown();
    });

    ml.dt.add(ml.dd).mouseleave(function() {
        var t = $(this);
        if (t.hasClass('active') || t.prev().hasClass('active'))
            ml.timeout = setTimeout(function() { ml.dd.filter(':visible').stop(true, true).slideUp().prev().removeClass('active'); }, 10000);
    });
    ml.dt.add(ml.dd).mouseenter(function() {
        var t = $(this);
        if (t.hasClass('active') || t.prev().hasClass('active')) clearTimeout(ml.timeout);
    });

    //ml.dd.find('li p.link a').click(function(event) {
        //event.preventDefault();
    //});

    ml.dd.find('li')
        .hover(
        function () {
            //if ($(this).find('p.link a').length) {
            //$(this).css({ 'cursor': 'pointer', 'background-color': '#f0f0f0' });
            $(this).css({ 'background-color': '#f0f0f0' });
            //}
        },
        function () { $(this).css({ 'background-color': '#fff' }); }
        //)
        );
        //.click(function() {
            //if ($(this).find('p.link a').length) {
            //    //window.location = $(this).find('p.link a').attr('href');
            //    var theURL = $(this).find('p.link a').attr('href');
            //    window.open(theURL, '_blank');
            //}
        //});
}

/** Tabs **/

function tabs(id) {
    this.container = this.tabContainer = this.tabContents = null;
    this.max = { w: 0, h: 0 };

    this.init(id);
}

tabs.prototype.init = function(id) {
    var t = this;

    t.container = $('#' + id);

    t.tabContents = t.container.find('>div');
    t.tabContainer = $('<ul class="tabs"></ul>');
    t.container.prepend(t.tabContainer);

    for (var i = 0, len = t.tabContents.length; i < len; i++) {
        var tc = t.tabContents.eq(i);
        var tabTitle = tc.find('.tab');
        var tab = $('<li class="' + tabTitle.attr('class') + '"><span><a href="#" rel="' + i + '">' + tabTitle.html() + '</a></span></li>');
        tab.find('a').click(function() {
            t.tabContainer.find('.active').removeClass('active');
            $(this).parents('.tab').addClass('active');
            t.tabContents.filter(':visible').hide();
            t.tabContents.eq($(this).attr('rel')).show();
            return false;
        });
        t.tabContainer.append(tab);
        tabTitle.remove();
        if (tc.height() > t.max.h) t.max.h = tc.height();
        if (tc.innerWidth() > t.max.w) t.max.w = tc.innerWidth();
    }

    t.tabContents.hide();
    t.tabContainer.find('li a').eq(0).trigger('click');

    t.setTabWidths();

    t.setWidths();
    t.setHeights();
};
tabs.prototype.setTabWidths = function() {
    var tabWidth = this.max.w / this.tabContents.length;
    this.tabContainer.find('li').each(function() {
        var li = $(this);
        var dif = li.outerWidth() - li.innerWidth();
        li.css({ width: tabWidth - dif });
    });
};
tabs.prototype.setWidths = function() {
    var t = this;
    this.tabContents.each(function() {
        var e = $(this);
        var dif = e.outerWidth() - e.innerWidth();
        e.css({ width: t.max.w - dif });
    });
};
tabs.prototype.setHeights = function() {
    var t = this;
    this.tabContents.each(function() {
        var e = $(this);
        var dif = e.outerHeight() - e.innerHeight();
        e.css({ height: t.max.h - dif });
    });
};
tabs.prototype.resetContentDimensions = function() {
    for (var i = 0, len = this.tabContents.length; i < len; i++) {
        var tc = this.tabContents.eq(i);
        if (tc.innerHeight() > this.max.h) this.max.h = tc.innerHeight();
        if (tc.innerWidth() > this.max.w) this.max.w = tc.innerWidth();
    }
    this.setHeights();
    this.setWidths();
};
/** SLIDESHOW **/

function slideshow(id) {
    this.slides = [];
    this.container = this.nextBtn = this.controls = null;
    this.init(id);
    //this.autoScroll();
}

slideshow.prototype.init = function(id) {
    var SS = this;

    SS.container = $('#' + id);
    SS.slides = SS.container.find('.slide');

    SS.slides.each(
        function() {
            var targetURL = $(this).find('a.btnSlideshow').attr('href');
            $(this).find('.slideshowCopy p').wrapInner('<a></a>').find('a').attr('href', targetURL);
        });
    $('<div class="next"><img src="/images/btn_slideshow_next.png" title="Next Slide" /></div>')
        .css({ opacity: 0.001 })
        .appendTo(SS.container)
        .mouseenter(function() { $(this).stop(true, true).animate({ opacity: 0.2 }, 'slow'); })
        .mouseleave(function() { $(this).stop(true, true).animate({ opacity: 0.001 }, 'slow'); })
        .click(function() { SS.showNext(); });

    SS.controls = $('<div class="controls"></div>').appendTo(SS.container);
    for (var i = 0, len = SS.slides.length; i < len; i++) {
        var activeclass = i == 0 ? 'active' : '';
        $('<a class="but ' + activeclass + '" href="#" rel="' + i + '"></a>').prependTo(SS.controls)
            .click(
            function() {
                var l = $(this);
                SS.container.find('.slideshowContainer').animate({ 'left': -960 * l.attr('rel') });
                l.parent().find('.active').removeClass('active');
                l.addClass('active');
                return false;
            }
                );

        SS.slides.eq(i).css({ left: 960 * i });
    }

    SS.controls.prepend('<span class="last"></span>');
    SS.controls.append('<span class="first"></span>');

};
slideshow.prototype.showNext = function() {
    var SS = this;
    var activeControl = SS.controls.find('.active');
    var nextControl = activeControl.prev().hasClass('but') ? activeControl.prev() : SS.controls.find('.but:[rel="0"]');
    nextControl.click();
};
slideshow.prototype.autoScroll = function() {
    var SS = this;
    var activeControl = SS.controls.find('.active');
    var nextControl = activeControl.prev().hasClass('but') ? activeControl.prev() : SS.controls.find('.but:[rel="0"]');
    SS.container.find('.slideshowContainer').animate({ 'left': -960 * nextControl.attr('rel') }, 300, 'linear', function() {
        nextControl.parent().find('.active').removeClass('active');
        nextControl.addClass('active');
        setTimeout(function() {
            SS.autoScroll();
        }, 10000);
    });

};
/* Slider Class */

function HSlider(id) {
    this.offset = this.containerWidth = this.contentWidth = this.slideContainerWidth = this.sliderWidth = this.sliderDistance = this.overflowWidth = this.ratio = this.slideRatio = 0;
    this.countryList = this.clubs = this.container = this.content = this.slide = this.slideContainer = this.slider = this.arrowLeft = this.arrowRight = this.clubHover = this.scrollInterval = null;
    this.logoWidth = 74;
    this.countries = [];

    this.init(id);
}

HSlider.prototype.init = function(id) {

    var HS = this;

    HS.container = $('#' + id).css({ overflow: 'visible' });
    HS.clubs = HS.container.find('.clubs').css({ overflow: 'hidden' });
    HS.content = HS.container.find('dl');

    HS.countryList = $('<ul class="countryList"></ul>').insertBefore(HS.clubs);
    HS.clubHover = $('<div class="clubHover"></div>').insertBefore(HS.clubs);

    HS.clubHover.mouseenter(function() { $(this).stop().show(); });
    HS.clubHover.mouseleave(function() {
        HS.content.find('dt.hover').removeClass('hover');
        $(this).hide();
    });

    HS.containerWidth = HS.container.innerWidth();
    var children = HS.container.find('dt');
    var prevCountry = '';
    for (var i = 0; i < children.length; i++) {
        var child = children.eq(i);
        //child.css({'width':HS.logoWidth, 'float':'left', 'textAlign':'center'});

        child.mouseover(function() { HS.showHover($(this)); });
        child.mouseout(function() { HS.hideHover(); });

        var country = child.attr('title');
        if (country != prevCountry) {
            var pos = HS.contentWidth + (HS.logoWidth / 2);
            HS.countries.push(
                [
                    $('<li>' + country + '</li>').appendTo(HS.countryList).css({ left: pos }),
                    pos
                ]);
            prevCountry = country;
        }

        HS.contentWidth = HS.contentWidth + child.outerWidth(true);
    }

    for (var j in HS.countries) {
        var w = HS.countries[j][0].outerWidth(true) / 2;
        HS.countries[j][1] = HS.countries[j][1] - w;
        HS.countries[j][0].css({ left: HS.countries[j][1] }).hide();
    }

    HS.content.css({ width: HS.contentWidth, position: 'relative' });

    HS.slide = $('<div class="slideSurround"></div>').appendTo(HS.container);

    HS.arrowLeft = $('<a href="#" class="arrowLeft"></a>')
        .click(function() { return false; })
        .mouseover(function() { HS.scrollInterval = setInterval(function() { HS.scroll(-1); }, 30); })
        .mouseout(function() { HS.scrollStop(); })
        .appendTo(HS.slide);
    HS.arrowRight = $('<a href="#" class="arrowRight"></a>')
        .click(function() { return false; })
        .mouseover(function() { HS.scrollInterval = setInterval(function() { HS.scroll(1); }, 30); })
        .mouseout(function() { HS.scrollStop(); })
        .appendTo(HS.slide);

    HS.slideContainer = $('<div class="slideContainer"></div>').appendTo(HS.slide);

    HS.slideContainerWidth = HS.slideContainer.innerWidth();

    HS.ratio = HS.slideContainerWidth / HS.contentWidth;
    HS.sliderWidth = Math.ceil(HS.slideContainerWidth * HS.ratio);
    if (window.console)
        //console.log(HS.containerWidth,HS.sliderWidth,HS.slideContainerWidth,HS.ratio);
        
        if (HS.sliderWidth > HS.slideContainerWidth) HS.sliderWidth = HS.slideContainerWidth;

    HS.slider = $('<div class="slider"><span class="left"></span><span class="right"></span></div>')
        .css({ width: HS.sliderWidth })
        .appendTo(HS.slideContainer)
        .draggable({
                containment: 'parent',
                axis: 'x',
                drag: function(event, ui) {
                    HS.offset = Math.ceil(ui.position.left / HS.ratio);
                    HS.content.css({ left: -HS.offset });
                    HS.countryList.css({ left: -HS.offset });
                    HS.showCountries();
                },
                stop: function(event, ui) { HS.hideCountries(); }
            });
};
HSlider.prototype.showCountries = function() {
    for (var i in this.countries) {
        if (this.countries[i][1] > this.offset - (this.logoWidth / 2) && this.countries[i][1] < this.offset + this.slideContainerWidth) {

            this.countries[i][0].stop(true, true).show();
        } else
            this.countries[i][0].hide();
    }
};
HSlider.prototype.hideCountries = function() { for (var i in this.countries) this.countries[i][0].fadeOut(2000); };
HSlider.prototype.showHover = function(dt) {
    var dd = dt.next();
    if (dt.attr("rel")) {
        $.ajax({
                url: "/Resources/Public/Handlers/clubInfo.ashx",
                async: false,
                cache: true,
                contentType: "application/json; charset=utf-8",
                data: { 'clubId': dt.attr("rel") },
                success: function(result) {
                    dd.html(result);
                    dt.removeAttr("rel");
                }
            });
    }
    this.clubHover
        .stop(true, true)
        .show()
        .fadeIn()
        .html(dd.html())
        .css({ left: -10000 });

    var hoverOffset = ((dt.position().left - this.offset) / this.slideContainerWidth) * (this.clubHover.width() - this.logoWidth);
    this.clubHover.css({ left: dt.position().left - this.offset - hoverOffset });

    dt.addClass('hover');
};
HSlider.prototype.hideHover = function(element) {
    var dt = this.content.find('dt.hover');
    this.clubHover.fadeOut(10, function() { dt.removeClass('hover'); });
};
HSlider.prototype.scroll = function(direction) {
    if ((direction > 0 && this.offset >= this.content.width() - this.container.width()) ||
        (direction < 0 && this.offset <= 0))
        return;
    this.offset = this.offset + (10 * direction);
    this.content.css({ left: -this.offset });
    this.countryList.css({ left: -this.offset });
    this.showCountries();
    this.slider.css({ left: this.offset * this.ratio });
};
HSlider.prototype.scrollStop = function() {
    clearInterval(this.scrollInterval);
    this.hideCountries();
};
/****** rankings hover functionality *******/

$(document).ready(function() {

    $('#accessList').prepend('<div class="clubHover"></div>');
    var theHover = $('#accessList').find('.clubHover');

    $("#accessList dt img").mouseenter(
        function() {
            var dt = $(this).parent();
            dt.addClass('hover');
            var dd = dt.next('dd');
            if (dt.attr("rel")) {
                $.ajax({
                        url: "/Resources/Public/Handlers/clubInfo.ashx",
                        async: false,
                        cache: true,
                        contentType: "application/json; charset=utf-8",
                        data: { 'clubId': dt.attr("rel") },
                        success: function(result) {
                            dd.html(result);
                            dt.removeAttr("rel");
                        }
                    });
            }
            var position = dt.position();
            var posX = (position.left - 65);
            var posY = (position.top - 100);

            $(theHover.stop(true, true).show().fadeIn().html(dd.html()).css({ left: posX }).css({ top: posY }));
        }
         );

    $("#accessList dt img").mouseleave(
        function() {
            $(theHover).fadeOut(10, function() { $("#accessList dt").removeClass('hover'); });
        }
            );

    $(theHover).mouseenter(function() {
        $(this).stop().show();
    });

    $(theHover).mouseleave(function() {
        $("#accessList").find('dt.hover').removeClass('hover');
        $(this).hide();
    });

});


/****** PLUGINS *******/

(function($) {

    /** jQuery defaultText plugin **/

    $.fn.defaultText = function(inText) {
        return this.each(function() {
            var self = $(this);
            var theText = inText;

            // if (self.val() == '' || self.val() == theText) self.css({ color: '#666' }).val(theText);
            // self.focus(function () { if (self.val() == theText) self.css({ color: '#666' }).val(''); });
            // self.blur(function () { if (self.val() == '' || self.val() == theText) self.css({ color: '#666' }).val(theText); });

            if (self.val() == '' || self.val() == theText) self.val(theText);
            self.focus(function() { if (self.val() == theText) self.val(''); });
            self.blur(function() { if (self.val() == '' || self.val() == theText) self.val(theText); });
        });
    };


/** jQuery centerContent (modal pop-up) plugin **/

    $.fn.centerContent = function() {
        return this.each(function() {
            var top = ($(window).height() - $(this).outerHeight()) / 2;
            var left = ($(window).width() - $(this).outerWidth()) / 2;
            $(this).css({ position: 'absolute', margin: 0, top: (top > 0 ? top : 0) + 'px', left: (left > 0 ? left : 0) + 'px' });
        });

    };
})(jQuery);

/* Modal Popup Control */

function showModal() {

    var overlayHeight = $(document).height();

    if (!$('#overlay').length) {
        //var pageID = document.getElementById('hdnPageID').value;
        //var theForm = $('<div id="overlay"></div><iframe src="/Resources/Public/Templates/EmailFriend.aspx?pageID=' + pageID + '" width="612" height="560" id="emailForm" scrolling="auto" class="frameBorder"></iframe>');
        //console.log('modal not found');
        var theForm = $('<div id="overlay"></div>');
        $('body').append(theForm);
    }

    $('#overlay').height(overlayHeight);
    $('#overlay').css('visibility', 'visible');

    if ($('#emailForm').length) {
        $('body').append($('#emailForm'));
        $('#emailForm').css('visibility', 'visible');
        //$('#emailForm').centerContent();
    }

    $('html, body').animate({ scrollTop: 0 }, 0);
}


function hideModal() {
    //console.log('hide modal triggered');
    $('#overlay').css('visibility', 'hidden');
    $('#emailForm').css('visibility', 'hidden');
}

$(document).ready(function() {

    // hide modal popup by default in css   
    //handle browser resize 
    $(window).bind('resize', function() {
        if ($('#emailForm').length) {
            $('#emailForm').centerContent();
        } else if ($('#eventForm').length) {
            $('#eventForm').centerContent();
        }
    });

    //Button events
    $('.addEvent').click(function() {
        showModal();
    });

    $('#emailFriend').click(function() {
        showModal();
    });

    $('#btnCancel').click(function() {
        hideModal();
    });

    $('#emailForm .cancel').click(function() {
        hideModal();
    });

});


/******** document table code *********/
$(document).ready(function() {

    var lastFolder = null;
    $('.documentTable tr.subLevel').hide();

    $('a.folder').click(function(event) {

        event.preventDefault();

        $('.documentTable tr.subLevel').hide();

        if ($(this).hasClass('openFolder')) {
            $(this).removeClass('openFolder').addClass('closeFolder');

            $(this).parent().parent().nextAll('tr').each(function() {
                if ($(this).hasClass('topLevel')) {
                    return false;
                } else {
                    $(this).show();
                }
            });
            $(lastFolder).removeClass('closeFolder').addClass('openFolder');
            lastFolder = this;

        } else {
            $(this).removeClass('closeFolder').addClass('openFolder');
            $(lastFolder).removeClass('closeFolder').addClass('openFolder');
            lastFolder = this;
        }

    });

});


/******** Sitemap code *********/

function shrinkSitemap() {

    if ($('#sitemap').length) {

        $('#sitemap ul ul').hide();

        $('#sitemap ul li').has('ul').each(
            function() {

                $('<img src="/images/open-map.gif" class="expand" alt="Expand" />')
                    .toggle(
                    function() {
                        $(this).attr('src', '/images/close-map.gif').attr('alt', 'Collapse').parent().find(">ul").slideDown();
                        return false;
                    },
                    function() {
                        $(this).attr('src', '/images/open-map.gif').attr('alt', 'Expand').parent().find(">ul").slideUp();
                        return false;
                    }
                        )
                    .prependTo($(this));

            }
                );

    }
}


/***** members pop-up *****/

$.fn.clubPopup = function (options) {
    var defaults = {
        width: 770,
        height: 325,
        hidden: true,
        popupContainer: $('#clubPopup'),
        overlay: $('#overlay')
    };

    var settings = $.extend(defaults, options);

    $('#btnClose').click(function () {
        settings.overlay.css('visibility', 'hidden');
        settings.popupContainer.fadeOut();
    });

    return this.each(function () {
        $(this).click(function () {
            try {
                debug('show');
                var clubId = $(this).attr('rel');
                // var clubId = href.toString().replace('#', '');

                // pull in new club details
                $('#clubDetailsFrame').attr('src', '/resources/private/templates/p12memberdetailspopup.aspx?clubId=' + clubId);

                // Show overlay at full height
                settings.overlay.height($(document).height());
                // Position popup relative to scroll position
                settings.popupContainer.css('top', parseInt($(document).scrollTop() + 50).toString() + 'px');

                settings.overlay.css('visibility', 'visible');
                settings.popupContainer.fadeIn();

                return false;
            } catch (ex) {
                debug('show failed ' + ex);
                return false;
            }
        });
    });

    function debug(msg) {
        try {
            if (window.console)
                console.log(msg);
        } catch (e) {
        }
    }
};

$(document).ready(function () {
    if ($('#membersList .clubLink a').length) {
        $('#membersList .clubLink a').clubPopup();
    }

    if ($('#members a.detailsLink').length) {
        $('#members a.detailsLink').clubPopup();
    }
});

/******** document list code *********/
$(function () {

    if ($('#documentTree').length) {
        $('#documentTree ul').hide();
        $('#documentTree ul ul').hide();
        $('#documentTree ul ul ul').hide();

        $('#documentTree a.folder').each(
            function () {

                $(this).toggle(
                    function () {
                        $(this).removeClass('openFolder').addClass('closeFolder');
                        $(this).parent().parent().children('li').show();
                        $(this).parent().parent().children('ul').show();
                        $(this).parent().parent().find('img.folderIcon:eq(0)').attr('src', '/images/icon-folder-open.png');
                        return false;
                    },
                    function () {
                        $(this).removeClass('closeFolder').addClass('openFolder').parent().parent().children('ul').hide();
                        $(this).parent().parent().find('img.folderIcon:eq(0)').attr('src', '/images/icon-folder-closed.png');
                        return false;
                    });

            });

        //click folder to open if linked from members homepage
        var hash = window.location.hash.substr(1);
        if (hash.length > 0) $('#' + hash).find('a').click();

    };

});


/******** print photo *********/

function PrintPhoto(photoUrl) {
    window.open("/printPhoto.aspx?image=" + photoUrl, "", "resizable=1,height=600,width=800");
}
