$j(document).ready(function () {


    // Standard Button States Animation
    $j('.standardButtonAnimation').mouseover(function () {
        var imagesource = $j(this).attr('src').split(".");
        $j(this).attr('src', imagesource[0] + "_hover." + imagesource[1]);
    });

    $j('.standardButtonAnimation').mouseout(function () {
        var imagesource = $j(this).attr('src').split(".");
        imagesource[0] = imagesource[0].replace("_hover", "").replace("_down", "");
        $j(this).attr('src', imagesource[0] + "." + imagesource[1]);
    });

    $j('.standardButtonAnimation').mousedown(function () {
        var imagesource = $j(this).attr('src').split(".");
        imagesource[0] = imagesource[0].replace("_hover", "").replace("_down", "");
        $j(this).attr('src', imagesource[0] + "_down." + imagesource[1]);
    });

    $j('.standardButtonAnimation').mouseup(function () {
        var imagesource = $j(this).attr('src').split(".");
        imagesource[0] = imagesource[0].replace("_hover", "").replace("_down", "");
        $j(this).attr('src', imagesource[0] + "." + imagesource[1]);
    });


    //Find a Class
    $j('div.findaClass').click(function () {
        $j('.findaClassInner').slideToggle(300);
        $j('.findaClassInner').focus();
        pageLoad();
    });
    $j('div.findaClassClose').click(function () {
        $j('.findaClassInner').slideUp(300);
    });


    //Show Substitute Teacher hover
    $j('.substituted').live('mouseover', function () {
        $j('.subtituteTeacherHover', this).fadeIn('fast');
    });
    $j('.substituted').live('mouseout', function () {
        $j('.subtituteTeacherHover', this).fadeOut('fast');
    });

    $j('.teacherCard').css("display", "block");
    // Navigation Menus
    $j('div.navItem').mouseenter(function () {

        $j(this).addClass('activeNav');
        $j('#' + $j(this).attr('id') + 'Menu').fadeIn('fast');
        $j('#' + $j(this).attr('id') + ' .navArrowActive').show();
    });

    $j('div.navWrapper').mouseleave(function () {
        $j('div.navItem').removeClass('activeNav');
        $j('div.navItem').each(function () {
            $j('#' + $j(this).attr('id') + 'Menu').hide();
            $j('#' + $j(this).attr('id') + ' .navArrowActive').hide();
        });
    });

    $j('#classesMenu div:eq(2)').addClass('menuListArea menuListAreaRightBorder').siblings("div:not('.topMenuBorder, #allClassOfferings, .navMenuFooter')").addClass('menuListAreaLeftBorder').children("div:not('.menuListAreaItem, .navMenuFooter div')").addClass("menuListAreaHeader");
    $j('#classesMenu div:eq(3)').addClass('menuListAreaHeader');

    // Main promotion area
    $j('#promotionImage').cycle({
        fx: 'fade',
        speed: 'slow',
        //timeout: 10000,
        timeout: $j("input[id$=TimerValue]") != null ? $j("input[id$=TimerValue]").val() : 10000,
        pause: 1,
        pager: '#promoThumbContainer',
        pagerAnchorBuilder: function (idx, slide) {
            return '';
        }
    });
    $j('div.promoThumbs img').click(function () {
        var idx = parseInt($j(this).parent().attr("alt"));
        $j('#promotionImage').cycle(idx);
        $j('#promotionImage').cycle('pause');
    });

    //$j('.customSelectBox').selectbox();

});


