

var $J = jQuery.noConflict();
var $j = $J; // easier to type

// Global Variables
var bootstrapSize = "?";
var bootstrapRadio;
var columnSize = 0;
var reservationsArrival = $J("#reservationsArrival");
var reservationsDeparture = $J("#reservationsDeparture");
var childrenDropdown = $J("select[name*='_child']");
var singleRoomChildrensAge = $J("#singleRoomChildrensAge");
var multipleRoomChlidrensAge = $J(".multipleRoomChildrensAge");
var loadingContainer = $J(".loadingContainer");
var loadingAnimation = $J(".loadingAnimation");
var focusVal = null;
var footerLinksInNewWindow;

var weatherJsonData;
var today = new Date();
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);

var dates;
var datepicker;
var datepickerMaxDate = new Date();
datepickerMaxDate = new Date(datepickerMaxDate.setMonth(datepickerMaxDate.getMonth() + 36)); // 36 months from today
var poiInfoWindowContent;
var hotelAddressforDirections;
var hotelNameForPOIInfoWindow;
var resizeTimer;
var startDate;
var endDate;
var QBonce = 0;
var IQBonce = 0;

// Get URL Variables Plugin
jQuery.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return jQuery.getUrlVars()[name];
    }
});

// Change for the group landing page to 
// open all links in new browser window
$j(document).ready(function () {
    if (footerLinksInNewWindow) {
        $j("#footerLinksContainerDiv a").each(function () {
            this.setAttribute("target", "_blank");
        }
        );
    }
    //French translation for Utility navigation
    var lang = $j("#secondary-language").data("language");
    if (lang === "fr-CA") {
        $j(".utility-nav").addClass("fr-lang");
    }
});

if ($J.getUrlVar('StartDate') && !$J.getUrlVar('EndDate')) {
    startDate = new Date($J.getUrlVar('StartDate').replace(/%2F/gi, "/"));
    endDate = new Date($J.getUrlVar('StartDate').replace(/%2F/gi, "/"));
    endDate.setDate(startDate.getDate() + 1);
} else if (!$J.getUrlVar('StartDate') && $J.getUrlVar('EndDate')) {
    startDate = today;
    endDate = new Date($J.getUrlVar('EndDate').replace(/%2F/gi, "/"));
} else if ($J.getUrlVar('StartDate') && $J.getUrlVar('EndDate')) {
    startDate = new Date($J.getUrlVar('StartDate').replace(/%2F/gi, "/"));
    endDate = new Date($J.getUrlVar('EndDate').replace(/%2F/gi, "/"));
}
else if ($J('#myTab').length < 1) {
    if ($j('#reservationsArrival').val() && $j('#reservationsDeparture').val()) {
        startDate = new Date($j('#reservationsArrival').val().replace(/%2F/gi, "/"));
        endDate = new Date($j('#reservationsDeparture').val().replace(/%2F/gi, "/"));
    } else {
        startDate = today;
        endDate = tomorrow;
    }
} else {
    startDate = today;
    endDate = tomorrow;
}

var defaultDates = [startDate, endDate];

//console.log(defaultDates);

function isTouchSupported() {
    return false;
    var msTouchEnabled = window.navigator.msMaxTouchPoints;
    var generalTouchEnabled = "ontouchstart" in document.createElement("div");

    if (msTouchEnabled || generalTouchEnabled) {
        return true;
    }
    return false;
}

var touchEnabled = isTouchSupported();

var Enquire = function () {
    this.addListener = function (functionName) {
        enquire.register("(min-width: 1200px)", {
            match: function () {
                functionName("LG");
            }
        }).register("(min-width: 992px) and (max-width: 1199px)", {
            match: function () {
                functionName("MD");
            }
        }).register("(min-width: 768px) and (max-width: 991px)", {
            match: function () {
                functionName("SM");
            }
        }).register("(max-width: 767px)", {
            match: function () {
                functionName("XS");
            }
        });
    }
};

function updateBootstrapSize(size) {
    // console.log(size + " - Bootstrap Size");
    bootstrapSize = size;
    $J("#bootstrapRadio").children("input").removeAttr("checked");
    $J("#bootstrapRadio").children("input[value='" + bootstrapSize + "']").attr("checked", "true").trigger('click');
}

// Setup Bootstrap Size
function registerBootstrapSize() {
    try {
        if (!$J("#bootstrapRadio").length) {
            var hiddenBootstrapDiv = $J('<div id="bootstrapRadio"></div>').hide();

            $J(["XS", "SM", "MD", "LG"]).each(function (index, value) {
                $J('<input />', { type: "radio", name: "bootstrapSize", val: value, title: value }).appendTo(hiddenBootstrapDiv);
            });

            $J(hiddenBootstrapDiv).appendTo("body");
            $J("#bootstrapRadio").children("input[value='XS']").attr("checked", "true").trigger('click');
        }
        bootstrapRadio = $J("#bootstrapRadio").children("input[name='bootstrapSize']");
        var registerSize = new Enquire;
        registerSize.addListener(updateBootstrapSize);
    } catch (e) { }
    $J("body").attr("data-bootstrap-size", bootstrapSize);
}
registerBootstrapSize();


// Google Map to display hotel(s) on a hotel page or destination detail page.
var zoomLevel;
var bounds;
function initialize() {

    if (typeof customZoomLevel == 'undefined')
        zoomLevel = 16;
    else
        zoomLevel = customZoomLevel;
    mapOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById('hotelGoogleMap'), mapOptions);

    addHotelsOnMap()
}


