﻿/* ----------------------CombinedVTC.js : combines js from ui.js, trip-planner.js, customvtc.js   ---------------------
Last Modified: 11/18/2011
---------------------------------------------------------------------------------------------------------------------*/

/*============= MISC ==============*/

function ValidateEmailRegex(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

/* ---------------------------------------------- ----- --------------------------------------------------------------- */
/* ---------------------------------------------- ui.js --------------------------------------------------------------- */
/* ---------------------------------------------- ----- --------------------------------------------------------------- */

//This is in a separate method so that it can be called again after UpdatePanel postbacks
function SetupEmailConfirmation() {
    var modal = $('.email-confirm');
    var viewport_x = $(document).height();
    var viewport_y = $(document).width();

    $('#newsletter-form').submit(function (e) {
        e.preventDefault();
    });

    $('.email-subscribe-send').click(function () {
        var scroll = $(modal).scrollTop();
        $('#overlay').css({
            height: viewport_x,
            width: viewport_y
        }).show();
        $('.email-confirm').show();
        $('select').hide();
    });
    $('.close-email-box').click(function () {
        $('.email-confirm').hide();
        $('#overlay').hide();
        $('select').show();
    });
}

$(document).ready(function () {

    /***** new code for login/registration ****/
    // Display placeholder in all browsers 
    $('input[placeholder]').placeholder();
    /**** end of login/registration onload code ****/

    /** Facebook share buttons - used by ATP **/
    $(".custom-share").each(function () {
        //get the URL
        var url = $(this).attr("href");
        $(this).click(function () {
            window.open(url, "customShare", "status=1, height=400, width=600, resizable=1");
            return false;
        });
    });

    //Not Necessary to assign a width to a div tag as the div resizes based on the image width
    //    if ($(".lander .img-has-caption img").size() > 0) {
    //        caption_img_box = parseInt($(".lander .img-has-caption img:eq(0)").width()) + 15;
    //        $(".lander .img-has-caption").css("width", caption_img_box + "px");
    //    }
    $(".tab").click(function () {
        if ($(this).parent().css("right") == "0px") {
            play_homepage();
            $(this).parent().animate({
                right: "-203px"
            },
            400, "");
        } else {
            pause_homepage();
            $(this).parent().animate({
                right: "0px"
            },
            400, "");
        }
    });

    // Email confirm
    SetupEmailConfirmation();

    // Blog flipper
    $('.blog-nav .controls .prev').click(function () {
        $('.article#first').show();
        $('.article#second').hide();
        $('.story-count').html("1 <span class=\"amp\">of</span> 2");
    });
    $('.blog-nav .controls .next').click(function () {
        $('.article#first').hide();
        $('.article#second').show();
        $('.story-count').html("2 <span class=\"amp\">of</span> 2");
    });

    // Directory filters
    $('#checkbox-all').click(function (toggle) {
        $('.checkbox-column input[type=checkbox]').attr('checked', true);
        return false;
    });
    $('#checkbox-reset').click(function (toggle) {
        $('.checkbox-column input[type=checkbox]').attr('checked', false);
        return false;
    });
    $('.more-options').click(function () {
        $('.extended-filters').slideToggle(240);
        modal_hs('none');
    });
    $('.close-search-controls').click(function () {
        $('.extended-filters').slideToggle(40);
    });

    $('#close-link').click(function () {
        $('.extended-filters').slideToggle(40);
    });

    // Hide show various directions panels
    /*
    TODO Add another method for closing this pullout sheet
    */
    function toHere(id) {
        $('html,body').animate({ scrollTop: $("#" + id).offset().top }, 'slow');
    }

    $('.driving-directions').click(function (e) {
        var address = $(this).attr("rel");
        $('.map-directions').slideDown(140);
        $('.listings').fadeOut(240);
        $('.listing').fadeOut(240);
        $('.map-filters').fadeOut(240);
        $('.pagination').hide();
        $('.dir_end').attr("value", address);
        $('.route-type-fastest').attr('checked', true);
        $('.route-display-map').attr('checked', true);
        $('.directions-panel').hide();
        toHere("internal-nav");
        e.preventDefault();
    });

    $('#get-directions').live("click", function () {
        $('.listings').hide();
        $('.listing').hide();
        $('.map-directions').hide();
        $('.map-filters').hide();
        $('.directions-panel').fadeIn().delay(300).load('directions-snippet.html');
    });

    function resetDirections() {
        $('.map-directions').slideUp(140);
        $('.listings').fadeIn(240);
        $('.listing').fadeIn(240);
        $('.map-filters').fadeIn(240);
        $('.directions-panel').hide();
        $('.pagination').show();
    }

    $('#reset-maps').click(function () {
        resetDirections();
    });

    /* 2011.02.15 jcominoli@boomyourbrand.com -- added close-directions click */
    $('#close-directions').click(function () {
        $('.map-directions').slideUp(140);
        $('.listings').fadeIn(240);
        $('.listing').fadeIn(240);
        $('.map-filters').fadeIn(240);
        $('.pagination').show();
        return false;
    });

    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            $('.map-directions').slideUp(140);
            $('.listings').fadeIn(240);
            $('.listing').fadeIn(240);
            $('.map-filters').fadeIn(240);
            $('.pagination').show();
        }
    });

    // Extended listing info
    $('.more-info').toggle(function () {
        $(this).siblings('.extended-info').slideDown(240);
        $(this).parent().find('.extended-info').css("display", "block");
        $(this).parent().find('.extended-info img').css("display", "inline");
        $(this).attr('src', '/resources/buttons/listing-extended-info-hide.gif');
    }, function () {
        //$(this).siblings('.extended-info').slideUp(140);
        $(this).parent().find('.extended-info').css("display", "none");
        $(this).attr('src', '/resources/buttons/listing-extended-info-reveal.gif');
    });

    /**
    * Gridview switching
    * Switches the gridview and sets the class on
    * the trigger button
    **/
    $.fn.gridswitch = function () {

        $(this).click(function (e) {
            var target = $(this).attr("id");
            if (target == "gridview") {
                // $(".extended-info").css("display", "none");
                $('.listings').attr("class", "listings is_grid");
                $(".listings .more-info").css("display", "none");
                //$('#letter_filter').hide();
            }
            else if (target == "listview") {
                $('.listings').attr("class", "listings is_list");
                $(".listings .more-info").css("display", "block");
                //$('#letter_filter').hide();
            }
            else if (target == "mapview") {
                //alert("Mapview coming soon.");
                $('#letter_filter').hide();
            }
            else if (target == "alphaview") {
                $('#letter_filter').show();
                e.preventDefault();
            }
            $(this).addClass("selected");
            $(this).siblings().removeClass("selected");

            //$(".directory-gridview h3").ThreeDots({ max_rows: 3, ellipsis_string: '' });

        });

    }

    $('.views-count ul li').gridswitch();

    // Planner buttons
    $('.add-to-planner').click(function () {
        $(this).children('img').attr("src", "/resources/buttons/button_added_to_planner.gif");
        $(this).attr("href", "/path/to/trip-planner/");
        $(this).unbind("click");
        // ADD JS TO ADD TO TRIP PLANNER
        return false;
    });

    // Keyword box
    $('#keyword').click(function () {
        $('#keyword-box').slideToggle(240);
    });
    $('#keyword-box #apply-filters').click(function () {
        $('#keyword-box .spinner').fadeIn(20).delay(400);
        $('#keyword-box').slideToggle(140);
    });

    // Feature boxes caption popups
    $('body.lander .feature').hover(function () {
        // alert("Hovered");
        $(this).children('div.caption').stop().animate({
            marginTop: "-60px"
        },
        100);
    },
    function () {
        $(this).children('div.caption').stop().animate({
            marginTop: "60px"
        },
        200);
    });

    // Clear inputs on focus
    /*do not execute the code below
    $("input[type=text]").focus(function() {
    if (this.value == this.defaultValue) {
    this.value = "";
    }
    }).blur(function() {
    if (!this.value.length) {
    this.value = this.defaultValue;
    }
    });
    */
    // Add To Trip Planner button behavior
    $('span.trip-button').click(function () {
        $(this).html("In Planner").animate({
            marginLeft: "-12px"
        },
        300);
    });

    // Additional info in list-style directory pages
    $('.more-info-trigger').click(function () {
        $(this).siblings('dd.extended-info').slideToggle(140);
    });

    $('li#event-button').click(function () {
        hideCalendarControl();
        $(this).siblings('li').addClass('inactive');
        $(this).removeClass('inactive');
        $('.hotel-form').hide();
        $('.event-form').show();
    });

    $('li#hotel-button').click(function () {
        hideCalendarControl();
        $(this).removeClass('inactive');
        $(this).siblings('li').addClass('inactive');
        $('.event-form').hide();
        $('.hotel-form').show();
    });


    /* ********************************************************* */
    // HOME PAGE

    /* BEGIN CHANGE */
    clickedPager = -1;
    var stage = $(document).find('#hero .stage');
    if (stage) {
        $('#hero .stage').cycle({
            fx: 'fade',
            speed: 1200,
            timeout: 10000,
            pager: '#pager',
            before: heartIn,
            after: heartOut
        }); // 12000
    }

    $('#hero .stage').cycle('resume');

    $('#pager a').click(function () {
        pause_homepage();
    });

    function heartOut() {
        // $('#hero .stage').cycle('pause').delay(2000).cycle('resume')
    }

    function heartIn() {
        $(this).find(".tray").delay(1000).animate({
            right: "0px"
        },
        800, "");
        $(this).find(".tray").delay(7600).animate({
            // 2600
            // 9800
            right: "-203px"
        },
        800, "");
    }

    // UNNEEDED ??
    if ($('#hero .stage div').length > 0) {
        tempwidth = 68;
    }

    /* END CHANGE */

    /* ********************************************************* */
    // LANDING PAGE

    /* BEGIN CHANGE */
    var cycle_target = $(document).find('#lander-hero .images');
    if (cycle_target) {
        $('#lander-hero .images').cycle({
            fx: 'scrollHorz',
            speed: 1200,
            timeout: 15000,
            pager: '#pager'
        });
    }
    /* END CHANGE */

    if ($('#lander-hero .images').length > 0) {
        $("#pager").append(" <span class=\"amp\">of</span> <span id=\"total\">" + $('#lander-hero .images img').size() + "</span>");
    }

    // UNNEEDED ??
    if ($('#lander-hero .images img').length > 0) {
        tempwidth = 35;
    }

    /* ********************************************************* */
    // HERO & LANDING
    $("#play_pause").live("click",
    function () {
        if ($('#hero .stage').length > 0) {
            if ($(this).hasClass("pause")) {
                $('#hero .stage').cycle('pause');
                $(this).removeClass("pause").addClass("play");
            } else if ($(this).hasClass("play")) {
                $('#hero .stage').cycle('resume');
                $(this).removeClass("play").addClass("pause");
            }
        }

        if ($('#lander-hero .images').length > 0) {
            if ($(this).hasClass("pause")) {
                $('#lander-hero .images').cycle('pause');
                $(this).removeClass("pause").addClass("play");
            } else if ($(this).hasClass("play")) {
                $('#lander-hero .images').cycle('resume');
                $(this).removeClass("play").addClass("pause");
            }
        }
    });

    /* ********************************************************* */
    // INLINE BLOG POST
    /*IW updated*/
    if ($("#inline-blog").length > 0) {

        $('.blog-posts').cycle({
            fx: 'fade',
            speed: 10,
            timeout: 12000,
            pager: '#inlineblogpager'
        });
        $('.blog-posts').cycle("pause");
        $("#inline-blog-pager-count").html($('.blog-posts .article').length);

    }

    /* ****************************************** */
    /*IW updated*/
    $("#internal-nav li a").click(function () {

        $("#internal-nav li").attr("class", "");
        $(this).parent().addClass("selected");

        $(".tab_content").css("display", "none");
        $($(this).attr("href")).css("display", "block");

        /* IW changed */
        if (typeof googlemap == 'undefined') {
            alert("No Map");
        } else {
            google.maps.event.trigger(googlemap, "resize");
        }

        return false;
    });

    $("#rate_it .rating-cancel").removeClass("rating-cancel").addClass("ha-ha").css("display", "none");

    /* RAINING BLOOD */
    /*if ($(".active-weather").length > 0) {
    $.ajax({
    url: "includes/weather.php",
    cache: false,
    success: function (xmlstr) {
    try {

    xmlDoc = $.parseXML(xmlstr);
    $xml = $(xmlDoc);


    for (z = 0; z < 7; z++) {

    if (z == 0) {
    zeroday = $xml.find('temperature[type="maximum"] value').eq(0).text() + "&deg;";
    if ($xml.find('temperature[type="minimum"] value').eq(0).text() == "") {
    zeroday += "/" + $xml.find('temperature[type="maximum"] value').eq(0).text() + "&deg;";
    } else {
    zeroday += "/" + $xml.find('temperature[type="minimum"] value').eq(0).text() + "&deg;";
    }
    $("#day_0 .hi-lo").html(zeroday);
    }

    $("#day_" + (z + 1) + " strong").html(getDayOfWeek($xml.find('time-layout[summarization="24hourly"] start-valid-time').eq(z).text()));
    $("#day_" + (z + 1) + " .high").html($xml.find('temperature[type="maximum"] value').eq(z).text() + "&deg;");
    if ($xml.find('temperature[type="minimum"] value').eq(z).text() == "") {
    $("#day_" + (z + 1) + " .low").html($xml.find('temperature[type="maximum"] value').eq(z).text() + "&deg;");
    } else {
    $("#day_" + (z + 1) + " .low").html($xml.find('temperature[type="minimum"] value').eq(z).text() + "&deg;");
    }
    }

    } catch (e) {
    // do nothing
    alert(e);
    }
    }
    });

    $.ajax({
    url: "includes/current.php",
    cache: false,
    success: function (xmlstr) {
    try {

    xmlDoc = $.parseXML(xmlstr);
    $xml = $(xmlDoc);

    $("#current_weather_time") = $xml.find('observation_time').eq(0).text();

    $("#current_weather_wind_dir") = $xml.find('wind_dir').eq(0).text();
    $("#current_weather_wind_mph") = $xml.find('wind_mph').eq(0).text();

    $("#current_weather_degrees") = $xml.find('temp_f').eq(0).text();
    $("#current_weather_wind_chill") = $xml.find('windchill_f').eq(0).text();
                    
    } catch (e) {
    // do nothing
    alert(e);
    }

    }
    });
    }*/
});