//This function is invoked on every page load, 
// INCLUDING partial postbacks
function pageLoad() {
    // Style Adjustments
    $j('.studioPromo:first-child, .promotionsLowerContainer a:first-child, .workshopPromotions a:first-child, .teacherRow .teacherCard:first-child').css("margin-left", "0px");

    //Build custom dropdowns using Stylish Select plugin
    // http://www.prismstudio.co.uk/plugins/stylish-select/0.4/
    $j('.customSelectBox:visible').sSelect({ ddMaxHeight: '300px' }).removeClass('customSelectBox');
    $j('#content select').sSelect({ ddMaxHeight: '300px' }).removeClass('customSelectBox');


    //Fix Ajax slider bubbles
    if ($j("input[type=hidden][id$=mhsDateRange_ClientState]")[0] != null) {
        updateSliderBubbles();
    }

    //Teacher Details Layer
    $j('.teacherHoverLink').mouseenter(function (e) {
        elem = $j(this);

        if (elem.parent().hasClass('substituted')) {
            // do nothing. Don't show the teacher bio if the class is being taught by a substitute.
        } else {

            $j('#teacherDetails').stop().show();
            clearTimeout(teacherHoverTimeout);
            clearTimeout(ajaxBusyTimeout);
            var position = $j(this).position();
            startBusyTimer($j('#teacherDetails').css({ left: position.left + 60, top: position.top - 55 }));
            PageMethods.GetTeacherDetailLayer($j(this).attr("rel"), appendToTeacherBubble);
        }
    });

    $j('#teacherDetails').mouseleave(function () {
        teacherHoverTimeout = setTimeout("hideTeacherBubble()", 500);
    });

    $j('#teacherDetails').mouseenter(function () {
        clearTimeout(teacherHoverTimeout);
    });

    var teacherHoverTimeout;
    $j('.teacherHoverLink').mouseleave(function (e) {
        teacherHoverTimeout = setTimeout("hideTeacherBubble()", 500);
    });


    //ClassType Details Layer
    $j('.classTypeHoverLink').mouseenter(function (e) {
        $j('#classTypeDetails').stop().show();
        clearTimeout(classTypeHoverTimeout);
        clearTimeout(ajaxBusyTimeout);
        var position = $j(this).position();
        startBusyTimer($j('#classTypeDetails').css({ left: position.left + 60, top: position.top - 55 }));
        PageMethods.GetClassTypeDetailLayer($j(this).attr("rel"), appendToClassTypeBubble);
    });
    $j('#classTypeDetails').mouseleave(function () {
        classTypeHoverTimeout = setTimeout("hideClassTypeBubble()", 500);
    });

    $j('#classTypeDetails').mouseenter(function () {
        clearTimeout(classTypeHoverTimeout);
    });

    var classTypeHoverTimeout;
    $j('.classTypeHoverLink').mouseleave(function (e) {
        classTypeHoverTimeout = setTimeout("hideClassTypeBubble()", 500);
    });

    replaceFonts();
    Cufon.now();

}

function replaceFonts() {
    Cufon.replace('.promoBoxTitle,.navItem,.navItemLast,.studioName,.selectStudioLabel,.aboutStudioTitle,.studioHeaderTitle,.classOfferingsHeader,.classOfferingsSelectRegionLabel,.classLevelTitle,.selectRegionLabel,.switchTeacherLabel,.bioLabel,.teacherListSortByLabel,.yogashopPageTitle,.selectSortByLabel,.ysMemberHeader,.myAccountPageTitle,.featuredMemberName, .teacherTrainingHeader, .scheduleResultsHeader,.contactFormHeader,.selectionHeader', {
        fontFamily: 'Gotham'
    });
    Cufon.replace('.findaClassLocationsLabel,.menuListAreaHeader,.menuListAreaHeader>a,.menuListAreaSubHeader,.addressListingHeader, .selectStudioLabel', {
        fontFamily: 'Gotham Medium'
    });
}

function appendToTeacherBubble(ResultString) {
    clearTimeout(ajaxBusyTimeout);
    $j('#teacherDetails').empty();
    $j('#teacherDetails').append(ResultString);
}

function appendToClassTypeBubble(ResultString) {
    clearTimeout(ajaxBusyTimeout);
    $j('#classTypeDetails').empty();
    $j('#classTypeDetails').append(ResultString);
}

function hideTeacherBubble() {
    $j('#teacherDetails').hide().empty();
}

function hideClassTypeBubble() {
    $j('#classTypeDetails').hide().empty();
}

var ajaxBusyTimeout;
function startBusyTimer($target) {
    ajaxBusyTimeout = setTimeout(function () { doBusyIcon($target) }, 250);
}
function doBusyIcon($target) {
    $target.empty().append('<img alt="busy" class="ajaxBusy" border="0" src="/Assets/images/ajax-loader.gif" />');
}

function findAClassOpen() {
    $j('.findaClassInner').slideDown(300);
    pageLoad();
}













// ---------------------

//Ajax slider events

var sliderBubbleInterval


var clientStateValue;
var startMonthName;
var endMonthName;