function addHotelsOnMap() {
    bounds = new google.maps.LatLngBounds();
    $J(DestinationHotelsListJson).each(function (i) {
        var url = DestinationHotelsListJson[i].Url;
        var hotelDisplayImage = DestinationHotelsListJson[i].HotelDisplayImage;
        var hotelName = DestinationHotelsListJson[i].DisplayName;
        hotelNameForPOIInfoWindow = hotelName;
        var address1 = DestinationHotelsListJson[i].Address;
        var address2 = DestinationHotelsListJson[i].City + ", " + DestinationHotelsListJson[i].State + ", " + DestinationHotelsListJson[i].Zipcode;
        var addressNoSpace = address1.replace(/ /g, "+") + ",+" + address2.replace(/ /g, "+");
        hotelAddressforDirections = addressNoSpace;
        var phone = DestinationHotelsListJson[i].Phonenumber;
        var fax = DestinationHotelsListJson[i].Fax;
        var hotelIntroContent = DestinationHotelsListJson[i].MapContent;

        var content = '<div class="row mapTopRow">';
        content = content + '<div class="col-sm-6">';
        if (hotelDisplayImage != "")
            content = content + '<a href=' + url + '>' + hotelDisplayImage + '</a><br />';
        content = content + '</div>';
        content = content + '<div class="col-sm-6 mapHotelInfo">';
        if (hotelName != "" && hotelName != null)
            content = content + '<a href=' + url + '><strong class="mapHotelName">' + hotelName + '</a></strong>';
        if (address1 != "" && address1 != null)
            content = content + address1 + '<br />';
        if (address2 != "" && address2 != null)
            content = content + address2 + '<br />';
        if (phone != "" && phone != null)
            content = content + 'PHONE: ' + phone + '<br />';
        if (fax != "" && fax != null)
            content = content + 'CONCIERGE: ' + fax + '<br />';
        content = content + '</div>';
        content = content + '<div class="row">';
        if (addressNoSpace != "" && addressNoSpace != null)
            content = content + '<a class="mapDirectionIcon" href="http://www.maps.google.com?daddr=' + addressNoSpace + '" target="_blank">GET DIRECTIONS</a>' + '<br />';
        content = content + '<hr style="margin:10px 0">';
        if (hotelIntroContent != "" && hotelIntroContent != null)
            content = content + hotelIntroContent + '<br />';
        content = content + '</div>';
        content = content + '</div>';

        if (DestinationHotelsListJson[i].IsResort) {
            image = "/images/global/googleMapIcon_tide.png";
        }
        else {
            image = "/images/global/googleMapIcon_ocean.png";
        }

        var hotelLatLong = new google.maps.LatLng(DestinationHotelsListJson[i].Latitude, DestinationHotelsListJson[i].Longitude);
        var hotelMarker = new google.maps.Marker({
            map: map,
            position: hotelLatLong,
            icon: image
        });

        bounds.extend(hotelMarker.position);

        markerMgr.push(hotelMarker);

        google.maps.event.addListener(hotelMarker, 'click', (function (hotelMarker, i) {
            return function () {
                if (infowindow) {
                    infowindow.close();
                }
                infowindow = new google.maps.InfoWindow({ maxWidth: 300 });
                infowindow.setContent(content);
                infowindow.open(map, hotelMarker);
            }
        })(hotelMarker, i));
    });
    map.fitBounds(bounds);
    google.maps.event.addListenerOnce(map, 'bounds_changed', function () {
        var zoom = map.getZoom();
        map.setZoom(typeof zoom === "undefined" || zoom > zoomLevel ? zoomLevel : zoom);
    });
    google.maps.event.addListener(map, 'zoom_changed', function () {
        var zoomLevel = map.getZoom();
        center = map.getCenter();
        if (zoomLevel <= 14) {
            for (var i = 0; i < poiMarkerMgr.length ; i++) {
                poiMarkerMgr[i].setVisible(false);
                poiMarkerMgr[i].setMap(null);
            }
            arePoiOnMap = false;
        }
        if (zoomLevel > 14 && !arePoiOnMap) {
            center = center.replace(/\(/g, '');
            center = center.replace(/\)/g, '');
            center = center.replace(/\ /g, '');
            getJsonfromGoogle(center);
            arePoiOnMap = true;
        }
        if (startingCenter != center && zoomLevel > 14) {
            center = center.replace(/\(/g, '');
            center = center.replace(/\)/g, '');
            center = center.replace(/\ /g, '');
            getJsonfromGoogle(center);
            arePoiOnMap = true;
        }
    });
}

function getJsonfromGoogle(center) {
    $J.ajax({
        type: 'GET',
        url: '/services/GoogleMaps/GoogleMapsPlaces.ashx',
        data: { 'Requset': "PoiList", 'Location': center, 'Types': POITypes, 'Radius': 500 },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (json) {
            addPointsOfInterestToHotelMap(json);
        },
        error: function (error) {
            var x = error;
            //console.log(x);
        }
    });
}

function addPointsOfInterestToHotelMap(jsonPOI) {
    for (var i = 0; i < jsonPOI.results.length; i++) {
        var image = {
            url: jsonPOI.results[i].icon,
            scaledSize: new google.maps.Size(15, 15)

        }
        var markerPOI = new google.maps.Marker({
            map: map,
            position: jsonPOI.results[i].geometry.location,
            icon: image
        });
        poiMarkerMgr.push(markerPOI);
        google.maps.event.addListener(markerPOI, 'click', (function (markerPOI, i) {
            infowindow = new google.maps.InfoWindow({ maxWidth: 200 });
            return function () {
                var poiLocation = jsonPOI.results[i].geometry.location.lat + "," + jsonPOI.results[i].geometry.location.lng;
                getPoiDetails(jsonPOI.results[i].reference, poiLocation);

                infowindow.setContent(poiInfoWindowContent);
                infowindow.open(map, markerPOI);
            }
        })(markerPOI, i));
    }
}

function getPoiDetails(reference, poiLocation) {
    $J.ajax({
        async: false,
        type: 'GET',
        url: '/services/GoogleMaps/GoogleMapsPlaces.ashx',
        data: { 'Requset': "PoiDetails", 'Reference': reference },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (json) {
            //console.log(json);
            poiInfoWindowContent = '<p>';
            if (json.result.name != null)
                poiInfoWindowContent = poiInfoWindowContent + '<b>' + json.result.name + '</b><br />';
            if (json.result.formatted_address != null)
                poiInfoWindowContent = poiInfoWindowContent + json.result.formatted_address + '<br />';
            if (json.result.formatted_phone_number != null)
                poiInfoWindowContent = poiInfoWindowContent + 'Phone: ' + json.result.formatted_phone_number + '<br /><br />';
            if (json.result.website != null)
                poiInfoWindowContent = poiInfoWindowContent + '<a href="' + json.result.website + '" target="_blank">' + json.result.website.replace("http://", "") + '</a><br/>';
            if (json.result.formatted_address != null)
                poiInfoWindowContent = poiInfoWindowContent + '<a class="mapDirectionIcon" href="http://www.maps.google.com?daddr=' + json.result.formatted_address + '" target="_blank">GET DIRECTIONS</a>';
            poiInfoWindowContent = poiInfoWindowContent + '<a target="_blank" href="http://maps.google.com/?cbll=' + poiLocation + '&cbp=12,20.09,,0,5&layer=c"><img src="http://maps.googleapis.com/maps/api/streetview?size=200x75&location=' + poiLocation + '&heading=235&sensor=false" ></a>';
            poiInfoWindowContent = poiInfoWindowContent + '</b>';
        },
        error: function (error) {
            var x = error;
            //console.log(x);
        }
    });
}

function hasColumnClass(id, screenSize) {
    try {

        screenSize = screenSize.toLowerCase();
        var parentClasses = $J(id).parent().attr("class");
        var columnSizeText = "col-" + screenSize + "-";
        if (parentClasses.lastIndexOf(columnSizeText) != -1) {
            var index1 = parentClasses.lastIndexOf(columnSizeText) + 7;
            var index2 = parentClasses.lastIndexOf(columnSizeText) + 8;
            var num1 = parentClasses.charAt(index1);
            var num2 = parentClasses.charAt(index2);
            var totalNum = num1.concat(num2);

            return totalNum;

        }

    } catch (e) { }
}