function moveinlineblog(dir) {
    $('.blog-posts').cycle(dir);
    $('.blog-posts').cycle('pause');
}

function movelander(dir) {
    $('#lander-hero .images').cycle(dir);
    pause_lander();
}

function movelisting(dir) {
    $('#listing-image-rotator').cycle(dir);
    // pause_lander();
}

function pause_homepage() {
    if ($("#play_pause").hasClass("pause")) {
        $("#play_pause").removeClass("pause").addClass("play");
    }
    $('#hero .stage').cycle('pause');
}

function play_homepage() {
    if ($("#play_pause").hasClass("play")) {
        $("#play_pause").removeClass("play").addClass("pause");
    }
    $('#hero .stage').cycle('resume');
}

function pause_lander() {
    if ($("#play_pause").hasClass("pause")) {
        $("#play_pause").removeClass("pause").addClass("play");
    }
    $('#lander-hero .images').cycle('pause');
}

/* ********************************* */
/* ROLL OVER MAP FUNCTIONALITY */

function modal_hs(view) {
    $("#map-modal").css("display", view);
    return false;
}

function map_hl(img, txt) {
    if (txt == '') { txt = "Click an area to select a region of Virginia"; }
    $("#virginia_map").attr("class", img);
    $("#map_text").html(txt)
}

