    var session_dirty = false;

    function smuggs_alert(msg, section) {
        if ( section == 2 ) {
            $('#smuggs_alert_area').css('top',0);
        } else if ( section == 3 ) {
            $('#smuggs_alert_area').css('top',700);
        } else {
            $('#smuggs_alert_area').css('top',470);
        }
        // alert(msg);
        $('#smuggs_alert_area').html(msg + '<a class="close">X</a>').show();
    }

    //  _____       ___   _       _____   __   _   _____       ___   _____   
    // /  ___|     /   | | |     | ____| |  \ | | |  _  \     /   | |  _  \  
    // | |        / /| | | |     | |__   |   \| | | | | |    / /| | | |_| |  
    // | |       / / | | | |     |  __|  | |\   | | | | |   / / | | |  _  /  
    // | |___   / /  | | | |___  | |___  | | \  | | |_| |  / /  | | | | \ \  
    // \_____| /_/   |_| |_____| |_____| |_|  \_| |_____/ /_/   |_| |_|  \_\ 
    //

    // ============================ //
    //    UTILITY DATE FUNCTIONS    //
    // ============================ //
    function calendarDayID(year, month, day) {
        return 'DAY_' + year + '_' + month + '_' + day;
    }
    
    function calendarDate(year, month, day) {
        if ( month < 10 ) month = '0' + month + '';
        if ( day < 10 ) day = '0' + day + '';
        return '' + year + '-' + month + '-' + day;
    }
    function julianDate(year, month, day) {
        // returns #days since Jan 1, 1970
        var date = new Date(year, month, day);
        var days = Math.floor(date.getTime() / 86400000);
        return days;
    }
    function julianDateFromString(dateString) {
        // returns #days since Jan 1, 1970
        var date = new Date(dateString);
        var days = Math.floor(date.getTime() / 86400000);
        if ( days < 0 ) days += 36525; // fix for dates with 2 digit year
        return days;
    }
    function addDaysToDate(year, month, day, offset) {
        // returns #days since Jan 1, 1970
        // alert(year+ '-' +month+ '-' +day+ '+' +offset);
        var Dte = new Date(year, month, day);
        var newDte = new Date(Dte.getTime() + (offset * 86400000));
        var Y = newDte.getFullYear();
        var M = newDte.getMonth();
        var D = newDte.getDate();
        return calendarDate(Y, M, D);
    }

    function ymd2julian(y, m, d) {
        m--;  // months are 0 indexed
        var date = new Date(y, m, d);
        var jsNow = Math.floor(date.getTime() / 1000 / (24 * 3600));
        return jsNow;
    }
    function julian2date(julian) {
        var date = new Date(julian * 1000 * 24 * 3600 + 12*3600*1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1; // months are ZERO indexed here
        var d = date.getDate();
        if ( m < 10 ) m = '0' + m;
        if ( d < 10 ) d = '0' + d;
        var dStr = y + '-' + m + '-' + d;
        return dStr;
    }
        
    function julian2nice(julian) {
        var date = new Date(julian * 1000 * 24 * 3600 + 12*3600*1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1; // months are ZERO indexed here
        var d = date.getDate();
        if ( m < 10 ) m = '0' + m;
        if ( d < 10 ) d = '0' + d;
        var dStr = m + '/' + d + '/' + y;
        return dStr;
    }
        
    // get the value of the month of the left most calendar from #CAL_0.firstDay
    var current_year = 0;
    var current_month = 0;
    
    $(document).ready(function(event){    
        var firstDay = $('#CAL_0').attr('firstDay');
        var today = new Date( julian2nice(firstDay) );
        current_year  = today.getFullYear();
        current_month = today.getMonth()+1; // damn thing is 0 indexed
    });
    
    // ======================= //
    //                         //
    //       CHECK_MONTH       //
    //                         //
    // ======================= //
    var calendarIsScrolling = false;
    var calendarScrollExempt = false;
    function checkMonth() {
        var correct_start    = $('#selection-start').val();
        var $correct_julian  = julianDateFromString(correct_start);
        var $correct_element = $('#C'+$correct_julian);

        var correct_end          = $('#selection-end').val();
        var $correct_end_julian  = julianDateFromString(correct_end);
        var $correct_end_element = $('#C'+$correct_end_julian);
    
        // alert('Checking: ' + correct_start +'-'+ correct_end);
    
        if ( $correct_element.length && $correct_end_element.length ) {
            if ( !calendarScrollExempt ) {
                // this date is showing
                if ( $correct_element.attr('avail') != '' ) {
                    //alert('scroll end');
                    selection_start_julian  = $correct_julian; 
                    selection_start_nice    = julian2nice(selection_start_julian);
                    selection_start         = julian2date(selection_start_julian);
                    var temp_days = selection_end_julian - selection_start_julian;
                    if ( calendarIsScrolling || temp_days > MAX_STAY ) {
                        // set the end to the same day
                        selection_end_julian  = $correct_julian+1; 
                        selection_end_nice    = julian2nice(selection_end_julian);
                        selection_end         = julian2date(selection_end_julian);
                        selection_nights      = 1;
                    }
                    $('#selection-start').val(selection_start_nice);
                    $('#selection-end').val(selection_end_nice);
                    $('#selection-nights').val(selection_nights);
                } else {
                    $('#selection-start').val(selection_start_nice);
                }
                session_dirty = true;
                saveToSession('checkMonth');
            }
            
            // highlightDates();

            resetCalendarLabel();        
            highlightDates();
            showLodging();
            refreshPricingDivs();
            calendarScrollExempt = false;
        } else {
            // this date is NOT showing
            if ( $correct_julian < $('#CAL_0').attr('firstday') ) {
                calendarIsScrolling = true;
                prevMonth(checkMonth); 
            }
            if ( $correct_julian >= $('#CAL_0').attr('lastday') || $correct_end_julian >= $('#CAL_0').attr('lastday') ) {
                calendarIsScrolling = true;
                nextMonth(checkMonth); 
            }
        }
    }
    
    var next_month_button = 'active';
    // ====================== //
    //       NEXT_MONTH       //
    // ====================== //
    function nextMonth(callback) {
        if ( next_month_button == 'dead' ) return false;
        
        next_month_button = 'dead';
        
        resetDateHighlighting();
        // calculate the next month for the left position
        current_month++;
        if ( current_month > 12 ) {
            current_month = current_month - 12;
            current_year++;
        }
        
        // calculate the next month for the right position
        last_year = current_year;
        last_month = current_month + 3;
        if ( last_month > 12 ) {
            last_month = last_month - 12;
            last_year++;
        }
        
        // move calendars to the left
        $('#CAL_0').html($('#CAL_1').html());
        $('#CAL_1').html($('#CAL_2').html());
        $('#CAL_2').html($('#CAL_3').html());
        $('#CAL_3').html('');
        
        // move calendar properties to the left
        $('#CAL_0').attr('firstDay', $('#CAL_1').attr('firstDay'));
        $('#CAL_1').attr('firstDay', $('#CAL_2').attr('firstDay'));
        $('#CAL_2').attr('firstDay', $('#CAL_3').attr('firstDay'));

        $('#CAL_0').attr('lastDay', $('#CAL_1').attr('lastDay'));
        $('#CAL_1').attr('lastDay', $('#CAL_2').attr('lastDay'));
        $('#CAL_2').attr('lastDay', $('#CAL_3').attr('lastDay'));
        
        $('#CAL_3').attr('firstDay', ymd2julian(last_year, last_month, 1) );
        $('#CAL_3').attr('lastDay',  ymd2julian(last_year, last_month+1, 0) );
        
        // x_getCalendarHTML(last_month, last_year, nextMonth_cb);
        
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=getCalendarHTML",
            data: 'month=' + last_month + '&year=' + last_year,
            success: function(msg){
                $('#CAL_3').html(msg);
                next_month_button = 'active';
                highlightDates();
                if(callback != undefined){ callback(); }
            }
        });

    }
    
    var previous_month_button = 'active';
    // ====================== //
    //       PREV_MONTH       //
    // ====================== //
    function prevMonth(callback) {
        if ( previous_month_button == 'dead' ) return false;
        
        previous_month_button = 'dead';
        
        resetDateHighlighting();
        // calculate the prev month for the left position
        current_month--;
        if ( current_month <1 ) {
            current_month = current_month + 12;
            current_year--;
        }
        
        // move calendars to the left
        $('#CAL_3').html($('#CAL_2').html());
        $('#CAL_2').html($('#CAL_1').html());
        $('#CAL_1').html($('#CAL_0').html());
        $('#CAL_0').html('');
        
        // move calendar properties to the left
        $('#CAL_3').attr('firstDay', $('#CAL_2').attr('firstDay'));
        $('#CAL_2').attr('firstDay', $('#CAL_1').attr('firstDay'));
        $('#CAL_1').attr('firstDay', $('#CAL_0').attr('firstDay'));

        $('#CAL_3').attr('lastDay', $('#CAL_2').attr('lastDay'));
        $('#CAL_2').attr('lastDay', $('#CAL_1').attr('lastDay'));
        $('#CAL_1').attr('lastDay', $('#CAL_0').attr('lastDay'));

        $('#CAL_0').attr('firstDay', ymd2julian(current_year, current_month, 1) );
        $('#CAL_0').attr('lastDay',  ymd2julian(current_year, current_month+1, 0) );
        
        // x_getCalendarHTML(current_month, current_year, prevMonth_cb);

        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=getCalendarHTML",
            data: 'month=' + current_month + '&year=' + current_year,
            success: function(msg){
                $('#CAL_0').html(msg);
                previous_month_button = 'active';
                highlightDates();
                
                if(callback != undefined){ callback(); }
            }
        });
    }
    
        
    // ================================ //
    //       UPDATE_CALENDAR_ENDS       //
    // ================================ //
    function updateCalendarEnds() {
        // if ( console ) console.log("updateCalendarEnds :: showLodging");
        showLodging();
    }
    
    var selection_click         = 'first';
    var calendar_first_day      = '<?= $firstCalendarDay ?>';
    var calendar_last_day       = '<?= $lastCalendarDay ?>';
    
    var selection_start_julian  = ''; // Y-m-d
    var selection_start_nice    = ''; // m/d/Y
    var selection_start         = ''; // always maintain this - when above changes, change this
    
    var selection_end_julian    = ''; // Y-m-d
    var selection_end_nice      = ''; // m/d/Y
    var selection_end           = ''; // always maintain this - when above changes, change this
    
    var MAX_STAY                = 10; // don't allow a selection longer than this
    
    var selection_availability  = ''; // track the total availability for the selection
    var selection_season        = ''; // summer, winter, or fall
    
    function resetCalendar() {
        resetDateHighlighting();
        selection_click         = 'first';
        
        selection_start_julian  = '';
        selection_start_nice    = '';
        selection_start         = '';
        
        selection_end_julian    = '';
        selection_end_nice      = '';
        selection_end           = '';
        
        selection_availability  = '';
        recalcRoomPricing();
        session_dirty = true;
        saveToSession('resetCalendar');
        resetCalendarLabel();

        $('#selection-start').val('');
        $('#selection-end').val('');

        $('#vacation-total').html('');
        $('#vacation-tax').html('');
        $('#vacation-deposit').html('');
        $('#vacation-promo').html('');
        $('#vacation-grand-total').html('');
    }
    
    // ======================= //
    //       SELECT_DATE       //
    // ======================= //
    function selectDate(julian) {
        var availStr = $('#C'+julian).attr('avail');

        $resoPhone = '';
        if ( $('#promo_0').length ) $resoPhone = $('#promo_0').attr('resoPhone');
        if ( $resoPhone == '' ) $resoPhone = '1-800-419-4615';
        //if ( $alert_section == '' ) { var $alert_section = 1; }

        // check and see if it's a valid day
        if ( availStr == '' || availStr == '000000000' ) {

            $('#reso_phone_display').html($resoPhone);
            $('#lodging_error_phone').html($resoPhone);
            $('#lodging_info_phone').html($resoPhone);
            
            smuggs_alert("<em>The specific date you selected is currently not available online.<br><br>Please try another date,<br>or call </em><b>" + $resoPhone + "</b><em> for more information.</em>", $alert_section);
        } else {
            // remove any existing highlighting, if any
            resetDateHighlighting();
            $('#C'+julian).addClass('selected');
            session_dirty = true;
            if ( selection_click == 'first' ) {
                // first click
                selection_start_julian  = julian; 
                selection_end_julian    = julian; 
    
                var rate = $('#C'+julian).attr('rate');
                setSeason( $('#RATE_'+rate).attr('season') );
                selection_click = 'last';
            } else {
                // second click
                if ( julian < selection_start_julian ) {
                    selection_end_julian    = selection_start_julian; 
                    selection_start_julian  = julian; 
                } else {
                    selection_end_julian    = julian; 
                }
                selection_click = 'first';
                
                // check for too long vacation
                if ( selection_end_julian - selection_start_julian > MAX_STAY ) {
                    selection_start_julian = selection_end_julian;
                    selection_click = 'last';
                }
                
            }
        
            // check for crossing seasons
            var rate_start = $('#C'+selection_start_julian).attr('rate');
            setSeason( $('#RATE_'+rate_start).attr('season') );
            
            var rate_end = $('#C'+selection_end_julian).attr('rate');
            var season_end = $('#RATE_'+rate_end).attr('season');
            
            // alert(rate_start + ' - ' + season_end);
            
            if ( selection_season != season_end ) {
                selection_start_julian = julian; 
                selection_end_julian   = julian; 
                var rate = $('#C'+julian).attr('rate');
                setSeason( $('#RATE_'+rate).attr('season') );
                alert('If you want to book a vacation across seasons, Please call us at 800-419-4615');
            }
            
            // check for sold-out dates in the selected range
            var rangeOK = true;
            for(i=selection_start_julian; i<selection_end_julian; i++) { // was <=
                var avail = $('#C'+i).attr('avail');
                // alert('#C'+i + ': ' + avail);
                if ( avail.indexOf('1') == -1 ) {
                    // this day is not available
                    rangeOK = false;
                }
            }
            if ( rangeOK == false ) {
                smuggs_alert("<em>The dates you selected include dates currently not available online.<br><br>Please try other dates,<br>or call </em><b>" + $resoPhone + "</b><em> for more information.</em>", $alert_section);
                selection_start_julian = julian; 
                selection_end_julian   = julian; 
            }
            
            selection_nights = selection_end_julian - selection_start_julian;
            
            // reset the date strings from the julian
            selection_start_nice   = julian2nice(selection_start_julian);
            selection_start        = julian2date(selection_start_julian);
    
            selection_end_nice     = julian2nice(selection_end_julian);
            selection_end          = julian2date(selection_end_julian);
    
            // now, add the highlighting
            saveToSession('selectDate');
            $('#C'+julian).removeClass('selected');
            
            // show dates in suitcase
            var display_date_str = '<sup>' + selection_start_nice +'</sup> - <sup>'+ selection_end_nice + '</sup>';
            $('#suitcase_pricing div span cite[details=dates]').html(display_date_str);
            
            // if ( console ) console.log("selectDate :: showLodging");
            resetCalendarLabel();        
            highlightDates();
            showLodging();
            refreshPricingDivs();
        }
    }
    
    function resetCalendarLabel() {
        if(selection_start_nice != ''){
            $('#vacation_calendar h2').html('Your Vacation Dates: <b>' + selection_start_nice +' - '+ selection_end_nice +'</b><a onclick="resetCalendar(); return false;" href="#">refine your search</a>');
        } else {
            $('#vacation_calendar h2').html('Select your vacation dates<a onclick="resetCalendar(); return false;" href="#">refine your search</a>');
        }
        
        var occupancy = parseInt(selection_adults) + parseInt(selection_children) + parseInt(selection_infants);
        if ( occupancy > 0 ) {
            $('#vacation_guests h2').html(occupancy + ' guests');        
        } else {
            $('#vacation_guests h2').html('# guests');        
        }
    }
    
    function refreshPricingDivs() {
        // update the room rate data
        dataStr = 'selection_start=' + selection_start;
        dataStr += '&selection_end=' + selection_end;
        dataStr += '&selection_nights=' + selection_nights;
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=getPricingDivs",
            data: dataStr,
            success: function(msg){
                $('#rate_data_area').html(msg);
                recalcRoomPricing();
                selectRoom(selected_room);

                // show dates in suitcase
                var display_date_str = '<sup>' + selection_start_nice +'</sup> - <sup>'+ selection_end_nice + '</sup>';
                $('#suitcase_pricing div span cite[details=dates]').html(display_date_str);

                // show guests in suitcase
                var display_guest_str = '<sup>' + selection_adults +' adults</sup>';
                if ( selection_children > 0 ) display_guest_str += ', <sup>' + selection_children + ' kid(s) <i>3-17 yrs</i></sup>';
                if ( selection_infants > 0 ) display_guest_str += ',<br/> <sup>' + selection_infants + ' kid(s) <i>0-2 yrs</i></sup>';
                $('#suitcase_pricing div span cite[details=guests]').html(display_guest_str);
            }
        });
    }
    
    // =========================== //
    //       UPDATE_CALENDAR       //
    // =========================== //
    function updateCalendar() {
    
        return false; // don't do this anymore...
    
        // // Update the calendar to remove links from any day where needed sizes are not available
        // if ( occupancy == 0 ) return false;
        // 
        // var startDate = $('#CAL_0').attr('firstDay');
        // var endDate   = $('#CAL_3').attr('lastDay');
        // var date      = '';
        // var link      = '';
        // var debug     = '';
        // var ok        = true;
        // var lastOK    = true;
        // 
        // // alert(startDate + ' - ' + endDate);
        // for(var i=startDate; i<=endDate; i++){
        //     avail = $('#C'+i).attr('avail');
        //     date  = $('#C'+i).attr('date');
        //     if ( avail != '' ) {
        //         ok = false;
        //         // alert(avail);
        //         for (var j=0; j<=8; j++) {
        //             // if ( console ) console.log("updateCalendar :: showLodging");
        //             if ( lodgingOptionOK(j, avail) ) ok = true;
        //         }
        //         
        //         if ( date == 1 ) debug += "<br>\n";
        //         if ( ok ) {
        //             link = "<a href='javascript:selectDate(" + i + ");'>" + date + "</a>";
        //             // debug += '<b>' + date + '</b>, ';
        //         } else {
        //             // debug += '<strike>' + date + ':' + avail + '(' + lastOK + ')</strike>, ';
        //             link = date;
        //         }
        //         // alert(i + ': ' + date);
        //         $('#C'+i).html(link);
        //     }
        // }
        // // $('#debug-area').html('<pre>' + debug + '</pre>');
    }

    function resetDateHighlighting() {
        if ( selection_start_julian != '' ) {
            for(var i=selection_start_julian; i<=selection_end_julian; i++) {
                if ( $('#C'+i).length ) $('#C'+i).removeClass('selected');
            }
        }
    }
    
    
    var selection_nights = 0;
    
    
    function coerce_dates(event){
        var $d          = new Date();
        var $today      = julianDate($d.getFullYear(),$d.getMonth(),$d.getDate());
    
        $('table.calendar td[id^="C"]').each(function(event){
            var $date   = $(this).attr('id').replace('C','');
            if($date    < $today){ $(this).attr({'class':'calendarDay','avail':''}); }
        });
    }
    
    
    function highlightDates(){
        coerce_dates();
     
        selection_availability = '';
        
        $('#vacation_lodging_details').hide();
        
        for(var i=selection_start_julian; i<=selection_end_julian; i++) {
            if ( $('#C'+i).length ) {
                $('#C'+i).addClass('selected');
                if ( i != selection_end_julian ) {
                    // last day doesn't count for availability (nights only)
                    avail = $('#C'+i).attr('avail');
                    selection_availability = mergeAvail(selection_availability,avail);
                }
            }
        }
        selection_nights = selection_end_julian - selection_start_julian;

        $('#selection-start').val(selection_start_nice);
        $('#selection-end').val(selection_end_nice);
        $('#selection-nights').val(selection_nights);
        // $('#selection-middle').html(selection_availability);
    }
    
    function mergeAvail(A, B) {
        if ( A == '' ) return B; // first time...
        var len = A.length;
        if ( B.length > len ) len = B.length;
        
        var avail = '';
        for (var i=0; i<len; i++) {
            if ( A.charAt(i) == '1' && B.charAt(i) == '1' ) {
                avail += '1';
            } else {
                avail += '0';
            }
        }
        return avail;
    }

    // ======================= //
    //       SHOW_SEASON       //
    // ======================= //
    
    function setSeason(season,force){
        if(season != selection_season || force){
            selection_season = season;

            if($('#vacation_story').length > 0){
                $('#vacation_story #story_promo').attr('season') != selection_season ? $('#story_promo').hide() : $('#story_promo').show();
                      
                if($('#vacation_story #story_titles div.current').attr('season') != selection_season){
                    $('#vacation_story #story_titles div.current').removeClass('current');
                    $('#vacation_story #story_titles div h1').removeClass('current');
                    
                    $('#vacation_story #story_titles div[season='+selection_season+']').addClass('current');
                    $('#vacation_story #story_titles div.current h1:first').addClass('current');
                }
                if($('#vacation_story #story_values div.current').attr('season') != selection_season){
                    $('#vacation_story #story_values div.current').removeClass('current');
                    $('#vacation_story #story_values div img').removeClass('current');
                    $('#vacation_story #story_values div object').removeClass('current');
                    
                    $('#vacation_story #story_values div[season='+selection_season+']').addClass('current');
                    $('#vacation_story #story_values div.current :first-child').addClass('current');
                    
                    if($('#story_values img.current').attr('url') != ''){            
                        var $video      = $('#story_values img.current').attr('url');
                        var $image      = $('#story_values img.current').attr('src');
                        var $video_id   = $('#story_values img.current').attr('id');
                        
                        swfobject.embedSWF('/media/video_player.swf?video_path='+$video+'&image_path='+$image,$video_id,'300','225','8.0.0','/media/expressInstall.swf','',{'wmode':'transparent'},{'video_path':$video,'styleclass':'current'});
                    } 
                }
                if($('#vacation_story dl ol div.current').attr('season') != selection_season){
                    $('#vacation_story dl ol div.current').removeClass('current');
                    $('#vacation_story dl ol div.current a').removeClass('current');
                
                    $('#vacation_story dl ol div[season='+selection_season+']').addClass('current');
                    $('#vacation_story dl ol div.current a:first').addClass('current');
                }
                
                $('#vacation_story dl ol').css('top',0);
                $stories        = $('#vacation_story dl ol div.current a').length; 
                $story_toggle   = $('#vacation_story dl a#story_toggle');
                $stories < 6 ? $story_toggle.addClass('inactive') : $story_toggle.removeClass('inactive');
            }
            
            if($('form#select_lodging').length > 0 && $('form#select_lodging ol div.current').attr('season') != selection_season){
                $('form#select_lodging ol div.current').removeClass('current');
                $('form#select_lodging ol div[season='+selection_season+']').addClass('current');
            }
            
            if($('#suitcase_inclusions').length > 0 && $('#suitcase_inclusions dl div.current').attr('season') != selection_season){
                $('#suitcase_inclusions dl div.current').removeClass('current');
                $('#suitcase_inclusions dl div[season='+selection_season+']').addClass('current');
                
                // change the header above the package listing AND above the lodging options
                if(selection_season == 'winter'){
                    $('#suitcase_inclusions h2').html("What's Included in Your Winter <em>Club Smugglers' Advantage Package</em>:");
                    $('#vacation_lodging h2 i').html("Club Smugglers' Advantage Package");
                    $('#vacation_lodging_terms p').html("All <i>Club Smugglers' Advantage Packages</i> are subject to service charge, 9% Vermont Meals and Rooms Tax on lodging and meal components, 6% Vermont Sales Tax on lift tickets, equipment rental and Resort amenities and 18% gratuity on meal components. These total additions, including service charge, equal 15% of the package rates. All rates are quoted in U.S. Funds.");
                
                    $('#suitcase_pricing div a[rel="save"]').attr({'class':'save_20','href':'/pages/winter/promotions/winter-10-qualifications.php','title':'Save up to 20%!'}).show();
                } else if(selection_season == 'summer'){ 
                    $('#suitcase_inclusions h2').html("What's Included in Your Summer <em>FamilyFest Package</em>:");
                    $('#vacation_lodging h2 i').html("FamilyFest Package");
                    $('#vacation_lodging_terms p').html("All package rates are subject to service charge, 9% Vermont Meals and Rooms tax on lodging and meal components, 6% Vermont Sales Tax on Resort amenities and 18% gratuity on meal components. These total additions plus service charge equal 15% of the package price.");
                
                    $('#suitcase_pricing div a[rel="save"]').attr({'class':'save_10','href':'/pages/summer/promotions/ten-percent-qualifications.php','title':'Save up to 10%!'}).show();
                } else if(selection_season == 'fall'){ 
                    $('#suitcase_inclusions h2').html("What's Included in Your Fall <em>AutumnFest Package</em>:");
                    $('#vacation_lodging h2 i').html("AutumnFest Package");
                    $('#vacation_lodging_terms p').html("All package rates are subject to service charge, 9% Vermont Meals and Rooms Tax on lodging and meal components, 6% Vermont Sales Tax on Resort amenities, and 18% gratuity on any meal components. These total additions plus service charge equal 15% of the package price. All rates are payable in U.S. Funds. Sorry, no pets; boarding is available locally.");
                
                    $('#suitcase_pricing div a[rel="save"]').hide();//attr({'class':'save_10','href':'/pages/summer/promotions/ten-percent-qualifications.php','title':'Save up to 10%!'});
                }

            }
        }
    }

    //  ######  ########  ######   ######  ####  #######  ##    ## 
    // ##    ## ##       ##    ## ##    ##  ##  ##     ## ###   ## 
    // ##       ##       ##       ##        ##  ##     ## ####  ## 
    //  ######  ######    ######   ######   ##  ##     ## ## ## ## 
    //       ## ##             ##       ##  ##  ##     ## ##  #### 
    // ##    ## ##       ##    ## ##    ##  ##  ##     ## ##   ### 
    //  ######  ########  ######   ######  ####  #######  ##    ## 


    // =========================== //
    //       SAVE_TO_SESSION       //
    // =========================== //
    
    function saveToSession(area) {
        if ( session_dirty == false ) return false;
        // if ( console ) console.log('SAVING SESSION: ' + selection_start_nice + ' - ' + selection_end_nice);

        dataStr  =  'area='                    + area; // for debugging
        dataStr += '&selection_availability='  + selection_availability;
        dataStr += '&selection_start='         + selection_start;
        dataStr += '&selection_start_nice='    + selection_start_nice;
        dataStr += '&selection_start_julian='  + selection_start_julian;
        dataStr += '&selection_end='           + selection_end;
        dataStr += '&selection_end_nice='      + selection_end_nice;
        dataStr += '&selection_end_julian='    + selection_end_julian;
        dataStr += '&selection_nights='        + selection_nights;
        dataStr += '&selection_adults='        + selection_adults;
        dataStr += '&selection_children='      + selection_children;
        dataStr += '&selection_infants='       + selection_infants;
        dataStr += '&selected_room='           + selected_room;
        dataStr += '&selection_season='        + selection_season;
        dataStr += '&vacation_total='          + vacation_total;
        dataStr += '&vacation_tax='            + vacation_tax;
        dataStr += '&vacation_grand_total='    + vacation_grand_total;
        dataStr += '&vacation_deposit='        + vacation_deposit;
        dataStr += '&selection_description='   + encodeURIComponent(selection_description);
        dataStr += '&fullDescription='         + encodeURIComponent(fullDescription);
        dataStr += '&selection_guest_details=' + encodeURIComponent(selection_guest_details);
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=saveToSession",
            data: dataStr,
            success: function(msg){
            }
        });
        session_dirty = false;
    }




    //                _____   _   _   _____   _____   _____   _____  
    //               /  ___| | | | | | ____| /  ___/ |_   _| /  ___/ 
    //               | |     | | | | | |__   | |___    | |   | |___  
    //               | |  _  | | | | |  __|  \___  \   | |   \___  \ 
    //               | |_| | | |_| | | |___   ___| |   | |    ___| | 
    //               \_____/ \_____/ |_____| /_____/   |_|   /_____/     
    //     




    var occupancy = 0;
    var selection_adults = 0;
    var selection_children = 0;
    var selection_infants = 0;
    // ========================= //
    //       UPDATE_GUESTS       //
    // ========================= //
    function updateGuests() {
        calendarScrollExempt = true;
        checkMonth();

        session_dirty = true;
        selection_adults = $('#adults').val();
        selection_children = $('#children').val();
        selection_infants = $('#infants').val();
        var kids = parseInt(selection_children) + parseInt(selection_infants);
        occupancy = parseFloat(selection_adults) + parseFloat(selection_children) + parseFloat(selection_infants);
        $('#vacation_guests h2').html(occupancy + ' guests');
        
        $('#vacation_lodging_details').hide();
        
        // show guests in suitcase
        var display_guest_str = '<sup>' + selection_adults +' adults</sup>';
        if ( selection_children > 0 ) display_guest_str += ', <sup>' + selection_children + ' kid(s) 3-17 yrs</sup>';
        if ( selection_infants > 0 ) display_guest_str += ',<br/> <sup>' + selection_infants + ' kid(s) 0-2 yrs</sup>';
        $('#suitcase_pricing div span cite[details=guests]').html(display_guest_str);
        
        resetGuestDetails(selection_adults, selection_children, selection_infants);
        // saveToSession('updateGuests'); // previous function does that...
        
        showLodging();
        recalcRoomPricing();
        // showGuestInfo();
        
    }
    
    // ======================= //
    //       SHOW_GUESTS       //
    // ======================= //
    function showGuests() {
         $('#adults').val(selection_adults);
         $('#children').val(selection_children);
         $('#infants').val(selection_infants);
         occupancy = parseFloat(selection_adults) + parseFloat(selection_children);
         activateGuestLinks();
    }
    

    // =========================== //
    //       SHOW_GUEST_INFO       //
    // =========================== //
    function showGuestInfo() {
        return false; // this is OFF
    
        var idx = 1;
        var $guest_info = '';
        for(var i=0; i<selection_adults; i++){
            $guest_info += '<a id="guest_'+idx+'" class="empty" first_name="" last_name="" birthday="" slope_level="" slope_lesson="" category="adult"><b>Adult #'+idx+'</b> <i>edit</i></a>';
            saveGuestDetails('guest_'+idx, 'Adult #'+idx, '', '', '', '', 'adult');
            idx++;
        }
        
        var cNum = 1;
        for(var i=0; i<selection_children; i++){
            $guest_info += '<a id="guest_'+idx+'" class="empty" first_name="" last_name="" birthday="" slope_level="" slope_lesson="" category="child"><b>Child #'+cNum+'</b> <i>edit</i></a>';
            saveGuestDetails('guest_'+idx, 'Child #'+cNum, '', '', '', '', 'child');
            idx++;
            cNum++;
        }

        for(var i=0; i<selection_infants; i++){
            saveGuestDetails('guest_'+idx, '', '', '', '', '', 'infant');
            $guest_info += '<a id="guest_'+idx+'" class="empty" first_name="" last_name="" birthday="" slope_level="" slope_lesson="" category="infant"><b>Child #'+cNum+'</b> <i>edit</i></a>';
            idx++;
        }
                
        $('#vacation_details ol').html($guest_info);
        activateGuestLinks();
    }
    
    // ============================== //
    //       SAVE_GUEST_DETAILS       //
    // ============================== //
    function saveGuestDetails(guest_id, first_name, last_name, birthday, slope_level, slope_lesson, category){
        // save guest data to session
        var $dataStr  = '';
        $dataStr     += 'guest_id='     + guest_id;
        $dataStr     += '&first_name='  + first_name;
        $dataStr     += '&last_name='   + last_name;
        $dataStr     += '&birthday='    + birthday;
        $dataStr     += '&slope_level=' + slope_level;
        $dataStr     += '&slope_lesson='+ slope_lesson;
        $dataStr     += '&category='    + category;
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=saveGuestToSession",
            data: $dataStr,
            success: function(msg){
            }
        });
    }

    // =============================== //
    //       CLEAR_GUEST_DETAILS       //
    // =============================== //
    function clearGuestsThenShow(){
        // save guest data to session
        var $dataStr  = '';
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=clearGuestDetails",
            data: $dataStr,
            success: function(msg){
                // showGuestInfo();
            }
        });
    }

    // =============================== //
    //       RESET_GUEST_DETAILS       //
    // =============================== //
    function resetGuestDetails(){
        // save guest data to session
        var $dataStr  = '';
        $dataStr     +=  'adults='   + selection_adults;
        $dataStr     += '&children=' + selection_children;
        $dataStr     += '&infants='  + selection_infants;
        $.ajax({
            type: "POST",
            url: "includes/index.ajax.php?function=resetGuestDetails",
            data: $dataStr,
            success: function(msg){
                $('#vacation_details ol').html(msg);
                activateGuestLinks();
            }
        });
    }

    // ================================ //
    //       ACTIVATE_GUEST_LINKS       //
    // ================================ //
    function activateGuestLinks() {
        //
        // Assign the function to the links
        //
        $('#vacation_details ol a').click(function(event){
            if(!$(this).hasClass('current')){
                var $guest_id       = $(this).attr('id');
                var $first_name     = $(this).attr('first_name');
                var $last_name      = $(this).attr('last_name');
                var $birthday       = $(this).attr('birthday');
                var $slope_level    = $(this).attr('slope_level');
                var $slope_lesson   = $(this).attr('slope_lesson');
                var $category       = $(this).attr('category');
                                
                $('form#select_details [name=guest]').val($guest_id);
                $('form#select_details h3').text($(this).children('b').text().replace(' edit',''));
                $('form#select_details [name=first_name]').val($first_name);
                $('form#select_details [name=last_name]').val($last_name);
                $('form#select_details [name=birthday]').val($birthday);
                $('form#select_details [name=slope_level]').val($slope_level);
                $('form#select_details [name=slope_lesson]').val($slope_lesson);
                $('form#select_details [name=category]').val($category);
                
                $('#vacation_details ol a').removeClass('current');

                $('#vacation_details #lesson_choice_area').hide();
                $('#vacation_details #lesson_choice_alt').hide();

                $(this).addClass('current');
                $('form#select_details').show();
                
                $('form#select_details [name=birthday]').change();
                $('form#select_details [name=slope_level]').change();
            }
        });
    }

    // ================================= //
    //       MAKE_ONE_GUEST_DETAIL       //
    // ================================= //

    // generate the nice looking details for one guest
    function makeOneGuestDetail(id) {
        var first_name     = $('#'+id).attr('first_name');
        var last_name      = $('#'+id).attr('last_name');
        var birthday       = $('#'+id).attr('birthday');
        var slope_level    = $('#'+id).attr('slope_level');
        var slope_lesson   = $('#'+id).attr('slope_lesson');
        var category       = $('#'+id).attr('category');
        
        var output = '';
        output += '<div style="display: block; margin: 2px 0px; padding: 10px; padding: 10px; background-color: #e7e7e7;">';
    	output += '<h4>' + first_name + ' ' + last_name + '</h4>';
    	output += birthday + '<br>';
    	output += 'Ski/Snowboard Level: ' + slope_level + '<br>';
    	output += '1&frac12; hour Group Lesson ' + slope_lesson + '<br>';
        output += '</div>';
        
        return output;
    }

    var selection_guest_details = '';
    
    // ============================== //
    //       MAKE_GUEST_DETAILS       //
    // ============================== //

    // gather all the nice looking details and put them in the correct div
    function makeGuestDetails() {
        var idx = 1;
        selection_guest_details = ''; // fullDescription + '<br><br>';
        for(var i=0; i<selection_adults; i++){
            selection_guest_details += makeOneGuestDetail('guest_'+idx);
            idx++;
        }
        
        var cNum = 1;
        for(var i=0; i<selection_children; i++){
            selection_guest_details += makeOneGuestDetail('guest_'+idx);
            idx++;
            cNum++;
        }

        for(var i=0; i<selection_infants; i++){
            selection_guest_details += makeOneGuestDetail('guest_'+idx);
            idx++;
        }
        $('#your_vacation_details').html(fullDescription + '<br><br>' + selection_guest_details);
        saveToSession('makeGuestDetails');
        recalcRoomPricing();
    }




    //                 _       _____   _____   _____   _   __   _   _____  
    //                | |     /  _  \ |  _  \ /  ___| | | |  \ | | /  ___| 
    //                | |     | | | | | | | | | |     | | |   \| | | |     
    //                | |     | | | | | | | | | |  _  | | | |\   | | |  _  
    //                | |___  | |_| | | |_| | | |_| | | | | | \  | | |_| | 
    //                |_____| \_____/ |_____/ \_____/ |_| |_|  \_| \_____/     
    //     




    // ======================== //
    //       SHOW_LODGING       //
    // ======================== //
    function showLodging(event){
        $('[kind=room],[lodge]').removeClass('available');
        if ( selection_availability == '' ) {                                               
            if ( lodgingCapacityOK(0) == 1 )   $('#ROOM_S').addClass('available'); $('[lodge_id=ROOM_S]').addClass('available'); 
            if ( lodgingCapacityOK(1) == 1 )  $('#ROOM_1B').addClass('available'); $('[lodge_id=ROOM_1B]').addClass('available');
            if ( lodgingCapacityOK(2) == 1 ) $('#ROOM_1BP').addClass('available'); $('[lodge_id=ROOM_1BP]').addClass('available');
            if ( lodgingCapacityOK(3) == 1 )  $('#ROOM_2B').addClass('available'); $('[lodge_id=ROOM_2B]').addClass('available');
            if ( lodgingCapacityOK(4) == 1 ) $('#ROOM_2BP').addClass('available'); $('[lodge_id=ROOM_2BP]').addClass('available');
            if ( lodgingCapacityOK(5) == 1 )  $('#ROOM_3B').addClass('available'); $('[lodge_id=ROOM_3B]').addClass('available');
            if ( lodgingCapacityOK(6) == 1 ) $('#ROOM_3BP').addClass('available'); $('[lodge_id=ROOM_3BP]').addClass('available');
            if ( lodgingCapacityOK(7) == 1 )  $('#ROOM_4B').addClass('available'); $('[lodge_id=ROOM_4B]').addClass('available');
            if ( lodgingCapacityOK(8) == 1 )  $('#ROOM_5B').addClass('available'); $('[lodge_id=ROOM_5B]').addClass('available');
        } else {
            var noneAvailable = true;
            if ( lodgingOptionOK(0, selection_availability) == 1 ) {   $('#ROOM_S').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(1, selection_availability) == 1 ) {  $('#ROOM_1B').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(2, selection_availability) == 1 ) { $('#ROOM_1BP').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(3, selection_availability) == 1 ) {  $('#ROOM_2B').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(4, selection_availability) == 1 ) { $('#ROOM_2BP').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(5, selection_availability) == 1 ) {  $('#ROOM_3B').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(6, selection_availability) == 1 ) { $('#ROOM_3BP').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(7, selection_availability) == 1 ) {  $('#ROOM_4B').addClass('available'); noneAvailable = false; }
            if ( lodgingOptionOK(8, selection_availability) == 1 ) {  $('#ROOM_5B').addClass('available'); noneAvailable = false; }
            
            // if selected lodging is also NOT available, show err
            if ( !$('#vacation_lodging ol a.selected').hasClass('available') && $('#vacation_lodging ol a.selected').length ) {
                $('#vacation_lodging ol a.selected').removeClass('selected');
                $('#vacation_lodging ol a').removeClass('current');
                $('#vacation_lodging dl div.current').removeClass('current');
                
                $('.vacation_lodging_details').css('visibility','hidden');
                $('.book_now').hide();
                selected_room = '';
                
                $('#vacation-total').html('0.00');
                $('#vacation-tax').html('0.00');
                $('#vacation-deposit').html('0.00');
                $('#vacation-grand-total').html('0.00');

                // alert(selection_availability);
                smuggs_alert('Please update your lodging selection.', 3);
                $('#vacation_lodging dl div.info').hide();
                $('#vacation_lodging dl div.err').show();
            } else {
                if ( noneAvailable && selection_adults != 0 ) {
                    // alert(noneAvailable +' && '+ selection_adults);
                    $('#vacation_lodging dl div.info').hide();
                    $('#vacation_lodging dl div.err').show();
                } else {
                    $('#vacation_lodging dl div.info').show();
                    $('#vacation_lodging dl div.err').hide();
                }
            }
        }
        // alert(selection_availability);
        
        selectRoom(selected_room);
        window.setTimeout('updateCalendar()', 100);
        // getPricing(selected_room);
    }

    function lodgingOptionOK(pos, availability) {
        // if ( console ) console.log(pos + ' - ' + availability);
        if ( occupancy == 0 ) return false;
        if ( availability == undefined ) return false;
        if ( availability.charAt(pos) != 1 ) { return false; }
        
        // get occupancy limits from object at end of html
        var occMin = $('#occ_'+pos).attr('min');
        var occMax = $('#occ_'+pos).attr('max');
        // if ( occupancy < occMin ) { return false; }
        if ( occupancy > occMax ) { return false; }
        // alert(pos + ': ' + availability + '; ' + occupancyMin[pos] + '-' +  occupancy  + '-' + occupancyMax[pos]);
        return true;
    }
    
    function lodgingCapacityOK(pos) {
        // use this when there are no dates selected
        if ( occupancy == 0 ) return true;
        var occMin = $('#occ_'+pos).attr('min');
        var occMax = $('#occ_'+pos).attr('max');
        // if ( occupancy < occMin ) { return false; }
        if ( occupancy > occMax ) { return false; }
        return true;
    }


    var currentlyActive = '.calendarArea'; // page loads with this area active

    // ==================== //
    //       ACTIVATE       //
    // ==================== //
    function activate(objID) {
        if ( currentlyActive != objID ) {
            $(currentlyActive).removeClass('active');
            $(currentlyActive).addClass('inactive');
            
            $(objID).removeClass('inactive');
            $(objID).addClass('active');
            
            currentlyActive = objID;
        }
    }
    
    var selected_room = ''; // used to store the currently selected room (S, 1B, 1bp, etc)

    // ======================= //
    //       SELECT_ROOM       //
    // ======================= //
    function selectRoom(code) {
        if ( code == '' ) return '';
        selected_room = code;
        session_dirty = true;
        // alert('selectRoom(' + code + ') = ' + selected_room);
        var roomID = '#ROOM_' + code;
        var detailID = '#DETAIL_' + code;
        if ( $(roomID).hasClass('roomActive') ) {
            // manage the listing
            $('.roomSelected').removeClass('roomSelected').addClass('roomActive'); // remove any instance of a room selected
            $(roomID).removeClass('roomActive').addClass('roomSelected');
            
            // manage the details
            $('.detailsShowing').removeClass('detailsShowing').addClass('detailsHidden'); // remove any instance of a room selected
            $(detailID).removeClass('detailsHidden').addClass('detailsShowing');
        }
            
        var display_room_str = '<sup>' + $('#occ_'+selected_room).attr('name') + '</sup>';
        $('#suitcase_pricing div span cite[details=lodging]').html(display_room_str);

        getPricing(selected_room);
        saveToSession('selectRoom');
    }




    //                 _____   _____    _   _____   _   __   _   _____  
    //                |  _  \ |  _  \  | | /  ___| | | |  \ | | /  ___| 
    //                | |_| | | |_| |  | | | |     | | |   \| | | |     
    //                |  ___/ |  _  /  | | | |     | | | |\   | | |  _  
    //                | |     | | \ \  | | | |___  | | | | \  | | |_| | 
    //                |_|     |_|  \_\ |_| \_____| |_| |_|  \_| \_____/     
    //     




    var TAX_RATE              = 0.15;
    var selection_description = '';
    var fullDescription       = '';
    var vacation_total        = 0;
    var vacation_tax          = 0;
    var vacation_grand_total  = 0;
    var vacation_deposit      = 0;

    // ======================= //
    //       GET_PRICING       //
    // ======================= //
    function getPricing(room) {
        if ( room == '' ) return false;
        if ( selection_nights == '' ) return false;

        var promo = getPromotionID();
        
        // <div>
        //     <h2>Daily Rate Details <b>including the</b> <i>Club Smugglers' Advantage Package</i></h2>
        //     <p>Here is the daily price for each of your proposed vacation days:<br>(All prices in U.S. dollars before tax &amp; service fees.)</p>
        
        var output = '';
        output += '<div>';
        output += "<h2>Daily Rate Details <b>including the</b> <i>Club Smugglers' Advantage Package</i></h2>";
        output += '<p>Here is the daily price for each of your proposed vacation days:<br>(All prices in U.S. dollars before tax &amp; service fees.)</p>';

        //     <h5>3-Bedroom Condominium for 3 night(s)<br>with 2 adult(s) 2 kid(s) (1 3-17yrs; 1 0-2yrs)</h5>

        // Winter Club Smugglers' Advantage Package
        // Family of 3 in a 1 Bedroom Condominium
        // with 1 adult, 1 child (age 3-17), and 1 child (age 0-2)
        // 3 Nights, ARRIVAL January 4, 2010, DEPARTURE January 7, 2010

        var description = '<b>' + $('#occ_'+room).attr('name') + '</b>';
        var min = $('#occ_'+room).attr('min');
        description += ' for ' + selection_nights + ' night';
        if ( selection_nights != 1 ) description += 's';
        description += ' with';
        
        var adults   = parseInt($('#adults').val());
        var children = parseInt($('#children').val());
        var infants  = parseInt($('#infants').val());
        var kids     = children + infants;
        var people   = adults + children;
        

        if ( people == 0 ) return false;
        
        if ( adults == 1 )   A_S = ''; else A_S = 's';
        if ( children == 1 ) C_S = ''; else C_S = 'ren';
        if ( infants == 1 )  I_S = ''; else I_S = 'ren';

        description += ' ' + adults + ' adult' + A_S;
        if ( children > 0 ) {
            description += ', ' + children + ' child' + C_S + ' aged 3-17yrs';
        }
        if ( infants > 0 ) {
            description += ', ' +  infants + ' child'+ I_S + ' aged 0-2yrs';
        }
        
        fullDescription = description;
        fullDescription += ', Arrival ' + selection_start_nice + ', Departure ' + selection_end_nice;

        output += description;
        
        output += '<dl>';
        output += '  <p>';
        output += '    <label>Date</label>';
        output += '    <label>Rate Period</label>';
        output += '    <label>Price</label>';
        output += '    <label>Avg. Person Daily Rate</label>';
        output += '  </p>';
        
        var showOriginalPrice = ''; 
        if ( promo != '' ) {
            // Set Up Promotion
            
            // if getting a free night, pay based on nights paid
            // 
            // freeNight="0" 

            var promo_chgNights = selection_nights;
            var freeNight = $(id).attr('freeNight');
            if ( selection_nights >= freeNight && freeNight != 0 ) promo_chgNights--;
            
            showOriginalPrice = $(promo).attr('showOriginalPrice');

            var $resoPhone = $(promo).attr('resoPhone');
            if ( $resoPhone != '' ) { 
                $('#reso_phone_display').html($resoPhone);
                $('#lodging_error_phone').html($resoPhone);
                $('#lodging_info_phone').html($resoPhone);
            }
        }

        //
        // Calculate and display the pricing
        //
        var day = 1;
        var gross = parseFloat(0.00); // before discount
        var total = parseFloat(0.00);
        $('#debug_area').append('selection_season: '+selection_season+'<br>');
        for(var i=selection_start_julian; i<selection_end_julian; i++) {
            var date = julian2nice(i);
            var rate = $('#C'+i).attr('rate');
            var name = $('#RATE_'+rate).attr('name');
            var id = '#' + rate + '_' + room + '_' + selection_nights;
            var aPrice = parseFloat( $(id).attr('A') );
            var cPrice = parseFloat( $(id).attr('C') );
            var uPrice = parseFloat( $(id).attr('U') );
            var oPrice = parseFloat( $(id).attr('O') );
            var min    = parseFloat( $(id).attr('M') );
            $('#debug_area').append(id + ' : '+aPrice+'<br>');
            
            switch(selection_season) {
                case 'summer':
                    var price  = aPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;

                case 'fall':
                    var price  = aPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;

                case 'winter':
                default:
                    var price  = (adults * aPrice) + (children * cPrice);
                    if ( people < min ) price += (min - people) * uPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;
            }
            var originalPrice = price;
            if ( promo != '' ) {
                // Apply Promotion
                
                // if getting a free night, pay based on nights paid
                if ( day == freeNight ) price = 0; // free day

                // check for a percent-of promotion
                //
                // dayDiscount_1="0" dayDiscount_2="0" dayDiscount_3="30" dayDiscount_4="40" dayDiscount_5="40" dayDiscount_6="40" dayDiscount_7="40" dayDiscount_8="40" dayDiscount_9="40" dayDiscount_10="40" 
                // dayApplied_1="1" dayApplied_2="1" dayApplied_3="1" dayApplied_4="1" dayApplied_5="1" dayApplied_6="1" dayApplied_7="1" dayApplied_8="0" dayApplied_9="0" dayApplied_10="0" 

                var dayDiscount = parseInt( $(promo).attr('dayDiscount_'+selection_nights) ); // used to be +day
                var dayApplied  = parseInt( $(promo).attr('dayApplied_'+day)  );
                var discountApplies = 1.00;
                if ( dayDiscount > 0 && dayApplied == 1 ) {
                    //$('#debug_area').append('Discount = ' + price+' * '+dayDiscount+' / 100<br>');
                    var discount = price * dayDiscount / 100;
                    price = price - discount;
                }                
                // $('#debug_area').append(promo+', '+dayDiscount+', '+dayApplied+', '+price+', '+originalPrice+', '+discountApplies+'<br>');
            }
            
            total += price;
            gross += originalPrice;
            var daily = price / people;
            price = dollars(price);
            originalPrice = dollars(originalPrice);
            daily = dollars(daily);
            $('#debug_area').append(total+', '+price+'<br>');
            output += '<p id="detail_row_' + day + '">';
            output += '  <cite>' + date + '</cite>'; 
            output += '  <cite>' + name + '</cite>';
            if ( originalPrice != price && showOriginalPrice == 'yes' ) {
                output += '  <cite><strike>' + originalPrice + '</strike> <u>' + price + '</u></cite>'; 
            } else {
                output += '  <cite>' + price + '</cite>'; 
            }
            output += '  <cite>' + daily + '</cite>'; 
            output += '</p>';
            
            day++;
        }
        
        var tax         = total * TAX_RATE;
        var grand_total = total + tax;
        var deposit     = grand_total / 2;
        var totalEach   = total / people / selection_nights;
        var discountAmt = gross - total;

        var gross       = formatCurrency(gross);
        var discountAmt = formatCurrency(discountAmt);
        var total       = formatCurrency(total);
        var tax         = formatCurrency(tax);
        var grand_total = formatCurrency(grand_total);
        var deposit     = formatCurrency(deposit);
        var totalEach   = formatCurrency(totalEach);
        
                
        //     </dl>
        // </div>
        output += '</dl>';
        output += '</div>';
        
        $('#vacation_lodging_details').html(output);
        
        //
        // now insert the total row at the top
        //
        totalRow  = '';
        totalRow += '<p id="detail_row_' + day + '">';
        totalRow += '  <cite><b>TOTAL</b></cite>'; 
        totalRow += '  <cite><b>' + name + '</b></cite>';
        totalRow += '  <cite><b>' + total + '</b></cite>'; 
        totalRow += '  <cite><b>' + totalEach + '</b></cite>'; 
        totalRow += '</p>';
        $('#detail_row_1').before(totalRow);
        

        // alert(room + ' == ' + selected_room);
        if ( room == selected_room ) {
            if ( parseInt(total) >= 1 ) {
                if ( gross == total ) {
                    $('#vacation-total').html('<sup>$</sup>'+gross);
                    $('#vacation-promo').html('');
                    $('#vacation_total_area label').html('Vacation Total');
                    $('#vacation_promo_area').hide();
                } else {
                    $('#vacation-total').html('<sup>$</sup><strike>'+gross+'</strike>');
                    $('#vacation-promo').html('<sup>$</sup>'+total);
                    $('#vacation_total_area label').html('Regular Rate');
                    $('#vacation_promo_area label').html('Your Rate');
                    $('#vacation_promo_area').show();
                }
                $('#vacation-tax').html('<sup>$</sup>'+tax);
                $('#vacation-deposit').html('<sup>$</sup>'+deposit);
                $('#vacation-grand-total').html('<sup>$</sup>'+grand_total);
                
                // alert( $('#vacation-total').html() );
    
                // save this description in the session
                selection_description = description;
                vacation_total        = total;
                vacation_tax          = tax;
                vacation_grand_total  = grand_total;
                vacation_deposit      = deposit;
    
                pageTracker._trackPageview('/vacation_planner/book_now/user_ip='+user_session+'&arrive='+selection_start_nice+'&depart='+selection_end_nice+'&adults='+adults+'&children='+children+'&infants='+infants+'&room='+selected_room+'&grand_total='+grand_total);

                $('.vacation_lodging_details').css('visibility','visible');
                $('.book_now').show();
            }
        }
        
        // add total to lodging entry
        
        
        makeGuestDetails();
    }

    function recalcRoomPricing() {
        // alert('recalculating...');
        $('[lodge_id=ROOM_S]   h4').html(getJustPricing('S'));
        $('[lodge_id=ROOM_1B]  h4').html(getJustPricing('1B'));
        $('[lodge_id=ROOM_1BP] h4').html(getJustPricing('1BP'));
        $('[lodge_id=ROOM_2B]  h4').html(getJustPricing('2B'));
        $('[lodge_id=ROOM_2BP] h4').html(getJustPricing('2BP'));
        $('[lodge_id=ROOM_3B]  h4').html(getJustPricing('3B'));
        $('[lodge_id=ROOM_3BP] h4').html(getJustPricing('3BP'));
        $('[lodge_id=ROOM_4B]  h4').html(getJustPricing('4B'));
        $('[lodge_id=ROOM_5B]  h4').html(getJustPricing('5B'));
    }

    // ============================ //
    //       GET_JUST_PRICING       //
    // ============================ //
    function getJustPricing(room) {
        if ( room == '' ) return '';
        if ( selection_nights == '' ) return '';
        if ( selection_adults == '' ) return '';
        
        if ( lodgingCapacityOK(roomIndex(room)) == false ) {
            return '<b>Number of guests entered exceeds maximum occupancy.</b>';
        }
        
        
        var season_package  = '';
        
        switch(selection_season){
            case 'summer'   : season_package = "FamilyFest Package"; break;
            case 'fall'     : season_package = "AutumnFest Package"; break;
            case 'winter'   : season_package = "Club Smugglers' Advantage Package"; break;
        }
        
        var prefix = "<i>"+season_package+"</i> Price: $";
        var promo = getPromotionID();
        
        if ( promo != '' ) {
            var promo_chgNights = selection_nights;
            var freeNight = $(id).attr('freeNight');
            if ( selection_nights >= freeNight && freeNight != 0 ) promo_chgNights--;
        }

        //
        // Calculate and display the pricing
        //
        var adults   = parseInt($('#adults').val());
        var children = parseInt($('#children').val());
        var infants  = parseInt($('#infants').val());
        var kids     = children + infants;
        var people   = adults + children;
        // alert(adults +'-'+ children +'-'+ infants);

        var day = 1;
        var total = parseFloat(0.00);
        for(var i=selection_start_julian; i<selection_end_julian; i++) {
            var date = julian2nice(i);
            var rate = $('#C'+i).attr('rate');
            var avail = $('#C'+i).attr('avail');
            if ( avail.charAt(roomIndex(room)) == '0' ) { 
                // alert(room + '.' + i + ' : ' + avail + ' : ' + roomIndex(room) + ' = ' + avail.charAt(roomIndex(room)));
                // this room is NOT available for this date
                return '<b>Currently unavailable for selected dates.</b>';
            }

            var name = $('#RATE_'+rate).attr('name');
            var id = '#' + rate + '_' + room + '_' + selection_nights;
            var aPrice = parseFloat( $(id).attr('A') );
            var cPrice = parseFloat( $(id).attr('C') );
            var uPrice = parseFloat( $(id).attr('U') );
            var oPrice = parseFloat( $(id).attr('O') );
            var min    = parseFloat( $(id).attr('M') );
            
            // alert(id +'-'+ aPrice);
            
            switch(selection_season) {
                case 'summer':
                    var price  = aPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;

                case 'fall':
                    var price  = aPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;

                case 'winter':
                default:
                    var price  = (adults * aPrice) + (children * cPrice);
                    if ( people < min ) price += (min - people) * uPrice;
                    if ( people > min ) price += (people - min) * oPrice;
                    break;
            }
            
            if ( promo != '' ) {
                if ( day == freeNight ) price = 0; // free day
                var dayDiscount = parseInt( $(promo).attr('dayDiscount_'+selection_nights) ); // used to be +day
                var dayApplied  = parseInt( $(promo).attr('dayApplied_'+day)  );
                var discountApplies = 1.00;
                if ( dayDiscount > 0 && dayApplied == 1 ) {
                    var discount = price * dayDiscount / 100;
                    price = price - discount;
                }                
            }
            total += price;            
            day++;
        }
        
        total = prefix + formatCurrency(total);
        return total;
    }

    function roomIndex(room) {
        if ( room == 'S'   ) return 0;
        if ( room == '1B'  ) return 1;
        if ( room == '1BP' ) return 2;
        if ( room == '2B'  ) return 3;
        if ( room == '2BP' ) return 4;
        if ( room == '3B'  ) return 5;
        if ( room == '3BP' ) return 6;
        if ( room == '4B'  ) return 7;
        if ( room == '5B'  ) return 8;
    }
    
    function dollars(price) {
        if ( price.toFixed ) {
            return price.toFixed(2);
        } else {
            return Math.round(price * 100) / 100;
        }
    }

    function CurrencyFormatted(amount) {
        var i = parseFloat(amount);
        if(isNaN(i)) { i = 0.00; }
        var minus = '';
        if(i < 0) { minus = '-'; }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        s = new String(i);
        if(s.indexOf('.') < 0) { s += '.00'; }
        if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;
        return s;
    }

    function formatCurrency(strValue) {
    	strValue = strValue.toString().replace(/\$|\,/g,'');
    	dblValue = parseFloat(strValue);
    
    	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    	dblValue = Math.floor(dblValue*100+0.50000000001);
    	intCents = dblValue%100;
    	strCents = intCents.toString();
    	dblValue = Math.floor(dblValue/100).toString();
    	if(intCents<10)
    		strCents = "0" + strCents;
    	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
    		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
    		dblValue.substring(dblValue.length-(4*i+3));
    	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
    }

    // ============================ //
    //       GET_PROMOTION_ID       //
    // ============================ //
    function getPromotionID() {
    
        var active_promo = '';
        var done = false;
        var i = 0;
        var limit = 5;
        do {
            var id = '#promo_' + i;
            if ( parseInt($(id).attr('vp_promotionsID')) > 0 ) {
                var ok = false;
                
                // check for valid vacation date
                var vacationStartDate = $(id).attr('vacationStartDate');
                var vacationEndDate   = $(id).attr('vacationEndDate');
                if ( selection_start < selection_end && selection_start >= vacationStartDate && selection_end < vacationEndDate ) ok = true;
                
                if ( ok == true ) {
                    active_promo = id;
                    done = true; // stop looking for promotions
                }
            } else {
                done = true;
            }
            limit--;
        } while ( done == false && limit > 0 );

        // $('#selection-middle').html(active_promo);
        return active_promo;
    }