function assignColumnNumber(id) {
    try {

        switch (bootstrapSize) {
            case "LG":
                {
                    columnSize = hasColumnClass(id, "LG");
                    if (columnSize == null) {
                        columnSize = hasColumnClass(id, "MD");
                        if (columnSize == null) {
                            columnSize = hasColumnClass(id, "SM");
                            if (columnSize == null) {
                                columnSize = hasColumnClass(id, "XS");
                            }
                        }
                    }
                    break;
                }
            case "MD":
                {
                    columnSize = hasColumnClass(id, "MD");
                    if (columnSize == null) {
                        columnSize = hasColumnClass(id, "SM");
                        if (columnSize == null) {
                            columnSize = hasColumnClass(id, "XS");
                        }
                    }
                    break;
                }
            case "SM":
                {
                    columnSize = hasColumnClass(id, "SM");
                    if (columnSize == null) {
                        columnSize = hasColumnClass(id, "XS");
                    }
                    break;
                }
            case "XS":
                {
                    columnSize = hasColumnClass(id, "XS");
                    break;
                }
        }
        return columnSize;

    } catch (e) { }
}

// Date Picker Month Header Replacement
function datePickMonthHeaders(datePicker) {
    try {

        setTimeout(function () {
            var monthHeader = $J(datePicker).find(".datepick-month-header");
            var headerSelects = monthHeader.find("select").hide();
            var firstMonth = $J(headerSelects).find("option[selected]").text();
            var secondMonth = $J(datePicker).find(".datepick-month-header").eq(1).text();
            if (monthHeader) {
                if (monthHeader.eq(0).find("span").length > 0) {
                    monthHeader.eq(0).find("span").text(firstMonth.replace(/\d+/g, ''));
                } else {
                    monthHeader.eq(0).append("<span>" + firstMonth.replace(/\d+/g, '') + "</span>");
                }
                monthHeader.eq(1).text(secondMonth.replace(/\d+/g, ''));
            }
            $J(".datepick-today").removeClass("datepick-highlight").removeClass("datepick-today");
        }, 10);

    } catch (e) { }
}

// Convert Date to Timestamp Ex: 02/14/2014
function convertToDateTimestamp(date) {
    var timestamp = new Date(date);
    return timestamp;
}

// Convert Date to Timestamp Ex: 02/14/2014
function convertToUnixTimestamp(date) {
    var timestamp = new Date($J.datepick.formatDate('mm/dd/yyyy', date));
    return timestamp.getDate();
}

// Get Day Difference Between Two Days
function dayDifference(date1, date2) {
    date1 = new Date(date1);
    date2 = new Date(date2);

    //return daysDifference
    date1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
    date2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
    var ms = Math.abs(date1 - date2);
    return Math.floor(ms / 1000 / 60 / 60 / 24);
}

// Date Validation
function isDateValid(txtDate) {
    try {

        var currVal = txtDate;
        if (currVal == '')
            return false;

        //Declare Regex  
        var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
        var dtArray = currVal.match(rxDatePattern); // is format OK?

        if (dtArray == null)
            return false;

        //Checks for mm/dd/yyyy format.
        dtMonth = dtArray[1];
        dtDay = dtArray[3];
        dtYear = dtArray[5];

        if (dtMonth < 1 || dtMonth > 12)
            return false;
        else if (dtDay < 1 || dtDay > 31)
            return false;
        else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
            return false;
        else if (dtMonth == 2) {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
            if (dtDay > 29 || (dtDay == 29 && !isleap))
                return false;
        }
        return true;

    } catch (e) { }
}

// Reservations Input Field Functionality
function reservationInputFunctionality(inputDate, inputFields) {
    try {

        if (isDateValid(inputDate)) {
            inputFields[0].removeClass("invalidDate");
        } else {
            inputFields[0].addClass("invalidDate");
        }

    } catch (e) { }
}