function hide_map(val) {
    $("#region-name").val(val);
    modal_hs('none');
    return false;
}

function getDayOfWeek(dateval) {
    var weekday = new Array(7);
    weekday[0] = "Sun";
    weekday[1] = "Mon";
    weekday[2] = "Tue";
    weekday[3] = "Wed";
    weekday[4] = "Thu";
    weekday[5] = "Fri";
    weekday[6] = "Sat";

    temp = dateval.split("T");
    dateparts = temp[0].split("-");
    var currdate = new Date(dateparts[0], dateparts[1], dateparts[2]);
    return weekday[currdate.getDay()];
}

$(document).ready(function () {
    // Collapse listing groups on trip planner
    $('.listing-group h3:first-child').click(function (e) {
        e.preventDefault();
        $(this).next('.horizontal-listings').animate({
            height: "toggle"
        }, 240);

        if ($(this).find(".listing-group-arrow").attr("src").indexOf("close.gif") == -1) {
            $(this).find(".listing-group-arrow").attr("src", "/resources/icons/arrow_close.gif");
        } else {
            $(this).find(".listing-group-arrow").attr("src", "/resources/icons/arrow_open.gif");
        }
    });

    $('#select-all-listings').toggle(function () {
        $(this).empty().html("Select None");
        $('input.delete-me').attr("checked", true);

        toRemove = $('input.delete-me:checked').length;
        $('.remove-count').empty().append("(" + toRemove + ")");
        if (toRemove == 0) {
            $('.remove-count').empty();
        }
    }, function () {
        $(this).empty().html("Select All");
        $('input.delete-me').attr("checked", false);

        toRemove = $('input.delete-me:checked').length;
        $('.remove-count').empty().append("(" + toRemove + ")");
        if (toRemove == 0) {
            $('.remove-count').empty();
        }
    });

    $("#options-all").toggle(function () {
        $('.horizontal-listings').hide();
        $('.listing-group-arrow').attr("src", "/resources/icons/arrow_close.gif");
    }, function () {
        $('.horizontal-listings').show();
        $('.listing-group-arrow').attr("src", "/resources/icons/arrow_open.gif");
    });
});