function ajax__slider_OnDragStart(sender, args) {
    sliderBubbleInterval = setInterval("updateSliderBubbles();", 100);
}

function ajax__slider_OnDragEnd(sender, args) {
    clearInterval(sliderBubbleInterval);
}

function ajax__slider_OnDragEndTT(sender, args) {
    clearInterval(sliderBubbleInterval);
    $j(".teacherTrainingSearchButton").click();
}

function ajax__slider_OnClientValueChanged() {
    setTimeout("updateSliderBubbles()", 100);    
}

function ajax__slider_OnClientValueChangedTT() {
    setTimeout("updateSliderBubblesTT()", 100);
}


function updateSliderBubbles() {
    var $startHandle = $j("div.sliderContainer .handle_horizontal, div.sliderContainer .handle_horizontal_hover, div.sliderContainer .handle_horizontal_down").eq(0);
    var $endHandle = $j("div.sliderContainer .handle_horizontal, div.sliderContainer .handle_horizontal_hover, div.sliderContainer .handle_horizontal_down").eq(1);
    //var $monthList = $j("div.sliderContainer .clientSideMonthList option");
    clientStateValue = $j("input[type=hidden][id$=mhsDateRange_ClientState]").attr("value");
    startMonthName = $j("div.sliderContainer .clientSideMonthList option").eq(parseInt(clientStateValue.split(",")[0])).val();
    endMonthName = $j("div.sliderContainer .clientSideMonthList option").eq(parseInt(clientStateValue.split(",")[1])).val();

    $j("#startMonthArrowContainer").css("left", $startHandle.css("left")).find(".monthNoteMiddle").html(startMonthName);
    $j("#endMonthArrowContainer").css("left", $endHandle.css("left")).find(".monthNoteMiddle").html(endMonthName);

}

function updateSliderBubblesTT() {
    var $startHandle = $j("div.sliderContainer .handle_horizontal, div.sliderContainer .handle_horizontal_hover, div.sliderContainer .handle_horizontal_down").eq(0);
    var $endHandle = $j("div.sliderContainer .handle_horizontal, div.sliderContainer .handle_horizontal_hover, div.sliderContainer .handle_horizontal_down").eq(1);
    //var $monthList = $j("div.sliderContainer .clientSideMonthList option");
    clientStateValue = $j("input[type=hidden][id$=mhsDateRange_ClientState]").attr("value");
    startMonthName = $j("div.sliderContainer .clientSideMonthList option").eq(parseInt(clientStateValue.split(",")[0])).val();
    endMonthName = $j("div.sliderContainer .clientSideMonthList option").eq(parseInt(clientStateValue.split(",")[1])).val();

    $j("#startMonthArrowContainer").css("left", $startHandle.css("left")).find(".monthNoteMiddle").html(startMonthName);
    $j("#endMonthArrowContainer").css("left", $endHandle.css("left")).find(".monthNoteMiddle").html(endMonthName);

    $j(".teacherTrainingSearchButton").click();
}


// Class Schedule day filters
function deselectAllDays() {
    $j('.weekdaySelection input').attr('checked', false);
}

function selectAllDays() {
    $j('.weekdaySelection input').attr('checked', true);
}
function selectWeekdays() {
    selectAllDays();
    $j('.weekdaySelection input').eq(5).attr('checked', false);
    $j('.weekdaySelection input').eq(6).attr('checked', false);
}

function selectWeekends() {
    deselectAllDays();
    $j('.weekdaySelection input').eq(5).attr('checked', true);
    $j('.weekdaySelection input').eq(6).attr('checked', true);
}





//Sitemap behavior

jQuery.fn.quickTree = function () {
    return this.each(function () {
        var $tree = $j(this);
        var $roots = $tree.find('li');
        $tree.find('li:last-child').addClass('last');
        $tree.addClass('tree');
        $tree.find('ul').hide();
        $roots.each(function () {
            if ($j(this).children('ul').length > 0) {
                $j(this).addClass('root').prepend('<span class="expand" />');
            } else {
                $j(this).prepend('<span class="leaf" />');
            }
        });
        $j('span.expand').toggle(function () {
            $j(this).toggleClass('contract').nextAll('ul').slideDown();
        }, function () {
            $j(this).toggleClass('contract').nextAll('ul').slideUp();
        });
    });
};