// Reservations Length of Stay Functionality
function lengthStayFunctionality() {
    var arrival = $J.trim(reservationsArrival.val().replace(/_/g, "").replace(/\//g, ""));
    var departure = $J.trim(reservationsDeparture.val().replace(/_/g, "").replace(/\//g, ""));
    var lengthStay = $J("input[name='lengthStay']");
    lengthStay.val(dayDifference(reservationsArrival.val(), reservationsDeparture.val()));
    if (arrival == "" || arrival == "NaN" ||
		departure == "" || departure == "NaN" ||
		departure == "NaN" || lengthStay.val() == "NaN" || lengthStay.val() == 0) {
        lengthStay.val("");
    }
}

function resize() {
    try {

        registerBootstrapSize();

        $J(".ruler").each(function (i) {
            var blockWidth = window.getComputedStyle(this).width;
            /*console.log('blockWidth: ' + blockWidth);*/
            blockWidth = blockWidth.replace('px', '');
            blockWidth = Math.ceil(blockWidth);
            /*console.log(' / ' + blockWidth);*/

            var columnNumber = assignColumnNumber($J(this));

            var value = $J(this).html();

            if (value == "") {
                $J(this).html("<span class='leftArrow'></span><div class='columnNumber'>" + columnNumber + "</div><span class='width'>" + blockWidth + "</span>");
            }
            else {
                $J(this).html("<span class='leftArrow'></span><div class='columnNumber'>" + columnNumber + "</div><span class='width'>" + blockWidth + "</span>");
            }

            $J(this).addClass("bootstrapColNum");
        });

        $J(".columnNumber").each(function (i) {
            var parentWidth = $J(this).parent().width();
            var thisWidth = $J(this).width();
            $J(this).css("left", (parentWidth / 2) - (thisWidth));
        });

        // Reinitialize Zones upon resize
        if ($J('.zonedArea').length != 0) {
            $J('.zonedArea').remove();
            $J('#tool_highlightZones').trigger('click');
        }

    } catch (e) { }
}

/* Navigation Toggle */
$J('#menuToggle').click(function (e) {
    $J('body').toggleClass('active');
    e.preventDefault();
});

$J('#myTab a, #QBTab a').click(function (e) {
    $J(this).tab('show');
    $j(this).attr("aria-selected", "true");
    $j(this).parent().siblings().children("a").attr("aria-selected", "false");
    e.preventDefault();
});

$J('.nav-tabs').tabdrop();

function scrollToAnchor(aid) {
    var aTag = $J("a[name='" + aid + "']");
    $J('html,body').animate({ scrollTop: aTag.offset().top }, 'fast');
}

/* Modal */
$J(function () {
    /* SINGLE IMAGE */
    $J(document).on('click', '.modalImageControl', function (e) {
        e.preventDefault();
        var photoPath = $J(this).html();
        photoPath = photoPath.replace('?thn=1&amp;bc=efebe8', '');
        photoPath = photoPath.replace("/thumbnails/", "/preview/");
        $J("#imgSingleModal .modal-body").html(photoPath);
    });

    /* CONTENT */
    $J(document).on('click', '.modalContentControl', function (e) {
        e.preventDefault();
        var $mcontent = $J(this).attr("content");
        var modalhtml = $J('.' + $mcontent).wrapInner('<div id="modalContainer" content="' + $mcontent + '"></div>');
        $J("#contentModal .modal-body").empty().html('<div class="clearfix"></div>');
        $J("#contentModal .modal-body").prepend($J("#modalContainer"));
    });

    /* SLIDER */
    $J(document).on('click', '.modalSliderControl', function (e) {
        e.preventDefault();
        var datasizevalue = $J(this).attr('data-size').toLowerCase();
        var bootstrapSize1 = bootstrapSize.toLowerCase();
        if (datasizevalue.indexOf(bootstrapSize1) >= 0) {
            $J(".modal-dialog").addClass("full");
            var $mcontent = $J(this).attr("content");
            var modalhtml = $J('.' + $mcontent).wrapInner('<div id="modalContainer" content="' + $mcontent + '"></div>');
            $J("#contentModal .modal-body").empty().html('<div class="clearfix"></div>');
            $J("#contentModal .modal-body").prepend($J("#modalContainer"));
        }
    });

    /* MODAL CLOSE */
    $J('#contentModal').on('hidden.bs.modal', function () {
        var $mcontent = $J("#modalContainer").attr("content");
        $J("#modalContainer").prependTo('.' + $mcontent);
        $J("#modalContainer").children().unwrap();
    });
});

// SLIDER: Go To Slide
function goToSlideFunction(object) {
    var index = $J(object).data("slide-number") + 1;
    $J("#golfHoleNumbers").children("li").removeClass("active");
    $J("#golfHoleNumbers").children("li").eq(index).addClass("active");
    $J("select[name='golfHoleNumber']").val(index);
};

// Have Hero Slider Animate When Modal Slider Animates
function homepageSliderModalFollow(object) {
    var index = $J(object).data("slide-number");
    $J("#rotatingBanner").find(".mpyCarousel").trigger('slideTo', index);
};

function carouselTabChange(next) {
    if (next.attr("data-tab")) {
        var tabNumber = next.attr("data-tab");
        var tab = $J("#gallery .nav-tabs li.tabNumber" + tabNumber);
        if (!tab.hasClass("active")) {
            tab.find("a").trigger('click');
        }
    }
};

// create <div class="item"><img /></div>
function makeItemElem() {
    var item = document.createElement('div');
    item.className = 'item is-hidden';
    var img = document.createElement('img');
    // random image size
    var width = Math.floor(Math.random() * 200) + 50;
    var height = Math.floor(Math.random() * 200) + 50;
    img.src = 'http://lorempixel.com/' + width + '/' + height;
    item.appendChild(img);
    return item;
}

// Redirect Select Dropdown Functionality
function redirectSelect(selectName) {
    var select = $J("select[name='" + selectName + "']");
    var href = select.val();
    var target = (select.find("option:selected").attr("target")) ? "_" + select.find("option:selected").attr("target") : "_blank";
    window.open(href, target);
}

// SLIDERS
if (typeof jsonData != 'undefined') { // jsonData is a variable declared on the page
    $J("#rotatingBanner").mpySlider({
        jsonData: jsonData,						// Pass JSON Data to the plugin (ex: "scripts/tooltipJSON.json")
        thumbnailSelector: '.sliderThumbnails',	// Adding a selector will add thumbnail images
        headlineContainer: '.headline',			// Adding a selector will let you add a headline
        subHeadlineContainer: '.subHeadline',	// Adding a selector will let you add a subHeadline
        carouselAnimationSpeed: 2500,			// Speed of animation between slides
        carouselModal: true,					// Allow the Carousel to open in modal on click
        carouselModalContent: "mContent1",		// Adds data attribute content for modal to find content,
        carouselModalSlider: "#homepageSlider",	// The selector of the slider inside the modal
    });

    $J("#homepageSlider").mpySlider({
        jsonData: jsonData,						// Pass JSON Data to the plugin (ex: "scripts/tooltipJSON.json")
        headlineContainer: '.headline',			// Adding a selector will let you add a headline
        subHeadlineContainer: '.subHeadline',	// Adding a selector will let you add a subHeadline
        carouselAnimationSpeed: 2500,			// Speed of animation between slides
        arrivingFunction: homepageSliderModalFollow
    });

    $J("#slider").mpySlider({
        jsonData: jsonData,						// Pass JSON Data to the plugin (ex: "scripts/tooltipJSON.json")
        carouselSlideDuration: 900000,			// How long to stay on each slide before animating
        headlineContainer: '.headline',			// Adding a selector will let you add a headline
        subHeadlineContainer: '.subHeadline',	// Adding a selector will let you add a subHeadline
        carouselAnimationSpeed: 1500,			// Speed of animation between slides
        arrivingFunction: carouselTabChange
    });
}

if (typeof golfJsonData != 'undefined') {
    $J("#golfSlider").mpySlider({
        jsonData: golfJsonData,					// Pass JSON Data to the plugin (ex: "scripts/tooltipJSON.json")
        carouselAnimationSpeed: 1000,			// Speed of animation between slides
        headlineContainer: '.golfHeadline',		// Adding a selector will let you add a headline
        headlineTag: 'h2',						// Change headline HTML tag (default: h3)
        contentSelector: '.golfContent',		// Adding a selector will let you add content
        contentFadeSpeed: 500,					// 0 means it will just show instead of fade
        arrivingFunction: goToSlideFunction
    });
}

$J("#loyaltyBenefits").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    hasNavigationCounter: false,
    carouselSlideDuration: 200000			// Speed of animation between slides
});

$J(".newsTicker").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    hasNavigationCounter: false
});

$J("#featuredDestinations").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    carouselSlidesVisible: 1,				// How many slides are showing at once
    carouselSlidesVisible_SM: 2,			// How many slides are showing at once on bootstrap SM
    carouselSlidesVisible_MD: 3,			// How many slides are showing at once on bootstrap MD
    carouselSlidesVisible_LG: 4,			// How many slides are showing at once on bootstrap LG
    carouselSlidingOffset: 1,				// How many slides away to animate to
    carouselSlideDuration: 600000,			// How long to stay on each slide before animating
    carouselAnimationSpeed: 1500			// Speed of animation between slides
});

$J("#featuredPromotions").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    carouselSlidesVisible: 1,				// How many slides are showing at once
    carouselSlidesVisible_SM: 2,			// How many slides are showing at once on bootstrap SM
    carouselSlidesVisible_MD: 3,			// How many slides are showing at once on bootstrap MD
    carouselSlidesVisible_LG: 4,			// How many slides are showing at once on bootstrap LG
    carouselSlidingOffset: 1,				// How many slides away to animate to
    carouselSlideDuration: 600000,			// How long to stay on each slide before animating
    carouselAnimationSpeed: 1500			// Speed of animation between slides
});