/* ---------------------------------------------- --------------- ----------------------------------------------------- */
/* ---------------------------------------------- trip-planner.js ----------------------------------------------------- */
/* ---------------------------------------------- --------------- ----------------------------------------------------- */
(function ($) {
    /** expose a simple API **/
    $.extend($, {
        tripPlanner: {
            /**
            * The URL of the trip planner - used to set the added destination click in the default implementation.
            */
            tripPlannerUrl: "", //Set to give the location of the trip planner.  Should be an absolute URL (e.g. /tripPlanner/home).
            /**
            * Updates the current DOM with the correct classes and refreshes the cache.
            */
            updateTripPlanner: function () {
                $(window).trigger("updateTrips");
            },            
            /**
            * Reports a list of all ids and associated information: id, the dom node, computed id (cid), and type (C for content D for data).
            */
            reportIds: function () { //Exposed for debugging
                var ids = [];

                var curType;
                if ($(this).attr("vtc-tp:tripContentId") !== undefined)
                    curType = "C";
                else if ($(this).attr("vtc-tp:tripDataId") !== undefined)
                    curType = "D";
                else if ($(this).attr("vtc-tp:tripCityId") !== undefined)
                    curType = "T";
                else if ($(this).attr("vtc-tp:tripLocalityId") !== undefined)
                    curType = "L";

                $('.trip-planner').each(function () {
                    var id = $(this).attr("vtc-tp:tripContentId") || $(this).attr("vtc-tp:tripDataId") || $(this).attr("vtc-tp:tripCityId") || $(this).attr("vtc-tp:tripLocalityId"),
						type = curType,
						cid = type + id;
                    ids.push({
                        id: id,
                        node: this,
                        cid: cid,
                        type: type
                    });
                });
                return ids;
            },
            /**
            * Finds the ID
            * @param {Object} cid
            */
            findId: function (cid) {
                return findItem(cid);
            },
            /**
            * Clears the cookie
            */
            clearCookie: function () {
                writeCookie(null);
            },
            /**
            * Removes the ID 
            * @param {Object} cid
            */
            removeId: function (cid) {

                oldCookie = getCookie();
                oldCookieData = oldCookie.split(',');

                //remove the value from the cookie
                //D74092,D74754,D73092,D37582,D26726,D37953
                oldCookie = "";
                for (var i = 0; i < oldCookieData.length; i++) {
                    if (oldCookieData[i] != cid)
                        oldCookie += "," + oldCookieData[i];
                }

                if (oldCookie.length > 1 && oldCookie.substr(0, 1) == ",")
                    oldCookie = oldCookie.substr(1);

                //Update the final cookie and write it again.
                writeCookieString(oldCookie);
            }
        }
    });

    //Private function
    /**
    * retreives the item using an optimized selector - or backfills using older techniques for IE6
    * @param {Object} tripId
    */
    function findItem(tripId) {
        //Try the selector:
        if (tripId) {
            var id = tripId.substring(1);
            var type = tripId.substring(0, 1);

            var typeAtt;
            if (type == "D")
                typeAtt = "tripDataId";
            else if (type == "T")
                typeAtt = "tripCityId";
            else if (type == "C")
                typeAtt = "tripContentId";
            else if (type == "L")
                typeAtt = "tripLocalityId";

            var sel = ".trip-planner[vtc-tp\\:" + typeAtt + "='" + id + "']";
            var item = $(sel);
            if (item.length === 0) {
                $(".trip-planner").each(function () {
                    if ($(this).attr("vtc-tp:" + typeAtt) == tripId) {
                        item = $(this);
                        return false;
                    }
                });
            }
            return item;
        }
    }
    /**
    * Writes the managed cookie
    * @param {Object} oldCookieData
    */
    function writeCookie(oldCookieData) { //Centralize writing
        if (oldCookieData) {
            oldCookieData = oldCookieData.join(',');
        }
        writeCookieString(oldCookieData);
    }

    function writeCookieString(s) { //Centralize writing        
        $.cookie("trip_planner", s, { path: '/', expires: 30 });
    }
    /**
    * Reads the managed cookie
    */
    function getCookie() {
        return $.cookie("trip_planner") || "";
    }
    //Register custom 'updateTrips' on document object.
    $(document).bind('updateTrips', function () {
                
        //for each element in comma-separated list tripIdsCsv, assign the trip-planned class to the corresponding div
        function assignAllTripDivClasses(tripIdsCsv, elem) {                            
            if (tripIdsCsv) {
                var list = tripIdsCsv.split(',');
                for (var i = 0, len = list.length; i < len; i++) {
                    var tripId = list[i];                     
                    var item = findItem(tripId);                     
                    if (item) {                                               
                        item.addClass("trip-planned");                        
                    }
                }
            }            
            
            //show all trip planners - they were temp hidden while the appropriate button class was applied
            $(".trip-planner").css("display", "block");
        }

        function hardAjaxError(tripPlannerElem) {
            //if error is from a specific element being clicked, make sure it doesn't say 'added to trip planner'
            if (tripPlannerElem)
                $(tripPlannerElem).removeClass("trip-planned").addClass("trip-planner");
                       
            alert('Error: Trip planner is currently experiencing a server communication failure.  Please try again later.');
        }

        function testSoftError(strRv, tripPlannerElem, successCallback) {

            if (strRv.match(/^Error:/i)) {
                if (tripPlannerElem && $(tripPlannerElem).hasClass("trip-planned")) {
                    $(tripPlannerElem).removeClass("trip-planned").addClass("trip-planner");
                }

                alert('Error: Trip planner is currently experiencing a server communication failure.  Please try again later.');                
            }
            else if (successCallback) {
                successCallback(strRv, tripPlannerElem);
            }
        }

        function getListOfTripsFromDB(username, tripPlannerElem) {
            
            $.ajax({
                url: '/handlers/TripPlanner.ashx?mode=getItems',
                type: 'POST',
                data: { },
                dataType: 'text',
                success: function (data) {                    
                    testSoftError(data, tripPlannerElem, assignAllTripDivClasses);                          
                },
                error: function (request, status, error) {                    
                    hardAjaxError(tripPlannerElem);
                }
            });
        }

        function addTripToDB(username, tripPlannerElem) {
            
            var itemType, itemId; 

            if (itemId = $(tripPlannerElem).attr("vtc-tp:tripContentId"))  { itemType = "C"; }
            else if (itemId =  $(tripPlannerElem).attr("vtc-tp:tripDataId"))  {itemType = "D"; }                
            else if (itemId = $(tripPlannerElem).attr("vtc-tp:tripCityId")) { itemType = "T"; }
            else if (itemId = $(tripPlannerElem).attr("vtc-tp:tripLocalityId")) { itemType = "L"; }
                                    
            if ($(tripPlannerElem).hasClass("trip-planned")) {
                window.location = $.tripPlanner.tripPlannerUrl;
            }
            else {                                                                          
                $.ajax({
                    url: '/handlers/TripPlanner.ashx?mode=addItems',
                    type: 'POST',
                    data: { siteUserName: username, queueItemId : itemId, queueItemType : itemType },
                    dataType: 'text',
                    success: function (data) {                        
                        testSoftError(data, tripPlannerElem, null); 
                    },
                    error: function (request, status, error) {                        
                        hardAjaxError(tripPlannerElem);
                    }
                });

                $(tripPlannerElem).addClass("trip-planned");
            }
        }
        
        var $tripPlannerElems = $(".trip-planner");
                                
        /** wire up each trip planner div attributes & click handlers**/
        $tripPlannerElems.each(function () {
            //Grab the attribute
            var tripId, pTripId; 

            if (tripId = $(this).attr("vtc-tp:tripContentId"))  { pTripId = "C"+tripId; }
            else if (tripId = $(this).attr("vtc-tp:tripDataId"))  { pTripId = "D"+tripId; }
            else if (tripId = $(this).attr("vtc-tp:tripCityId"))  { pTripId = "T"+tripId; }
            else if (tripId = $(this).attr("vtc-tp:tripLocalityId"))  { pTripId = "L"+tripId; }

            $(this).removeClass("trip-planned"); // Clean the trip just in case
            $(this).unbind("click.tripPlan");

            if (tripId) {
                $(this).data("tripId", pTripId);

                //Fix position: in case we forget to 'relative' the container.
                if ($(this).parent().css("position") != "relative") {
                    $(this).parent().css("position", "relative");
                }
                //if logged in, initially hide all trip-planner buttons until ajax callback assigns appropriate state (ie if it has been added  or not)
                $(this).css("display", GetSiteUsername() ? "none" : "block");                
                
                //assign click handler
                $(this).bind('click.tripPlan', function () {
                    $(this).trigger("beforeTripPlanClick");

                    var curSiteUserName = GetSiteUsername();

                    if (curSiteUserName) {
                        addTripToDB(curSiteUserName, this);  
                        //todo add error handling on success callback. (use similar functions)
                    }
                    else {
                        //Here we need to update the cookie, so grab it directly from the browser
                        var oldCookie = getCookie();
                        var oldCookieData = oldCookie.split(',');
                        var trip = $(this).data('tripId');
                        if ($.inArray(trip, oldCookieData) >= 0) {                        
                            window.location = $.tripPlanner.tripPlannerUrl;
                        }
                        else {
                            oldCookieData.push(trip); //Push the trip ID onto the stack of IDs
                            $(this).addClass("trip-planned");
                        }
                        //Update the final cookie and write it again.
                        oldCookieData = $.grep(oldCookieData, function (x) { return !!x; }); //removes any 'blank' entries - a bug when we're dealing with a blank cookie.
                        writeCookie(oldCookieData);
                    }
                });
            }
            else {
                if (debug) {
                    alert('no trip id!');
                }
            }
        });

        if ($tripPlannerElems.length) {
            //set appropriate initial classes on trip planner div elements
            var debug = false;        
            var siteUserName = GetSiteUsername();
            if (siteUserName) {
                getListOfTripsFromDB(siteUserName, null);            
            }
            else
            {
                var cookie = getCookie();        
                //setup if not there
                if (debug && !cookie) {
                    writeCookie(["C123211598933345", "D123211598933346"]);
                }

                assignAllTripDivClasses(cookie, null);
            }
        }
        
    });
//    $(function () { //Basic update trips on load.  This could go away
//        $(document).trigger('updateTrips');
//    });
})(jQuery);


/* ---------------------------------------------- ------------ -------------------------------------------------------- */
/* ---------------------------------------------- customvtc.js -------------------------------------------------------- */
/* ---------------------------------------------- ------------ -------------------------------------------------------- */


/******* Event Search *******/
$(document).ready(function () {
    //clear text inputs for event and hotel search control/widgets
    $("input[type=text].eventSearch").focus(function () {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function () {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });

    $(".content-wrapper table tr:odd td").addClass("ieAltRows");
});


/****** Trip Ideas *******/
var showingMoreIdeas = false;
function MoreTripIdeas() {

    if (!showingMoreIdeas) {
        $(".tripIdeas > li").addClass("show");

        //now how the "Show More" button
        $(".tripIdeasMore").hide();
    }
    else
        $(".tripIdeas > li:gt(4)").removeClass("show");  //index is 0 based.

    showingMoreIdeas = !showingMoreIdeas;
}

/******* Recently Viewed *******/
function SetRecentlyViewed(url, title) {

    if (url && title && url != "" && title != "" && url.match(/^\/Templates\/Listing.aspx?.*stageListingId=.*$/i) == null) {
        
        //get the recently viewed cookie value
        var oldVal = $.cookie("recently_viewed") || "";
        var arr = oldVal.split('|');

        //append the new url and title to the beginning of the array
        arr.unshift(title);
        arr.unshift(url);  //url will be at the top of the array

        //get the last 10 views (last 20 array items) and join them into one string
        var hash = new Array();
        var str = "";
        var max = 10;
        for (var i = 0; i < arr.length - 1 && i < (max*2)-1; i+=2) {
                   
            if (typeof(hash[arr[i]]) == 'undefined') {
                if (arr[i] && arr[i].length > 0)
                    str += arr[i] + "|" + arr[i + 1] + "|";

                hash[arr[i]] = arr[i + 1];
            }
        }

        //alert(str);

        //put the new value in the cookie
        $.cookie("recently_viewed", str, { path: '/', expires: 30 });
    }
}

/********** Mapping/What's Nearby *********************/

function addMarker(map, latlng, iconRef) {

    var marker;

    if (iconRef == null)
        iconRef = "/resources/icons/map-marker.png";

    if (latlng != null) {

        marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: iconRef
        });
        markers.push(marker);
    }

    return marker;
}