$J("#brandSpecialsSlider").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    carouselSlidesVisible: 1,				// How many slides are showing at once
    carouselSlidesVisible_SM: 2,			// How many slides are showing at once on bootstrap SM
    carouselSlidesVisible_MD: 3,			// How many slides are showing at once on bootstrap MD
    carouselSlidesVisible_LG: 4,			// How many slides are showing at once on bootstrap LG
    carouselSlidingOffset: 1,				// How many slides away to animate to
    carouselSlideDuration: 600000,			// How long to stay on each slide before animating
    carouselAnimationSpeed: 1500			// Speed of animation between slides
});

$J("#gallerySlider").mpySlider({
    carouselAnimationStyle: 'scroll',		// Examples: 'scroll', fade', crossfade'
    carouselIsGallery: true
});

function getProfilePhoto() {
    if ($J.cookie("login_fg_public") && $J(".profilePhoto").length) {
        var element = $J(".profilePhoto");
        var cookie = $J.cookie("login_fg_public").split("|");
        var url = element.attr("baseURL").replace("/Omni", "");
        var URL_profile_photo = "/ProfilePhoto";
        var userID = "";
        $J.each(cookie, function (i, val) {
            if (val.indexOf("URL_profile_photo") > -1) {
                var value = val.split(":");
                URL_profile_photo = value[1];
            }
            if (val.indexOf("SG_membershipNumber") > -1) {
                var value = val.split(":");
                userID = value[1];
            }
        });
        var imageSrc = (URL_profile_photo == "/ProfilePhoto") ? url + URL_profile_photo + "/" + userID : URL_profile_photo;
        element.html("<img src='" + imageSrc + "' class='img-responsive' />");
    }
};

function GetQueryStringParams(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}