function doAssociateWithInfoWindow(curMarker, infowindow, map, listingInfo) {
    google.maps.event.addListener(curMarker, 'click', function () {
        var contentLine1 = listingInfo.RowNum + ". <a style='text-decoration:none;' href='" + listingInfo.ListingLink + "'> " + listingInfo.ShortenedName + "</a>";
        var contentLine2 = listingInfo.FormattedAddress;
        var contentLine3 = "<a style='text-decoration:none;' href='" + listingInfo.ListingLink + "'>More Info</a>";
        if (listingInfo.DoDrivingDirs)
            contentLine3 += "| <a style='text-decoration:none;' href='#DrivingDirections' rel='" + listingInfo.FullAddress + "' class='driving-directions'>Driving Directions</a>";

        contentLine3 += "<div class='trip-planner rightBottom' vtc-tp:tripDataId='" + listingInfo.ListingId + "'><!-- --></div>";

        infowindow.setContent("<div style='height:95px;overflow:hidden;width=300px;'>" + contentLine1 + "<br/>" + contentLine2 + "<br/>" + contentLine3);
        infowindow.open(map, curMarker);

        $.tripPlanner.tripPlannerUrl = listingInfo.TripPlannerUrl;
        $(document).trigger('updateTrips');

        $('.driving-directions').click(function (e) {
            var address = $(this).attr("rel");
            $('.map-directions').slideDown(140);
            $('.listings').fadeOut(240);
            $('.listing').fadeOut(240);
            $('.map-filters').fadeOut(240);
            $('.pagination').hide();
            $('.dir_end').attr("value", address);
            $('.route-type-fastest').attr('checked', true);
            $('.route-display-map').attr('checked', true);
            $('.directions-panel').hide();
            infowindow.close();
            //toHere("internal-nav");
            //e.preventDefault();
        });
    });
}

//function factory- due to closure
function associateWithInfoWindow(curMarker, infowindow, map, listingInfo) {    
    return function() { doAssociateWithInfoWindow(curMarker, infowindow, map, listingInfo); }
}

function showNearbySites(sites, map, centerPt, infowindow) {

    var bounds = new google.maps.LatLngBounds();
    var curMarker;

    if (sites != null && sites.length > 0) {

        for (i = 0; i < sites.length; i++) {

            var myLatlng = new google.maps.LatLng(sites[i].Latitude, sites[i].Longitude);

            curMarker = addMarker(map, myLatlng, sites[i].MapIconPath);
            
            bounds.extend(myLatlng);

            var bindToInfoWindow = associateWithInfoWindow(curMarker, infowindow, map, sites[i]);
            bindToInfoWindow();

        }

        map.fitBounds(bounds);

    }

    if (centerPt != null) {
        bounds.extend(centerPt);
        map.fitBounds(bounds);
    }
}

/**************** VaMap *********************/
$(document).ready(function () {
    var default_title = "About Virginia";
    var default_text = "Place your mouse over the map to learn more about Virginia's nine distinct regions.";
    
    $('#map-virginia .region').hover(
					function () {					    
					    $(this).find('.region-img').show();
					    $('#map-virginia .text-box .title').text($(this).find('.region-img').attr('title'));
					    $('#map-virginia .text-box .text').text($(this).find('.region-img').attr('alt'));
					},
					function () {
					    $(this).find('.region-img').hide();
					    $('#map-virginia .text-box .title').text(default_title);
					    $('#map-virginia .text-box .text').text(default_text);
					}
    );
});


/**************** Groups, Sports, and Meetings ********************/

function GSMMapGo() {
    var region = $(".mapFormSelect #srchRegion").val();
    var url = $(".mapFormSelect .srchType").val();

    if (region != "0" && region != "-1" && region != "") {
        if (url.indexOf("?") < 0)
            url += "?regionid=" + region;
        else
            url += "&regionid=" + region;
    }    
    window.location.href = url;
    return false;
}

function hide_map(val) {
    $(".mapFormSelect #srchRegion").val(val);
	return false;
}

/******************* Login, Registration, and Facebook *********************/
function statusChangeHandler(response) {
    if (response.status === "connected" && response.authResponse && response.authResponse.accessToken) {
        $("#fbLoginProgress").show();
        FacebookLoginRedirect(response.authResponse.accessToken);
    }
}

function FacebookLogout() {
    //User types: 0 = none, 1 = custom, 2 = facebook, 3 = google 
    var userType = GetSiteUserType();

    if (userType == 1)
        FormsAuthSignout();
    else {        
        FB.Event.unsubscribe('auth.statusChange', statusChangeHandler);
        
        FB.getLoginStatus(function (response) {                        
            if (response.status === "connected" && response.authResponse && response.authResponse.accessToken) {
                FB.logout(function (response) {                    
                    //user is now logged out of Facebook
                    FormsAuthSignout();
                });
            }
            else {
                //sign out of forms authentication
                FormsAuthSignout();
            }
        });
      }
}

function FormsAuthSignout() {
    //use AJAX to pass to membership handler
    $.ajax({
        url: '/handlers/membership.ashx?mode=logout',
        type: 'POST',
        data: {},
        dataType: 'text',
        success: function (data) {
            window.location.href = GetLogoutRedirectUrl();
        }
    });
}

$(document).ready(function () {
    $('#loginDialog').jqm();
    $('#fpassword').jqm();

    //set up the login textboxes to log the user in when they hit the enter key
    $("#loginDialog .login-password, #loginDialog .login-email").keydown(function (e) {
        if (e.which == 13) {
            e.preventDefault(); //don't submit the form in IE
            LoginUser();
            return false;
        }
    });

    //make sure that hitting enter in the other textboxes doesn't submit the form in IE
    //add this class to any textbox that shouldn't postback when enter key is hit
    $(".stopFormSubmit").keydown(function (e) {
        if (e.which == 13) {
            e.preventDefault(); //don't submit the form in IE
            return false;
        }
    });

    //handle the enter key on the forgot password modal
    $(".txtForgotPwdEmail").keydown(function (e) {
        if (e.which == 13) {
            e.preventDefault(); //don't submit the form in IE
            ProcessForgotPassword();
            return false;
        }
    });

    //handle the enter key on the change password modal
    $("#change-password input[type='password']").keydown(function (e) {
        if (e.which == 13) {
            e.preventDefault(); //don't submit the form in IE
            ChangeUserPassword();
            return false;
        }
    });

    //set up placeholders on textareas
    //first see if the browser already supports it
    var input = document.createElement('input');
    var phSupported = ('placeholder' in input);
    if (!phSupported) {
        $("textarea[placeholder]").each(function () {
            //initially set the text
            var phText = $(this).attr("placeholder");
            $(this).val(phText);

            $(this).focus(function () {
                if ($(this).val() == phText) { $(this).val(""); }
            }).blur(function () {
                if ($(this).val() == "") { $(this).val(phText); }
            });
        });

        // Clear at window reload to avoid it stored in autocomplete
        $(window).bind("unload", function () {
            $("textarea[placeholder]").each(function () {
                var phText = $(this).attr("placeholder");
                if ($(this).val() == phText) { $(this).val(""); }
            });
        });
    }

    //check the query string to see if we need to show the login dialog
    var m = getQueryString("m");
    var username = GetSiteUsername();
    if (m == "login" && (!username || username == "")) {
        ShowLoginModal(null);
    }
});