$J(document).ready(function () {

    getProfilePhoto();

    $J(".predictiveSearch").swipe({
        tap: function () {
            var passedVars = "";
            console.log($(this).data());
            console.log("_________________");
            console.log($(this).data().join(","));
        }
    });

    if ($J('#social-stream').length > 0) {
        $J('#social-stream').dcSocialStream({
            feeds: {
                facebook: {
                    id: '157969574262873,Facebook/10151498156121729',
                    out: 'intro,text,user,share',
                    text: 'content'
                },
                youtube: {
                    id: 'OMNIHOTELS',
                    thumb: '0'
                },
                pinterest: {
                    id: 'omnihotels',
                    out: 'intro,thumb,text,user,share'
                },
                instagram: { id: '!186786085', accessToken: '186786085.91dbf99.da4d8fab71544cdba8645bd0a02f07a1', clientId: '91dbf99a184e43dca3cc115500a5ba58', comments: 3, likes: 10 }
            },
            rotate: {
                delay: 0
            },
            control: false,
            filter: true,
            wall: true,
            limit: 5,
            max: 'limit',
            iconPath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/',
            imagePath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/'
        });

        $J('#social-stream-2').dcSocialStream({
            feeds: {
                pinterest: {
                    id: 'omnihotels',
                    out: 'intro,thumb,text,user,share'
                },
            },
            rotate: {
                delay: 0
            },
            control: false,
            filter: false,
            wall: true,
            limit: 5,
            max: 'limit',
            iconPath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/',
            imagePath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/'
        });

        $J('#social-stream-3').dcSocialStream({
            feeds: {
                youtube: {
                    id: 'OMNIHOTELS',
                    thumb: '0'
                },
            },
            rotate: {
                delay: 0
            },
            control: false,
            filter: false,
            wall: true,
            limit: 5,
            max: 'limit',
            iconPath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/',
            imagePath: 'http://www.designchemical.com/blog/wp-content/themes/dc2011/dcsns/images/dcsns-dark/'
        });
    }


	$J(window).resize(function () {

		clearTimeout(resizeTimer);
		resizeTimer = setTimeout(function () {
			registerBootstrapSize;
		}, 100);
	});

    if (bootstrapRadio.length) {
        bootstrapRadio.change(function () {
            //changeGallery(callouts);
        });
    }

    // Temporary code to make photos & videos gallery 
    if (typeof jsonData != 'undefined' && $J("#gallery").length) { // jsonData is a variable declared on the page
        var count = $J('#gallery .nav-tabs li[class*="tabNumber"]').length;
        for (var i = 0; i < count; i++) {
            var output = "";
            var tabClass = "tabNumber" + (i + 1);
            var divLocation = $J("#gallery li." + tabClass + " a").attr("href").replace('#', '');
            for (var j = 0; j < jsonData.length; j++) {
                if (jsonData[j]["Tab"] == (i + 1)) {
                    output += '<div data-item="' + jsonData[j]["Id"] + '" data-tab="' + jsonData[j]["Tab"] + '"class="col-xs-4 col-sm-3 col-lg-2 padding-bottom-15 photo-gallery">';
                    output += '<a data-toggle="modalMPY" href="#" class="modalSliderControl" matchingmodal="#contentModal" content="mContent1" data-size="xs|sm|md|lg">';
                    output += '<img src="' + jsonData[j]["ImageUrl"] + '" class="img-responsive" alt="' + jsonData[j]["Alt"] + '" />';
                    output += '</a>';
                    output += '</div>';
                }
            }
            var galleryContainer = $J("div[id='" + divLocation + "']");
            $J(galleryContainer).find(".row").append(output);
        }
    }

    $J("#gallery a.modalSliderControl").click(function (e) {

        var item = $J(this).parent().attr("data-item");

        if ($J("#sliderGallery .caroufredsel_wrapper").length <= 0) {
            $J(".modal-body").attr("starting-slide", item);
            $J("#sliderGallery").mpySlider({
                jsonData: jsonData,						// Pass JSON Data to the plugin (ex: "scripts/tooltipJSON.json")
                carouselSlideDuration: 900000,			// How long to stay on each slide before animating
                headlineContainer: '.headline',			// Adding a selector will let you add a headline
                subHeadlineContainer: '.subHeadline',	// Adding a selector will let you add a subHeadline
                carouselAnimationSpeed: 1500,			// Speed of animation between slides
                arrivingFunction: carouselTabChange,
                gallery: true
            });
        } else { $J(".modal-body").removeAttr("starting-slide"); }


        $J("#sliderGallery").find(".sliderCarousel").attr("data-start", item);
        e.preventDefault();
    });

    $J(".sliderCarousel.modalSliderControl").on('click', '.carouselSlide', function (e) {
        var item = $J(this).attr("data-slide-number");
        $J("#homepageSlider").find(".sliderCarousel").attr("data-start", item);
        e.preventDefault();
    });

    $J("#homepageSlider").hover(function () {
        $J("#rotatingBanner").find(".sliderCarousel").trigger("pause");
    }, function () {
        $J("#rotatingBanner").find(".sliderCarousel").trigger("resume");
    });

    $J("#slider").find(".sliderCarousel").attr("data-start", 0);
    $J("#homepageSlider").find(".sliderCarousel").attr("data-start", 0);

    $J("#golfHoleNumbers li a").on('click', function (e) {
        var index = parseInt($J(this).text()) - 1;
        var carousel = $J("#golfSlider");
        carousel.find(".sliderCarousel").trigger('slideTo', [carousel.find('div[data-slide-number="' + index + '"]')]);
        e.preventDefault()
    });
    goToSlideFunction(0);

    $J("select[name='golfHoleNumber']").on('change', function (e) {
        var index = $J(this).val() - 1;
        var carousel = $J("#golfSlider");
        carousel.find(".sliderCarousel").trigger('slideTo', [carousel.find('div[data-slide-number="' + index + '"]')]);
        e.preventDefault()
    });

    $J('.tooltipContainer').popover({
        trigger: 'hover',
        selector: "[data-toggle=popover]",
        container: "body"
    });

    var lineThrough = $J(".lineThrough");
    lineThrough.each(function () {
        var text = $J(this).html();
        $J(this).html("<span>" + text + "</span>");
    });

    var lineThroughOrange = $J(".lineThroughOrange");
    lineThroughOrange.each(function () {
        var text = $J(this).html();
        $J(this).html("<span>" + text + "</span>");
    });

    var lineThroughOrangeWithTan = $J(".lineThroughOrangeTan");
    lineThroughOrangeWithTan.each(function () {
        var text = $J(this).html();
        $J(this).addClass("padding-left-right-15").wrap("<div class='text-center'></div>");
        $J(this).html("<span class='background-color-tan'>" + text + "</span>");
    });

    // Image Text Hover Display
    $J(".imgHover").mouseenter(function () {
        $J(this).find(".imgHoverTxt").show();
    })
	.mouseleave(function () {
	    $J(this).find(".imgHoverTxt").hide();
	});

    $J('.orz .radioPromoCode').click(function () {
        $J('input.inputPromoCode').focus();
    });

    $J('.orz .radioGroupCode').click(function () {
        $J('input.inputGroupCode').focus();
    });

    $J('.orz input.inputPromoCode').click(function () {
        $J("input.radioPromoCode").prop('checked', true);
    });

    $J('.orz input.inputGroupCode').click(function () {
        $J("input.radioGroupCode").prop('checked', true);
    });

    $J('.orz .radioCamera').click(function () {
        $J(this).parents(".selectionOptions .radioSelection").prop('checked', false);
        $J(this).parents(".selectionOptions").find('.radioSelection').prop('checked', true);
    });

    $J('.orz .enhancement select').change(function () {
        if ($J(this).val() != '0') {
            $J(this).closest('.col-lg-6').prev('div').find('input[type=checkbox]').prop('checked', true);
        }
        else {
            $J(this).closest('.col-lg-6').prev('div').find('input[type=checkbox]').prop('checked', false);
        }
    });

    $J('.btnReadMore').click(function (e) {
        e.preventDefault();
        $J(this).prev('.readMoreContent').slideDown();
        $J(this).css("display", "none");
        $J(this).next('.btnReadLess').css("display", "inline-block");
    });

    $J('.btnReadLess').click(function (e) {
        e.preventDefault();
        $J(this).prev().prev('.readMoreContent').slideUp();
        $J(this).css("display", "none");
        $J(this).prev('.btnReadMore').css("display", "inline-block");
    });

    // Login Functionality
    $J("#btnLogIn").click(function () {
        $J('#logInContent').fadeIn("slow");
    });

    if (!$J("body").hasClass("orz")) {
        $J(".loggedOut").click(function () {
            setTimeout(function () {
                $J("#loginOverlay").add("#logInContent").fadeIn(300);
            }, 10);
        }).css("cursor", "pointer");
    }

    $J("#loginOverlay").add("header").click(function () {
        if ($J("#loginOverlay").is(":visible")) {
            $J("#loginOverlay").add("#logInContent").fadeOut(300);
        }
    });

    //creditcard
    $J("input[name^='creditcard']").change(function () {
        if ($J(this).val() == "yes") {
            $J(".termsConditions").css("display", "block");
        }
        else {
            $J(".termsConditions").css("display", "none");
        }
    });

    // Hidden active tab fix
    if ($J("#myTab.nav-tabs > li").not(".tabdrop").length > 0) {
        $J("#myTab.nav-tabs .dropdown-menu li.active").removeClass("active");
        $J("#myTab.nav-tabs > li").not(".tabdrop").first().addClass("active");
    }
    $J("#myTab.nav-tabs > li").not(".tabdrop").first().addClass("active");
    //For guest gallery dynamic tabs
    $J("#guestgalleryTabs > #myTab.nav-tabs > li").not(".tabdrop").first().addClass("active");
    $J("#guestgalleryTabsContent > div").first().addClass("active");

    // Javascript to enable link to tab
    var url = document.location.toString();
    if (url.match('#') != null) {
        var url2 = url.split('#')[1];
        url2 = url2.split('?')[0];
        var script = '#myTab a[href="#' + url2 + '"]';
        $J(script).tab('show');
    }

    //Tab Query String
    if (window.location.href.indexOf("?") > -1) {
        var tab = GetQueryStringParams('tab');

        if (tab != null && tab != "") {
            var script = '#myTab a[href="#' + tab + '"]';
            $J(script).tab('show');
        }
    }

    // Reservations Number Of Guests
    var room2 = $J("#numberOfGuests").find(".room2").hide();
    var room3 = $J("#numberOfGuests").find(".room3").hide();
    var room1children = $J("select[name*='room1_childage']").parent().hide();
    var room2children = $J("select[name*='room2_childage']").parent().hide();
    var room3children = $J("select[name*='room3_childage']").parent().hide();
    $J(".room1 .childrensAges").prev().hide();
    $J(".room2 .childrensAges").prev().removeClass("visible-xs").hide();
    $J(".room3 .childrensAges").prev().removeClass("visible-xs").hide();
    $J("#reservationsRooms").change(function () {
        if ($J(this).val() == 1) {
            room2.hide();
            room3.hide();
        }
        if ($J(this).val() == 2) {
            room2.show();
            room3.hide();
        }
        if ($J(this).val() == 3) {
            room2.show();
            room3.show();
        }
    });

    // Children's Ages Label
    function showchildrensAgesHeader(value) {
        try {

            if (bootstrapSize != "XS" && value > 0) {
                $J(".room1 .childrensAges").prev().show();
            } else {
                if ($J("select[name*='room1_child_qty']").val() == 0 && $J("select[name*='room2_child_qty']").val() == 0 && $J("select[name*='room3_child_qty']").val() == 0) {
                    $J(".room1 .childrensAges").prev().hide();
                }
            }

        } catch (e) { }
    }

    $J("select[name*='room1_child_qty']").change(function () {
        var value = $J(this).val();
        room1children.hide();
        for (var i = 0; i < value; i++) {
            room1children.eq(i).show();
        }
        if (bootstrapSize == "XS" && value > 0) {
            $J(".room1 .childrensAges").prev().show();
        } else if (bootstrapSize == "XS" && value == 0) { $J(".room1 .childrensAges").prev().hide(); }
        showchildrensAgesHeader(value);
    });

    $J("select[name*='room2_child_qty']").change(function () {
        var value = $J(this).val();
        room2children.hide();
        for (var i = 0; i < value ; i++) {
            room2children.eq(i).show();
        }
        if (value > 0) {
            $J(".room2 .childrensAges").prev().addClass("visible-xs");
        } else { $J(".room2 .childrensAges").prev().removeClass("visible-xs").hide(); }
        showchildrensAgesHeader(value);
    });

    $J("select[name*='room3_child_qty']").change(function () {
        var value = $J(this).val();
        room3children.hide();
        for (var i = 0; i < value ; i++) {
            room3children.eq(i).show();
        }
        if (value > 0) {
            $J(".room3 .childrensAges").prev().addClass("visible-xs");
        } else { $J(".room3 .childrensAges").prev().removeClass("visible-xs").hide(); }
        showchildrensAgesHeader(value);
    });

    // Hide Select Dropdown Button in IE
    if ($J("body").hasClass("Explorer9") || $J("body").hasClass("Explorer8")) {
        $J(".styled-select select").width("157%");
    }

    // Reservations Date Picker
    reservationsArrival.add(reservationsDeparture).datepick({
        minDate: 0,
        maxDate: datepickerMaxDate,
        monthsToShow: 2,
        onShow: function () {
            datePickMonthHeaders($J(".datepick-popup"));
            if (touchEnabled) {
                // Swipe Functionality for Popup Calendar
                $J(".datepick-popup").swipe({
                    swipeLeft: function (event, direction, distance, duration, fingerCount) {
                        $J(this).find("a.datepick-cmd-next").trigger("click");
                    },
                    swipeRight: function (event, direction, distance, duration, fingerCount) {
                        $J(this).find("a.datepick-cmd-prev").trigger("click");
                    }
                });
            }
        },
        onSelect: function (dates) {
            if (this.id == 'reservationsArrival') {
                reservationsDeparture.datepick('option', 'minDate', $J.datepick.add(dates[0], 1, 'd'));
                reservationInputFunctionality(reservationsArrival.val(), [reservationsArrival, reservationsDeparture]);
                //if ($J.trim(reservationsDeparture.val().replace(/_/g, "").replace(/\//g, "")) == "") {
                reservationsDeparture.datepick('setDate', $J.datepick.add(dates[0], 0, 'd'));
                //}
            }
            else {
                reservationInputFunctionality(reservationsDeparture.val(), [reservationsDeparture, reservationsArrival]);
            }
            lengthStayFunctionality();
            if ($J('input[name="lengthStay"]').val() < 0) {
                $J('input[name="lengthStay"]').val("");
                reservationsDeparture.datepick('setDate', $J.datepick.add(dates[0], 0, 'd'));
                lengthStayFunctionality();
            }
        },
        onChangeMonthYear: function () {
            datePickMonthHeaders($J(".datepick-popup"));
        }
    });

    // Reservations Input Mask Functionality
    reservationsArrival.mask("99/99/9999", {
        completed: function () {
            reservationInputFunctionality(this.val(), [reservationsArrival, reservationsDeparture]);
            if (reservationsArrival.val().match(/\d+/g) != null) {
                reservationsDeparture.datepick('option', 'minDate', reservationsArrival.val());
                reservationsDeparture.datepick('setDate', reservationsDeparture.val());
            }
            $J('.datepick-cmd-close').trigger("click");
            lengthStayFunctionality();
        }
    }).focusout(function () {
        reservationInputFunctionality(reservationsArrival.val(), [reservationsArrival, reservationsDeparture]);
        if (reservationsArrival.val().match(/\d+/g) != null) {
            reservationsDeparture.datepick('option', 'minDate', reservationsArrival.val());
            reservationsDeparture.datepick('setDate', reservationsDeparture.val());
        }
        if ($J.trim($J(this).val().replace(/_/g, "").replace(/\//g, "")) == "") {
            reservationsDeparture.val("");
        }
        lengthStayFunctionality();
    });
    reservationsDeparture.mask("99/99/9999", {
        completed: function () {
            reservationInputFunctionality(this.val(), [reservationsDeparture, reservationsArrival]);
            $J('.datepick-cmd-close').trigger("click");
            lengthStayFunctionality();
        }
    }).focusout(function () {
        reservationInputFunctionality(reservationsDeparture.val(), [reservationsDeparture, reservationsArrival]);
        lengthStayFunctionality();
    });

    // Set Default Dates for RR Datepicker
    reservationsArrival.datepick('setDate', defaultDates[0]);
    reservationsDeparture.datepick('setDate', defaultDates[1]);

    var reservationsStart = convertToDateTimestamp(reservationsArrival.val());
    var reservationsEnd = convertToDateTimestamp(reservationsDeparture.val());
    $J("input[name='lengthStay']").val(dayDifference(reservationsStart, reservationsEnd));

    $J("input[name='lengthStay']").change(function () {
        var arrival = $J.trim(reservationsArrival.val().replace(/_/g, "").replace(/\//g, ""));
        var departure = $J.trim(reservationsDeparture.val().replace(/_/g, "").replace(/\//g, ""));
        if (arrival == "" && departure == "") {
            reservationsArrival.val($J.datepick.formatDate('mm/dd/yyyy', today));
            reservationInputFunctionality(reservationsArrival.val(), [reservationsArrival, reservationsDeparture]);
        }
        var value = parseInt($J(this).val());
        var startDate = convertToDateTimestamp(reservationsArrival.val());
        var newDate = $J.datepick.add(new Date(startDate), value, "d");

        var testDate = '04/05/2014';

        reservationsDeparture.datepick('setDate', newDate);
        $J('.datepick-cmd-close').trigger("click");
        lengthStayFunctionality();
    }).focusout(function () {
        var arrival = $J.trim(reservationsArrival.val().replace(/_/g, "").replace(/\//g, ""));
        var departure = $J.trim(reservationsDeparture.val().replace(/_/g, "").replace(/\//g, ""));
        if (arrival == "" && departure == "") {
            reservationsArrival.val($J.datepick.formatDate('mm/dd/yyyy', today));
            reservationInputFunctionality(reservationsArrival.val(), [reservationsArrival, reservationsDeparture]);
        }
        var value = parseInt($J(this).val());
        var startDate = convertToDateTimestamp(reservationsArrival.val());
        var newDate = $J.datepick.add(new Date(startDate), value, "d");

        reservationsDeparture.datepick('setDate', newDate);
        $J('.datepick-cmd-close').trigger("click");
        lengthStayFunctionality();
    });

    //Accordion - Adding/Removing classes for header panels
    $J(".panel-title").addClass("collapsed");
    $J(".panel-title").on("click", function () {
        if ($J(this).hasClass("collapsed")) {
            $J(this).closest(".panel-heading").addClass("active");
        } else {
            $J(this).closest(".panel-heading").removeClass("active");
        }
    })

    $J(".panel-title").on("tap", function () {
        if ($J(this).hasClass("collapsed")) {
            $J(this).closest(".panel-heading").addClass("active");
        } else {
            $J(this).closest(".panel-heading").removeClass("active");
        }
    })

    $J(".panel-title").on("click", function () {
        //console.log("alert");
        if ($J(this).hasClass("collapsed")) {
            $J(this).addClass("active");
        } else {
            $J(this).removeClass("active");
        }
    })

    $J(".panel-title").on("tap", function () {
        //console.log("alert");
        if ($J(this).hasClass("collapsed")) {
            $J(this).addClass("active");
        } else {
            $J(this).removeClass("active");
        }
    })

    if (touchEnabled) {
        $J(".panel-collapse").removeClass("collapse");
        $J(".panel-title").parent(".panel-collapse-header").removeClass("collapsed");
    }

    //Hide/Show Development Infrastructure   
    $J("#omniDepartments").on('click', 'li', function (e) {
        //which anchor is clicked and getting that number 
        e.preventDefault();
        var anchorSelected = $J(this).data('anchorselected');

        //selecting the <div> with the number that matches the index of the anchor selected 
        //if you select anchor #3, you'll get <div> #3 within the departmentDescription <div>
        $J("#departmentDescription div").hide();
        $J("#" + anchorSelected).show();
        $J('#omniDepartments li').removeClass('on');
        $J(this).addClass('on');
    });

    $J("#omniDepartment").change(function () {
        var anchorSelected = $J(this).find(':selected').data('anchorselected');
        $J("#departmentDescription div").hide();
        $J("#" + anchorSelected).show();
    });

    $J('nav > ul > li:not(.nav-book-link)').hover(function () {
        var timer = $J(this).data('timer');
        if (timer) clearTimeout(timer);
        $J('nav > ul > li').removeClass('active');
        $J(this).addClass('active');
    },
	function () {
	    var li = $J(this);
	    li.data('timer', setTimeout(function () {
	        li.removeClass('active');
	    }, 300));
	});

    $J('nav li ul li:not(.nav-book-link)').hover(function () {
        $J(this).addClass('active');
        $J(this).children().first().attr("aria-expanded", "true");
    },
	function () {
	    $J(this).removeClass('active');
        $J(this).children().first().attr("aria-expanded", "false");
	});


    $J("#leftNavigation .sectionTitle + ul ul a.active").parent("li").parent("ul").prev("a").addClass("active");

    if (typeof (phNum) != "undefined") {
        if (phNum != null && phNum.length > 0) {
            $J("#phNumContactUs").html(phNum);
        }
    }

    if (touchEnabled) {
        $J("#mainContainer").swipe({
            swipeLeft: function (event, direction, distance, duration, fingerCount) {
                $J("body").removeClass("active")
            },
            excludedElements: "a, input, select, .st_sharethis, #menuToggle, #amazingslider-1"
        });
    }

    $J("#amazingslider-1 video").each(function () {
        var videoSrc = $J(this).attr("src");
        videoSrc = videoSrc.replace("watch?v=", "embed/");
        $J(this).attr("src", videoSrc);
    });

    $J("#amazingslider-1 div[class*='amazingslider-bullet-0']").add(".amazingslider-play-0").on('click', function () {
        $J("iframe[src*='youtube']").each(function () {
            var videoSrc = $J(this).attr("src");
            videoSrc = videoSrc.replace("watch?v=", "embed/").replace(/&/, "?");
            $J(this).attr("src", videoSrc);
        });
    });

    /* Specials - Receive Offers By Email */
    $J('#specialsMailingList').click(function () {
        var emailInput = $J('#specialsMailListEmail');
        emailInput.removeClass("form-error");
        var val = emailInput.val();
        if (val != null && val.trim().length > 0 && val != emailInput.attr('placeholder')) {
            window.location.href = $J(this).attr('href').replace("{0}", val);
        } else {
            emailInput.addClass("form-error");
        }
        return false;
    });

    $J('#specialsMailListEmail').click(function () { $J('#specialsMailListEmail').removeClass("form-error") });

    /* Footer - Mailing List */
    $J('#joinMailingList').click(function () {
        //?EMAIL=test@test.com&pagedst=enewsoptin
        $J('#mailListEmail').removeClass("form-error");
        var val = $J('#mailListEmail').val();
        if (val != null && val.trim().length > 0 && val != $J('#mailListEmail').attr('placeholder')) {
            window.location.href = $J(this).attr('href').replace("{0}", val);
        } else {
            $J('#mailListEmail').addClass("form-error");
        }
        return false;
    });

    $J('#mailListEmail').click(function () { $J('#mailListEmail').removeClass("form-error") });

    // for Press Release auto scroll
    if (focusVal && focusVal === 1) {
        var lastrecord = $J('.row .margin-top-bottom-15');
        if (lastrecord != null && lastrecord.first() != null)
            $J('html, body').animate({ scrollTop: lastrecord.first().offset().top }, 'slow');
    }

    // START Specials - Book This Offer button conditional disable/enable.

    if ($J("select[data-dropdownid='ddlHotels'] option:selected").val() === "") {
        $J("a[data-linkbuttonid='lbBookNow']").addClass("disabledButton");
    }

    $J("select[data-dropdownid='ddlHotels']")
        .change(function () {
            if ($J("select[data-dropdownid='ddlHotels'] option:selected").val() === "") {
                $J("a[data-linkbuttonid='lbBookNow']").attr("disabled", "disabled");
                $J("a[data-linkbuttonid='lbBookNow']").addClass("disabledButton");
            } else {
                $J("a[data-linkbuttonid='lbBookNow']").removeAttr("disabled", "");
                $J("a[data-linkbuttonid='lbBookNow']").removeClass("disabledButton");
            }
        });

    if (!$j(".btn-mobileSelect-gen")) {
        $J("a[data-linkbuttonid='lbBookNow']")
            .on("click",
                function (e) {
                    if ($J("select[data-dropdownid='ddlHotels'] option:selected").val() === "")
                        e.preventDefault();
                })
            .mouseover(function (e) {
                if ($J("select[data-dropdownid='ddlHotels'] option:selected").val() === "") {
                    $J("body")
                        .append("<p id='tooltip'>" +
                            $J("a[data-linkbuttonid='lbBookNow']").attr("data-title-validation") +
                            "</p>");
                    $J("#tooltip")
                        .css("top", (e.pageY - 10) + "px")
                        .css("left", (e.pageX + 20) + "px")
                        .fadeIn("fast");
                }
            })
            .mouseout(function (e) {
                $J("#tooltip").remove();
            })
            .mousemove(function (e) {
                $J("#tooltip")
                    .css("top", (e.pageY - 10) + "px")
                    .css("left", (e.pageX + 20) + "px");
            });
    }

    // END Specials
});