function ShowLoginModal(mode) {

    if (mode && mode.length > 0) {
        $("#loginModeData").val(mode);
        $(".registerLink").each(function () {
            var url = $(this).attr("href");
            if (url.indexOf("?") < 0)
                url += "?mode=" + mode;
            else
                url += "&mode=" + mode;
            $(this).attr("href", url);
        });
    }

    $("#loginDialog .processing").hide();
    $('#loginDialog').jqmShow();    
    $('.login-email').blur();    
}

function ShowForgotPassword() {
    $('.forgotpassword').show();
    $("#forgotpwdError").hide();
    $('.pw-confirm').hide();
    $("#txtForgotPwdEmailError").hide();
    $("#fpassword .processing").hide();

    $(".txtForgotPwdEmail").val("");

    $('#loginDialog').jqmHide();
    $('#fpassword').jqmShow();
}

function ProcessForgotPassword() {    
    $("#forgotpwdError").hide();
    $("#txtForgotPwdEmailError").hide();

    var email = $(".txtForgotPwdEmail").val();

    //validate the email address
    if (!email || email == "" || ValidateEmailRegex(email) == false) {
        $("#txtForgotPwdEmailError").show();
        return;
    }

    $("#fpassword .processing").show();
    
    //use AJAX to pass to membership handler
    $.ajax({
        url: '/handlers/membership.ashx?mode=forgotpwd',
        type: 'POST',
        data: { email: email },
        dataType: 'text',
        success: function (data) {
            $("#fpassword .processing").hide();            
            if (data == "success") {
                $('.forgotpassword').hide();
                $('.pw-confirm').show();
            }
            else {
                $("#forgotpwdError").html(data).show();
            }
        },
        error: function (request, status, error) {

            //hide the progress icon
            $("#fpassword .processing").hide();

            //alert(request.responseText);
            alert("An error occurred while resetting your password.  Please try again later.");
        }
    });    
}

function ValidateLoginEmail(sender, args) {
    //check the placeholder     
    var ph = $(".login-email").attr("placeholder");
    if (args.Value == "" || args.Value == ph)
        args.IsValid = false;
    else
        args.IsValid = ValidateEmailRegex(args.Value); //method in combinedvtc.js
}

function ValidateLoginPassword(sender, args) {
    //check the placeholder    
    //make sure to select with type='password' to workaround placeholder fake input issue        
    var ph = $("input[type='password'].login-password").attr("placeholder");
    var val = "";
    if ($("input[realType='password'].login-password").length > 0) //ie7
        val = $("input[realType='password'].login-password").val();
    else
        val = $("input[type='password'].login-password").val();
        
    if (val == "" || val == ph)
        args.IsValid = false;
    else
        args.IsValid = true;
}

function ValidateLoginPasswordLength(sender, args) {
    //make sure to select with type='password' to workaround placeholder fake input issue 
    var val = $("input[type='password'].login-password").val();
    if (!val || val == "")
        args.IsValid = true;
    else if ((val.length > 0 && val.length < 6) || val.length > 20)
        args.IsValid = false;
    else
        args.IsValid = true;
}

function LoginUser() {

    //validate the "registration" group
    if (Page_ClientValidate("login")) {

        //clear the error message
        $("#loginError").html("").hide();

        //get the field values
        var rem = "0";
        var email = $(".login-email").val();

        //make sure to select with type='password' to workaround placeholder fake input issue 
        var pwd = "";
        if ($("input[realType='password'].login-password").length > 0) //ie7
            pwd = $("input[realType='password'].login-password").val();
        else
            pwd = $("input[type='password'].login-password").val();
        
        if ($('#rememberme').prop('checked'))
            rem = "1";

        if (email == $(".login-email").attr("placeholder"))
            email = "";

        if (pwd == $(".login-password").attr("placeholder"))
            pwd = "";

        //show progress icon
        $("#loginDialog .processing").show();

        //use AJAX to pass to membership handler
        $.ajax({
            url: '/handlers/membership.ashx?mode=login',
            type: 'POST',
            data: { email: email, password: pwd, remember: rem },
            dataType: 'text',
            success: function (data) {
                if (data == "success") {
                    //redirect to the ATP page
                    window.location = GetATPAdvancedUrl();
                }
                else {
                    //hide the progress icon
                    $("#loginDialog .processing").hide();

                    //show the error on this page
                    var msg = "Wrong email address or password";

                    $("#loginError").html(msg).show();
                }
            },
            error: function (request, status, error) {

                //hide the progress icon
                $("#loginDialog .processing").hide();

                //alert(request.responseText);
                alert("An error occurred while logging you in.  Please try again later.");
            }
        });
    } //end of if valid
} //end of LoginUser


function ClearValidationErrors(group) {
    for (var i = 0; i < Page_Validators.length; i++) {
        if (!group || Page_Validators[i].validationGroup == group)
            Page_Validators[i].style.display = "none";
    }
}

function getQueryString(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
