/* Minification failed. Returning unminified contents.
(8622,7): run-time error JS1004: Expected ';'
(8644,22-25): run-time error JS1009: Expected '}': ...
(8644,21): run-time error JS1004: Expected ';'
(8683,1-2): run-time error JS1002: Syntax error: }
(9957,5415-5416): run-time error JS1195: Expected expression: .
(9957,5457-5458): run-time error JS1195: Expected expression: .
(9957,5470-5471): run-time error JS1003: Expected ':': ,
(10601,71-72): run-time error JS1195: Expected expression: .
(10601,100-101): run-time error JS1003: Expected ':': ,
(10601,110-111): run-time error JS1009: Expected '}': :
(10601,110-111): run-time error JS1194: Expected ',' or ']': :
(10595,18): run-time error JS1004: Expected ';'
(10601,110-111): run-time error JS1195: Expected expression: :
(10601,123): run-time error JS1004: Expected ';'
(10601,123-124): run-time error JS1195: Expected expression: :
(10601,145): run-time error JS1004: Expected ';'
(10601,145-146): run-time error JS1195: Expected expression: :
(10602,5-6): run-time error JS1009: Expected '}': {
(10602,5-6): run-time error JS1006: Expected ')': {
(10562,19): run-time error JS1004: Expected ';'
(10602,32): run-time error JS1004: Expected ';'
(10602,32-33): run-time error JS1195: Expected expression: :
(10602,84-85): run-time error JS1195: Expected expression: .
(10602,118-119): run-time error JS1003: Expected ':': ,
(10602,128): run-time error JS1004: Expected ';'
(10602,128-129): run-time error JS1195: Expected expression: :
(10602,141): run-time error JS1004: Expected ';'
(10602,141-142): run-time error JS1195: Expected expression: :
(10602,163): run-time error JS1004: Expected ';'
(10602,163-164): run-time error JS1195: Expected expression: :
(10607,4-5): run-time error JS1006: Expected ')': ]
(10607,4-5): run-time error JS1195: Expected expression: ]
(10612,3-4): run-time error JS1002: Syntax error: }
(10612,4-5): run-time error JS1195: Expected expression: ,
(10613,47-48): run-time error JS1010: Expected identifier: (
(10681,4-5): run-time error JS1195: Expected expression: ,
(10682,34-35): run-time error JS1010: Expected identifier: (
(10709,4-5): run-time error JS1195: Expected expression: ,
(10710,45-46): run-time error JS1010: Expected identifier: (
(10768,4-5): run-time error JS1195: Expected expression: ,
(10769,41-42): run-time error JS1010: Expected identifier: (
(10840,4-5): run-time error JS1195: Expected expression: ,
(10841,41-42): run-time error JS1010: Expected identifier: (
(10850,2-3): run-time error JS1002: Syntax error: }
(10850,3-4): run-time error JS1195: Expected expression: )
(10851,1-2): run-time error JS1002: Syntax error: }
(10851,2-3): run-time error JS1195: Expected expression: )
(5902,3,5938,4): run-time error JS1314: Implicit property name must be identifier: CategorizeURLPath() {
			const url = document.location.pathname;

			// Define regular expressions for the different URL patterns
			const routes = {
				home: /^\/$/,
				facilityPage: /^\/tee-times\/facility\/[\w-]+\/search$/,
				teeTimeDetails: /^\/tee-times\/facility\/\d+\/tee-time\/\d+$/,
				hotDeals: /^\/tee-times\/hot-deals$/,
				coursesNearMe: /^\/tee-times\/courses-near-me$/,
				bestCourses: /^\/tee-times\/best-golf-courses-near-me\/search$/,
				golfPass: /^\/memberships\/golfpass$/
			};

			// Check the URL against each pattern
			for (const [category, pattern] of Object.entries(routes)) {
				if (pattern.test(url)) {
					switch (category) {
						case 'facilityPage':
							return 'Facility Page';
						case 'teeTimeDetails':
							return 'Tee Time Details';
						case 'hotDeals':
							return 'Hot Deals Near Me';
						case 'bestCourses':
							return 'Best Courses Near Me';
						case 'golfPass':
							return 'GolfPass Landing Page';
						default:
							return category.charAt(0).toUpperCase() + category.slice(1).replace(/([A-Z])/g, ' $1').trim();
					}
				}
			}

			// If none of the predefined categories match, return the URL path directly
			return url;
		}
(10611,4-30): run-time error JS1018: 'return' statement outside of function: return labelObjArraySorted
(8677,2,8682,3): run-time error JS1018: 'return' statement outside of function: return {
		ReportPmpImpressionEvent: _reportPmpImpressionEvent,
		ReportPmpClickEvent: _reportPmpClickEvent,
		ReportPmpPurchaseEvent: _reportPmpPurchaseEvent,
		Init: init
	}
 */
/*!
 * jQuery.ScrollTo
 * Copyright (c) 2007-2014 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
 * Licensed under MIT
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * @projectDescription Easy element scrolling using jQuery.
 * @author Ariel Flesler
 * @version 1.4.12
 */

; (function (plugin) {
    // AMD Support
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], plugin);
    } else {
        plugin(jQuery);
    }
}(function ($) {

    var $scrollTo = $.scrollTo = function (target, duration, settings) {
        return $(window).scrollTo(target, duration, settings);
    };

    $scrollTo.defaults = {
        axis: 'xy',
        duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1,
        limit: true
    };

    // Returns the element that needs to be animated to scroll the window.
    // Kept for backwards compatibility (specially for localScroll & serialScroll)
    $scrollTo.window = function (scope) {
        return $(window)._scrollable();
    };

    // Hack, hack, hack :)
    // Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
    $.fn._scrollable = function () {
        return this.map(function () {
            var elem = this,
				isWin = !elem.nodeName || $.inArray(elem.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1;

            if (!isWin)
                return elem;

            var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;

            return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
				doc.body :
				doc.documentElement;
        });
    };

    $.fn.scrollTo = function (target, duration, settings) {
        if (typeof duration == 'object') {
            settings = duration;
            duration = 0;
        }
        if (typeof settings == 'function')
            settings = { onAfter: settings };

        if (target == 'max')
            target = 9e9;

        settings = $.extend({}, $scrollTo.defaults, settings);
        // Speed is still recognized for backwards compatibility
        duration = duration || settings.duration;
        // Make sure the settings are given right
        settings.queue = settings.queue && settings.axis.length > 1;

        if (settings.queue)
            // Let's keep the overall duration
            duration /= 2;
        settings.offset = both(settings.offset);
        settings.over = both(settings.over);

        return this._scrollable().each(function () {
            // Null target yields nothing, just like jQuery does
            if (target == null) return;

            var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

            switch (typeof targ) {
                // A number will pass the regex
                case 'number':
                case 'string':
                    if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
                        targ = both(targ);
                        // We are done
                        break;
                    }
                    // Relative/Absolute selector, no break!
                    targ = win ? $(targ) : $(targ, this);
                    if (!targ.length) return;
                case 'object':
                    // DOMElement / jQuery
                    if (targ.is || targ.style)
                        // Get the real position of the target
                        toff = (targ = $(targ)).offset();
            }

            var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;

            $.each(settings.axis.split(''), function (i, axis) {
                var Pos = axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

                if (toff) {// jQuery / DOMElement
                    attr[key] = toff[pos] + (win ? 0 : old - $elem.offset()[pos]);

                    // If it's a dom element, reduce the margin
                    if (settings.margin) {
                        attr[key] -= parseInt(targ.css('margin' + Pos)) || 0;
                        attr[key] -= parseInt(targ.css('border' + Pos + 'Width')) || 0;
                    }

                    attr[key] += offset[pos] || 0;

                    if (settings.over[pos])
                        // Scroll to a fraction of its width/height
                        attr[key] += targ[axis == 'x' ? 'width' : 'height']() * settings.over[pos];
                } else {
                    var val = targ[pos];
                    // Handle percentage values
                    attr[key] = val.slice && val.slice(-1) == '%' ?
						parseFloat(val) / 100 * max
						: val;
                }

                // Number or 'number'
                if (settings.limit && /^\d+$/.test(attr[key]))
                    // Check the limits
                    attr[key] = attr[key] <= 0 ? 0 : Math.min(attr[key], max);

                // Queueing axes
                if (!i && settings.queue) {
                    // Don't waste time animating, if there's no need.
                    if (old != attr[key])
                        // Intermediate animation
                        animate(settings.onAfterFirst);
                    // Don't animate this axis again in the next iteration.
                    delete attr[key];
                }
            });

            animate(settings.onAfter);

            function animate(callback) {
                $elem.animate(attr, duration, settings.easing, callback && function () {
                    callback.call(this, targ, settings);
                });
            };

        }).end();
    };

    // Max scrolling position, works on quirks mode
    // It only fails (not too badly) on IE, quirks mode.
    $scrollTo.max = function (elem, axis) {
        var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll' + Dim;

        if (!$(elem).is('html,body'))
            return elem[scroll] - $(elem)[Dim.toLowerCase()]();

        var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

        return Math.max(html[scroll], body[scroll])
			 - Math.min(html[size], body[size]);
    };

    function both(val) {
        return $.isFunction(val) || typeof val == 'object' ? val : { top: val, left: val };
    };

    // AMD requirement
    return $scrollTo;
}));
;
/*!
 * pickadate.js v3.6.0, 2019/03/12
 * By Amsul, http://amsul.ca
 * Hosted on http://amsul.github.io/pickadate.js
 * Licensed under MIT
 */

(function ( factory ) {

    // AMD.
    if ( typeof define == 'function' && define.amd )
        define( 'picker', ['jquery'], factory )

    // Node.js/browserify.
    else if ( typeof exports == 'object' )
        module.exports = factory( require('jquery') )

    // Browser globals.
    else this.Picker = factory( jQuery )

}(function( $ ) {

var $window = $( window )
var $document = $( document )
var $html = $( document.documentElement )
var supportsTransitions = document.documentElement.style.transition != null


/**
 * The picker constructor that creates a blank picker.
 */
function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) {

    // If there’s no element, return the picker constructor.
    if ( !ELEMENT ) return PickerConstructor


    var
        IS_DEFAULT_THEME = false,


        // The state of the picker.
        STATE = {
            id: ELEMENT.id || 'P' + Math.abs( ~~(Math.random() * new Date()) )
        },


        // Merge the defaults and options passed.
        SETTINGS = COMPONENT ? $.extend( true, {}, COMPONENT.defaults, OPTIONS ) : OPTIONS || {},


        // Merge the default classes with the settings classes.
        CLASSES = $.extend( {}, PickerConstructor.klasses(), SETTINGS.klass ),


        // The element node wrapper into a jQuery object.
        $ELEMENT = $( ELEMENT ),


        // Pseudo picker constructor.
        PickerInstance = function() {
            return this.start()
        },


        // The picker prototype.
        P = PickerInstance.prototype = {

            constructor: PickerInstance,

            $node: $ELEMENT,


            /**
             * Initialize everything
             */
            start: function() {

                // If it’s already started, do nothing.
                if ( STATE && STATE.start ) return P


                // Update the picker states.
                STATE.methods = {}
                STATE.start = true
                STATE.open = false
                STATE.type = ELEMENT.type


                // Confirm focus state, convert into text input to remove UA stylings,
                // and set as readonly to prevent keyboard popup.
                ELEMENT.autofocus = ELEMENT == getActiveElement()
                ELEMENT.readOnly = !SETTINGS.editable
                ELEMENT.id = ELEMENT.id || STATE.id
                if ( ELEMENT.type != 'text' ) {
                    ELEMENT.type = 'text'
                }


                // Create a new picker component with the settings.
                P.component = new COMPONENT(P, SETTINGS)


                // Create the picker root and then prepare it.
                P.$root = $( '<div class="' + CLASSES.picker + '" id="' + ELEMENT.id + '_root" />' )
                prepareElementRoot()


                // Create the picker holder and then prepare it.
                P.$holder = $( createWrappedComponent() ).appendTo( P.$root )
                prepareElementHolder()


                // If there’s a format for the hidden input element, create the element.
                if ( SETTINGS.formatSubmit ) {
                    prepareElementHidden()
                }


                // Prepare the input element.
                prepareElement()


                // Insert the hidden input as specified in the settings.
                if ( SETTINGS.containerHidden ) $( SETTINGS.containerHidden ).append( P._hidden )
                else $ELEMENT.after( P._hidden )


                // Insert the root as specified in the settings.
                if ( SETTINGS.container ) $( SETTINGS.container ).append( P.$root )
                else $ELEMENT.after( P.$root )


                // Bind the default component and settings events.
                P.on({
                    start: P.component.onStart,
                    render: P.component.onRender,
                    stop: P.component.onStop,
                    open: P.component.onOpen,
                    close: P.component.onClose,
                    set: P.component.onSet
                }).on({
                    start: SETTINGS.onStart,
                    render: SETTINGS.onRender,
                    stop: SETTINGS.onStop,
                    open: SETTINGS.onOpen,
                    close: SETTINGS.onClose,
                    set: SETTINGS.onSet
                })


                // Once we’re all set, check the theme in use.
                IS_DEFAULT_THEME = isUsingDefaultTheme( P.$holder[0] )


                // If the element has autofocus, open the picker.
                if ( ELEMENT.autofocus ) {
                    P.open()
                }


                // Trigger queued the “start” and “render” events.
                return P.trigger( 'start' ).trigger( 'render' )
            }, //start


            /**
             * Render a new picker
             */
            render: function( entireComponent ) {

                // Insert a new component holder in the root or box.
                if ( entireComponent ) {
                    P.$holder = $( createWrappedComponent() )
                    prepareElementHolder()
                    P.$root.html( P.$holder )
                }
                else P.$root.find( '.' + CLASSES.box ).html( P.component.nodes( STATE.open ) )

                // Trigger the queued “render” events.
                return P.trigger( 'render' )
            }, //render


            /**
             * Destroy everything
             */
            stop: function() {

                // If it’s already stopped, do nothing.
                if ( !STATE.start ) return P

                // Then close the picker.
                P.close()

                // Remove the hidden field.
                if ( P._hidden ) {
                    P._hidden.parentNode.removeChild( P._hidden )
                }

                // Remove the root.
                P.$root.remove()

                // Remove the input class, remove the stored data, and unbind
                // the events (after a tick for IE - see `P.close`).
                $ELEMENT.removeClass( CLASSES.input ).removeData( NAME )
                setTimeout( function() {
                    $ELEMENT.off( '.' + STATE.id )
                }, 0)

                // Restore the element state
                ELEMENT.type = STATE.type
                ELEMENT.readOnly = false

                // Trigger the queued “stop” events.
                P.trigger( 'stop' )

                // Reset the picker states.
                STATE.methods = {}
                STATE.start = false

                return P
            }, //stop


            /**
             * Open up the picker
             */
            open: function( dontGiveFocus ) {

                // If it’s already open, do nothing.
                if ( STATE.open ) return P

                // Add the “active” class.
                $ELEMENT.addClass( CLASSES.active )
                aria( ELEMENT, 'expanded', true )

                // * A Firefox bug, when `html` has `overflow:hidden`, results in
                //   killing transitions :(. So add the “opened” state on the next tick.
                //   Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
                setTimeout( function() {

                    // Add the “opened” class to the picker root.
                    P.$root.addClass( CLASSES.opened )
                    aria( P.$root[0], 'hidden', false )

                }, 0 )

                // If we have to give focus, bind the element and doc events.
                if ( dontGiveFocus !== false ) {

                    // Set it as open.
                    STATE.open = true

                    // Prevent the page from scrolling.
                    if ( IS_DEFAULT_THEME ) {
                        $('body').
                            css( 'overflow', 'hidden' ).
                            css( 'padding-right', '+=' + getScrollbarWidth() )
                    }

                    // Pass focus to the root element’s jQuery object.
                    focusPickerOnceOpened()

                    // Bind the document events.
                    $document.on( 'click.' + STATE.id + ' focusin.' + STATE.id, function( event ) {

                        var target = getRealEventTarget( event, ELEMENT )

                        // If the target of the event is not the element, close the picker picker.
                        // * Don’t worry about clicks or focusins on the root because those don’t bubble up.
                        //   Also, for Firefox, a click on an `option` element bubbles up directly
                        //   to the doc. So make sure the target wasn't the doc.
                        // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling,
                        //   which causes the picker to unexpectedly close when right-clicking it. So make
                        //   sure the event wasn’t a right-click.
                        // * In Chrome 62 and up, password autofill causes a simulated focusin event which
                        //   closes the picker.
                        if ( ! event.isSimulated && target != ELEMENT && target != document && event.which != 3 ) {

                            // If the target was the holder that covers the screen,
                            // keep the element focused to maintain tabindex.
                            P.close( target === P.$holder[0] )
                        }

                    }).on( 'keydown.' + STATE.id, function( event ) {

                        var
                            // Get the keycode.
                            keycode = event.keyCode,

                            // Translate that to a selection change.
                            keycodeToMove = P.component.key[ keycode ],

                            // Grab the target.
                            target = getRealEventTarget( event, ELEMENT )


                        // On escape, close the picker and give focus.
                        if ( keycode == 27 ) {
                            P.close( true )
                        }


                        // Check if there is a key movement or “enter” keypress on the element.
                        else if ( target == P.$holder[0] && ( keycodeToMove || keycode == 13 ) ) {

                            // Prevent the default action to stop page movement.
                            event.preventDefault()

                            // Trigger the key movement action.
                            if ( keycodeToMove ) {
                                PickerConstructor._.trigger( P.component.key.go, P, [ PickerConstructor._.trigger( keycodeToMove ) ] )
                            }

                            // On “enter”, if the highlighted item isn’t disabled, set the value and close.
                            else if ( !P.$root.find( '.' + CLASSES.highlighted ).hasClass( CLASSES.disabled ) ) {
                                P.set( 'select', P.component.item.highlight )
                                if ( SETTINGS.closeOnSelect ) {
                                    P.close( true )
                                }
                            }
                        }


                        // If the target is within the root and “enter” is pressed,
                        // prevent the default action and trigger a click on the target instead.
                        else if ( $.contains( P.$root[0], target ) && keycode == 13 ) {
                            event.preventDefault()
                            target.click()
                        }
                    })
                }

                // Trigger the queued “open” events.
                return P.trigger( 'open' )
            }, //open


            /**
             * Close the picker
             */
            close: function( giveFocus ) {

                // If we need to give focus, do it before changing states.
                if ( giveFocus ) {
                    if ( SETTINGS.editable ) {
                        ELEMENT.focus()
                    }
                    else {
                        // ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
                        // The focus is triggered *after* the close has completed - causing it
                        // to open again. So unbind and rebind the event at the next tick.
                        P.$holder.off( 'focus.toOpen' ).focus()
                        setTimeout( function() {
                            P.$holder.on( 'focus.toOpen', handleFocusToOpenEvent )
                        }, 0 )
                    }
                }

                // Remove the “active” class.
                $ELEMENT.removeClass( CLASSES.active )
                aria( ELEMENT, 'expanded', false )

                // * A Firefox bug, when `html` has `overflow:hidden`, results in
                //   killing transitions :(. So remove the “opened” state on the next tick.
                //   Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
                setTimeout( function() {

                    // Remove the “opened” and “focused” class from the picker root.
                    P.$root.removeClass( CLASSES.opened + ' ' + CLASSES.focused )
                    aria( P.$root[0], 'hidden', true )

                }, 0 )

                // If it’s already closed, do nothing more.
                if ( !STATE.open ) return P

                // Set it as closed.
                STATE.open = false

                // Allow the page to scroll.
                if ( IS_DEFAULT_THEME ) {
                    $('body').
                        css( 'overflow', '' ).
                        css( 'padding-right', '-=' + getScrollbarWidth() )
                }

                // Unbind the document events.
                $document.off( '.' + STATE.id )

                // Trigger the queued “close” events.
                return P.trigger( 'close' )
            }, //close


            /**
             * Clear the values
             */
            clear: function( options ) {
                return P.set( 'clear', null, options )
            }, //clear


            /**
             * Set something
             */
            set: function( thing, value, options ) {

                var thingItem, thingValue,
                    thingIsObject = $.isPlainObject( thing ),
                    thingObject = thingIsObject ? thing : {}

                // Make sure we have usable options.
                options = thingIsObject && $.isPlainObject( value ) ? value : options || {}

                if ( thing ) {

                    // If the thing isn’t an object, make it one.
                    if ( !thingIsObject ) {
                        thingObject[ thing ] = value
                    }

                    // Go through the things of items to set.
                    for ( thingItem in thingObject ) {

                        // Grab the value of the thing.
                        thingValue = thingObject[ thingItem ]

                        // First, if the item exists and there’s a value, set it.
                        if ( thingItem in P.component.item ) {
                            if ( thingValue === undefined ) thingValue = null
                            P.component.set( thingItem, thingValue, options )
                        }

                        // Then, check to update the element value and broadcast a change.
                        if ( ( thingItem == 'select' || thingItem == 'clear' ) && SETTINGS.updateInput ) {
                            $ELEMENT.
                                val( thingItem == 'clear' ? '' : P.get( thingItem, SETTINGS.format ) ).
                                trigger( 'change' )
                        }
                    }

                    // Render a new picker.
                    P.render()
                }

                // When the method isn’t muted, trigger queued “set” events and pass the `thingObject`.
                return options.muted ? P : P.trigger( 'set', thingObject )
            }, //set


            /**
             * Get something
             */
            get: function( thing, format ) {

                // Make sure there’s something to get.
                thing = thing || 'value'

                // If a picker state exists, return that.
                if ( STATE[ thing ] != null ) {
                    return STATE[ thing ]
                }

                // Return the submission value, if that.
                if ( thing == 'valueSubmit' ) {
                    if ( P._hidden ) {
                        return P._hidden.value
                    }
                    thing = 'value'
                }

                // Return the value, if that.
                if ( thing == 'value' ) {
                    return ELEMENT.value
                }

                // Check if a component item exists, return that.
                if ( thing in P.component.item ) {
                    if ( typeof format == 'string' ) {
                        var thingValue = P.component.get( thing )
                        return thingValue ?
                            PickerConstructor._.trigger(
                                P.component.formats.toString,
                                P.component,
                                [ format, thingValue ]
                            ) : ''
                    }
                    return P.component.get( thing )
                }
            }, //get



            /**
             * Bind events on the things.
             */
            on: function( thing, method, internal ) {

                var thingName, thingMethod,
                    thingIsObject = $.isPlainObject( thing ),
                    thingObject = thingIsObject ? thing : {}

                if ( thing ) {

                    // If the thing isn’t an object, make it one.
                    if ( !thingIsObject ) {
                        thingObject[ thing ] = method
                    }

                    // Go through the things to bind to.
                    for ( thingName in thingObject ) {

                        // Grab the method of the thing.
                        thingMethod = thingObject[ thingName ]

                        // If it was an internal binding, prefix it.
                        if ( internal ) {
                            thingName = '_' + thingName
                        }

                        // Make sure the thing methods collection exists.
                        STATE.methods[ thingName ] = STATE.methods[ thingName ] || []

                        // Add the method to the relative method collection.
                        STATE.methods[ thingName ].push( thingMethod )
                    }
                }

                return P
            }, //on



            /**
             * Unbind events on the things.
             */
            off: function() {
                var i, thingName,
                    names = arguments;
                for ( i = 0, namesCount = names.length; i < namesCount; i += 1 ) {
                    thingName = names[i]
                    if ( thingName in STATE.methods ) {
                        delete STATE.methods[thingName]
                    }
                }
                return P
            },


            /**
             * Fire off method events.
             */
            trigger: function( name, data ) {
                var _trigger = function( name ) {
                    var methodList = STATE.methods[ name ]
                    if ( methodList ) {
                        methodList.map( function( method ) {
                            PickerConstructor._.trigger( method, P, [ data ] )
                        })
                    }
                }
                _trigger( '_' + name )
                _trigger( name )
                return P
            } //trigger
        } //PickerInstance.prototype


    /**
     * Wrap the picker holder components together.
     */
    function createWrappedComponent() {

        // Create a picker wrapper holder
        return PickerConstructor._.node( 'div',

            // Create a picker wrapper node
            PickerConstructor._.node( 'div',

                // Create a picker frame
                PickerConstructor._.node( 'div',

                    // Create a picker box node
                    PickerConstructor._.node( 'div',

                        // Create the components nodes.
                        P.component.nodes( STATE.open ),

                        // The picker box class
                        CLASSES.box
                    ),

                    // Picker wrap class
                    CLASSES.wrap
                ),

                // Picker frame class
                CLASSES.frame
            ),

            // Picker holder class
            CLASSES.holder,

            'tabindex="-1"'
        ) //endreturn
    } //createWrappedComponent



    /**
     * Prepare the input element with all bindings.
     */
    function prepareElement() {

        $ELEMENT.

            // Store the picker data by component name.
            data(NAME, P).

            // Add the “input” class name.
            addClass(CLASSES.input).

            // If there’s a `data-value`, update the value of the element.
            val( $ELEMENT.data('value') ?
                P.get('select', SETTINGS.format) :
                ELEMENT.value
            ).

			// On focus/click, open the picker.
			on('focus.' + STATE.id + ' click.' + STATE.id,
				debounce(function (event) {
					event.preventDefault()
					P.open()
				}, 100))

        // Only bind keydown events if the element isn’t editable.
        if ( !SETTINGS.editable ) {

            $ELEMENT.

                // Handle keyboard event based on the picker being opened or not.
                on( 'keydown.' + STATE.id, handleKeydownEvent )
        }


        // Update the aria attributes.
        aria(ELEMENT, {
            haspopup: true,
            expanded: false,
            readonly: false,
            owns: ELEMENT.id + '_root'
        })
    }


    /**
     * Prepare the root picker element with all bindings.
     */
    function prepareElementRoot() {
        aria( P.$root[0], 'hidden', true )
    }


     /**
      * Prepare the holder picker element with all bindings.
      */
    function prepareElementHolder() {

        P.$holder.

            on({

                // For iOS8.
                keydown: handleKeydownEvent,

                'focus.toOpen': handleFocusToOpenEvent,

                blur: function() {
                    // Remove the “target” class.
                    $ELEMENT.removeClass( CLASSES.target )
                },

                // When something within the holder is focused, stop from bubbling
                // to the doc and remove the “focused” state from the root.
                focusin: function( event ) {
                    P.$root.removeClass( CLASSES.focused )
                    event.stopPropagation()
                },

                // When something within the holder is clicked, stop it
                // from bubbling to the doc.
                'mousedown click': function( event ) {

                    var target = getRealEventTarget( event, ELEMENT )

                    // Make sure the target isn’t the root holder so it can bubble up.
                    if ( target != P.$holder[0] ) {

                        event.stopPropagation()

                        // * For mousedown events, cancel the default action in order to
                        //   prevent cases where focus is shifted onto external elements
                        //   when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
                        //   Also, for Firefox, don’t prevent action on the `option` element.
                        if ( event.type == 'mousedown' && !$( target ).is( 'input, select, textarea, button, option' )) {

                            event.preventDefault()

                            // Re-focus onto the holder so that users can click away
                            // from elements focused within the picker.
                            P.$holder.eq(0).focus()
                        }
                    }
                }

            }).

            // If there’s a click on an actionable element, carry out the actions.
            on( 'click', '[data-pick], [data-nav], [data-clear], [data-close]', function() {

                var $target = $( this ),
                    targetData = $target.data(),
                    targetDisabled = $target.hasClass( CLASSES.navDisabled ) || $target.hasClass( CLASSES.disabled ),

                    // * For IE, non-focusable elements can be active elements as well
                    //   (http://stackoverflow.com/a/2684561).
                    activeElement = getActiveElement()
                    activeElement = activeElement && ( (activeElement.type || activeElement.href ) ? activeElement : null);

                // If it’s disabled or nothing inside is actively focused, re-focus the element.
                if ( targetDisabled || activeElement && !$.contains( P.$root[0], activeElement ) ) {
                    P.$holder.eq(0).focus()
                }

                // If something is superficially changed, update the `highlight` based on the `nav`.
                if ( !targetDisabled && targetData.nav ) {
                    P.set( 'highlight', P.component.item.highlight, { nav: targetData.nav } )
                }

                // If something is picked, set `select` then close with focus.
                else if ( !targetDisabled && 'pick' in targetData ) {
                    P.set( 'select', targetData.pick )
                    if ( SETTINGS.closeOnSelect ) {
                        P.close( true )
                    }
                }

                // If a “clear” button is pressed, empty the values and close with focus.
                else if ( targetData.clear ) {
                    P.clear()
                    if ( SETTINGS.closeOnClear ) {
                        P.close( true )
                    }
                }

                else if ( targetData.close ) {
                    P.close( true )
                }

            }) //P.$holder

    }


     /**
      * Prepare the hidden input element along with all bindings.
      */
    function prepareElementHidden() {

        var name

        if ( SETTINGS.hiddenName === true ) {
            name = ELEMENT.name
            ELEMENT.name = ''
        }
        else {
            name = [
                typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',
                typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'
            ]
            name = name[0] + ELEMENT.name + name[1]
        }

        P._hidden = $(
            '<input ' +
            'type=hidden ' +

            // Create the name using the original input’s with a prefix and suffix.
            'name="' + name + '"' +

            // If the element has a value, set the hidden value as well.
            (
                $ELEMENT.data('value') || ELEMENT.value ?
                    ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' :
                    ''
            ) +
            '>'
        )[0]

        $ELEMENT.

            // If the value changes, update the hidden input with the correct format.
            on('change.' + STATE.id, function() {
                P._hidden.value = ELEMENT.value ?
                    P.get('select', SETTINGS.formatSubmit) :
                    ''
            })
    }


    // Wait for transitions to end before focusing the holder. Otherwise, while
    // using the `container` option, the view jumps to the container.
    function focusPickerOnceOpened() {

        if (IS_DEFAULT_THEME && supportsTransitions) {
            P.$holder.find('.' + CLASSES.frame).one('transitionend', function() {
                P.$holder.eq(0).focus()
            })
        }
        else {
            setTimeout(function() {
                P.$holder.eq(0).focus()
            }, 0)
        }
    }


    function handleFocusToOpenEvent(event) {

        // Stop the event from propagating to the doc.
        event.stopPropagation()

        // Add the “target” class.
        $ELEMENT.addClass( CLASSES.target )

        // Add the “focused” class to the root.
        P.$root.addClass( CLASSES.focused )

        // And then finally open the picker.
        P.open()
    }


    // For iOS8.
    function handleKeydownEvent( event ) {

        var keycode = event.keyCode,

            // Check if one of the delete keys was pressed.
            isKeycodeDelete = /^(8|46)$/.test(keycode)

        // For some reason IE clears the input value on “escape”.
        if ( keycode == 27 ) {
            P.close( true )
            return false
        }

        // Check if `space` or `delete` was pressed or the picker is closed with a key movement.
        if ( keycode == 32 || isKeycodeDelete || !STATE.open && P.component.key[keycode] ) {

            // Prevent it from moving the page and bubbling to doc.
            event.preventDefault()
            event.stopPropagation()

            // If `delete` was pressed, clear the values and close the picker.
            // Otherwise open the picker.
            if ( isKeycodeDelete ) { P.clear().close() }
            else { P.open() }
        }
    }


    // Return a new picker instance.
    return new PickerInstance()
} //PickerConstructor



/**
 * The default classes and prefix to use for the HTML classes.
 */
PickerConstructor.klasses = function( prefix ) {
    prefix = prefix || 'picker'
    return {

        picker: prefix,
        opened: prefix + '--opened',
        focused: prefix + '--focused',

        input: prefix + '__input',
        active: prefix + '__input--active',
        target: prefix + '__input--target',

        holder: prefix + '__holder',

        frame: prefix + '__frame',
        wrap: prefix + '__wrap',

        box: prefix + '__box'
    }
} //PickerConstructor.klasses



/**
 * Check if the default theme is being used.
 */
function isUsingDefaultTheme( element ) {

    var theme,
        prop = 'position'

    // For IE.
    if ( element.currentStyle ) {
        theme = element.currentStyle[prop]
    }

    // For normal browsers.
    else if ( window.getComputedStyle ) {
        theme = getComputedStyle( element )[prop]
    }

    return theme == 'fixed'
}



/**
 * Get the width of the browser’s scrollbar.
 * Taken from: https://github.com/VodkaBears/Remodal/blob/master/src/jquery.remodal.js
 */
function getScrollbarWidth() {

    if ( $html.height() <= $window.height() ) {
        return 0
    }

    var $outer = $( '<div style="visibility:hidden;width:100px" />' ).
        appendTo( 'body' )

    // Get the width without scrollbars.
    var widthWithoutScroll = $outer[0].offsetWidth

    // Force adding scrollbars.
    $outer.css( 'overflow', 'scroll' )

    // Add the inner div.
    var $inner = $( '<div style="width:100%" />' ).appendTo( $outer )

    // Get the width with scrollbars.
    var widthWithScroll = $inner[0].offsetWidth

    // Remove the divs.
    $outer.remove()

    // Return the difference between the widths.
    return widthWithoutScroll - widthWithScroll
}



/**
 * Get the target element from the event.
 * If ELEMENT is supplied and present in the event path (ELEMENT is ancestor of the target),
 * returns ELEMENT instead
 */
function getRealEventTarget( event, ELEMENT ) {

    var path = []

    if ( event.path ) {
        path = event.path
    }

    if ( event.originalEvent && event.originalEvent.path ) {
        path = event.originalEvent.path
    }

    if ( path && path.length > 0 ) {
        if ( ELEMENT && path.indexOf( ELEMENT ) >= 0 ) {
            return ELEMENT
        } else {
            return path[0]
        }
    }

    return event.target
}

	// taken from https://davidwalsh.name/javascript-debounce-function

	function debounce(func, wait, immediate) {
		var timeout;
		return function () {
			var context = this, args = arguments;
			var later = function () {
				timeout = null;
				if (!immediate) func.apply(context, args);
			};
			var callNow = immediate && !timeout;
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
			if (callNow) func.apply(context, args);
		};
	}

/**
 * PickerConstructor helper methods.
 */
PickerConstructor._ = {

    /**
     * Create a group of nodes. Expects:
     * `
        {
            min:    {Integer},
            max:    {Integer},
            i:      {Integer},
            node:   {String},
            item:   {Function}
        }
     * `
     */
    group: function( groupObject ) {

        var
            // Scope for the looped object
            loopObjectScope,

            // Create the nodes list
            nodesList = '',

            // The counter starts from the `min`
            counter = PickerConstructor._.trigger( groupObject.min, groupObject )


        // Loop from the `min` to `max`, incrementing by `i`
        for ( ; counter <= PickerConstructor._.trigger( groupObject.max, groupObject, [ counter ] ); counter += groupObject.i ) {

            // Trigger the `item` function within scope of the object
            loopObjectScope = PickerConstructor._.trigger( groupObject.item, groupObject, [ counter ] )

            // Splice the subgroup and create nodes out of the sub nodes
            nodesList += PickerConstructor._.node(
                groupObject.node,
                loopObjectScope[ 0 ],   // the node
                loopObjectScope[ 1 ],   // the classes
                loopObjectScope[ 2 ]    // the attributes
            )
        }

        // Return the list of nodes
        return nodesList
    }, //group


    /**
     * Create a dom node string
     */
    node: function( wrapper, item, klass, attribute ) {

        // If the item is false-y, just return an empty string
        if ( !item ) return ''

        // If the item is an array, do a join
        item = $.isArray( item ) ? item.join( '' ) : item

        // Check for the class
        klass = klass ? ' class="' + klass + '"' : ''

        // Check for any attributes
        attribute = attribute ? ' ' + attribute : ''

        // Return the wrapped item
        return '<' + wrapper + klass + attribute + '>' + item + '</' + wrapper + '>'
    }, //node


    /**
     * Lead numbers below 10 with a zero.
     */
    lead: function( number ) {
        return ( number < 10 ? '0': '' ) + number
    },


    /**
     * Trigger a function otherwise return the value.
     */
    trigger: function( callback, scope, args ) {
        return typeof callback == 'function' ? callback.apply( scope, args || [] ) : callback
    },


    /**
     * If the second character is a digit, length is 2 otherwise 1.
     */
    digits: function( string ) {
        return ( /\d/ ).test( string[ 1 ] ) ? 2 : 1
    },


    /**
     * Tell if something is a date object.
     */
    isDate: function( value ) {
        return {}.toString.call( value ).indexOf( 'Date' ) > -1 && this.isInteger( value.getDate() )
    },


    /**
     * Tell if something is an integer.
     */
    isInteger: function( value ) {
        return {}.toString.call( value ).indexOf( 'Number' ) > -1 && value % 1 === 0
    },


    /**
     * Create ARIA attribute strings.
     */
    ariaAttr: ariaAttr
} //PickerConstructor._



/**
 * Extend the picker with a component and defaults.
 */
PickerConstructor.extend = function( name, Component ) {

    // Extend jQuery.
    $.fn[ name ] = function( options, action ) {

        // Grab the component data.
        var componentData = this.data( name )

        // If the picker is requested, return the data object.
        if ( options == 'picker' ) {
            return componentData
        }

        // If the component data exists and `options` is a string, carry out the action.
        if ( componentData && typeof options == 'string' ) {
            return PickerConstructor._.trigger( componentData[ options ], componentData, [ action ] )
        }

        // Otherwise go through each matched element and if the component
        // doesn’t exist, create a new picker using `this` element
        // and merging the defaults and options with a deep copy.
        return this.each( function() {
            var $this = $( this )
            if ( !$this.data( name ) ) {
                new PickerConstructor( this, name, Component, options )
            }
        })
    }

    // Set the defaults.
    $.fn[ name ].defaults = Component.defaults
} //PickerConstructor.extend



function aria(element, attribute, value) {
    if ( $.isPlainObject(attribute) ) {
        for ( var key in attribute ) {
            ariaSet(element, key, attribute[key])
        }
    }
    else {
        ariaSet(element, attribute, value)
    }
}
function ariaSet(element, attribute, value) {
    element.setAttribute(
        (attribute == 'role' ? '' : 'aria-') + attribute,
        value
    )
}
function ariaAttr(attribute, data) {
    if ( !$.isPlainObject(attribute) ) {
        attribute = { attribute: data }
    }
    data = ''
    for ( var key in attribute ) {
        var attr = (key == 'role' ? '' : 'aria-') + key,
            attrVal = attribute[key]
        data += attrVal == null ? '' : attr + '="' + attribute[key] + '"'
    }
    return data
}

// IE8 bug throws an error for activeElements within iframes.
function getActiveElement() {
    try {
        return document.activeElement
    } catch ( err ) { }
}



// Expose the picker constructor.
return PickerConstructor


}));
;
/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-05-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. 
 * @website: http://www.datejs.com/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|aft(er)?|from|hence)/i,subtract:/^(\-|bef(ore)?|ago)/i,yesterday:/^yes(terday)?/i,today:/^t(od(ay)?)?/i,tomorrow:/^tom(orrow)?/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^mn|min(ute)?s?/i,hour:/^h(our)?s?/i,week:/^w(eek)?s?/i,month:/^m(onth)?s?/i,day:/^d(ay)?s?/i,year:/^y(ear)?s?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a(?!u|p)|p)/i},timezones:[{name:"UTC",offset:"-000"},{name:"GMT",offset:"-000"},{name:"EST",offset:"-0500"},{name:"EDT",offset:"-0400"},{name:"CST",offset:"-0600"},{name:"CDT",offset:"-0500"},{name:"MST",offset:"-0700"},{name:"MDT",offset:"-0600"},{name:"PST",offset:"-0800"},{name:"PDT",offset:"-0700"}]};
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,p=function(s,l){if(!l){l=2;}
return("000"+s).slice(l*-1);};$P.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};$P.setTimeToNow=function(){var n=new Date();this.setHours(n.getHours());this.setMinutes(n.getMinutes());this.setSeconds(n.getSeconds());this.setMilliseconds(n.getMilliseconds());return this;};$D.today=function(){return new Date().clearTime();};$D.compare=function(date1,date2){if(isNaN(date1)||isNaN(date2)){throw new Error(date1+" - "+date2);}else if(date1 instanceof Date&&date2 instanceof Date){return(date1<date2)?-1:(date1>date2)?1:0;}else{throw new TypeError(date1+" - "+date2);}};$D.equals=function(date1,date2){return(date1.compareTo(date2)===0);};$D.getDayNumberFromName=function(name){var n=$C.dayNames,m=$C.abbreviatedDayNames,o=$C.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s||o[i].toLowerCase()==s){return i;}}
return-1;};$D.getMonthNumberFromName=function(name){var n=$C.monthNames,m=$C.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};$D.isLeapYear=function(year){return((year%4===0&&year%100!==0)||year%400===0);};$D.getDaysInMonth=function(year,month){return[31,($D.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};$D.getTimezoneAbbreviation=function(offset){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].offset===offset){return z[i].name;}}
return null;};$D.getTimezoneOffset=function(name){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].name===name.toUpperCase()){return z[i].offset;}}
return null;};$P.clone=function(){return new Date(this.getTime());};$P.compareTo=function(date){return Date.compare(this,date);};$P.equals=function(date){return Date.equals(this,date||new Date());};$P.between=function(start,end){return this.getTime()>=start.getTime()&&this.getTime()<=end.getTime();};$P.isAfter=function(date){return this.compareTo(date||new Date())===1;};$P.isBefore=function(date){return(this.compareTo(date||new Date())===-1);};$P.isToday=function(){return this.isSameDay(new Date());};$P.isSameDay=function(date){return this.clone().clearTime().equals(date.clone().clearTime());};$P.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};$P.addSeconds=function(value){return this.addMilliseconds(value*1000);};$P.addMinutes=function(value){return this.addMilliseconds(value*60000);};$P.addHours=function(value){return this.addMilliseconds(value*3600000);};$P.addDays=function(value){this.setDate(this.getDate()+value);return this;};$P.addWeeks=function(value){return this.addDays(value*7);};$P.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,$D.getDaysInMonth(this.getFullYear(),this.getMonth())));return this;};$P.addYears=function(value){return this.addMonths(value*12);};$P.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.milliseconds){this.addMilliseconds(x.milliseconds);}
if(x.seconds){this.addSeconds(x.seconds);}
if(x.minutes){this.addMinutes(x.minutes);}
if(x.hours){this.addHours(x.hours);}
if(x.weeks){this.addWeeks(x.weeks);}
if(x.months){this.addMonths(x.months);}
if(x.years){this.addYears(x.years);}
if(x.days){this.addDays(x.days);}
return this;};var $y,$m,$d;$P.getWeek=function(){var a,b,c,d,e,f,g,n,s,w;$y=(!$y)?this.getFullYear():$y;$m=(!$m)?this.getMonth()+1:$m;$d=(!$d)?this.getDate():$d;if($m<=2){a=$y-1;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=0;f=$d-1+(31*($m-1));}else{a=$y;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=s+1;f=$d+((153*($m-3)+2)/5)+58+s;}
g=(a+b)%7;d=(f+g-e)%7;n=(f+3-d)|0;if(n<0){w=53-((g-s)/5|0);}else if(n>364+s){w=1;}else{w=(n/7|0)+1;}
$y=$m=$d=null;return w;};$P.getISOWeek=function(){$y=this.getUTCFullYear();$m=this.getUTCMonth()+1;$d=this.getUTCDate();return p(this.getWeek());};$P.setWeek=function(n){return this.moveToDayOfWeek(1).addWeeks(n-this.getWeek());};$D._validate=function(n,min,max,name){if(typeof n=="undefined"){return false;}else if(typeof n!="number"){throw new TypeError(n+" is not a Number.");}else if(n<min||n>max){throw new RangeError(n+" is not a valid value for "+name+".");}
return true;};$D.validateMillisecond=function(value){return $D._validate(value,0,999,"millisecond");};$D.validateSecond=function(value){return $D._validate(value,0,59,"second");};$D.validateMinute=function(value){return $D._validate(value,0,59,"minute");};$D.validateHour=function(value){return $D._validate(value,0,23,"hour");};$D.validateDay=function(value,year,month){return $D._validate(value,1,$D.getDaysInMonth(year,month),"day");};$D.validateMonth=function(value){return $D._validate(value,0,11,"month");};$D.validateYear=function(value){return $D._validate(value,0,9999,"year");};$P.set=function(config){if($D.validateMillisecond(config.millisecond)){this.addMilliseconds(config.millisecond-this.getMilliseconds());}
if($D.validateSecond(config.second)){this.addSeconds(config.second-this.getSeconds());}
if($D.validateMinute(config.minute)){this.addMinutes(config.minute-this.getMinutes());}
if($D.validateHour(config.hour)){this.addHours(config.hour-this.getHours());}
if($D.validateMonth(config.month)){this.addMonths(config.month-this.getMonth());}
if($D.validateYear(config.year)){this.addYears(config.year-this.getFullYear());}
if($D.validateDay(config.day,this.getFullYear(),this.getMonth())){this.addDays(config.day-this.getDate());}
if(config.timezone){this.setTimezone(config.timezone);}
if(config.timezoneOffset){this.setTimezoneOffset(config.timezoneOffset);}
if(config.week&&$D._validate(config.week,0,53,"week")){this.setWeek(config.week);}
return this;};$P.moveToFirstDayOfMonth=function(){return this.set({day:1});};$P.moveToLastDayOfMonth=function(){return this.set({day:$D.getDaysInMonth(this.getFullYear(),this.getMonth())});};$P.moveToNthOccurrence=function(dayOfWeek,occurrence){var shift=0;if(occurrence>0){shift=occurrence-1;}
else if(occurrence===-1){this.moveToLastDayOfMonth();if(this.getDay()!==dayOfWeek){this.moveToDayOfWeek(dayOfWeek,-1);}
return this;}
return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek,+1).addWeeks(shift);};$P.moveToDayOfWeek=function(dayOfWeek,orient){var diff=(dayOfWeek-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};$P.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};$P.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/86400000)+1;};$P.getTimezone=function(){return $D.getTimezoneAbbreviation(this.getUTCOffset());};$P.setTimezoneOffset=function(offset){var here=this.getTimezoneOffset(),there=Number(offset)*-6/10;return this.addMinutes(there-here);};$P.setTimezone=function(offset){return this.setTimezoneOffset($D.getTimezoneOffset(offset));};$P.hasDaylightSavingTime=function(){return(Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.isDaylightSavingTime=function(){return(this.hasDaylightSavingTime()&&new Date().getTimezoneOffset()===Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r.charAt(0)+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};$P.getElapsed=function(date){return(date||new Date())-this;};if(!$P.toISOString){$P.toISOString=function(){function f(n){return n<10?'0'+n:n;}
return'"'+this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z"';};}
$P._toString=$P.toString;$P.toString=function(format){var x=this;if(format&&format.length==1){var c=$C.formatPatterns;x.t=x.toString;switch(format){case"d":return x.t(c.shortDate);case"D":return x.t(c.longDate);case"F":return x.t(c.fullDateTime);case"m":return x.t(c.monthDay);case"r":return x.t(c.rfc1123);case"s":return x.t(c.sortableDateTime);case"t":return x.t(c.shortTime);case"T":return x.t(c.longTime);case"u":return x.t(c.universalSortableDateTime);case"y":return x.t(c.yearMonth);}}
var ord=function(n){switch(n*1){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};return format?format.replace(/(\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S)/g,function(m){if(m.charAt(0)==="\\"){return m.replace("\\","");}
x.h=x.getHours;switch(m){case"hh":return p(x.h()<13?(x.h()===0?12:x.h()):(x.h()-12));case"h":return x.h()<13?(x.h()===0?12:x.h()):(x.h()-12);case"HH":return p(x.h());case"H":return x.h();case"mm":return p(x.getMinutes());case"m":return x.getMinutes();case"ss":return p(x.getSeconds());case"s":return x.getSeconds();case"yyyy":return p(x.getFullYear(),4);case"yy":return p(x.getFullYear());case"dddd":return $C.dayNames[x.getDay()];case"ddd":return $C.abbreviatedDayNames[x.getDay()];case"dd":return p(x.getDate());case"d":return x.getDate();case"MMMM":return $C.monthNames[x.getMonth()];case"MMM":return $C.abbreviatedMonthNames[x.getMonth()];case"MM":return p((x.getMonth()+1));case"M":return x.getMonth()+1;case"t":return x.h()<12?$C.amDesignator.substring(0,1):$C.pmDesignator.substring(0,1);case"tt":return x.h()<12?$C.amDesignator:$C.pmDesignator;case"S":return ord(x.getDate());default:return m;}}):this._toString();};}());
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,$N=Number.prototype;$P._orient=+1;$P._nth=null;$P._is=false;$P._same=false;$P._isSecond=false;$N._dateElement="day";$P.next=function(){this._orient=+1;return this;};$D.next=function(){return $D.today().next();};$P.last=$P.prev=$P.previous=function(){this._orient=-1;return this;};$D.last=$D.prev=$D.previous=function(){return $D.today().last();};$P.is=function(){this._is=true;return this;};$P.same=function(){this._same=true;this._isSecond=false;return this;};$P.today=function(){return this.same().day();};$P.weekday=function(){if(this._is){this._is=false;return(!this.is().sat()&&!this.is().sun());}
return false;};$P.at=function(time){return(typeof time==="string")?$D.parse(this.toString("d")+" "+time):this.set(time);};$N.fromNow=$N.after=function(date){var c={};c[this._dateElement]=this;return((!date)?new Date():date.clone()).add(c);};$N.ago=$N.before=function(date){var c={};c[this._dateElement]=this*-1;return((!date)?new Date():date.clone()).add(c);};var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),pxf=("Milliseconds Seconds Minutes Hours Date Week Month FullYear").split(/\s/),nth=("final first second third fourth fifth").split(/\s/),de;$P.toObject=function(){var o={};for(var i=0;i<px.length;i++){o[px[i].toLowerCase()]=this["get"+pxf[i]]();}
return o;};$D.fromObject=function(config){config.week=null;return Date.today().set(config);};var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
if(this._nth!==null){if(this._isSecond){this.addSeconds(this._orient*-1);}
this._isSecond=false;var ntemp=this._nth;this._nth=null;var temp=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(n,ntemp);if(this>temp){throw new RangeError($D.getDayName(n)+" does not occur "+ntemp+" times in the month of "+$D.getMonthName(temp.getMonth())+" "+temp.getFullYear()+".");}
return this;}
return this.moveToDayOfWeek(n,this._orient);};};var sdf=function(n){return function(){var t=$D.today(),shift=n-t.getDay();if(n===0&&$C.firstDayOfWeek===1&&t.getDay()!==0){shift=shift+7;}
return t.addDays(shift);};};for(var i=0;i<dx.length;i++){$D[dx[i].toUpperCase()]=$D[dx[i].toUpperCase().substring(0,3)]=i;$D[dx[i]]=$D[dx[i].substring(0,3)]=sdf(i);$P[dx[i]]=$P[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};var smf=function(n){return function(){return $D.today().set({month:n,day:1});};};for(var j=0;j<mx.length;j++){$D[mx[j].toUpperCase()]=$D[mx[j].toUpperCase().substring(0,3)]=j;$D[mx[j]]=$D[mx[j].substring(0,3)]=smf(j);$P[mx[j]]=$P[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(this._isSecond){this._isSecond=false;return this;}
if(this._same){this._same=this._is=false;var o1=this.toObject(),o2=(arguments[0]||new Date()).toObject(),v="",k=j.toLowerCase();for(var m=(px.length-1);m>-1;m--){v=px[m].toLowerCase();if(o1[v]!=o2[v]){return false;}
if(k==v){break;}}
return true;}
if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$P[de]=$P[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}
$P._ss=ef("Second");var nthfn=function(n){return function(dayOfWeek){if(this._same){return this._ss(arguments[0]);}
if(dayOfWeek||dayOfWeek===0){return this.moveToNthOccurrence(dayOfWeek,n);}
this._nth=n;if(n===2&&(dayOfWeek===undefined||dayOfWeek===null)){this._isSecond=true;return this.addSeconds(this._orient);}
return this;};};for(var l=0;l<nth.length;l++){$P[nth[l]]=(l===0)?nthfn(-1):nthfn(l);}}());
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo;var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};$D.Grammar={};$D.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=(s.length==3)?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4:Number(s)-1;};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<$C.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
var now=new Date();if((this.hour||this.minute)&&(!this.month&&!this.year&&!this.day)){this.day=now.getDate();}
if(!this.year){this.year=now.getFullYear();}
if(!this.month&&this.month!==0){this.month=now.getMonth();}
if(!this.day){this.day=1;}
if(!this.hour){this.hour=0;}
if(!this.minute){this.minute=0;}
if(!this.second){this.second=0;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.day>$D.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
var today=$D.today();if(this.now&&!this.unit&&!this.operator){return new Date();}else if(this.now){today=new Date();}
var expression=!!(this.days&&this.days!==null||this.orient||this.operator);var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(!this.now&&"hour minute second".indexOf(this.unit)!=-1){today.setTimeToNow();}
if(this.month||this.month===0){if("year day hour minute second".indexOf(this.unit)!=-1){this.value=this.month+1;this.month=null;expression=true;}}
if(!expression&&this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(!this.month){this.month=temp.getMonth();}
this.year=temp.getFullYear();}
if(expression&&this.weekday&&this.unit!="month"){this.unit="day";gap=($D.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month&&this.unit=="day"&&this.operator){this.value=(this.month+1);this.month=null;}
if(this.value!=null&&this.month!=null&&this.year!=null){this.day=this.value*1;}
if(this.month&&!this.day&&this.value){today.set({day:this.value*1});if(!expression){this.day=this.value*1;}}
if(!this.month&&this.value&&this.unit=="month"&&!this.now){this.month=this.value;expression=true;}
if(expression&&(this.month||this.month===0)&&this.unit!="year"){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(!this.value&&this.operator&&this.operator!==null&&this[this.unit+"s"]&&this[this.unit+"s"]!==null){this[this.unit+"s"]=this[this.unit+"s"]+((this.operator=="add")?1:-1)+(this.value||0)*orient;}else if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
this[this.unit+"s"]=this.value*orient;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(temp.getMonth()!==today.getMonth()){this.month=temp.getMonth();}}
if((this.month||this.month===0)&&!this.day){this.day=1;}
if(!this.orient&&!this.operator&&this.unit=="week"&&this.value&&!this.day&&!this.month){return Date.today().setWeek(this.value);}
if(expression&&this.timezone&&this.day&&this.days){this.day=this.days;}
return(expression)?today.add(this):today.set(this);}};var _=$D.Parsing.Operators,g=$D.Grammar,t=$D.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|@|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=$C.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken($C.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.m,g.s],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("second minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[$C.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw $D.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["\"yyyy-MM-ddTHH:mm:ssZ\"","yyyy-MM-ddTHH:mm:ssZ","yyyy-MM-ddTHH:mm:ssz","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mmZ","yyyy-MM-ddTHH:mmz","yyyy-MM-ddTHH:mm","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","MMddyyyy","ddMMyyyy","Mddyyyy","ddMyyyy","Mdyyyy","dMyyyy","yyyy","Mdyy","dMyy","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};$D._parse=$D.parse;$D.parse=function(s){var r=null;if(!s){return null;}
if(s instanceof Date){return s;}
try{r=$D.Grammar.start.call({},s.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"));}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};$D.getParseFunction=function(fx){var fn=$D.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};$D.parseExact=function(s,fx){return $D.getParseFunction(fx)(s);};}());;
/*!
 * Date picker for pickadate.js v3.6.0
 * http://amsul.github.io/pickadate.js/date.htm
 */

(function ( factory ) {

    // AMD.
    if ( typeof define == 'function' && define.amd )
        define( ['./picker', 'jquery'], factory )

    // Node.js/browserify.
    else if ( typeof exports == 'object' )
        module.exports = factory( require('./picker.js'), require('jquery') )

    // Browser globals.
    else factory( Picker, jQuery )

}(function( Picker, $ ) {


/**
 * Globals and constants
 */
var DAYS_IN_WEEK = 7,
    WEEKS_IN_CALENDAR = 6,
    _ = Picker._



/**
 * The date picker constructor
 */
function DatePicker( picker, settings ) {

    var calendar = this,
        element = picker.$node[ 0 ],
        elementValue = element.value,
        elementDataValue = picker.$node.data( 'value' ),
        valueString = elementDataValue || elementValue,
        formatString = elementDataValue ? settings.formatSubmit : settings.format,
        isRTL = function() {

            return element.currentStyle ?

                // For IE.
                element.currentStyle.direction == 'rtl' :

                // For normal browsers.
                getComputedStyle( picker.$root[0] ).direction == 'rtl'
        }

    calendar.settings = settings
    calendar.$node = picker.$node

    // The queue of methods that will be used to build item objects.
    calendar.queue = {
        min: 'measure create',
        max: 'measure create',
        now: 'now create',
        select: 'parse create validate',
        highlight: 'parse navigate create validate',
        view: 'parse create validate viewset',
        disable: 'deactivate',
        enable: 'activate'
    }

    // The component's item object.
    calendar.item = {}

    calendar.item.clear = null
    calendar.item.disable = ( settings.disable || [] ).slice( 0 )
    calendar.item.enable = -(function( collectionDisabled ) {
        return collectionDisabled[ 0 ] === true ? collectionDisabled.shift() : -1
    })( calendar.item.disable )

    calendar.
        set( 'min', settings.min ).
        set( 'max', settings.max ).
        set( 'now' )

    // When there’s a value, set the `select`, which in turn
    // also sets the `highlight` and `view`.
    if ( valueString ) {
        calendar.set( 'select', valueString, {
            format: formatString,
            defaultValue: true
        })
    }

    // If there’s no value, default to highlighting “today”.
    else {
        calendar.
            set( 'select', null ).
            set( 'highlight', calendar.item.now )
    }


    // The keycode to movement mapping.
    calendar.key = {
        40: 7, // Down
        38: -7, // Up
        39: function() { return isRTL() ? -1 : 1 }, // Right
        37: function() { return isRTL() ? 1 : -1 }, // Left
        go: function( timeChange ) {
            var highlightedObject = calendar.item.highlight,
                targetDate = new Date( highlightedObject.year, highlightedObject.month, highlightedObject.date + timeChange )
            calendar.set(
                'highlight',
                targetDate,
                { interval: timeChange }
            )
            this.render()
        }
    }


    // Bind some picker events.
    picker.
        on( 'render', function() {
            picker.$root.find( '.' + settings.klass.selectMonth ).on( 'change', function() {
                var value = this.value
                if ( value ) {
                    picker.set( 'highlight', [ picker.get( 'view' ).year, value, picker.get( 'highlight' ).date ] )
                    picker.$root.find( '.' + settings.klass.selectMonth ).trigger( 'focus' )
                }
            })
            picker.$root.find( '.' + settings.klass.selectYear ).on( 'change', function() {
                var value = this.value
                if ( value ) {
                    picker.set( 'highlight', [ value, picker.get( 'view' ).month, picker.get( 'highlight' ).date ] )
                    picker.$root.find( '.' + settings.klass.selectYear ).trigger( 'focus' )
                }
            })
        }, 1 ).
        on( 'open', function() {
            var includeToday = ''
            if ( calendar.disabled( calendar.get('now') ) ) {
                includeToday = ':not(.' + settings.klass.buttonToday + ')'
            }
            picker.$root.find( 'button' + includeToday + ', select' ).attr( 'disabled', false )
        }, 1 ).
        on( 'close', function() {
            picker.$root.find( 'button, select' ).attr( 'disabled', true )
        }, 1 )

} //DatePicker


/**
 * Set a datepicker item object.
 */
DatePicker.prototype.set = function( type, value, options ) {

    var calendar = this,
        calendarItem = calendar.item

    // If the value is `null` just set it immediately.
    if ( value === null ) {
        if ( type == 'clear' ) type = 'select'
        calendarItem[ type ] = value
        return calendar
    }

    // Otherwise go through the queue of methods, and invoke the functions.
    // Update this as the time unit, and set the final value as this item.
    // * In the case of `enable`, keep the queue but set `disable` instead.
    //   And in the case of `flip`, keep the queue but set `enable` instead.
    calendarItem[ ( type == 'enable' ? 'disable' : type == 'flip' ? 'enable' : type ) ] = calendar.queue[ type ].split( ' ' ).map( function( method ) {
        value = calendar[ method ]( type, value, options )
        return value
    }).pop()

    // Check if we need to cascade through more updates.
    if ( type == 'select' ) {
        calendar.set( 'highlight', calendarItem.select, options )
    }
    else if ( type == 'highlight' ) {
        calendar.set( 'view', calendarItem.highlight, options )
    }
    else if ( type.match( /^(flip|min|max|disable|enable)$/ ) ) {
        if ( calendarItem.select && calendar.disabled( calendarItem.select ) ) {
            calendar.set( 'select', calendarItem.select, options )
        }
        if ( calendarItem.highlight && calendar.disabled( calendarItem.highlight ) ) {
            calendar.set( 'highlight', calendarItem.highlight, options )
        }
    }

    return calendar
} //DatePicker.prototype.set


/**
 * Get a datepicker item object.
 */
DatePicker.prototype.get = function( type ) {
    return this.item[ type ]
} //DatePicker.prototype.get


/**
 * Create a picker date object.
 */
DatePicker.prototype.create = function( type, value, options ) {

    var isInfiniteValue,
        calendar = this

    // If there’s no value, use the type as the value.
    value = value === undefined ? type : value


    // If it’s infinity, update the value.
    if ( value == -Infinity || value == Infinity ) {
        isInfiniteValue = value
    }

    // If it’s an object, use the native date object.
    else if ( $.isPlainObject( value ) && _.isInteger( value.pick ) ) {
        value = value.obj
    }

    // If it’s an array, convert it into a date and make sure
    // that it’s a valid date – otherwise default to today.
    else if ( $.isArray( value ) ) {
        value = new Date( value[ 0 ], value[ 1 ], value[ 2 ] )
        value = _.isDate( value ) ? value : calendar.create().obj
    }

    // If it’s a number or date object, make a normalized date.
    else if ( _.isInteger( value ) || _.isDate( value ) ) {
        value = calendar.normalize( new Date( value ), options )
    }

    // If it’s a literal true or any other case, set it to now.
    else /*if ( value === true )*/ {
        value = calendar.now( type, value, options )
    }

    // Return the compiled object.
    return {
        year: isInfiniteValue || value.getFullYear(),
        month: isInfiniteValue || value.getMonth(),
        date: isInfiniteValue || value.getDate(),
        day: isInfiniteValue || value.getDay(),
        obj: isInfiniteValue || value,
        pick: isInfiniteValue || value.getTime()
    }
} //DatePicker.prototype.create


/**
 * Create a range limit object using an array, date object,
 * literal “true”, or integer relative to another time.
 */
DatePicker.prototype.createRange = function( from, to ) {

    var calendar = this,
        createDate = function( date ) {
            if ( date === true || $.isArray( date ) || _.isDate( date ) ) {
                return calendar.create( date )
            }
            return date
        }

    // Create objects if possible.
    if ( !_.isInteger( from ) ) {
        from = createDate( from )
    }
    if ( !_.isInteger( to ) ) {
        to = createDate( to )
    }

    // Create relative dates.
    if ( _.isInteger( from ) && $.isPlainObject( to ) ) {
        from = [ to.year, to.month, to.date + from ];
    }
    else if ( _.isInteger( to ) && $.isPlainObject( from ) ) {
        to = [ from.year, from.month, from.date + to ];
    }

    return {
        from: createDate( from ),
        to: createDate( to )
    }
} //DatePicker.prototype.createRange


/**
 * Check if a date unit falls within a date range object.
 */
DatePicker.prototype.withinRange = function( range, dateUnit ) {
    range = this.createRange(range.from, range.to)
    return dateUnit.pick >= range.from.pick && dateUnit.pick <= range.to.pick
}


/**
 * Check if two date range objects overlap.
 */
DatePicker.prototype.overlapRanges = function( one, two ) {

    var calendar = this

    // Convert the ranges into comparable dates.
    one = calendar.createRange( one.from, one.to )
    two = calendar.createRange( two.from, two.to )

    return calendar.withinRange( one, two.from ) || calendar.withinRange( one, two.to ) ||
        calendar.withinRange( two, one.from ) || calendar.withinRange( two, one.to )
}


/**
 * Get the date today.
 */
DatePicker.prototype.now = function( type, value, options ) {
    value = new Date()
    if ( options && options.rel ) {
        value.setDate( value.getDate() + options.rel )
    }
    return this.normalize( value, options )
}


/**
 * Navigate to next/prev month.
 */
DatePicker.prototype.navigate = function( type, value, options ) {

    var targetDateObject,
        targetYear,
        targetMonth,
        targetDate,
        isTargetArray = $.isArray( value ),
        isTargetObject = $.isPlainObject( value ),
        viewsetObject = this.item.view/*,
        safety = 100*/


    if ( isTargetArray || isTargetObject ) {

        if ( isTargetObject ) {
            targetYear = value.year
            targetMonth = value.month
            targetDate = value.date
        }
        else {
            targetYear = +value[0]
            targetMonth = +value[1]
            targetDate = +value[2]
        }

        // If we’re navigating months but the view is in a different
        // month, navigate to the view’s year and month.
        if ( options && options.nav && viewsetObject && viewsetObject.month !== targetMonth ) {
            targetYear = viewsetObject.year
            targetMonth = viewsetObject.month
        }

        // Figure out the expected target year and month.
        targetDateObject = new Date( targetYear, targetMonth + ( options && options.nav ? options.nav : 0 ), 1 )
        targetYear = targetDateObject.getFullYear()
        targetMonth = targetDateObject.getMonth()

        // If the month we’re going to doesn’t have enough days,
        // keep decreasing the date until we reach the month’s last date.
        while ( /*safety &&*/ new Date( targetYear, targetMonth, targetDate ).getMonth() !== targetMonth ) {
            targetDate -= 1
            /*safety -= 1
            if ( !safety ) {
                throw 'Fell into an infinite loop while navigating to ' + new Date( targetYear, targetMonth, targetDate ) + '.'
            }*/
        }

        value = [ targetYear, targetMonth, targetDate ]
    }

    return value
} //DatePicker.prototype.navigate


/**
 * Normalize a date by setting the hours to midnight.
 */
DatePicker.prototype.normalize = function( value/*, options*/ ) {
    value.setHours( 0, 0, 0, 0 )
    return value
}


/**
 * Measure the range of dates.
 */
DatePicker.prototype.measure = function( type, value/*, options*/ ) {

    var calendar = this
    
    // If it's an integer, get a date relative to today.
    if ( _.isInteger( value ) ) {
        value = calendar.now( type, value, { rel: value } )
    }

    // If it’s anything false-y, remove the limits.
    else if ( !value ) {
        value = type == 'min' ? -Infinity : Infinity
    }

    // If it’s a string, parse it.
    else if ( typeof value == 'string' ) {
        value = calendar.parse( type, value )
    }

    return value
} ///DatePicker.prototype.measure


/**
 * Create a viewset object based on navigation.
 */
DatePicker.prototype.viewset = function( type, dateObject/*, options*/ ) {
    return this.create([ dateObject.year, dateObject.month, 1 ])
}


/**
 * Validate a date as enabled and shift if needed.
 */
DatePicker.prototype.validate = function( type, dateObject, options ) {

    var calendar = this,

        // Keep a reference to the original date.
        originalDateObject = dateObject,

        // Make sure we have an interval.
        interval = options && options.interval ? options.interval : 1,

        // Check if the calendar enabled dates are inverted.
        isFlippedBase = calendar.item.enable === -1,

        // Check if we have any enabled dates after/before now.
        hasEnabledBeforeTarget, hasEnabledAfterTarget,

        // The min & max limits.
        minLimitObject = calendar.item.min,
        maxLimitObject = calendar.item.max,

        // Check if we’ve reached the limit during shifting.
        reachedMin, reachedMax,

        // Check if the calendar is inverted and at least one weekday is enabled.
        hasEnabledWeekdays = isFlippedBase && calendar.item.disable.filter( function( value ) {

            // If there’s a date, check where it is relative to the target.
            if ( $.isArray( value ) ) {
                var dateTime = calendar.create( value ).pick
                if ( dateTime < dateObject.pick ) hasEnabledBeforeTarget = true
                else if ( dateTime > dateObject.pick ) hasEnabledAfterTarget = true
            }

            // Return only integers for enabled weekdays.
            return _.isInteger( value )
        }).length/*,

        safety = 100*/



    // Cases to validate for:
    // [1] Not inverted and date disabled.
    // [2] Inverted and some dates enabled.
    // [3] Not inverted and out of range.
    //
    // Cases to **not** validate for:
    // • Navigating months.
    // • Not inverted and date enabled.
    // • Inverted and all dates disabled.
    // • ..and anything else.
    if ( !options || (!options.nav && !options.defaultValue) ) if (
        /* 1 */ ( !isFlippedBase && calendar.disabled( dateObject ) ) ||
        /* 2 */ ( isFlippedBase && calendar.disabled( dateObject ) && ( hasEnabledWeekdays || hasEnabledBeforeTarget || hasEnabledAfterTarget ) ) ||
        /* 3 */ ( !isFlippedBase && (dateObject.pick <= minLimitObject.pick || dateObject.pick >= maxLimitObject.pick) )
    ) {


        // When inverted, flip the direction if there aren’t any enabled weekdays
        // and there are no enabled dates in the direction of the interval.
        if ( isFlippedBase && !hasEnabledWeekdays && ( ( !hasEnabledAfterTarget && interval > 0 ) || ( !hasEnabledBeforeTarget && interval < 0 ) ) ) {
            interval *= -1
        }


        // Keep looping until we reach an enabled date.
        while ( /*safety &&*/ calendar.disabled( dateObject ) ) {

            /*safety -= 1
            if ( !safety ) {
                throw 'Fell into an infinite loop while validating ' + dateObject.obj + '.'
            }*/


            // If we’ve looped into the next/prev month with a large interval, return to the original date and flatten the interval.
            if ( Math.abs( interval ) > 1 && ( dateObject.month < originalDateObject.month || dateObject.month > originalDateObject.month ) ) {
                dateObject = originalDateObject
                interval = interval > 0 ? 1 : -1
            }


            // If we’ve reached the min/max limit, reverse the direction, flatten the interval and set it to the limit.
            if ( dateObject.pick <= minLimitObject.pick ) {
                reachedMin = true
                interval = 1
                dateObject = calendar.create([
                    minLimitObject.year,
                    minLimitObject.month,
                    minLimitObject.date + (dateObject.pick === minLimitObject.pick ? 0 : -1)
                ])
            }
            else if ( dateObject.pick >= maxLimitObject.pick ) {
                reachedMax = true
                interval = -1
                dateObject = calendar.create([
                    maxLimitObject.year,
                    maxLimitObject.month,
                    maxLimitObject.date + (dateObject.pick === maxLimitObject.pick ? 0 : 1)
                ])
            }


            // If we’ve reached both limits, just break out of the loop.
            if ( reachedMin && reachedMax ) {
                break
            }


            // Finally, create the shifted date using the interval and keep looping.
            dateObject = calendar.create([ dateObject.year, dateObject.month, dateObject.date + interval ])
        }

    } //endif


    // Return the date object settled on.
    return dateObject
} //DatePicker.prototype.validate


/**
 * Check if a date is disabled.
 */
DatePicker.prototype.disabled = function( dateToVerify ) {

    var
        calendar = this,

        // Filter through the disabled dates to check if this is one.
        isDisabledMatch = calendar.item.disable.filter( function( dateToDisable ) {

            // If the date is a number, match the weekday with 0index and `firstDay` check.
            if ( _.isInteger( dateToDisable ) ) {
                return dateToVerify.day === ( calendar.settings.firstDay ? dateToDisable : dateToDisable - 1 ) % 7
            }

            // If it’s an array or a native JS date, create and match the exact date.
            if ( $.isArray( dateToDisable ) || _.isDate( dateToDisable ) ) {
                return dateToVerify.pick === calendar.create( dateToDisable ).pick
            }

            // If it’s an object, match a date within the “from” and “to” range.
            if ( $.isPlainObject( dateToDisable ) ) {
                return calendar.withinRange( dateToDisable, dateToVerify )
            }
        })

    // If this date matches a disabled date, confirm it’s not inverted.
    isDisabledMatch = isDisabledMatch.length && !isDisabledMatch.filter(function( dateToDisable ) {
        return $.isArray( dateToDisable ) && dateToDisable[3] == 'inverted' ||
            $.isPlainObject( dateToDisable ) && dateToDisable.inverted
    }).length

    // Check the calendar “enabled” flag and respectively flip the
    // disabled state. Then also check if it’s beyond the min/max limits.
    return calendar.item.enable === -1 ? !isDisabledMatch : isDisabledMatch ||
        dateToVerify.pick < calendar.item.min.pick ||
        dateToVerify.pick > calendar.item.max.pick

} //DatePicker.prototype.disabled


/**
 * Parse a string into a usable type.
 */
DatePicker.prototype.parse = function( type, value, options ) {

    var calendar = this,
        parsingObject = {}

    // If it’s already parsed, we’re good.
    if ( !value || typeof value != 'string' ) {
        return value
    }

    // We need a `.format` to parse the value with.
    if ( !( options && options.format ) ) {
        options = options || {}
        options.format = calendar.settings.format
    }

    // Convert the format into an array and then map through it.
    calendar.formats.toArray( options.format ).map( function( label ) {

        var
            // Grab the formatting label.
            formattingLabel = calendar.formats[ label ],

            // The format length is from the formatting label function or the
            // label length without the escaping exclamation (!) mark.
            formatLength = formattingLabel ? _.trigger( formattingLabel, calendar, [ value, parsingObject ] ) : label.replace( /^!/, '' ).length

        // If there's a format label, split the value up to the format length.
        // Then add it to the parsing object with appropriate label.
        if ( formattingLabel ) {
            parsingObject[ label ] = value.substr( 0, formatLength )
        }

        // Update the value as the substring from format length to end.
        value = value.substr( formatLength )
    })

    // Compensate for month 0index.
    return [
        parsingObject.yyyy || parsingObject.yy,
        +( parsingObject.mm || parsingObject.m ) - 1,
        parsingObject.dd || parsingObject.d
    ]
} //DatePicker.prototype.parse


/**
 * Various formats to display the object in.
 */
DatePicker.prototype.formats = (function() {

    // Return the length of the first word in a collection.
    function getWordLengthFromCollection( string, collection, dateObject ) {

        // Grab the first word from the string.
        // Regex pattern from http://stackoverflow.com/q/150033
        var word = string.match( /[^\x00-\x7F]+|\w+/ )[ 0 ]

        // If there's no month index, add it to the date object
        if ( !dateObject.mm && !dateObject.m ) {
            dateObject.m = collection.indexOf( word ) + 1
        }

        // Return the length of the word.
        return word.length
    }

    // Get the length of the first word in a string.
    function getFirstWordLength( string ) {
        return string.match( /\w+/ )[ 0 ].length
    }

    return {

        d: function( string, dateObject ) {

            // If there's string, then get the digits length.
            // Otherwise return the selected date.
            return string ? _.digits( string ) : dateObject.date
        },
        dd: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected date with a leading zero.
            return string ? 2 : _.lead( dateObject.date )
        },
        ddd: function( string, dateObject ) {

            // If there's a string, then get the length of the first word.
            // Otherwise return the short selected weekday.
            return string ? getFirstWordLength( string ) : this.settings.weekdaysShort[ dateObject.day ]
        },
        dddd: function( string, dateObject ) {

            // If there's a string, then get the length of the first word.
            // Otherwise return the full selected weekday.
            return string ? getFirstWordLength( string ) : this.settings.weekdaysFull[ dateObject.day ]
        },
        m: function( string, dateObject ) {

            // If there's a string, then get the length of the digits
            // Otherwise return the selected month with 0index compensation.
            return string ? _.digits( string ) : dateObject.month + 1
        },
        mm: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected month with 0index and leading zero.
            return string ? 2 : _.lead( dateObject.month + 1 )
        },
        mmm: function( string, dateObject ) {

            var collection = this.settings.monthsShort

            // If there's a string, get length of the relevant month from the short
            // months collection. Otherwise return the selected month from that collection.
            return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
        },
        mmmm: function( string, dateObject ) {

            var collection = this.settings.monthsFull

            // If there's a string, get length of the relevant month from the full
            // months collection. Otherwise return the selected month from that collection.
            return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
        },
        yy: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected year by slicing out the first 2 digits.
            return string ? 2 : ( '' + dateObject.year ).slice( 2 )
        },
        yyyy: function( string, dateObject ) {

            // If there's a string, then the length is always 4.
            // Otherwise return the selected year.
            return string ? 4 : dateObject.year
        },

        // Create an array by splitting the formatting string passed.
        toArray: function( formatString ) { return formatString.split( /(d{1,4}|m{1,4}|y{4}|yy|!.)/g ) },

        // Format an object into a string using the formatting options.
        toString: function ( formatString, itemObject ) {
            var calendar = this
            return calendar.formats.toArray( formatString ).map( function( label ) {
                return _.trigger( calendar.formats[ label ], calendar, [ 0, itemObject ] ) || label.replace( /^!/, '' )
            }).join( '' )
        }
    }
})() //DatePicker.prototype.formats




/**
 * Check if two date units are the exact.
 */
DatePicker.prototype.isDateExact = function( one, two ) {

    var calendar = this

    // When we’re working with weekdays, do a direct comparison.
    if (
        ( _.isInteger( one ) && _.isInteger( two ) ) ||
        ( typeof one == 'boolean' && typeof two == 'boolean' )
     ) {
        return one === two
    }

    // When we’re working with date representations, compare the “pick” value.
    if (
        ( _.isDate( one ) || $.isArray( one ) ) &&
        ( _.isDate( two ) || $.isArray( two ) )
    ) {
        return calendar.create( one ).pick === calendar.create( two ).pick
    }

    // When we’re working with range objects, compare the “from” and “to”.
    if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
        return calendar.isDateExact( one.from, two.from ) && calendar.isDateExact( one.to, two.to )
    }

    return false
}


/**
 * Check if two date units overlap.
 */
DatePicker.prototype.isDateOverlap = function( one, two ) {

    var calendar = this,
        firstDay = calendar.settings.firstDay ? 1 : 0

    // When we’re working with a weekday index, compare the days.
    if ( _.isInteger( one ) && ( _.isDate( two ) || $.isArray( two ) ) ) {
        one = one % 7 + firstDay
        return one === calendar.create( two ).day + 1
    }
    if ( _.isInteger( two ) && ( _.isDate( one ) || $.isArray( one ) ) ) {
        two = two % 7 + firstDay
        return two === calendar.create( one ).day + 1
    }

    // When we’re working with range objects, check if the ranges overlap.
    if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
        return calendar.overlapRanges( one, two )
    }

    return false
}


/**
 * Flip the “enabled” state.
 */
DatePicker.prototype.flipEnable = function(val) {
    var itemObject = this.item
    itemObject.enable = val || (itemObject.enable == -1 ? 1 : -1)
}


/**
 * Mark a collection of dates as “disabled”.
 */
DatePicker.prototype.deactivate = function( type, datesToDisable ) {

    var calendar = this,
        disabledItems = calendar.item.disable.slice(0)


    // If we’re flipping, that’s all we need to do.
    if ( datesToDisable == 'flip' ) {
        calendar.flipEnable()
    }

    else if ( datesToDisable === false ) {
        calendar.flipEnable(1)
        disabledItems = []
    }

    else if ( datesToDisable === true ) {
        calendar.flipEnable(-1)
        disabledItems = []
    }

    // Otherwise go through the dates to disable.
    else {

        datesToDisable.map(function( unitToDisable ) {

            var matchFound

            // When we have disabled items, check for matches.
            // If something is matched, immediately break out.
            for ( var index = 0; index < disabledItems.length; index += 1 ) {
                if ( calendar.isDateExact( unitToDisable, disabledItems[index] ) ) {
                    matchFound = true
                    break
                }
            }

            // If nothing was found, add the validated unit to the collection.
            if ( !matchFound ) {
                if (
                    _.isInteger( unitToDisable ) ||
                    _.isDate( unitToDisable ) ||
                    $.isArray( unitToDisable ) ||
                    ( $.isPlainObject( unitToDisable ) && unitToDisable.from && unitToDisable.to )
                ) {
                    disabledItems.push( unitToDisable )
                }
            }
        })
    }

    // Return the updated collection.
    return disabledItems
} //DatePicker.prototype.deactivate


/**
 * Mark a collection of dates as “enabled”.
 */
DatePicker.prototype.activate = function( type, datesToEnable ) {

    var calendar = this,
        disabledItems = calendar.item.disable,
        disabledItemsCount = disabledItems.length

    // If we’re flipping, that’s all we need to do.
    if ( datesToEnable == 'flip' ) {
        calendar.flipEnable()
    }

    else if ( datesToEnable === true ) {
        calendar.flipEnable(1)
        disabledItems = []
    }

    else if ( datesToEnable === false ) {
        calendar.flipEnable(-1)
        disabledItems = []
    }

    // Otherwise go through the disabled dates.
    else {

        datesToEnable.map(function( unitToEnable ) {

            var matchFound,
                disabledUnit,
                index,
                isExactRange

            // Go through the disabled items and try to find a match.
            for ( index = 0; index < disabledItemsCount; index += 1 ) {

                disabledUnit = disabledItems[index]

                // When an exact match is found, remove it from the collection.
                if ( calendar.isDateExact( disabledUnit, unitToEnable ) ) {
                    matchFound = disabledItems[index] = null
                    isExactRange = true
                    break
                }

                // When an overlapped match is found, add the “inverted” state to it.
                else if ( calendar.isDateOverlap( disabledUnit, unitToEnable ) ) {
                    if ( $.isPlainObject( unitToEnable ) ) {
                        unitToEnable.inverted = true
                        matchFound = unitToEnable
                    }
                    else if ( $.isArray( unitToEnable ) ) {
                        matchFound = unitToEnable
                        if ( !matchFound[3] ) matchFound.push( 'inverted' )
                    }
                    else if ( _.isDate( unitToEnable ) ) {
                        matchFound = [ unitToEnable.getFullYear(), unitToEnable.getMonth(), unitToEnable.getDate(), 'inverted' ]
                    }
                    break
                }
            }

            // If a match was found, remove a previous duplicate entry.
            if ( matchFound ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
                if ( calendar.isDateExact( disabledItems[index], unitToEnable ) ) {
                    disabledItems[index] = null
                    break
                }
            }

            // In the event that we’re dealing with an exact range of dates,
            // make sure there are no “inverted” dates because of it.
            if ( isExactRange ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
                if ( calendar.isDateOverlap( disabledItems[index], unitToEnable ) ) {
                    disabledItems[index] = null
                    break
                }
            }

            // If something is still matched, add it into the collection.
            if ( matchFound ) {
                disabledItems.push( matchFound )
            }
        })
    }

    // Return the updated collection.
    return disabledItems.filter(function( val ) { return val != null })
} //DatePicker.prototype.activate


/**
 * Create a string for the nodes in the picker.
 */
DatePicker.prototype.nodes = function( isOpen ) {

    var
        calendar = this,
        settings = calendar.settings,
        calendarItem = calendar.item,
        nowObject = calendarItem.now,
        selectedObject = calendarItem.select,
        highlightedObject = calendarItem.highlight,
        viewsetObject = calendarItem.view,
        disabledCollection = calendarItem.disable,
        minLimitObject = calendarItem.min,
        maxLimitObject = calendarItem.max,


        // Create the calendar table head using a copy of weekday labels collection.
        // * We do a copy so we don't mutate the original array.
        tableHead = (function( collection, fullCollection ) {

            // If the first day should be Monday, move Sunday to the end.
            if ( settings.firstDay ) {
                collection.push( collection.shift() )
                fullCollection.push( fullCollection.shift() )
            }

            // Create and return the table head group.
            return _.node(
                'thead',
                _.node(
                    'tr',
                    _.group({
                        min: 0,
                        max: DAYS_IN_WEEK - 1,
                        i: 1,
                        node: 'th',
                        item: function( counter ) {
                            return [
                                collection[ counter ],
                                settings.klass.weekdays,
                                'scope=col title="' + fullCollection[ counter ] + '"'
                            ]
                        }
                    })
                )
            ) //endreturn
        })( ( settings.showWeekdaysFull ? settings.weekdaysFull : settings.weekdaysShort ).slice( 0 ), settings.weekdaysFull.slice( 0 ) ), //tableHead


        // Create the nav for next/prev month.
        createMonthNav = function( next ) {

            // Otherwise, return the created month tag.
            return _.node(
                'div',
                ' ',
                settings.klass[ 'nav' + ( next ? 'Next' : 'Prev' ) ] + (

                    // If the focused month is outside the range, disabled the button.
                    ( next && viewsetObject.year >= maxLimitObject.year && viewsetObject.month >= maxLimitObject.month ) ||
                    ( !next && viewsetObject.year <= minLimitObject.year && viewsetObject.month <= minLimitObject.month ) ?
                    ' ' + settings.klass.navDisabled : ''
                ),
                'data-nav=' + ( next || -1 ) + ' ' +
                _.ariaAttr({
                    role: 'button',
                    controls: calendar.$node[0].id + '_table'
                }) + ' ' +
                'title="' + (next ? settings.labelMonthNext : settings.labelMonthPrev ) + '"'
            ) //endreturn
        }, //createMonthNav


        // Create the month label.
        createMonthLabel = function() {

            var monthsCollection = settings.showMonthsShort ? settings.monthsShort : settings.monthsFull

            // If there are months to select, add a dropdown menu.
            if ( settings.selectMonths ) {

                return _.node( 'select',
                    _.group({
                        min: 0,
                        max: 11,
                        i: 1,
                        node: 'option',
                        item: function( loopedMonth ) {

                            return [

                                // The looped month and no classes.
                                monthsCollection[ loopedMonth ], 0,

                                // Set the value and selected index.
                                'value=' + loopedMonth +
                                ( viewsetObject.month == loopedMonth ? ' selected' : '' ) +
                                (
                                    (
                                        ( viewsetObject.year == minLimitObject.year && loopedMonth < minLimitObject.month ) ||
                                        ( viewsetObject.year == maxLimitObject.year && loopedMonth > maxLimitObject.month )
                                    ) ?
                                    ' disabled' : ''
                                )
                            ]
                        }
                    }),
                    settings.klass.selectMonth,
                    ( isOpen ? '' : 'disabled' ) + ' ' +
                    _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
                    'title="' + settings.labelMonthSelect + '"'
                )
            }

            // If there's a need for a month selector
            return _.node( 'div', monthsCollection[ viewsetObject.month ], settings.klass.month )
        }, //createMonthLabel


        // Create the year label.
        createYearLabel = function() {

            var focusedYear = viewsetObject.year,

            // If years selector is set to a literal "true", set it to 5. Otherwise
            // divide in half to get half before and half after focused year.
            numberYears = settings.selectYears === true ? 5 : ~~( settings.selectYears / 2 )

            // If there are years to select, add a dropdown menu.
            if ( numberYears ) {

                var
                    minYear = minLimitObject.year,
                    maxYear = maxLimitObject.year,
                    lowestYear = focusedYear - numberYears,
                    highestYear = focusedYear + numberYears

                // If the min year is greater than the lowest year, increase the highest year
                // by the difference and set the lowest year to the min year.
                if ( minYear > lowestYear ) {
                    highestYear += minYear - lowestYear
                    lowestYear = minYear
                }

                // If the max year is less than the highest year, decrease the lowest year
                // by the lower of the two: available and needed years. Then set the
                // highest year to the max year.
                if ( maxYear < highestYear ) {

                    var availableYears = lowestYear - minYear,
                        neededYears = highestYear - maxYear

                    lowestYear -= availableYears > neededYears ? neededYears : availableYears
                    highestYear = maxYear
                }

                return _.node( 'select',
                    _.group({
                        min: lowestYear,
                        max: highestYear,
                        i: 1,
                        node: 'option',
                        item: function( loopedYear ) {
                            return [

                                // The looped year and no classes.
                                loopedYear, 0,

                                // Set the value and selected index.
                                'value=' + loopedYear + ( focusedYear == loopedYear ? ' selected' : '' )
                            ]
                        }
                    }),
                    settings.klass.selectYear,
                    ( isOpen ? '' : 'disabled' ) + ' ' + _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
                    'title="' + settings.labelYearSelect + '"'
                )
            }

            // Otherwise just return the year focused
            return _.node( 'div', focusedYear, settings.klass.year )
        } //createYearLabel


    // Create and return the entire calendar.
    return _.node(
        'div',
        ( settings.selectYears ? createYearLabel() + createMonthLabel() : createMonthLabel() + createYearLabel() ) +
        createMonthNav() + createMonthNav( 1 ),
        settings.klass.header
    ) + _.node(
        'table',
        tableHead +
        _.node(
            'tbody',
            _.group({
                min: 0,
                max: WEEKS_IN_CALENDAR - 1,
                i: 1,
                node: 'tr',
                item: function( rowCounter ) {

                    // If Monday is the first day and the month starts on Sunday, shift the date back a week.
                    var shiftDateBy = settings.firstDay && calendar.create([ viewsetObject.year, viewsetObject.month, 1 ]).day === 0 ? -7 : 0

                    return [
                        _.group({
                            min: DAYS_IN_WEEK * rowCounter - viewsetObject.day + shiftDateBy + 1, // Add 1 for weekday 0index
                            max: function() {
                                return this.min + DAYS_IN_WEEK - 1
                            },
                            i: 1,
                            node: 'td',
                            item: function( targetDate ) {

                                // Convert the time date from a relative date to a target date.
                                targetDate = calendar.create([ viewsetObject.year, viewsetObject.month, targetDate + ( settings.firstDay ? 1 : 0 ) ])

                                var isSelected = selectedObject && selectedObject.pick == targetDate.pick,
                                    isHighlighted = highlightedObject && highlightedObject.pick == targetDate.pick,
                                    isDisabled = disabledCollection && calendar.disabled( targetDate ) || targetDate.pick < minLimitObject.pick || targetDate.pick > maxLimitObject.pick,
                                    formattedDate = _.trigger( calendar.formats.toString, calendar, [ settings.format, targetDate ] )

                                return [
                                    _.node(
                                        'div',
                                        targetDate.date,
                                        (function( klasses ) {

                                            // Add the `infocus` or `outfocus` classes based on month in view.
                                            klasses.push( viewsetObject.month == targetDate.month ? settings.klass.infocus : settings.klass.outfocus )

                                            // Add the `today` class if needed.
                                            if ( nowObject.pick == targetDate.pick ) {
                                                klasses.push( settings.klass.now )
                                            }

                                            // Add the `selected` class if something's selected and the time matches.
                                            if ( isSelected ) {
                                                klasses.push( settings.klass.selected )
                                            }

                                            // Add the `highlighted` class if something's highlighted and the time matches.
                                            if ( isHighlighted ) {
                                                klasses.push( settings.klass.highlighted )
                                            }

                                            // Add the `disabled` class if something's disabled and the object matches.
                                            if ( isDisabled ) {
                                                klasses.push( settings.klass.disabled )
                                            }

                                            return klasses.join( ' ' )
                                        })([ settings.klass.day ]),
                                        'data-pick=' + targetDate.pick + ' ' + _.ariaAttr({
                                            role: 'gridcell',
                                            label: formattedDate,
                                            selected: isSelected && calendar.$node.val() === formattedDate ? true : null,
                                            activedescendant: isHighlighted ? true : null,
                                            disabled: isDisabled ? true : null
                                        })
                                    ),
                                    '',
                                    _.ariaAttr({ role: 'presentation' })
                                ] //endreturn
                            }
                        })
                    ] //endreturn
                }
            })
        ),
        settings.klass.table,
        'id="' + calendar.$node[0].id + '_table' + '" ' + _.ariaAttr({
            role: 'grid',
            controls: calendar.$node[0].id,
            readonly: true
        })
    ) +

    // * For Firefox forms to submit, make sure to set the buttons’ `type` attributes as “button”.
    _.node(
        'div',
        _.node( 'button', settings.today, settings.klass.buttonToday,
            'type=button data-pick=' + nowObject.pick +
            ( isOpen && !calendar.disabled(nowObject) ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ) +
        _.node( 'button', settings.clear, settings.klass.buttonClear,
            'type=button data-clear=1' +
            ( isOpen ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ) +
        _.node('button', settings.close, settings.klass.buttonClose,
            'type=button data-close=true ' +
            ( isOpen ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ),
        settings.klass.footer
    ) //endreturn
} //DatePicker.prototype.nodes




/**
 * The date picker defaults.
 */
DatePicker.defaults = (function( prefix ) {

    return {

        // The title label to use for the month nav buttons
        labelMonthNext: 'Next month',
        labelMonthPrev: 'Previous month',

        // The title label to use for the dropdown selectors
        labelMonthSelect: 'Select a month',
        labelYearSelect: 'Select a year',

        // Months and weekdays
        monthsFull: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
        monthsShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
        weekdaysFull: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
        weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],

        // Today and clear
        today: 'Today',
        clear: 'Clear',
        close: 'Close',

        // Picker close behavior
        closeOnSelect: true,
        closeOnClear: true,

        // Update input value on select/clear
        updateInput: true,

        // The format to show on the `input` element
        format: 'd mmmm, yyyy',

        // Classes
        klass: {

            table: prefix + 'table',

            header: prefix + 'header',

            navPrev: prefix + 'nav--prev',
            navNext: prefix + 'nav--next',
            navDisabled: prefix + 'nav--disabled',

            month: prefix + 'month',
            year: prefix + 'year',

            selectMonth: prefix + 'select--month',
            selectYear: prefix + 'select--year',

            weekdays: prefix + 'weekday',

            day: prefix + 'day',
            disabled: prefix + 'day--disabled',
            selected: prefix + 'day--selected',
            highlighted: prefix + 'day--highlighted',
            now: prefix + 'day--today',
            infocus: prefix + 'day--infocus',
            outfocus: prefix + 'day--outfocus',

            footer: prefix + 'footer',

            buttonClear: prefix + 'button--clear',
            buttonToday: prefix + 'button--today',
            buttonClose: prefix + 'button--close'
        }
    }
})( Picker.klasses().picker + '__' )





/**
 * Extend the picker to add the date picker.
 */
Picker.extend( 'pickadate', DatePicker )


}));



;
!function(a,b,c,d){"use strict";var e="prettyCheckable",f="plugin_"+e,g={label:"",labelPosition:"right",customClass:"",color:"blue"},h=function(c){b.ko&&a(c).on("change",function(b){if(b.preventDefault(),b.originalEvent===d){var c=a(this).closest(".clearfix"),e=a(c).find("a:first"),f=e.hasClass("checked");f===!0?e.addClass("checked"):e.removeClass("checked")}}),c.find("a:first, label").on("touchstart click",function(c){c.preventDefault();var d=a(this).closest(".clearfix"),e=d.find("input"),f=d.find("a:first");f.hasClass("disabled")!==!0&&("radio"===e.prop("type")&&a('input[name="'+e.attr("name")+'"]').each(function(b,c){a(c).prop("checked",!1).parent().find("a:first").removeClass("checked")}),b.ko?ko.utils.triggerEvent(e[0],"click"):e.prop("checked")?e.prop("checked",!1).change():e.prop("checked",!0).change(),f.toggleClass("checked"))}),c.find("a:first").on("keyup",function(b){32===b.keyCode&&a(this).click()})},i=function(b){this.element=b,this.options=a.extend({},g)};i.prototype={init:function(b){a.extend(this.options,b);var c=a(this.element);c.parent().addClass("has-pretty-child"),c.css("display","none");var e=c.data("type")!==d?c.data("type"):c.attr("type"),f=null,g=c.attr("id");if(g!==d){var i=a("label[for="+g+"]");i.length>0&&(f=i.text(),i.remove())}""===this.options.label&&(this.options.label=f),f=c.data("label")!==d?c.data("label"):this.options.label;var j=c.data("labelposition")!==d?"label"+c.data("labelposition"):"label"+this.options.labelPosition,k=c.data("customclass")!==d?c.data("customclass"):this.options.customClass,l=c.data("color")!==d?c.data("color"):this.options.color,m=c.prop("disabled")===!0?"disabled":"",n=["pretty"+e,j,k,l].join(" ");c.wrap('<div class="clearfix '+n+'"></div>').parent().html();var o=[],p=c.prop("checked")?"checked":"";"labelright"===j?(o.push('<a href="#" class="'+p+" "+m+'"></a>'),o.push('<label for="'+c.attr("id")+'">'+f+"</label>")):(o.push('<label for="'+c.attr("id")+'">'+f+"</label>"),o.push('<a href="#" class="'+p+" "+m+'"></a>')),c.parent().append(o.join("\n")),h(c.parent())},check:function(){"radio"===a(this.element).prop("type")&&a('input[name="'+a(this.element).attr("name")+'"]').each(function(b,c){a(c).prop("checked",!1).attr("checked",!1).parent().find("a:first").removeClass("checked")}),a(this.element).prop("checked",!0).attr("checked",!0).parent().find("a:first").addClass("checked")},uncheck:function(){a(this.element).prop("checked",!1).attr("checked",!1).parent().find("a:first").removeClass("checked")},enable:function(){a(this.element).removeAttr("disabled").parent().find("a:first").removeClass("disabled")},disable:function(){a(this.element).attr("disabled","disabled").parent().find("a:first").addClass("disabled")},destroy:function(){var b=a(this.element),c=b.clone(),e=b.attr("id");if(e!==d){var f=a("label[for="+e+"]");f.length>0&&f.insertBefore(b.parent())}c.removeAttr("style").insertAfter(f),b.parent().remove()}},a.fn[e]=function(b){var c,d;if(this.data(f)instanceof i||this.data(f,new i(this)),d=this.data(f),d.element=this,"undefined"==typeof b||"object"==typeof b)"function"==typeof d.init&&d.init(b);else{if("string"==typeof b&&"function"==typeof d[b])return c=Array.prototype.slice.call(arguments,1),d[b].apply(d,c);a.error("Method "+b+" does not exist on jQuery."+e)}}}(jQuery,window,document);;
/*! tooltipster v4.2.6 */!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){function b(a){this.$container,this.constraints=null,this.__$tooltip,this.__init(a)}function c(b,c){var d=!0;return a.each(b,function(a,e){return void 0===c[a]||b[a]!==c[a]?(d=!1,!1):void 0}),d}function d(b){var c=b.attr("id"),d=c?h.window.document.getElementById(c):null;return d?d===b[0]:a.contains(h.window.document.body,b[0])}function e(){if(!g)return!1;var a=g.document.body||g.document.documentElement,b=a.style,c="transition",d=["Moz","Webkit","Khtml","O","ms"];if("string"==typeof b[c])return!0;c=c.charAt(0).toUpperCase()+c.substr(1);for(var e=0;e<d.length;e++)if("string"==typeof b[d[e]+c])return!0;return!1}var f={animation:"fade",animationDuration:350,content:null,contentAsHTML:!1,contentCloning:!1,debug:!0,delay:300,delayTouch:[300,500],functionInit:null,functionBefore:null,functionReady:null,functionAfter:null,functionFormat:null,IEmin:6,interactive:!1,multiple:!1,parent:null,plugins:["sideTip"],repositionOnScroll:!1,restoration:"none",selfDestruction:!0,theme:[],timer:0,trackerInterval:500,trackOrigin:!1,trackTooltip:!1,trigger:"hover",triggerClose:{click:!1,mouseleave:!1,originClick:!1,scroll:!1,tap:!1,touchleave:!1},triggerOpen:{click:!1,mouseenter:!1,tap:!1,touchstart:!1},updateAnimation:"rotate",zIndex:9999999},g="undefined"!=typeof window?window:null,h={hasTouchCapability:!(!g||!("ontouchstart"in g||g.DocumentTouch&&g.document instanceof g.DocumentTouch||g.navigator.maxTouchPoints)),hasTransitions:e(),IE:!1,semVer:"4.2.6",window:g},i=function(){this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__instancesLatestArr=[],this.__plugins={},this._env=h};i.prototype={__bridge:function(b,c,d){if(!c[d]){var e=function(){};e.prototype=b;var g=new e;g.__init&&g.__init(c),a.each(b,function(a,b){0!=a.indexOf("__")&&(c[a]?f.debug&&console.log("The "+a+" method of the "+d+" plugin conflicts with another plugin or native methods"):(c[a]=function(){return g[a].apply(g,Array.prototype.slice.apply(arguments))},c[a].bridged=g))}),c[d]=g}return this},__setWindow:function(a){return h.window=a,this},_getRuler:function(a){return new b(a)},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_plugin:function(b){var c=this;if("string"==typeof b){var d=b,e=null;return d.indexOf(".")>0?e=c.__plugins[d]:a.each(c.__plugins,function(a,b){return b.name.substring(b.name.length-d.length-1)=="."+d?(e=b,!1):void 0}),e}if(b.name.indexOf(".")<0)throw new Error("Plugins must be namespaced");return c.__plugins[b.name]=b,b.core&&c.__bridge(b.core,c,b.name),this},_trigger:function(){var a=Array.prototype.slice.apply(arguments);return"string"==typeof a[0]&&(a[0]={type:a[0]}),this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,a),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,a),this},instances:function(b){var c=[],d=b||".tooltipstered";return a(d).each(function(){var b=a(this),d=b.data("tooltipster-ns");d&&a.each(d,function(a,d){c.push(b.data(d))})}),c},instancesLatest:function(){return this.__instancesLatestArr},off:function(){return this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},origins:function(b){var c=b?b+" ":"";return a(c+".tooltipstered").toArray()},setDefaults:function(b){return a.extend(f,b),this},triggerHandler:function(){return this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.tooltipster=new i,a.Tooltipster=function(b,c){this.__callbacks={close:[],open:[]},this.__closingTime,this.__Content,this.__contentBcr,this.__destroyed=!1,this.__$emitterPrivate=a({}),this.__$emitterPublic=a({}),this.__enabled=!0,this.__garbageCollector,this.__Geometry,this.__lastPosition,this.__namespace="tooltipster-"+Math.round(1e6*Math.random()),this.__options,this.__$originParents,this.__pointerIsOverOrigin=!1,this.__previousThemes=[],this.__state="closed",this.__timeouts={close:[],open:null},this.__touchEvents=[],this.__tracker=null,this._$origin,this._$tooltip,this.__init(b,c)},a.Tooltipster.prototype={__init:function(b,c){var d=this;if(d._$origin=a(b),d.__options=a.extend(!0,{},f,c),d.__optionsFormat(),!h.IE||h.IE>=d.__options.IEmin){var e=null;if(void 0===d._$origin.data("tooltipster-initialTitle")&&(e=d._$origin.attr("title"),void 0===e&&(e=null),d._$origin.data("tooltipster-initialTitle",e)),null!==d.__options.content)d.__contentSet(d.__options.content);else{var g,i=d._$origin.attr("data-tooltip-content");i&&(g=a(i)),g&&g[0]?d.__contentSet(g.first()):d.__contentSet(e)}d._$origin.removeAttr("title").addClass("tooltipstered"),d.__prepareOrigin(),d.__prepareGC(),a.each(d.__options.plugins,function(a,b){d._plug(b)}),h.hasTouchCapability&&a(h.window.document.body).on("touchmove."+d.__namespace+"-triggerOpen",function(a){d._touchRecordEvent(a)}),d._on("created",function(){d.__prepareTooltip()})._on("repositioned",function(a){d.__lastPosition=a.position})}else d.__options.disabled=!0},__contentInsert:function(){var a=this,b=a._$tooltip.find(".tooltipster-content"),c=a.__Content,d=function(a){c=a};return a._trigger({type:"format",content:a.__Content,format:d}),a.__options.functionFormat&&(c=a.__options.functionFormat.call(a,a,{origin:a._$origin[0]},a.__Content)),"string"!=typeof c||a.__options.contentAsHTML?b.empty().append(c):b.text(c),a},__contentSet:function(b){return b instanceof a&&this.__options.contentCloning&&(b=b.clone(!0)),this.__Content=b,this._trigger({type:"updated",content:b}),this},__destroyError:function(){throw new Error("This tooltip has been destroyed and cannot execute your method call.")},__geometry:function(){var b=this,c=b._$origin,d=b._$origin.is("area");if(d){var e=b._$origin.parent().attr("name");c=a('img[usemap="#'+e+'"]')}var f=c[0].getBoundingClientRect(),g=a(h.window.document),i=a(h.window),j=c,k={available:{document:null,window:null},document:{size:{height:g.height(),width:g.width()}},window:{scroll:{left:h.window.scrollX||h.window.document.documentElement.scrollLeft,top:h.window.scrollY||h.window.document.documentElement.scrollTop},size:{height:i.height(),width:i.width()}},origin:{fixedLineage:!1,offset:{},size:{height:f.bottom-f.top,width:f.right-f.left},usemapImage:d?c[0]:null,windowOffset:{bottom:f.bottom,left:f.left,right:f.right,top:f.top}}};if(d){var l=b._$origin.attr("shape"),m=b._$origin.attr("coords");if(m&&(m=m.split(","),a.map(m,function(a,b){m[b]=parseInt(a)})),"default"!=l)switch(l){case"circle":var n=m[0],o=m[1],p=m[2],q=o-p,r=n-p;k.origin.size.height=2*p,k.origin.size.width=k.origin.size.height,k.origin.windowOffset.left+=r,k.origin.windowOffset.top+=q;break;case"rect":var s=m[0],t=m[1],u=m[2],v=m[3];k.origin.size.height=v-t,k.origin.size.width=u-s,k.origin.windowOffset.left+=s,k.origin.windowOffset.top+=t;break;case"poly":for(var w=0,x=0,y=0,z=0,A="even",B=0;B<m.length;B++){var C=m[B];"even"==A?(C>y&&(y=C,0===B&&(w=y)),w>C&&(w=C),A="odd"):(C>z&&(z=C,1==B&&(x=z)),x>C&&(x=C),A="even")}k.origin.size.height=z-x,k.origin.size.width=y-w,k.origin.windowOffset.left+=w,k.origin.windowOffset.top+=x}}var D=function(a){k.origin.size.height=a.height,k.origin.windowOffset.left=a.left,k.origin.windowOffset.top=a.top,k.origin.size.width=a.width};for(b._trigger({type:"geometry",edit:D,geometry:{height:k.origin.size.height,left:k.origin.windowOffset.left,top:k.origin.windowOffset.top,width:k.origin.size.width}}),k.origin.windowOffset.right=k.origin.windowOffset.left+k.origin.size.width,k.origin.windowOffset.bottom=k.origin.windowOffset.top+k.origin.size.height,k.origin.offset.left=k.origin.windowOffset.left+k.window.scroll.left,k.origin.offset.top=k.origin.windowOffset.top+k.window.scroll.top,k.origin.offset.bottom=k.origin.offset.top+k.origin.size.height,k.origin.offset.right=k.origin.offset.left+k.origin.size.width,k.available.document={bottom:{height:k.document.size.height-k.origin.offset.bottom,width:k.document.size.width},left:{height:k.document.size.height,width:k.origin.offset.left},right:{height:k.document.size.height,width:k.document.size.width-k.origin.offset.right},top:{height:k.origin.offset.top,width:k.document.size.width}},k.available.window={bottom:{height:Math.max(k.window.size.height-Math.max(k.origin.windowOffset.bottom,0),0),width:k.window.size.width},left:{height:k.window.size.height,width:Math.max(k.origin.windowOffset.left,0)},right:{height:k.window.size.height,width:Math.max(k.window.size.width-Math.max(k.origin.windowOffset.right,0),0)},top:{height:Math.max(k.origin.windowOffset.top,0),width:k.window.size.width}};"html"!=j[0].tagName.toLowerCase();){if("fixed"==j.css("position")){k.origin.fixedLineage=!0;break}j=j.parent()}return k},__optionsFormat:function(){return"number"==typeof this.__options.animationDuration&&(this.__options.animationDuration=[this.__options.animationDuration,this.__options.animationDuration]),"number"==typeof this.__options.delay&&(this.__options.delay=[this.__options.delay,this.__options.delay]),"number"==typeof this.__options.delayTouch&&(this.__options.delayTouch=[this.__options.delayTouch,this.__options.delayTouch]),"string"==typeof this.__options.theme&&(this.__options.theme=[this.__options.theme]),null===this.__options.parent?this.__options.parent=a(h.window.document.body):"string"==typeof this.__options.parent&&(this.__options.parent=a(this.__options.parent)),"hover"==this.__options.trigger?(this.__options.triggerOpen={mouseenter:!0,touchstart:!0},this.__options.triggerClose={mouseleave:!0,originClick:!0,touchleave:!0}):"click"==this.__options.trigger&&(this.__options.triggerOpen={click:!0,tap:!0},this.__options.triggerClose={click:!0,tap:!0}),this._trigger("options"),this},__prepareGC:function(){var b=this;return b.__options.selfDestruction?b.__garbageCollector=setInterval(function(){var c=(new Date).getTime();b.__touchEvents=a.grep(b.__touchEvents,function(a,b){return c-a.time>6e4}),d(b._$origin)||b.close(function(){b.destroy()})},2e4):clearInterval(b.__garbageCollector),b},__prepareOrigin:function(){var a=this;if(a._$origin.off("."+a.__namespace+"-triggerOpen"),h.hasTouchCapability&&a._$origin.on("touchstart."+a.__namespace+"-triggerOpen touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen",function(b){a._touchRecordEvent(b)}),a.__options.triggerOpen.click||a.__options.triggerOpen.tap&&h.hasTouchCapability){var b="";a.__options.triggerOpen.click&&(b+="click."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.tap&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&a._open(b)})}if(a.__options.triggerOpen.mouseenter||a.__options.triggerOpen.touchstart&&h.hasTouchCapability){var b="";a.__options.triggerOpen.mouseenter&&(b+="mouseenter."+a.__namespace+"-triggerOpen "),a.__options.triggerOpen.touchstart&&h.hasTouchCapability&&(b+="touchstart."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){!a._touchIsTouchEvent(b)&&a._touchIsEmulatedEvent(b)||(a.__pointerIsOverOrigin=!0,a._openShortly(b))})}if(a.__options.triggerClose.mouseleave||a.__options.triggerClose.touchleave&&h.hasTouchCapability){var b="";a.__options.triggerClose.mouseleave&&(b+="mouseleave."+a.__namespace+"-triggerOpen "),a.__options.triggerClose.touchleave&&h.hasTouchCapability&&(b+="touchend."+a.__namespace+"-triggerOpen touchcancel."+a.__namespace+"-triggerOpen"),a._$origin.on(b,function(b){a._touchIsMeaningfulEvent(b)&&(a.__pointerIsOverOrigin=!1)})}return a},__prepareTooltip:function(){var b=this,c=b.__options.interactive?"auto":"";return b._$tooltip.attr("id",b.__namespace).css({"pointer-events":c,zIndex:b.__options.zIndex}),a.each(b.__previousThemes,function(a,c){b._$tooltip.removeClass(c)}),a.each(b.__options.theme,function(a,c){b._$tooltip.addClass(c)}),b.__previousThemes=a.merge([],b.__options.theme),b},__scrollHandler:function(b){var c=this;if(c.__options.triggerClose.scroll)c._close(b);else if(d(c._$origin)&&d(c._$tooltip)){var e=null;if(b.target===h.window.document)c.__Geometry.origin.fixedLineage||c.__options.repositionOnScroll&&c.reposition(b);else{e=c.__geometry();var f=!1;if("fixed"!=c._$origin.css("position")&&c.__$originParents.each(function(b,c){var d=a(c),g=d.css("overflow-x"),h=d.css("overflow-y");if("visible"!=g||"visible"!=h){var i=c.getBoundingClientRect();if("visible"!=g&&(e.origin.windowOffset.left<i.left||e.origin.windowOffset.right>i.right))return f=!0,!1;if("visible"!=h&&(e.origin.windowOffset.top<i.top||e.origin.windowOffset.bottom>i.bottom))return f=!0,!1}return"fixed"==d.css("position")?!1:void 0}),f)c._$tooltip.css("visibility","hidden");else if(c._$tooltip.css("visibility","visible"),c.__options.repositionOnScroll)c.reposition(b);else{var g=e.origin.offset.left-c.__Geometry.origin.offset.left,i=e.origin.offset.top-c.__Geometry.origin.offset.top;c._$tooltip.css({left:c.__lastPosition.coord.left+g,top:c.__lastPosition.coord.top+i})}}c._trigger({type:"scroll",event:b,geo:e})}return c},__stateSet:function(a){return this.__state=a,this._trigger({type:"state",state:a}),this},__timeoutsClear:function(){return clearTimeout(this.__timeouts.open),this.__timeouts.open=null,a.each(this.__timeouts.close,function(a,b){clearTimeout(b)}),this.__timeouts.close=[],this},__trackerStart:function(){var a=this,b=a._$tooltip.find(".tooltipster-content");return a.__options.trackTooltip&&(a.__contentBcr=b[0].getBoundingClientRect()),a.__tracker=setInterval(function(){if(d(a._$origin)&&d(a._$tooltip)){if(a.__options.trackOrigin){var e=a.__geometry(),f=!1;c(e.origin.size,a.__Geometry.origin.size)&&(a.__Geometry.origin.fixedLineage?c(e.origin.windowOffset,a.__Geometry.origin.windowOffset)&&(f=!0):c(e.origin.offset,a.__Geometry.origin.offset)&&(f=!0)),f||(a.__options.triggerClose.mouseleave?a._close():a.reposition())}if(a.__options.trackTooltip){var g=b[0].getBoundingClientRect();g.height===a.__contentBcr.height&&g.width===a.__contentBcr.width||(a.reposition(),a.__contentBcr=g)}}else a._close()},a.__options.trackerInterval),a},_close:function(b,c,d){var e=this,f=!0;if(e._trigger({type:"close",event:b,stop:function(){f=!1}}),f||d){c&&e.__callbacks.close.push(c),e.__callbacks.open=[],e.__timeoutsClear();var g=function(){a.each(e.__callbacks.close,function(a,c){c.call(e,e,{event:b,origin:e._$origin[0]})}),e.__callbacks.close=[]};if("closed"!=e.__state){var i=!0,j=new Date,k=j.getTime(),l=k+e.__options.animationDuration[1];if("disappearing"==e.__state&&l>e.__closingTime&&e.__options.animationDuration[1]>0&&(i=!1),i){e.__closingTime=l,"disappearing"!=e.__state&&e.__stateSet("disappearing");var m=function(){clearInterval(e.__tracker),e._trigger({type:"closing",event:b}),e._$tooltip.off("."+e.__namespace+"-triggerClose").removeClass("tooltipster-dying"),a(h.window).off("."+e.__namespace+"-triggerClose"),e.__$originParents.each(function(b,c){a(c).off("scroll."+e.__namespace+"-triggerClose")}),e.__$originParents=null,a(h.window.document.body).off("."+e.__namespace+"-triggerClose"),e._$origin.off("."+e.__namespace+"-triggerClose"),e._off("dismissable"),e.__stateSet("closed"),e._trigger({type:"after",event:b}),e.__options.functionAfter&&e.__options.functionAfter.call(e,e,{event:b,origin:e._$origin[0]}),g()};h.hasTransitions?(e._$tooltip.css({"-moz-animation-duration":e.__options.animationDuration[1]+"ms","-ms-animation-duration":e.__options.animationDuration[1]+"ms","-o-animation-duration":e.__options.animationDuration[1]+"ms","-webkit-animation-duration":e.__options.animationDuration[1]+"ms","animation-duration":e.__options.animationDuration[1]+"ms","transition-duration":e.__options.animationDuration[1]+"ms"}),e._$tooltip.clearQueue().removeClass("tooltipster-show").addClass("tooltipster-dying"),e.__options.animationDuration[1]>0&&e._$tooltip.delay(e.__options.animationDuration[1]),e._$tooltip.queue(m)):e._$tooltip.stop().fadeOut(e.__options.animationDuration[1],m)}}else g()}return e},_off:function(){return this.__$emitterPrivate.off.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_on:function(){return this.__$emitterPrivate.on.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_one:function(){return this.__$emitterPrivate.one.apply(this.__$emitterPrivate,Array.prototype.slice.apply(arguments)),this},_open:function(b,c){var e=this;if(!e.__destroying&&d(e._$origin)&&e.__enabled){var f=!0;if("closed"==e.__state&&(e._trigger({type:"before",event:b,stop:function(){f=!1}}),f&&e.__options.functionBefore&&(f=e.__options.functionBefore.call(e,e,{event:b,origin:e._$origin[0]}))),f!==!1&&null!==e.__Content){c&&e.__callbacks.open.push(c),e.__callbacks.close=[],e.__timeoutsClear();var g,i=function(){"stable"!=e.__state&&e.__stateSet("stable"),a.each(e.__callbacks.open,function(a,b){b.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}),e.__callbacks.open=[]};if("closed"!==e.__state)g=0,"disappearing"===e.__state?(e.__stateSet("appearing"),h.hasTransitions?(e._$tooltip.clearQueue().removeClass("tooltipster-dying").addClass("tooltipster-show"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i)):e._$tooltip.stop().fadeIn(i)):"stable"==e.__state&&i();else{if(e.__stateSet("appearing"),g=e.__options.animationDuration[0],e.__contentInsert(),e.reposition(b,!0),h.hasTransitions?(e._$tooltip.addClass("tooltipster-"+e.__options.animation).addClass("tooltipster-initial").css({"-moz-animation-duration":e.__options.animationDuration[0]+"ms","-ms-animation-duration":e.__options.animationDuration[0]+"ms","-o-animation-duration":e.__options.animationDuration[0]+"ms","-webkit-animation-duration":e.__options.animationDuration[0]+"ms","animation-duration":e.__options.animationDuration[0]+"ms","transition-duration":e.__options.animationDuration[0]+"ms"}),setTimeout(function(){"closed"!=e.__state&&(e._$tooltip.addClass("tooltipster-show").removeClass("tooltipster-initial"),e.__options.animationDuration[0]>0&&e._$tooltip.delay(e.__options.animationDuration[0]),e._$tooltip.queue(i))},0)):e._$tooltip.css("display","none").fadeIn(e.__options.animationDuration[0],i),e.__trackerStart(),a(h.window).on("resize."+e.__namespace+"-triggerClose",function(b){var c=a(document.activeElement);(c.is("input")||c.is("textarea"))&&a.contains(e._$tooltip[0],c[0])||e.reposition(b)}).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)}),e.__$originParents=e._$origin.parents(),e.__$originParents.each(function(b,c){a(c).on("scroll."+e.__namespace+"-triggerClose",function(a){e.__scrollHandler(a)})}),e.__options.triggerClose.mouseleave||e.__options.triggerClose.touchleave&&h.hasTouchCapability){e._on("dismissable",function(a){a.dismissable?a.delay?(m=setTimeout(function(){e._close(a.event)},a.delay),e.__timeouts.close.push(m)):e._close(a):clearTimeout(m)});var j=e._$origin,k="",l="",m=null;e.__options.interactive&&(j=j.add(e._$tooltip)),e.__options.triggerClose.mouseleave&&(k+="mouseenter."+e.__namespace+"-triggerClose ",l+="mouseleave."+e.__namespace+"-triggerClose "),e.__options.triggerClose.touchleave&&h.hasTouchCapability&&(k+="touchstart."+e.__namespace+"-triggerClose",l+="touchend."+e.__namespace+"-triggerClose touchcancel."+e.__namespace+"-triggerClose"),j.on(l,function(a){if(e._touchIsTouchEvent(a)||!e._touchIsEmulatedEvent(a)){var b="mouseleave"==a.type?e.__options.delay:e.__options.delayTouch;e._trigger({delay:b[1],dismissable:!0,event:a,type:"dismissable"})}}).on(k,function(a){!e._touchIsTouchEvent(a)&&e._touchIsEmulatedEvent(a)||e._trigger({dismissable:!1,event:a,type:"dismissable"})})}e.__options.triggerClose.originClick&&e._$origin.on("click."+e.__namespace+"-triggerClose",function(a){e._touchIsTouchEvent(a)||e._touchIsEmulatedEvent(a)||e._close(a)}),(e.__options.triggerClose.click||e.__options.triggerClose.tap&&h.hasTouchCapability)&&setTimeout(function(){if("closed"!=e.__state){var b="",c=a(h.window.document.body);e.__options.triggerClose.click&&(b+="click."+e.__namespace+"-triggerClose "),e.__options.triggerClose.tap&&h.hasTouchCapability&&(b+="touchend."+e.__namespace+"-triggerClose"),c.on(b,function(b){e._touchIsMeaningfulEvent(b)&&(e._touchRecordEvent(b),e.__options.interactive&&a.contains(e._$tooltip[0],b.target)||e._close(b))}),e.__options.triggerClose.tap&&h.hasTouchCapability&&c.on("touchstart."+e.__namespace+"-triggerClose",function(a){e._touchRecordEvent(a)})}},0),e._trigger("ready"),e.__options.functionReady&&e.__options.functionReady.call(e,e,{origin:e._$origin[0],tooltip:e._$tooltip[0]})}if(e.__options.timer>0){var m=setTimeout(function(){e._close()},e.__options.timer+g);e.__timeouts.close.push(m)}}}return e},_openShortly:function(a){var b=this,c=!0;if("stable"!=b.__state&&"appearing"!=b.__state&&!b.__timeouts.open&&(b._trigger({type:"start",event:a,stop:function(){c=!1}}),c)){var d=0==a.type.indexOf("touch")?b.__options.delayTouch:b.__options.delay;d[0]?b.__timeouts.open=setTimeout(function(){b.__timeouts.open=null,b.__pointerIsOverOrigin&&b._touchIsMeaningfulEvent(a)?(b._trigger("startend"),b._open(a)):b._trigger("startcancel")},d[0]):(b._trigger("startend"),b._open(a))}return b},_optionsExtract:function(b,c){var d=this,e=a.extend(!0,{},c),f=d.__options[b];return f||(f={},a.each(c,function(a,b){var c=d.__options[a];void 0!==c&&(f[a]=c)})),a.each(e,function(b,c){void 0!==f[b]&&("object"!=typeof c||c instanceof Array||null==c||"object"!=typeof f[b]||f[b]instanceof Array||null==f[b]?e[b]=f[b]:a.extend(e[b],f[b]))}),e},_plug:function(b){var c=a.tooltipster._plugin(b);if(!c)throw new Error('The "'+b+'" plugin is not defined');return c.instance&&a.tooltipster.__bridge(c.instance,this,c.name),this},_touchIsEmulatedEvent:function(a){for(var b=!1,c=(new Date).getTime(),d=this.__touchEvents.length-1;d>=0;d--){var e=this.__touchEvents[d];if(!(c-e.time<500))break;e.target===a.target&&(b=!0)}return b},_touchIsMeaningfulEvent:function(a){return this._touchIsTouchEvent(a)&&!this._touchSwiped(a.target)||!this._touchIsTouchEvent(a)&&!this._touchIsEmulatedEvent(a)},_touchIsTouchEvent:function(a){return 0==a.type.indexOf("touch")},_touchRecordEvent:function(a){return this._touchIsTouchEvent(a)&&(a.time=(new Date).getTime(),this.__touchEvents.push(a)),this},_touchSwiped:function(a){for(var b=!1,c=this.__touchEvents.length-1;c>=0;c--){var d=this.__touchEvents[c];if("touchmove"==d.type){b=!0;break}if("touchstart"==d.type&&a===d.target)break}return b},_trigger:function(){var b=Array.prototype.slice.apply(arguments);return"string"==typeof b[0]&&(b[0]={type:b[0]}),b[0].instance=this,b[0].origin=this._$origin?this._$origin[0]:null,b[0].tooltip=this._$tooltip?this._$tooltip[0]:null,this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate,b),a.tooltipster._trigger.apply(a.tooltipster,b),this.__$emitterPublic.trigger.apply(this.__$emitterPublic,b),this},_unplug:function(b){var c=this;if(c[b]){var d=a.tooltipster._plugin(b);d.instance&&a.each(d.instance,function(a,d){c[a]&&c[a].bridged===c[b]&&delete c[a]}),c[b].__destroy&&c[b].__destroy(),delete c[b]}return c},close:function(a){return this.__destroyed?this.__destroyError():this._close(null,a),this},content:function(a){var b=this;if(void 0===a)return b.__Content;if(b.__destroyed)b.__destroyError();else if(b.__contentSet(a),null!==b.__Content){if("closed"!==b.__state&&(b.__contentInsert(),b.reposition(),b.__options.updateAnimation))if(h.hasTransitions){var c=b.__options.updateAnimation;b._$tooltip.addClass("tooltipster-update-"+c),setTimeout(function(){"closed"!=b.__state&&b._$tooltip.removeClass("tooltipster-update-"+c)},1e3)}else b._$tooltip.fadeTo(200,.5,function(){"closed"!=b.__state&&b._$tooltip.fadeTo(200,1)})}else b._close();return b},destroy:function(){var b=this;if(b.__destroyed)b.__destroyError();else{"closed"!=b.__state?b.option("animationDuration",0)._close(null,null,!0):b.__timeoutsClear(),b._trigger("destroy"),b.__destroyed=!0,b._$origin.removeData(b.__namespace).off("."+b.__namespace+"-triggerOpen"),a(h.window.document.body).off("."+b.__namespace+"-triggerOpen");var c=b._$origin.data("tooltipster-ns");if(c)if(1===c.length){var d=null;"previous"==b.__options.restoration?d=b._$origin.data("tooltipster-initialTitle"):"current"==b.__options.restoration&&(d="string"==typeof b.__Content?b.__Content:a("<div></div>").append(b.__Content).html()),d&&b._$origin.attr("title",d),b._$origin.removeClass("tooltipstered"),b._$origin.removeData("tooltipster-ns").removeData("tooltipster-initialTitle")}else c=a.grep(c,function(a,c){return a!==b.__namespace}),b._$origin.data("tooltipster-ns",c);b._trigger("destroyed"),b._off(),b.off(),b.__Content=null,b.__$emitterPrivate=null,b.__$emitterPublic=null,b.__options.parent=null,b._$origin=null,b._$tooltip=null,a.tooltipster.__instancesLatestArr=a.grep(a.tooltipster.__instancesLatestArr,function(a,c){return b!==a}),clearInterval(b.__garbageCollector)}return b},disable:function(){return this.__destroyed?(this.__destroyError(),this):(this._close(),this.__enabled=!1,this)},elementOrigin:function(){return this.__destroyed?void this.__destroyError():this._$origin[0]},elementTooltip:function(){return this._$tooltip?this._$tooltip[0]:null},enable:function(){return this.__enabled=!0,this},hide:function(a){return this.close(a)},instance:function(){return this},off:function(){return this.__destroyed||this.__$emitterPublic.off.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},on:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.on.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},one:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.one.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this},open:function(a){return this.__destroyed?this.__destroyError():this._open(null,a),this},option:function(b,c){return void 0===c?this.__options[b]:(this.__destroyed?this.__destroyError():(this.__options[b]=c,this.__optionsFormat(),a.inArray(b,["trigger","triggerClose","triggerOpen"])>=0&&this.__prepareOrigin(),"selfDestruction"===b&&this.__prepareGC()),this)},reposition:function(a,b){var c=this;return c.__destroyed?c.__destroyError():"closed"!=c.__state&&d(c._$origin)&&(b||d(c._$tooltip))&&(b||c._$tooltip.detach(),c.__Geometry=c.__geometry(),c._trigger({type:"reposition",event:a,helper:{geo:c.__Geometry}})),c},show:function(a){return this.open(a)},status:function(){return{destroyed:this.__destroyed,enabled:this.__enabled,open:"closed"!==this.__state,state:this.__state}},triggerHandler:function(){return this.__destroyed?this.__destroyError():this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic,Array.prototype.slice.apply(arguments)),this}},a.fn.tooltipster=function(){var b=Array.prototype.slice.apply(arguments),c="You are using a single HTML element as content for several tooltips. You probably want to set the contentCloning option to TRUE.";if(0===this.length)return this;if("string"==typeof b[0]){var d="#*$~&";return this.each(function(){var e=a(this).data("tooltipster-ns"),f=e?a(this).data(e[0]):null;if(!f)throw new Error("You called Tooltipster's \""+b[0]+'" method on an uninitialized element');if("function"!=typeof f[b[0]])throw new Error('Unknown method "'+b[0]+'"');this.length>1&&"content"==b[0]&&(b[1]instanceof a||"object"==typeof b[1]&&null!=b[1]&&b[1].tagName)&&!f.__options.contentCloning&&f.__options.debug&&console.log(c);var g=f[b[0]](b[1],b[2]);return g!==f||"instance"===b[0]?(d=g,!1):void 0}),"#*$~&"!==d?d:this}a.tooltipster.__instancesLatestArr=[];var e=b[0]&&void 0!==b[0].multiple,g=e&&b[0].multiple||!e&&f.multiple,h=b[0]&&void 0!==b[0].content,i=h&&b[0].content||!h&&f.content,j=b[0]&&void 0!==b[0].contentCloning,k=j&&b[0].contentCloning||!j&&f.contentCloning,l=b[0]&&void 0!==b[0].debug,m=l&&b[0].debug||!l&&f.debug;return this.length>1&&(i instanceof a||"object"==typeof i&&null!=i&&i.tagName)&&!k&&m&&console.log(c),this.each(function(){var c=!1,d=a(this),e=d.data("tooltipster-ns"),f=null;e?g?c=!0:m&&(console.log("Tooltipster: one or more tooltips are already attached to the element below. Ignoring."),console.log(this)):c=!0,c&&(f=new a.Tooltipster(this,b[0]),e||(e=[]),e.push(f.__namespace),d.data("tooltipster-ns",e),d.data(f.__namespace,f),f.__options.functionInit&&f.__options.functionInit.call(f,f,{origin:this}),f._trigger("init")),a.tooltipster.__instancesLatestArr.push(f)}),this},b.prototype={__init:function(b){this.__$tooltip=b,this.__$tooltip.css({left:0,overflow:"hidden",position:"absolute",top:0}).find(".tooltipster-content").css("overflow","auto"),this.$container=a('<div class="tooltipster-ruler"></div>').append(this.__$tooltip).appendTo(h.window.document.body)},__forceRedraw:function(){var a=this.__$tooltip.parent();this.__$tooltip.detach(),this.__$tooltip.appendTo(a)},constrain:function(a,b){return this.constraints={width:a,height:b},this.__$tooltip.css({display:"block",height:"",overflow:"auto",width:a}),this},destroy:function(){this.__$tooltip.detach().find(".tooltipster-content").css({display:"",overflow:""}),this.$container.remove()},free:function(){return this.constraints=null,this.__$tooltip.css({display:"",height:"",overflow:"visible",width:""}),this},measure:function(){this.__forceRedraw();var a=this.__$tooltip[0].getBoundingClientRect(),b={size:{height:a.height||a.bottom-a.top,width:a.width||a.right-a.left}};if(this.constraints){var c=this.__$tooltip.find(".tooltipster-content"),d=this.__$tooltip.outerHeight(),e=c[0].getBoundingClientRect(),f={height:d<=this.constraints.height,width:a.width<=this.constraints.width&&e.width>=c[0].scrollWidth-1};b.fits=f.height&&f.width}return h.IE&&h.IE<=11&&b.size.width!==h.window.document.documentElement.clientWidth&&(b.size.width=Math.ceil(b.size.width)+1),b}};var j=navigator.userAgent.toLowerCase();-1!=j.indexOf("msie")?h.IE=parseInt(j.split("msie")[1]):-1!==j.toLowerCase().indexOf("trident")&&-1!==j.indexOf(" rv:11")?h.IE=11:-1!=j.toLowerCase().indexOf("edge/")&&(h.IE=parseInt(j.toLowerCase().split("edge/")[1]));var k="tooltipster.sideTip";return a.tooltipster._plugin({name:k,instance:{__defaults:function(){return{arrow:!0,distance:6,functionPosition:null,maxWidth:null,minIntersection:16,minWidth:0,position:null,side:"top",viewportAware:!0}},__init:function(a){var b=this;b.__instance=a,b.__namespace="tooltipster-sideTip-"+Math.round(1e6*Math.random()),b.__previousState="closed",b.__options,b.__optionsFormat(),b.__instance._on("state."+b.__namespace,function(a){"closed"==a.state?b.__close():"appearing"==a.state&&"closed"==b.__previousState&&b.__create(),b.__previousState=a.state}),b.__instance._on("options."+b.__namespace,function(){b.__optionsFormat()}),b.__instance._on("reposition."+b.__namespace,function(a){b.__reposition(a.event,a.helper)})},__close:function(){this.__instance.content()instanceof a&&this.__instance.content().detach(),this.__instance._$tooltip.remove(),this.__instance._$tooltip=null},__create:function(){var b=a('<div class="tooltipster-base tooltipster-sidetip"><div class="tooltipster-box"><div class="tooltipster-content"></div></div><div class="tooltipster-arrow"><div class="tooltipster-arrow-uncropped"><div class="tooltipster-arrow-border"></div><div class="tooltipster-arrow-background"></div></div></div></div>');this.__options.arrow||b.find(".tooltipster-box").css("margin",0).end().find(".tooltipster-arrow").hide(),this.__options.minWidth&&b.css("min-width",this.__options.minWidth+"px"),this.__options.maxWidth&&b.css("max-width",this.__options.maxWidth+"px"),
this.__instance._$tooltip=b,this.__instance._trigger("created")},__destroy:function(){this.__instance._off("."+self.__namespace)},__optionsFormat:function(){var b=this;if(b.__options=b.__instance._optionsExtract(k,b.__defaults()),b.__options.position&&(b.__options.side=b.__options.position),"object"!=typeof b.__options.distance&&(b.__options.distance=[b.__options.distance]),b.__options.distance.length<4&&(void 0===b.__options.distance[1]&&(b.__options.distance[1]=b.__options.distance[0]),void 0===b.__options.distance[2]&&(b.__options.distance[2]=b.__options.distance[0]),void 0===b.__options.distance[3]&&(b.__options.distance[3]=b.__options.distance[1]),b.__options.distance={top:b.__options.distance[0],right:b.__options.distance[1],bottom:b.__options.distance[2],left:b.__options.distance[3]}),"string"==typeof b.__options.side){var c={top:"bottom",right:"left",bottom:"top",left:"right"};b.__options.side=[b.__options.side,c[b.__options.side]],"left"==b.__options.side[0]||"right"==b.__options.side[0]?b.__options.side.push("top","bottom"):b.__options.side.push("right","left")}6===a.tooltipster._env.IE&&b.__options.arrow!==!0&&(b.__options.arrow=!1)},__reposition:function(b,c){var d,e=this,f=e.__targetFind(c),g=[];e.__instance._$tooltip.detach();var h=e.__instance._$tooltip.clone(),i=a.tooltipster._getRuler(h),j=!1,k=e.__instance.option("animation");switch(k&&h.removeClass("tooltipster-"+k),a.each(["window","document"],function(d,k){var l=null;if(e.__instance._trigger({container:k,helper:c,satisfied:j,takeTest:function(a){l=a},results:g,type:"positionTest"}),1==l||0!=l&&0==j&&("window"!=k||e.__options.viewportAware))for(var d=0;d<e.__options.side.length;d++){var m={horizontal:0,vertical:0},n=e.__options.side[d];"top"==n||"bottom"==n?m.vertical=e.__options.distance[n]:m.horizontal=e.__options.distance[n],e.__sideChange(h,n),a.each(["natural","constrained"],function(a,d){if(l=null,e.__instance._trigger({container:k,event:b,helper:c,mode:d,results:g,satisfied:j,side:n,takeTest:function(a){l=a},type:"positionTest"}),1==l||0!=l&&0==j){var h={container:k,distance:m,fits:null,mode:d,outerSize:null,side:n,size:null,target:f[n],whole:null},o="natural"==d?i.free():i.constrain(c.geo.available[k][n].width-m.horizontal,c.geo.available[k][n].height-m.vertical),p=o.measure();if(h.size=p.size,h.outerSize={height:p.size.height+m.vertical,width:p.size.width+m.horizontal},"natural"==d?c.geo.available[k][n].width>=h.outerSize.width&&c.geo.available[k][n].height>=h.outerSize.height?h.fits=!0:h.fits=!1:h.fits=p.fits,"window"==k&&(h.fits?"top"==n||"bottom"==n?h.whole=c.geo.origin.windowOffset.right>=e.__options.minIntersection&&c.geo.window.size.width-c.geo.origin.windowOffset.left>=e.__options.minIntersection:h.whole=c.geo.origin.windowOffset.bottom>=e.__options.minIntersection&&c.geo.window.size.height-c.geo.origin.windowOffset.top>=e.__options.minIntersection:h.whole=!1),g.push(h),h.whole)j=!0;else if("natural"==h.mode&&(h.fits||h.size.width<=c.geo.available[k][n].width))return!1}})}}),e.__instance._trigger({edit:function(a){g=a},event:b,helper:c,results:g,type:"positionTested"}),g.sort(function(a,b){if(a.whole&&!b.whole)return-1;if(!a.whole&&b.whole)return 1;if(a.whole&&b.whole){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}if(a.fits&&!b.fits)return-1;if(!a.fits&&b.fits)return 1;if(a.fits&&b.fits){var c=e.__options.side.indexOf(a.side),d=e.__options.side.indexOf(b.side);return d>c?-1:c>d?1:"natural"==a.mode?-1:1}return"document"==a.container&&"bottom"==a.side&&"natural"==a.mode?-1:1}),d=g[0],d.coord={},d.side){case"left":case"right":d.coord.top=Math.floor(d.target-d.size.height/2);break;case"bottom":case"top":d.coord.left=Math.floor(d.target-d.size.width/2)}switch(d.side){case"left":d.coord.left=c.geo.origin.windowOffset.left-d.outerSize.width;break;case"right":d.coord.left=c.geo.origin.windowOffset.right+d.distance.horizontal;break;case"top":d.coord.top=c.geo.origin.windowOffset.top-d.outerSize.height;break;case"bottom":d.coord.top=c.geo.origin.windowOffset.bottom+d.distance.vertical}"window"==d.container?"top"==d.side||"bottom"==d.side?d.coord.left<0?c.geo.origin.windowOffset.right-this.__options.minIntersection>=0?d.coord.left=0:d.coord.left=c.geo.origin.windowOffset.right-this.__options.minIntersection-1:d.coord.left>c.geo.window.size.width-d.size.width&&(c.geo.origin.windowOffset.left+this.__options.minIntersection<=c.geo.window.size.width?d.coord.left=c.geo.window.size.width-d.size.width:d.coord.left=c.geo.origin.windowOffset.left+this.__options.minIntersection+1-d.size.width):d.coord.top<0?c.geo.origin.windowOffset.bottom-this.__options.minIntersection>=0?d.coord.top=0:d.coord.top=c.geo.origin.windowOffset.bottom-this.__options.minIntersection-1:d.coord.top>c.geo.window.size.height-d.size.height&&(c.geo.origin.windowOffset.top+this.__options.minIntersection<=c.geo.window.size.height?d.coord.top=c.geo.window.size.height-d.size.height:d.coord.top=c.geo.origin.windowOffset.top+this.__options.minIntersection+1-d.size.height):(d.coord.left>c.geo.window.size.width-d.size.width&&(d.coord.left=c.geo.window.size.width-d.size.width),d.coord.left<0&&(d.coord.left=0)),e.__sideChange(h,d.side),c.tooltipClone=h[0],c.tooltipParent=e.__instance.option("parent").parent[0],c.mode=d.mode,c.whole=d.whole,c.origin=e.__instance._$origin[0],c.tooltip=e.__instance._$tooltip[0],delete d.container,delete d.fits,delete d.mode,delete d.outerSize,delete d.whole,d.distance=d.distance.horizontal||d.distance.vertical;var l=a.extend(!0,{},d);if(e.__instance._trigger({edit:function(a){d=a},event:b,helper:c,position:l,type:"position"}),e.__options.functionPosition){var m=e.__options.functionPosition.call(e,e.__instance,c,l);m&&(d=m)}i.destroy();var n,o;"top"==d.side||"bottom"==d.side?(n={prop:"left",val:d.target-d.coord.left},o=d.size.width-this.__options.minIntersection):(n={prop:"top",val:d.target-d.coord.top},o=d.size.height-this.__options.minIntersection),n.val<this.__options.minIntersection?n.val=this.__options.minIntersection:n.val>o&&(n.val=o);var p;p=c.geo.origin.fixedLineage?c.geo.origin.windowOffset:{left:c.geo.origin.windowOffset.left+c.geo.window.scroll.left,top:c.geo.origin.windowOffset.top+c.geo.window.scroll.top},d.coord={left:p.left+(d.coord.left-c.geo.origin.windowOffset.left),top:p.top+(d.coord.top-c.geo.origin.windowOffset.top)},e.__sideChange(e.__instance._$tooltip,d.side),c.geo.origin.fixedLineage?e.__instance._$tooltip.css("position","fixed"):e.__instance._$tooltip.css("position",""),e.__instance._$tooltip.css({left:d.coord.left,top:d.coord.top,height:d.size.height,width:d.size.width}).find(".tooltipster-arrow").css({left:"",top:""}).css(n.prop,n.val),e.__instance._$tooltip.appendTo(e.__instance.option("parent")),e.__instance._trigger({type:"repositioned",event:b,position:d})},__sideChange:function(a,b){a.removeClass("tooltipster-bottom").removeClass("tooltipster-left").removeClass("tooltipster-right").removeClass("tooltipster-top").addClass("tooltipster-"+b)},__targetFind:function(a){var b={},c=this.__instance._$origin[0].getClientRects();if(c.length>1){var d=this.__instance._$origin.css("opacity");1==d&&(this.__instance._$origin.css("opacity",.99),c=this.__instance._$origin[0].getClientRects(),this.__instance._$origin.css("opacity",1))}if(c.length<2)b.top=Math.floor(a.geo.origin.windowOffset.left+a.geo.origin.size.width/2),b.bottom=b.top,b.left=Math.floor(a.geo.origin.windowOffset.top+a.geo.origin.size.height/2),b.right=b.left;else{var e=c[0];b.top=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil(c.length/2)-1]:c[0],b.right=Math.floor(e.top+(e.bottom-e.top)/2),e=c[c.length-1],b.bottom=Math.floor(e.left+(e.right-e.left)/2),e=c.length>2?c[Math.ceil((c.length+1)/2)-1]:c[c.length-1],b.left=Math.floor(e.top+(e.bottom-e.top)/2)}return b}}}),a});;
/*!
 * jQuery Smart Banner
 * Copyright (c) 2012 Arnold Daniels <arnold@jasny.net>
 * Based on 'jQuery Smart Web App Banner' by Kurt Zenisek @ kzeni.com
 */
(function (root, factory) {
    if (typeof define == 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory(root.jQuery);
    }
})(this, function ($) {
    var UA = navigator.userAgent;
    var isEdge = /Edge/i.test(UA);

    var SmartBanner = function (options) {
        // Get the original margin-top of the HTML element so we can take that into account.
        this.origHtmlMargin = parseFloat($('html').css('margin-top'));
        this.options = $.extend({}, $.smartbanner.defaults, options);

        // Check if it's already a standalone web app or running within a webui view of an app (not mobile safari).
        var standalone = navigator.standalone;

        // Detect banner type (iOS or Android).
        if (this.options.force) {
            this.type = this.options.force;
        }
        else if (UA.match(/Windows Phone/i) !== null && UA.match(/Edge|Touch/i) !== null) {
            this.type = 'windows';
        }
        else if (UA.match(/iPhone|iPod/i) !== null || (UA.match(/iPad/) && this.options.iOSUniversalApp)) {
            if (UA.match(/Safari/i) !== null &&
                (UA.match(/CriOS/i) !== null ||
                 UA.match(/FxiOS/i) != null ||
                  window.Number(UA.substr(UA.indexOf('OS ') + 3, 3).replace('_', '.')) < 6)) {
                // Check webview and native smart banner support (iOS 6+).
                this.type = 'ios';
            }
        }
        else if (UA.match(/\bSilk\/(.*\bMobile Safari\b)?/) || UA.match(/\bKF\w/) || UA.match('Kindle Fire')) {
            this.type = 'kindle';
        }
        else if (UA.match(/Android/i) !== null) {
            this.type = 'android';
        }
        // Don't show banner if device isn't iOS or Android, website is loaded in app or user dismissed banner.
        if (!this.type || standalone || this.getCookie('sb-closed') || this.getCookie('sb-installed')) {
            return;
        }
        // Calculate scale.
        this.scale = this.options.scale == 'auto' ? $(window).width() / window.screen.width : this.options.scale;
        if (this.scale < 1) {
            this.scale = 1;
        }
        // Get info from meta data.
        var meta = $(
          this.type == 'android'
            ? 'meta[name="google-play-app"]'
            : (this.type == 'ios'
                ? 'meta[name="apple-itunes-app"]'
                : (this.type == 'kindle'
                    ? 'meta[name="kindle-fire-app"]'
                    : 'meta[name="msApplication-ID"]'
                  )
              )
        );

        if (!meta.length) {
            return;
        }
        // For Windows Store apps, get the PackageFamilyName for protocol launch.
        if (this.type == 'windows') {
            if (isEdge) {
                this.appId = $('meta[name="msApplication-PackageEdgeName"]').attr('content');
            }
            if (!this.appId) {
                this.appId = $('meta[name="msApplication-PackageFamilyName"]').attr('content');
            }
        }
        else {
            // Try to pull the appId out of the meta tag and store the result.
            var parsedMetaContent = /app-id=([^\s,]+)/.exec(meta.attr('content'));
            if (parsedMetaContent) {
                this.appId = parsedMetaContent[1];
            } else {
                return;
            }
        }
        this.title = this.options.title
          ? this.options.title
          : (meta.data('title') || $('title').text().replace(/\s*[|\-·].*$/, ''));

        this.author = this.options.author
          ? this.options.author
          : (meta.data('author') || ($('meta[name="author"]').length ? $('meta[name="author"]').attr('content') : window.location.hostname));

        this.iconUrl = meta.data('icon-url');
        this.price = meta.data('price');

        // Set default onInstall callback if not set in options.
        if (typeof this.options.onInstall == 'function') {
            this.options.onInstall = this.options.onInstall;
        } else {
            this.options.onInstall = function () { };
        }
        // Set default onClose callback if not set in options.
        if (typeof this.options.onClose == 'function') {
            this.options.onClose = this.options.onClose;
        } else {
            this.options.onClose = function () { };
        }
        // Create banner.
        this.create();
        this.show();
        this.listen();
    };

    SmartBanner.prototype = {

        constructor: SmartBanner,

        create: function () {
            var iconURL;
            var price = this.price || this.options.price;

            var link = this.options.url || (function () {
                switch (this.type) {
                    case 'android':
                        return 'market://details?id=';
                    case 'kindle':
                        return 'amzn://apps/android?asin=';
                    case 'windows':
                        return isEdge
                          ? 'ms-windows-store://pdp/?productid='
                          : 'ms-windows-store:navigate?appid=';
                }
                return 'https://itunes.apple.com/' + this.options.appStoreLanguage + '/app/id';
            }.call(this) + this.appId);

            var inStore = !price ? '' : (function () {
                var result = price + ' - ';
                switch (this.type) {
                    case 'android':
                        return result + this.options.inGooglePlay;
                    case 'kindle':
                        return result + this.options.inAmazonAppStore;
                    case 'windows':
                        return result + this.options.inWindowsStore;
                }
                return result + this.options.inAppStore
            }.call(this));

            var gloss = this.options.iconGloss == null
              ? (this.type == 'ios')
              : this.options.iconGloss;

            if (this.type == 'android' && this.options.GooglePlayParams) {
                link += '&referrer=' + this.options.GooglePlayParams;
            }
            var banner = (
              '<div id="smartbanner" class="' + this.type + '">' +
                '<div class="sb-container">' +
                  '<a href="#" class="sb-close">&times;</a>' +
                  '<span class="sb-icon"></span>' +
                  '<div class="sb-info">' +
                    '<strong>' + this.title + '</strong>' +
                    '<span>' + this.author + '</span>' +
                    '<span>' + inStore + '</span>' +
                  '</div>' +
                  '<a href="' + link + '" class="sb-button">' +
                    '<span>' + this.options.button + '</span>' +
                  '</a>' +
                '</div>' +
              '</div>'
            );
            if (this.options.layer) {
                $(this.options.appendToSelector).append(banner);
            } else {
                $(this.options.appendToSelector).prepend(banner);
            }
            if (this.options.icon) {
                iconURL = this.options.icon;
            } else if (this.iconUrl) {
                iconURL = this.iconUrl;
            } else if ($('link[rel="apple-touch-icon-precomposed"]').length > 0) {
                iconURL = $('link[rel="apple-touch-icon-precomposed"]').attr('href');
                if (this.options.iconGloss == null) {
                    gloss = false;
                }
            } else if ($('link[rel="apple-touch-icon"]').length > 0) {
                iconURL = $('link[rel="apple-touch-icon"]').attr('href');
            } else if ($('meta[name="msApplication-TileImage"]').length > 0) {
                iconURL = $('meta[name="msApplication-TileImage"]').attr('content');
            } else if ($('meta[name="msapplication-TileImage"]').length > 0) {
                // Redundant because ms docs show two case usages.
                iconURL = $('meta[name="msapplication-TileImage"]').attr('content');
            }
            if (iconURL) {
                $('#smartbanner .sb-icon').css('background-image', 'url(' + iconURL + ')');
                if (gloss) {
                    $('#smartbanner .sb-icon').addClass('gloss');
                }
            } else {
                $('#smartbanner').addClass('no-icon');
            }
            this.bannerHeight = $('#smartbanner').outerHeight() + 2;

            if (this.scale > 1) {
                $('#smartbanner')
                  .css('top', parseFloat($('#smartbanner').css('top')) * this.scale)
                  .css('height', parseFloat($('#smartbanner').css('height')) * this.scale)
                  .hide();
                $('#smartbanner .sb-container')
                  .css('-webkit-transform', 'scale(' + this.scale + ')')
                  .css('-msie-transform', 'scale(' + this.scale + ')')
                  .css('-moz-transform', 'scale(' + this.scale + ')')
                  .css('width', $(window).width() / this.scale);
            }
            $('#smartbanner')
              .css('position', this.options.layer ? 'absolute' : 'static');
        },

        listen: function () {
            $('#smartbanner .sb-close').on('click', $.proxy(this.close, this));
            $('#smartbanner .sb-button').on('click', $.proxy(this.install, this));
        },

        show: function (callback) {
            var banner = $('#smartbanner');
            banner.stop();

            if (this.options.layer) {
                banner
                  .animate({ top: 0, display: 'block' }, this.options.speedIn)
                  .addClass('shown')
                  .show();
                $(this.pushSelector)
                  .animate({
                      paddingTop: this.origHtmlMargin + (this.bannerHeight * this.scale)
                  }, this.options.speedIn, 'swing', callback);
            }
            else {
                if ($.support.transition) {
                    banner.animate({ top: 0 }, this.options.speedIn).addClass('shown');
                    var transitionCallback = function () {
                        $('html').removeClass('sb-animation');
                        if (callback) {
                            callback();
                        }
                    };
                    $(this.pushSelector)
                      .addClass('sb-animation')
                      .one($.support.transition.end, transitionCallback)
                      .emulateTransitionEnd(this.options.speedIn)
                      .css('margin-top', this.origHtmlMargin + (this.bannerHeight * this.scale));
                }
                else {
                    banner
                      .slideDown(this.options.speedIn)
                      .addClass('shown');
                }
            }
        },

        hide: function (callback) {
            var banner = $('#smartbanner');
            banner.stop();

            if (this.options.layer) {
                banner.animate({
                    top: -1 * this.bannerHeight * this.scale,
                    display: 'block'
                }, this.options.speedIn)
                .removeClass('shown');

                $(this.pushSelector)
                  .animate({
                      paddingTop: this.origHtmlMargin
                  }, this.options.speedIn, 'swing', callback);
            }
            else {
                if ($.support.transition) {
                    if (this.type !== 'android') {
                        banner
                          .css('top', -1 * this.bannerHeight * this.scale)
                          .removeClass('shown');
                    }
                    else {
                        banner
                          .css({ display: 'none' })
                          .removeClass('shown');
                    }
                    var transitionCallback = function () {
                        $('html').removeClass('sb-animation');
                        if (callback) {
                            callback();
                        }
                    };
                    $(this.pushSelector)
                      .addClass('sb-animation')
                      .one($.support.transition.end, transitionCallback)
                      .emulateTransitionEnd(this.options.speedOut)
                      .css('margin-top', this.origHtmlMargin);
                }
                else {
                    banner.slideUp(this.options.speedOut).removeClass('shown');
                }
            }
        },

        close: function (e) {
            e.preventDefault();
            this.hide();
            this.setCookie('sb-closed', 'true', this.options.daysHidden);
            this.options.onClose(e);
        },

        install: function (e) {
            if (this.options.hideOnInstall) {
                this.hide();
            }
            this.setCookie('sb-installed', 'true', this.options.daysReminder);
            this.options.onInstall(e);
        },

        setCookie: function (name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            value = encodeURI(value) + ((exdays == null) ? '' : '; expires=' + exdate.toUTCString());
            document.cookie = name + '=' + value + '; path=/;';
        },

        getCookie: function (name) {
            var i, x, y, ARRcookies = document.cookie.split(';');
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
                x = x.replace(/^\s+|\s+$/g, '');
                if (x == name) {
                    return decodeURI(y);
                }
            }
            return null;
        },

        // Demo only.
        switchType: function () {
            var that = this;

            this.hide(function () {
                that.type = that.type == 'android' ? 'ios' : 'android';
                var meta = $(that.type == 'android' ? 'meta[name="google-play-app"]' : 'meta[name="apple-itunes-app"]').attr('content');
                that.appId = /app-id=([^\s,]+)/.exec(meta)[1];

                $('#smartbanner').detach();
                that.create();
                that.show();
            });
        }
    };

    $.smartbanner = function (option) {
        var $window = $(window);
        var data = $window.data('smartbanner');
        var options = typeof option == 'object' && option;
        if (!data) {
            $window.data('smartbanner', (data = new SmartBanner(options)));
        }
        if (typeof option == 'string') {
            data[option]();
        }
    };

    // override these globally if you like (they are all optional)
    $.smartbanner.defaults = {
        title: null, // What the title of the app should be in the banner (defaults to <title>)
        author: null, // What the author of the app should be in the banner (defaults to <meta name="author"> or hostname)
        price: 'FREE', // Price of the app
        appStoreLanguage: 'us', // Language code for App Store
        inAppStore: 'On the App Store', // Text of price for iOS
        inGooglePlay: 'In Google Play', // Text of price for Android
        inAmazonAppStore: 'In the Amazon Appstore',
        inWindowsStore: 'In the Windows Store', //Text of price for Windows
        GooglePlayParams: null, // Aditional parameters for the market
        icon: null, // The URL of the icon (defaults to <meta name="apple-touch-icon">)
        iconGloss: null, // Force gloss effect for iOS even for precomposed
        button: 'VIEW', // Text for the install button
        url: null, // The URL for the button. Keep null if you want the button to link to the app store.
        scale: 'auto', // Scale based on viewport size (set to 1 to disable)
        speedIn: 300, // Show animation speed of the banner
        speedOut: 400, // Close animation speed of the banner
        daysHidden: 15, // Duration to hide the banner after being closed (0 = always show banner)
        daysReminder: 90, // Duration to hide the banner after "VIEW" is clicked *separate from when the close button is clicked* (0 = always show banner)
        force: null, // Choose 'ios', 'android' or 'windows'. Don't do a browser check, just always show this banner
        hideOnInstall: true, // Hide the banner after "VIEW" is clicked.
        layer: false, // Display as overlay layer or slide down the page
        iOSUniversalApp: true, // If the iOS App is a universal app for both iPad and iPhone, display Smart Banner to iPad users, too.
        appendToSelector: 'body', //Append the banner to a specific selector
        pushSelector: 'html' // What element is going to push the site content down; this is where the banner append animation will start.
    };

    $.smartbanner.Constructor = SmartBanner;

    // ============================================================
    // Bootstrap transition
    // Copyright 2011-2014 Twitter, Inc.
    // Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)

    function transitionEnd() {
        var el = document.createElement('smartbanner');

        var transEndEventNames = {
            WebkitTransition: 'webkitTransitionEnd',
            MozTransition: 'transitionend',
            OTransition: 'oTransitionEnd otransitionend',
            transition: 'transitionend'
        };

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return { end: transEndEventNames[name] };
            }
        }
        // Explicit for ie8.
        return false;
    }
    if ($.support.transition !== undefined) {
        // Prevent conflict with Twitter Bootstrap.
        return;
    }

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function (duration) {
        var called = false, $el = this;
        $(this).one($.support.transition.end, function () {
            called = true;
        });
        var callback = function () {
            if (!called) {
                $($el).trigger($.support.transition.end);
            }
        };
        setTimeout(callback, duration);
        return this;
    };

    $(function () {
        $.support.transition = transitionEnd();
    });
    // ============================================================
});;
/*! jsviews.js v1.0.11 single-file version: http://jsviews.com/ */
/*! includes JsRender, JsObservable and JsViews - see: http://jsviews.com/#download */
!function (e, t) { var n = t.jQuery; "object" == typeof exports ? module.exports = n ? e(t, n) : function (n) { return e(t, n) } : "function" == typeof define && define.amd ? define(["jquery"], function (n) { return e(t, n) }) : e(t, !1) }(function (e, t) {
	"use strict"; function n(e, t) { return function () { var n, r = this, i = r.base; return r.base = e, n = t.apply(r, arguments), r.base = i, n } } function r(e, t) { return Ye(t) && (t = n(e ? e._d ? e : n(o, e) : o, t), t._d = (e && e._d || 0) + 1), t } function i(e, t) { var n, i = t.props; for (n in i) !jt.test(n) || e[n] && e[n].fix || (e[n] = "convert" !== n ? r(e.constructor.prototype[n], i[n]) : i[n]) } function a(e) { return e } function o() { return "" } function s(e) { try { throw console.log("JsRender dbg breakpoint: " + e), "dbg breakpoint" } catch (t) { } return this.base ? this.baseApply(arguments) : e } function l(e) { this.name = (t.link ? "JsViews" : "JsRender") + " Error", this.message = e || this.name } function d(e, t) { if (e) { for (var n in t) e[n] = t[n]; return e } } function p(e, t, n) { return e ? et(e) ? p.apply(We, e) : (ut = n ? n[0] : ut, /^(\W|_){5}$/.test(e + t + ut) || O("Invalid delimiters"), dt = e[0], pt = e[1], ct = t[0], ft = t[1], ot.delimiters = [dt + pt, ct + ft, ut], e = "\\" + dt + "(\\" + ut + ")?\\" + pt, t = "\\" + ct + "\\" + ft, ze = "(?:(\\w+(?=[\\/\\s\\" + ct + "]))|(\\w+)?(:)|(>)|(\\*))\\s*((?:[^\\" + ct + "]|\\" + ct + "(?!\\" + ft + "))*?)", at.rTag = "(?:" + ze + ")", ze = new RegExp("(?:" + e + ze + "(\\/)?|\\" + dt + "(\\" + ut + ")?\\" + pt + "(?:(?:\\/(\\w+))\\s*|!--[\\s\\S]*?--))" + t, "g"), at.rTmpl = new RegExp("^\\s|\\s$|<.*>|([^\\\\]|^)[{}]|" + e + ".*" + t), lt) : ot.delimiters } function c(e, t) { t || e === !0 || (t = e, e = void 0); var n, r, i, a, o = this, s = "root" === t; if (e) { if (a = t && o.type === t && o, !a) if (n = o.views, o._.useKey) { for (r in n) if (a = t ? n[r].get(e, t) : n[r]) break } else for (r = 0, i = n.length; !a && r < i; r++)a = t ? n[r].get(e, t) : n[r] } else if (s) a = o.root; else if (t) for (; o && !a;)a = o.type === t ? o : void 0, o = o.parent; else a = o.parent; return a || void 0 } function f() { var e = this.get("item"); return e ? e.index : void 0 } function u() { return this.index } function g(e, t, n, r) { var i, a, s, l = 0; if (1 === n && (r = 1, n = void 0), t) for (a = t.split("."), s = a.length; e && l < s; l++)i = e, e = a[l] ? e[a[l]] : e; return n && (n.lt = n.lt || l < s), void 0 === e ? r ? o : "" : r ? function () { return e.apply(i, arguments) } : e } function v(n, r, i) { var a, o, s, l, p, c, f, u = this, g = !vt && arguments.length > 1, v = u.ctx; if (n) { if (u._ || (p = u.index, u = u.tag), c = u, v && v.hasOwnProperty(n) || (v = rt).hasOwnProperty(n)) { if (s = v[n], "tag" === n || "tagCtx" === n || "root" === n || "parentTags" === n) return s } else v = void 0; if ((!vt && u.tagCtx || u.linked) && (s && s._cxp || (u = u.tagCtx || Ye(s) ? u : (u = u.scope || u, !u.isTop && u.ctx.tag || u), void 0 !== s && u.tagCtx && (u = u.tagCtx.view.scope), v = u._ocps, s = v && v.hasOwnProperty(n) && v[n] || s, s && s._cxp || !i && !g || ((v || (u._ocps = u._ocps || {}))[n] = s = [{ _ocp: s, _vw: c, _key: n }], s._cxp = { path: _t, ind: 0, updateValue: function (e, n) { return t.observable(s[0]).setProperty(_t, e), this } })), l = s && s._cxp)) { if (arguments.length > 2) return o = s[1] ? at._ceo(s[1].deps) : [_t], o.unshift(s[0]), o._cxp = l, o; if (p = l.tagElse, f = s[1] ? l.tag && l.tag.cvtArgs ? l.tag.cvtArgs(p, 1)[l.ind] : s[1](s[0].data, s[0], at) : s[0]._ocp, g) return at._ucp(n, r, u, l), u; s = f } return s && Ye(s) && (a = function () { return s.apply(this && this !== e ? this : c, arguments) }, d(a, s)), a || s } } function h(e) { return e && (e.fn ? e : this.getRsc("templates", e) || tt(e)) } function _(e, t, n, r) { var a, o, s, l, p, c = "number" == typeof n && t.tmpl.bnds[n - 1]; if (void 0 === r && c && c._lr && (r = ""), void 0 !== r ? n = r = { props: {}, args: [r] } : c && (n = c(t.data, t, at)), c = c._bd && c, e || c) { if (o = t._lc, a = o && o.tag, n.view = t, !a) { if (a = d(new at._tg, { _: { bnd: c, unlinked: !0, lt: n.lt }, inline: !o, tagName: ":", convert: e, onArrayChange: !0, flow: !0, tagCtx: n, tagCtxs: [n], _is: "tag" }), l = n.args.length, l > 1) for (p = a.bindTo = []; l--;)p.unshift(l); o && (o.tag = a, a.linkCtx = o), n.ctx = J(n.ctx, (o ? o.view : t).ctx), i(a, n) } a._er = r && s, a.ctx = n.ctx || a.ctx || {}, n.ctx = void 0, s = a.cvtArgs()[0], a._er = r && s } else s = n.args[0]; return s = c && t._.onRender ? t._.onRender(s, t, a) : s, void 0 != s ? s : "" } function m(e, t) { var n, r, i, a, o, s, l, d = this; if (d.tagName) { if (s = d, d = (s.tagCtxs || [d])[e || 0], !d) return } else s = d.tag; if (o = s.bindFrom, a = d.args, (l = s.convert) && "" + l === l && (l = "true" === l ? void 0 : d.view.getRsc("converters", l) || O("Unknown converter: '" + l + "'")), l && !t && (a = a.slice()), o) { for (i = [], n = o.length; n--;)r = o[n], i.unshift(b(d, r)); t && (a = i) } if (l) { if (l = l.apply(s, i || a), void 0 === l) return a; if (o = o || [0], n = o.length, et(l) && (l.arg0 === !1 || 1 !== n && l.length === n && !l.arg0) || (l = [l], o = [0], n = 1), t) a = l; else for (; n--;)r = o[n], +r === r && (a[r] = l[n]) } return a } function b(e, t) { return e = e[+t === t ? "args" : "props"], e && e[t] } function x(e) { return this.cvtArgs(e, 1) } function y(e, t) { var n, r, i = this; if ("" + t === t) { for (; void 0 === n && i;)r = i.tmpl && i.tmpl[e], n = r && r[t], i = i.parent; return n || We[e][t] } } function w(e, t, n, r, a, o) { function s(e) { var t = l[e]; if (void 0 !== t) for (t = et(t) ? t : [t], h = t.length; h--;)U = t[h], isNaN(parseInt(U)) || (t[h] = parseInt(U)); return t || [0] } t = t || Qe; var l, d, p, c, f, u, g, h, _, y, w, C, k, E, j, A, I, T, V, S, P, N, F, L, $, U, R, D, q, K, H = 0, z = "", Q = t._lc || !1, W = t.ctx, X = n || t.tmpl, Z = "number" == typeof r && t.tmpl.bnds[r - 1]; for ("tag" === e._is ? (l = e, e = l.tagName, r = l.tagCtxs, p = l.template) : (d = t.getRsc("tags", e) || O("Unknown tag: {{" + e + "}} "), p = d.template), void 0 === o && Z && (Z._lr = d.lateRender && Z._lr !== !1 || Z._lr) && (o = ""), void 0 !== o ? (z += o, r = o = [{ props: {}, args: [], params: { props: {} } }]) : Z && (r = Z(t.data, t, at)), g = r.length; H < g; H++)w = r[H], I = w.tmpl, (!Q || !Q.tag || H && !Q.tag.inline || l._er || I && +I === I) && (I && X.tmpls && (w.tmpl = w.content = X.tmpls[I - 1]), w.index = H, w.ctxPrm = v, w.render = M, w.cvtArgs = m, w.bndArgs = x, w.view = t, w.ctx = J(J(w.ctx, d && d.ctx), W)), (n = w.props.tmpl) && (w.tmpl = t._getTmpl(n), w.content = w.content || w.tmpl), l ? Q && Q.fn._lr && (T = !!l.init) : (l = new d._ctr, T = !!l.init, l.parent = u = W && W.tag, l.tagCtxs = r, Q && (l.inline = !1, Q.tag = l), l.linkCtx = Q, (l._.bnd = Z || Q.fn) ? (l._.ths = w.params.props["this"], l._.lt = r.lt, l._.arrVws = {}) : l.dataBoundOnly && O(e + " must be data-bound:\n{^{" + e + "}}")), L = l.dataMap, w.tag = l, L && r && (w.map = r[H].map), l.flow || (C = w.ctx = w.ctx || {}, c = l.parents = C.parentTags = W && J(C.parentTags, W.parentTags) || {}, u && (c[u.tagName] = u), c[l.tagName] = C.tag = l, C.tagCtx = w); if (!(l._er = o)) { for (i(l, r[0]), l.rendering = { rndr: l.rendering }, H = 0; H < g; H++) { if (w = l.tagCtx = r[H], F = w.props, l.ctx = w.ctx, !H) { if (T && (l.init(w, Q, l.ctx), T = void 0), w.args.length || w.argDefault === !1 || l.argDefault === !1 || (w.args = P = [w.view.data], w.params.args = ["#data"]), E = s("bindTo"), void 0 !== l.bindTo && (l.bindTo = E), void 0 !== l.bindFrom ? l.bindFrom = s("bindFrom") : l.bindTo && (l.bindFrom = l.bindTo = E), j = l.bindFrom || E, D = E.length, R = j.length, l._.bnd && (q = l.linkedElement) && (l.linkedElement = q = et(q) ? q : [q], D !== q.length && O("linkedElement not same length as bindTo")), (q = l.linkedCtxParam) && (l.linkedCtxParam = q = et(q) ? q : [q], R !== q.length && O("linkedCtxParam not same length as bindFrom/bindTo")), j) for (l._.fromIndex = {}, l._.toIndex = {}, _ = R; _--;)for (U = j[_], h = D; h--;)U === E[h] && (l._.fromIndex[h] = _, l._.toIndex[_] = h); Q && (Q.attr = l.attr = Q.attr || l.attr || Q._dfAt), f = l.attr, l._.noVws = f && f !== Mt } if (P = l.cvtArgs(H), l.linkedCtxParam) for (N = l.cvtArgs(H, 1), h = R, K = l.constructor.prototype.ctx; h--;)(k = l.linkedCtxParam[h]) && (U = j[h], A = N[h], w.ctx[k] = at._cp(K && void 0 === A ? K[k] : A, void 0 !== A && b(w.params, U), w.view, l._.bnd && { tag: l, cvt: l.convert, ind: h, tagElse: H })); (V = F.dataMap || L) && (P.length || F.dataMap) && (S = w.map, S && S.src === P[0] && !a || (S && S.src && S.unmap(), V.map(P[0], w, S, !l._.bnd), S = w.map), P = [S.tgt]), y = void 0, l.render && (y = l.render.apply(l, P), t.linked && y && !At.test(y) && (n = { links: [] }, n.render = n.fn = function () { return y }, y = B(n, t.data, void 0, !0, t, void 0, void 0, l))), P.length || (P = [t]), void 0 === y && ($ = P[0], l.contentCtx && ($ = l.contentCtx === !0 ? t : l.contentCtx($)), y = w.render($, !0) || (a ? void 0 : "")), z = z ? z + (y || "") : void 0 !== y ? "" + y : void 0 } l.rendering = l.rendering.rndr } return l.tagCtx = r[0], l.ctx = l.tagCtx.ctx, l._.noVws && l.inline && (z = "text" === f ? nt.html(z) : ""), Z && t._.onRender ? t._.onRender(z, t, l) : z } function C(e, t, n, r, i, a, o, s) { var l, d, p, c = this, u = "array" === t; c.content = s, c.views = u ? [] : {}, c.data = r, c.tmpl = i, p = c._ = { key: 0, useKey: u ? 0 : 1, id: "" + Pt++, onRender: o, bnds: {} }, c.linked = !!o, c.type = t || "top", t && (c.cache = { _ct: ot._cchCt }), n && "top" !== n.type || ((c.ctx = e || {}).root = c.data), (c.parent = n) ? (c.root = n.root || c, l = n.views, d = n._, c.isTop = d.scp, c.scope = (!e.tag || e.tag === n.ctx.tag) && !c.isTop && n.scope || c, d.useKey ? (l[p.key = "_" + d.useKey++] = c, c.index = $t, c.getIndex = f) : l.length === (p.key = c.index = a) ? l.push(c) : l.splice(a, 0, c), c.ctx = e || n.ctx) : t && (c.root = c) } function k(e) { var t, n, r; for (t in Kt) n = t + "s", e[n] && (r = e[n], e[n] = {}, We[n](r, e)) } function E(e, t, n) { function i() { var t = this; t._ = { unlinked: !0 }, t.inline = !0, t.tagName = e } var a, o, s, l = new at._tg; if (Ye(t) ? t = { depends: t.depends, render: t } : "" + t === t && (t = { template: t }), o = t.baseTag) { t.flow = !!t.flow, o = "" + o === o ? n && n.tags[o] || it[o] : o, o || O('baseTag: "' + t.baseTag + '" not found'), l = d(l, o); for (s in t) l[s] = r(o[s], t[s]) } else l = d(l, t); return void 0 !== (a = l.template) && (l.template = "" + a === a ? tt[a] || tt(a) : a), (i.prototype = l).constructor = l._ctr = i, n && (l._parentTmpl = n), l } function j(e) { return this.base.apply(this, e) } function A(e, n, r, i) { function a(n) { var a, s; if ("" + n === n || n.nodeType > 0 && (o = n)) { if (!o) if (/^\.?\/[^\\:*?"<>]*$/.test(n)) (s = tt[e = e || n]) ? n = s : o = document.getElementById(n); else if ("#" === n.charAt(0)) o = document.getElementById(n.slice(1)); else if (t.fn && !at.rTmpl.test(n)) try { o = t(n, document)[0] } catch (l) { } o && ("SCRIPT" !== o.tagName && O(n + ": Use script block, not " + o.tagName), i ? n = o.innerHTML : (a = o.getAttribute(Lt), a && (a !== Ot ? (n = tt[a], delete tt[a]) : t.fn && (n = t.data(o)[Ot])), a && n || (e = e || (t.fn ? Ot : n), n = A(e, o.innerHTML, r, i)), n.tmplName = e = e || a, e !== Ot && (tt[e] = n), o.setAttribute(Lt, e), t.fn && t.data(o, Ot, n))), o = void 0 } else n.fn || (n = void 0); return n } var o, s, l = n = n || ""; if (at._html = nt.html, 0 === i && (i = void 0, l = a(l)), i = i || (n.markup ? n.bnds ? d({}, n) : n : {}), i.tmplName = i.tmplName || e || "unnamed", r && (i._parentTmpl = r), !l && n.markup && (l = a(n.markup)) && l.fn && (l = l.markup), void 0 !== l) return l.render || n.render ? l.tmpls && (s = l) : (n = S(l, i), U(l.replace(xt, "\\$&"), n)), s || (s = d(function () { return s.render.apply(s, arguments) }, n), k(s)), s } function I(e, t) { return Ye(e) ? e.call(t) : e } function T(e, t, n) { Object.defineProperty(e, t, { value: n, configurable: !0 }) } function V(e, n) { function r(e) { p.apply(this, e) } function i() { return new r(arguments) } function a(e, t) { for (var n, r, i, a, o, s = 0; s < b; s++)i = u[s], n = void 0, i + "" !== i && (n = i, i = n.getter, o = n.parentRef), void 0 === (a = e[i]) && n && void 0 !== (r = n.defaultVal) && (a = I(r, e)), t(a, n && f[n.type], i, o) } function o(t) { t = t + "" === t ? JSON.parse(t) : t; var n, r, i, o, d = 0, p = t, c = []; if (et(t)) { for (t = t || [], n = t.length; d < n; d++)c.push(this.map(t[d])); return c._is = e, c.unmap = l, c.merge = s, c } if (t) { for (a(t, function (e, t) { t && (e = t.map(e)), c.push(e) }), p = this.apply(this, c), d = b; d--;)if (i = c[d], o = u[d].parentRef, o && i && i.unmap) if (et(i)) for (n = i.length; n--;)T(i[n], o, p); else T(i, o, p); for (r in t) r === Ge || y[r] || (p[r] = t[r]) } return p } function s(e, t, n) { e = e + "" === e ? JSON.parse(e) : e; var r, o, s, l, d, p, c, f, u, g, h = 0, _ = this; if (et(_)) { for (c = {}, u = [], o = e.length, s = _.length; h < o; h++) { for (f = e[h], p = !1, r = 0; r < s && !p; r++)c[r] || (d = _[r], v && (c[r] = p = v + "" === v ? f[v] && (y[v] ? d[v]() : d[v]) === f[v] : v(d, f))); p ? (d.merge(f), u.push(d)) : (u.push(g = i.map(f)), n && T(g, n, t)) } return void (x ? x(_).refresh(u, !0) : _.splice.apply(_, [0, _.length].concat(u))) } a(e, function (e, t, n, r) { t ? _[n]().merge(e, _, r) : _[n]() !== e && _[n](e) }); for (l in e) l === Ge || y[l] || (_[l] = e[l]) } function l() { function e(e) { for (var t = [], n = 0, r = e.length; n < r; n++)t.push(e[n].unmap()); return t } var t, n, r, i, a = 0, o = this; if (et(o)) return e(o); for (t = {}; a < b; a++)n = u[a], r = void 0, n + "" !== n && (r = n, n = r.getter), i = o[n](), t[n] = r && i && f[r.type] ? et(i) ? e(i) : i.unmap() : i; for (n in o) !o.hasOwnProperty(n) || "_" === n.charAt(0) && y[n.slice(1)] || n === Ge || Ye(o[n]) || (t[n] = o[n]); return t } var d, p, c, f = this, u = n.getters, g = n.extend, v = n.id, h = t.extend({ _is: e || "unnamed", unmap: l, merge: s }, g), _ = "", m = "", b = u ? u.length : 0, x = t.observable, y = {}; for (r.prototype = h, d = 0; d < b; d++)!function (e) { e = e.getter || e, y[e] = d + 1; var t = "_" + e; _ += (_ ? "," : "") + e, m += "this." + t + " = " + e + ";\n", h[e] = h[e] || function (n) { return arguments.length ? void (x ? x(this).setProperty(e, n) : this[t] = n) : this[t] }, x && (h[e].set = h[e].set || function (e) { this[t] = e }) }(u[d]); return m = new Function(_, m), p = function () { m.apply(this, arguments), (c = arguments[b + 1]) && T(this, arguments[b], c) }, p.prototype = h, h.constructor = p, i.map = o, i.getters = u, i.extend = g, i.id = v, i } function S(e, n) { var r, i = st._wm || {}, a = { tmpls: [], links: {}, bnds: [], _is: "template", render: M }; return n && (a = d(a, n)), a.markup = e, a.htmlTag || (r = Ct.exec(e), a.htmlTag = r ? r[1].toLowerCase() : ""), r = i[a.htmlTag], r && r !== i.div && (a.markup = t.trim(a.markup)), a } function P(e, t) { function n(i, a, o) { var s, l, d, p = at.onStore[e]; if (i && typeof i === Bt && !i.nodeType && !i.markup && !i.getTgt && !("viewModel" === e && i.getters || i.extend)) { for (l in i) n(l, i[l], a); return a || We } return i && "" + i !== i && (o = a, a = i, i = void 0), d = o ? "viewModel" === e ? o : o[r] = o[r] || {} : n, s = t.compile, void 0 === a && (a = s ? i : d[i], i = void 0), null === a ? i && delete d[i] : (s && (a = s.call(d, i, a, o, 0) || {}, a._is = e), i && (d[i] = a)), p && p(i, a, o, s), a } var r = e + "s"; We[r] = n } function N(e) { lt[e] = lt[e] || function (t) { return arguments.length ? (ot[e] = t, lt) : ot[e] } } function F(e) { function t(t, n) { this.tgt = e.getTgt(t, n), n.map = this } return Ye(e) && (e = { getTgt: e }), e.baseMap && (e = d(d({}, e.baseMap), e)), e.map = function (e, n) { return new t(e, n) }, e } function M(e, t, n, r, i, a) { var o, s, l, d, p, c, f, u, g = r, v = ""; if (t === !0 ? (n = t, t = void 0) : typeof t !== Bt && (t = void 0), (l = this.tag) ? (p = this, g = g || p.view, d = g._getTmpl(l.template || p.tmpl), arguments.length || (e = l.contentCtx && Ye(l.contentCtx) ? e = l.contentCtx(e) : g)) : d = this, d) { if (!r && e && "view" === e._is && (g = e), g && e === g && (e = g.data), c = !g, vt = vt || c, c && ((t = t || {}).root = e), !vt || st.useViews || d.useViews || g && g !== Qe) v = B(d, e, t, n, g, i, a, l); else { if (g ? (f = g.data, u = g.index, g.index = $t) : (g = Qe, f = g.data, g.data = e, g.ctx = t), et(e) && !n) for (o = 0, s = e.length; o < s; o++)g.index = o, g.data = e[o], v += d.fn(e[o], g, at); else g.data = e, v += d.fn(e, g, at); g.data = f, g.index = u } c && (vt = void 0) } return v } function B(e, t, n, r, i, a, o, s) { var l, p, c, f, u, g, v, h, _, m, b, x, y, w = ""; if (s && (_ = s.tagName, x = s.tagCtx, n = n ? J(n, s.ctx) : s.ctx, e === i.content ? v = e !== i.ctx._wrp ? i.ctx._wrp : void 0 : e !== x.content ? e === s.template ? (v = x.tmpl, n._wrp = x.content) : v = x.content || i.content : v = i.content, x.props.link === !1 && (n = n || {}, n.link = !1)), i && (o = o || i._.onRender, y = n && n.link === !1, y && i._.nl && (o = void 0), n = J(n, i.ctx), x = !s && i.tag ? i.tag.tagCtxs[i.tagElse] : x), (m = x && x.props.itemVar) && ("~" !== m[0] && $("Use itemVar='~myItem'"), m = m.slice(1)), a === !0 && (g = !0, a = 0), o && s && s._.noVws && (o = void 0), h = o, o === !0 && (h = void 0, o = i._.onRender), n = e.helpers ? J(e.helpers, n) : n, b = n, et(t) && !r) for (c = g ? i : void 0 !== a && i || new C(n, "array", i, t, e, a, o, v), c._.nl = y, i && i._.useKey && (c._.bnd = !s || s._.bnd && s, c.tag = s), l = 0, p = t.length; l < p; l++)f = new C(b, "item", c, t[l], e, (a || 0) + l, o, c.content), m && ((f.ctx = d({}, b))[m] = at._cp(t[l], "#data", f)), u = e.fn(t[l], f, at), w += c._.onRender ? c._.onRender(u, f) : u; else c = g ? i : new C(b, _ || "data", i, t, e, a, o, v), m && ((c.ctx = d({}, b))[m] = at._cp(t, "#data", c)), c.tag = s, c._.nl = y, w += e.fn(t, c, at); return s && (c.tagElse = x.index, x.contentView = c), h ? h(w, c) : w } function L(e, t, n) { var r = void 0 !== n ? Ye(n) ? n.call(t.data, e, t) : n || "" : "{Error: " + (e.message || e) + "}"; return ot.onError && void 0 !== (n = ot.onError.call(t.data, e, n && r, t)) && (r = n), t && !t._lc ? nt.html(r) : r } function O(e) { throw new at.Err(e) } function $(e) { O("Syntax error\n" + e) } function U(e, t, n, r, i) { function a(t) { t -= v, t && _.push(e.substr(v, t).replace(mt, "\\n")) } function o(t, n) { t && (t += "}}", $((n ? "{{" + n + "}} block has {{/" + t + " without {{" + t : "Unmatched or missing {{/" + t) + ", in template:\n" + e)) } function s(s, l, d, f, g, b, x, y, w, C, k, E) { (x && l || w && !d || y && ":" === y.slice(-1) || C) && $(s), b && (g = ":", f = Mt), w = w || n && !i; var j, A, I, T = (l || n) && [[]], V = "", S = "", P = "", N = "", F = "", M = "", B = "", L = "", O = !w && !g; d = d || (y = y || "#data", g), a(E), v = E + s.length, x ? u && _.push(["*", "\n" + y.replace(/^:/, "ret+= ").replace(bt, "$1") + ";\n"]) : d ? ("else" === d && (wt.test(y) && $('For "{{else if expr}}" use "{{else expr}}"'), T = m[9] && [[]], m[10] = e.substring(m[10], E), A = m[11] || m[0] || $("Mismatched: " + s), m = h.pop(), _ = m[2], O = !0), y && K(y.replace(mt, " "), T, t, n).replace(yt, function (e, t, n, r, i, a, o, s) { return "this:" === r && (a = "undefined"), s && (I = I || "@" === s[0]), r = "'" + i + "':", o ? (S += n + a + ",", N += "'" + s + "',") : n ? (P += r + "j._cp(" + a + ',"' + s + '",view),', M += r + "'" + s + "',") : t ? B += a : ("trigger" === i && (L += a), "lateRender" === i && (j = "false" !== s), V += r + a + ",", F += r + "'" + s + "',", c = c || jt.test(i)), "" }).slice(0, -1), T && T[0] && T.pop(), p = [d, f || !!r || c || "", O && [], D(N || (":" === d ? "'#data'," : ""), F, M), D(S || (":" === d ? "data," : ""), V, P), B, L, j, I, T || 0], _.push(p), O && (h.push(m), m = p, m[10] = v, m[11] = A)) : k && (o(k !== m[0] && k !== m[11] && k, m[0]), m[10] = e.substring(m[10], E), m = h.pop()), o(!m && k), _ = m[2] } var l, d, p, c, f, u = ot.allowCode || t && t.allowCode || lt.allowCode === !0, g = [], v = 0, h = [], _ = g, m = [, , g]; if (u && t._is && (t.allowCode = u), n && (void 0 !== r && (e = e.slice(0, -r.length - 2) + ct), e = dt + e + ft), o(h[0] && h[0][2].pop()[0]), e.replace(ze, s), a(e.length), (v = g[g.length - 1]) && o("" + v !== v && +v[10] === v[10] && v[0]), n) { for (d = H(g, e, n), f = [], l = g.length; l--;)f.unshift(g[l][9]); R(d, f) } else d = H(g, t); return d } function R(e, t) { var n, r, i = 0, a = t.length; for (e.deps = [], e.paths = []; i < a; i++) { e.paths.push(r = t[i]); for (n in r) "_jsvto" !== n && r.hasOwnProperty(n) && r[n].length && !r[n].skp && (e.deps = e.deps.concat(r[n])) } } function D(e, t, n) { return [e.slice(0, -1), t.slice(0, -1), n.slice(0, -1)] } function q(e, t) { return "\n\tparams:{args:[" + e[0] + "],\n\tprops:{" + e[1] + "}" + (e[2] ? ",\n\tctx:{" + e[2] + "}" : "") + "},\n\targs:[" + t[0] + "],\n\tprops:{" + t[1] + "}" + (t[2] ? ",\n\tctx:{" + t[2] + "}" : "") } function K(e, n, r, i) { function a(r, a, d, j, A, I, T, V, S, P, N, F, M, B, L, O, U, R, D, q, K) { function H(e, t, r, a, l, d, p, c) { if (X = "." === r, r && (A = A.slice(t.length), /^\.?constructor$/.test(c || A) && $(e), X || (e = (P ? (i ? "" : "(ltOb.lt=ltOb.lt||") + "(ob=" : "") + (a ? 'view.ctxPrm("' + a + '")' : l ? "view" : "data") + (P ? ")===undefined" + (i ? "" : ")") + '?"":view._getOb(ob,"' : "") + (c ? (d ? "." + d : a ? "" : l ? "" : "." + r) + (p || "") : (c = a ? "" : l ? d || "" : r, "")), e += c ? "." + c : "", e = t + ("view.data" === e.slice(0, 9) ? e.slice(5) : e) + (P ? (i ? '"' : '",ltOb') + (N ? ",1)" : ")") : "")), f)) { if (z = "_linkTo" === o ? s = n._jsvto = n._jsvto || [] : u.bd, Q = X && z[z.length - 1]) { if (Q._cpfn) { for (; Q.sb;)Q = Q.sb; Q.prm && (Q.bnd && (A = "^" + A.slice(1)), Q.sb = A, Q.bnd = Q.bnd || "^" === A[0]) } } else z.push(A); N && !X && (w[_] = Y, C[_] = k[_].length) } return e } j && !V && (A = j + A), I = I || "", M = M || "", d = d || a || M, A = A || S, P && (P = !/\)|]/.test(K[q - 1])) && (A = A.slice(1).split(".").join("^")), N = N || R || ""; var J, z, Q, W, X, Z, G, Y = q; if (!c && !p) { if (T && $(e), U && f) { if (J = w[_ - 1], K.length - 1 > Y - (J || 0)) { if (J = t.trim(K.slice(J, Y + r.length)), z = s || g[_ - 1].bd, Q = z[z.length - 1], Q && Q.prm) { for (; Q.sb && Q.sb.prm;)Q = Q.sb; W = Q.sb = { path: Q.sb, bnd: Q.bnd } } else z.push(W = { path: z.pop() }); Q && Q.sb === W && (k[_] = k[_ - 1].slice(Q._cpPthSt) + k[_], k[_ - 1] = k[_ - 1].slice(0, Q._cpPthSt)), W._cpPthSt = C[_ - 1], W._cpKey = J, k[_] += K.slice(E, q), E = q, W._cpfn = Ut[J] = Ut[J] || new Function("data,view,j", "//" + J + "\nvar v;\nreturn ((v=" + k[_] + ("]" === O ? ")]" : O) + ")!=null?v:null);"), k[_ - 1] += y[h] && st.cache ? 'view.getCache("' + J.replace(xt, "\\$&") + '"' : k[_], W.prm = u.bd, W.bnd = W.bnd || W.path && W.path.indexOf("^") >= 0 } k[_] = "" } "[" === N && (N = "[j._sq("), "[" === d && (d = "[j._sq(") } return G = c ? (c = !B, c ? r : M + '"') : p ? (p = !L, p ? r : M + '"') : (d ? (x[++h] = !0, m[h] = 0, f && (w[_++] = Y++, u = g[_] = { bd: [] }, k[_] = "", C[_] = 1), d) : "") + (D ? h ? "" : (v = K.slice(v, Y), (o ? (o = l = s = !1, "\b") : "\b,") + v + (v = Y + r.length, f && n.push(u.bd = []), "\b")) : V ? (_ && $(e), f && n.pop(), o = "_" + A, l = j, v = Y + r.length, f && (f = u.bd = n[o] = [], f.skp = !j), A + ":") : A ? A.split("^").join(".").replace(at.rPath, H) + (N || I) : I ? I : O ? "]" === O ? ")]" : ")" : F ? (y[h] || $(e), ",") : a ? "" : (c = B, p = L, '"')), c || p || O && (y[h] = !1, h--), f && (c || p || (O && (x[h + 1] && (u = g[--_], x[h + 1] = !1), b = m[h + 1]), N && (m[h + 1] = k[_].length + (d ? 1 : 0), (A || O) && (u = g[++_] = { bd: [] }, x[h + 1] = !0))), k[_] = (k[_] || "") + K.slice(E, q), E = q + r.length, c || p || ((Z = d && x[h + 1]) && (k[_ - 1] += d, C[_ - 1]++), "(" === N && X && !W && (k[_] = k[_ - 1].slice(b) + k[_], k[_ - 1] = k[_ - 1].slice(0, b))), k[_] += Z ? G.slice(1) : G), c || p || !N || (h++, A && "(" === N && (y[h] = !0)), c || p || !R || (f && (k[_] += N), G += N), G } var o, s, l, d, p, c, f = n && n[0], u = { bd: f }, g = { 0: u }, v = 0, h = 0, _ = 0, m = {}, b = 0, x = {}, y = {}, w = {}, C = { 0: 0 }, k = { 0: "" }, E = 0; return "@" === e[0] && (e = e.replace(St, ".")), d = (e + (r ? " " : "")).replace(at.rPrm, a), f && (d = k[0]), !h && d || $(e) } function H(e, t, n) { var r, i, a, o, s, l, d, p, c, f, u, g, v, h, _, m, b, x, y, w, C, k, E, j, A, I, T, V, P, N, F, M, B, L = 0, O = st.useViews || t.useViews || t.tags || t.templates || t.helpers || t.converters, U = "", D = {}, K = e.length; for ("" + t === t ? (x = n ? 'data-link="' + t.replace(mt, " ").slice(1, -1) + '"' : t, t = 0) : (x = t.tmplName || "unnamed", t.allowCode && (D.allowCode = !0), t.debug && (D.debug = !0), u = t.bnds, b = t.tmpls), r = 0; r < K; r++)if (i = e[r], "" + i === i) U += '+"' + i + '"'; else if (a = i[0], "*" === a) U += ";\n" + i[1] + "\nret=ret"; else { if (o = i[1], C = !n && i[2], s = q(i[3], v = i[4]), N = i[6], F = i[7], i[8] ? (M = "\nvar ob,ltOb={},ctxs=", B = ";\nctxs.lt=ltOb.lt;\nreturn ctxs;") : (M = "\nreturn ", B = ""), k = i[10] && i[10].replace(bt, "$1"), (A = "else" === a) ? g && g.push(i[9]) : (V = i[5] || ot.debugMode !== !1 && "undefined", u && (g = i[9]) && (g = [g], L = u.push(1))), O = O || v[1] || v[2] || g || /view.(?!index)/.test(v[0]), (I = ":" === a) ? o && (a = o === Mt ? ">" : o + a) : (C && (y = S(k, D), y.tmplName = x + "/" + a, y.useViews = y.useViews || O, H(C, y), O = y.useViews, b.push(y)), A || (w = a, O = O || a && (!it[a] || !it[a].flow), j = U, U = ""), E = e[r + 1], E = E && "else" === E[0]), P = V ? ";\ntry{\nret+=" : "\n+", h = "", _ = "", I && (g || N || o && o !== Mt || F)) { if (T = new Function("data,view,j", "// " + x + " " + ++L + " " + a + M + "{" + s + "};" + B), T._er = V, T._tag = a, T._bd = !!g, T._lr = F, n) return T; R(T, g), m = 'c("' + o + '",view,', f = !0, h = m + L + ",", _ = ")" } if (U += I ? (n ? (V ? "try{\n" : "") + "return " : P) + (f ? (f = void 0, O = c = !0, m + (T ? (u[L - 1] = T, L) : "{" + s + "}") + ")") : ">" === a ? (d = !0, "h(" + v[0] + ")") : (p = !0, "((v=" + v[0] + ")!=null?v:" + (n ? "null)" : '"")'))) : (l = !0, "\n{view:view,content:false,tmpl:" + (C ? b.length : "false") + "," + s + "},"), w && !E) { if (U = "[" + U.slice(0, -1) + "]", m = 't("' + w + '",view,this,', n || g) { if (U = new Function("data,view,j", " // " + x + " " + L + " " + w + M + U + B), U._er = V, U._tag = w, g && R(u[L - 1] = U, g), U._lr = F, n) return U; h = m + L + ",undefined,", _ = ")" } U = j + P + m + (g && L || U) + ")", g = 0, w = 0 } V && !E && (O = !0, U += ";\n}catch(e){ret" + (n ? "urn " : "+=") + h + "j._err(e,view," + V + ")" + _ + ";}" + (n ? "" : "\nret=ret")) } U = "// " + x + (D.debug ? "\ndebugger;" : "") + "\nvar v" + (l ? ",t=j._tag" : "") + (c ? ",c=j._cnvt" : "") + (d ? ",h=j._html" : "") + (n ? (i[8] ? ", ob" : "") + ";\n" : ',ret=""') + U + (n ? "\n" : ";\nreturn ret;"); try { U = new Function("data,view,j", U) } catch (J) { $("Compiled template code:\n\n" + U + '\n: "' + (J.message || J) + '"') } return t && (t.fn = U, t.useViews = !!O), U } function J(e, t) { return e && e !== t ? t ? d(d({}, t), e) : e : t && d({}, t) } function z(e, n) { var r, i, a = n.map, o = a && a.propsArr; if (!o) { if (o = [], typeof e === Bt || Ye(e)) for (r in e) i = e[r], r === Ge || !e.hasOwnProperty(r) || n.props.noFunctions && t.isFunction(i) || o.push({ key: r, prop: i }); a && (a.propsArr = a.options && o) } return Q(o, n) } function Q(e, n) { var r, i, a, o = n.tag, s = n.props, l = n.params.props, d = s.filter, p = s.sort, c = p === !0, f = parseInt(s.step), u = s.reverse ? -1 : 1; if (!et(e)) return e; if (c || p && "" + p === p ? (r = e.map(function (e, t) { return e = c ? e : g(e, p), { i: t, v: "" + e === e ? e.toLowerCase() : e } }), r.sort(function (e, t) { return e.v > t.v ? u : e.v < t.v ? -u : 0 }), e = r.map(function (t) { return e[t.i] })) : (p || u < 0) && !o.dataMap && (e = e.slice()), Ye(p) && (e = e.sort(function () { return p.apply(n, arguments) })), u < 0 && (!p || Ye(p)) && (e = e.reverse()), e.filter && d && (e = e.filter(d, n), n.tag.onFilter && n.tag.onFilter(n)), l.sorted && (r = p || u < 0 ? e : e.slice(), o.sorted ? t.observable(o.sorted).refresh(r) : n.map.sorted = r), i = s.start, a = s.end, (l.start && void 0 === i || l.end && void 0 === a) && (i = a = 0), isNaN(i) && isNaN(a) || (i = +i || 0, a = void 0 === a || a > e.length ? e.length : +a, e = e.slice(i, a)), f > 1) { for (i = 0, a = e.length, r = []; i < a; i += f)r.push(e[i]); e = r } return l.paged && o.paged && Ze(o.paged).refresh(e), e } function W(e, n, r) { var i = this.jquery && (this[0] || O("Unknown template")), a = i.getAttribute(Lt); return M.call(a && t.data(i)[Ot] || tt(i), e, n, r) } function X(e) { return Nt[e] || (Nt[e] = "&#" + e.charCodeAt(0) + ";") } function Z(e, t) { return Ft[t] || "" } function G(e) { return void 0 != e ? Et.test(e) && ("" + e).replace(It, X) || e : "" } function Y(e) { return "" + e === e ? e.replace(Tt, X) : e } function ee(e) { return "" + e === e ? e.replace(Vt, Z) : e } function te(e, t, n, r, i) { var a, o, s, l, d, p, c, f, u, g, v, h, _, m, b, x, y, w, C, k; if (r && r._tgId && (w = r, r = w._tgId, w.bindTo || (Ie(dr[r], w), w.bindTo = [0])), (p = dr[r]) && (v = p.to)) for (v = v[t || 0], a = p.linkCtx, u = a.elem, d = a.view, w = a.tag, !w && v._cxp && (w = v._cxp.path !== _t && v._cxp.tag, c = e[0], e = [], e[v._cxp.ind] = c), w && (w._.chg = 1, (s = w.convertBack) && (o = Ye(s) ? s : d.getRsc("converters", s))), "SELECT" === u.nodeName ? (u.multiple && null === e[0] && (e = [[]]), u._jsvSel = e) : u._jsvSel && (C = u._jsvSel, k = wr(u.value, C), k > -1 && !u.checked ? C.splice(k, 1) : k < 0 && u.checked && C.push(u.value), e = [C.slice()]), f = e, x = v.length, o && (e = o.apply(w, e), void 0 === e && (v = []), et(e) && (e.arg0 === !1 || 1 !== x && e.length === x && !e.arg0) || (e = [e])); x--;)if ((h = v[x]) && (h = h + "" === h ? [a.data, h] : h, l = h[0], _ = h.tag, c = (l && l._ocp && !l._vw ? f : e)[x], !(void 0 === c || w && w.onBeforeUpdateVal && w.onBeforeUpdateVal(i, { change: "change", data: l, path: h[1], index: x, tagElse: t, value: c }) === !1))) if (_) void 0 !== (y = _._.toIndex[h.ind]) && _.updateValue(c, y, h.tagElse, void 0, void 0, i), _.setValue(c, h.ind, h.tagElse); else if (void 0 !== c && l) { if ((_ = i && (g = i.target)._jsvInd === x && g._jsvLkEl) && void 0 !== (y = _._.fromIndex[x]) && _.setValue(f[x], y, g._jsvElse), l._cpfn) for (b = a._ctxCb, m = l, l = a.data, m._cpCtx && (l = m.data, b = m._cpCtx); m && m.sb;)l = b(m), m = m.sb; Ze(l, n).setProperty(h[1], c, void 0, h.isCpfn) } if (w) return w._.chg = void 0, w } function ne(e) { var n, r, i = e.target, a = le(i), o = Zn[a]; if (!i._jsvTr || e.delegateTarget !== wn && "number" !== i.type || "input" === e.type) { for (r = Ye(a) ? a(i) : o ? t(i)[o]() : t(i).attr(a), i._jsvChg = 1, br.lastIndex = 0; n = br.exec(i._jsvBnd);)Oe(r, i._jsvInd, i._jsvElse, void 0, n[1], e); i._jsvChg = void 0 } } function re(e, t) { var n, r, i, a, o, s, l, d, p, c = this, f = c.fn, u = c.tag, g = c.data, v = c.elem, h = c.convert, _ = v.parentNode, m = c.view, b = m._lc, x = t && Me(m, Mn, u); if (_ && (!x || x.call(u || c, e, t) !== !1) && (!t || "*" === e.data.prop || e.data.prop === t.path)) { if (m._lc = c, t || c._toLk) { if (c._toLk = 0, f._er) try { r = f(g, m, at) } catch (y) { o = f._er, s = L(y, m, new Function("data,view", "return " + o + ";")(g, m)), r = [{ props: {}, args: [s], tag: u }] } else r = f(g, m, at); if (n = u && u.attr || c.attr || (c._dfAt = le(v, !0, void 0 !== h)), c._dfAt === Kn && (u && u.parentElem || c.elem).type === $n && (n = On), u) { if (a = o || u._er, r = r[0] ? r : [r], i = !a && (u.onUpdate === !1 || t && Ye(u.onUpdate) && u.onUpdate(e, t, r) === !1), Ve(u, r, a), u._.chg && (n === Mt || n === Kn) || i || n === qn) return ke(u, e, t), u._.chg || ce(c, g, v), m._lc = b, t && (x = Me(m, Bn, u)) && x.call(u || c, e, t), void (u.tagCtx.props.dataMap && u.tagCtx.props.dataMap.map(u.tagCtx.args[0], u.tagCtx, u.tagCtx.map, vt || !u._.bnd)); for (u.onUnbind && u.onUnbind(u.tagCtx, c, u.ctx, e, t), u.linkedElems = u.linkedElem = u.mainElem = u.displayElem = void 0, p = u.tagCtxs.length; p--;)d = u.tagCtxs[p], d.linkedElems = d.mainElem = d.displayElem = void 0; r = ":" === u.tagName ? at._cnvt(u.convert, m, r[0]) : at._tag(u, m, m.tmpl, r, !0, s) } else f._tag && (h = "" === h ? Jn : h, r = h ? at._cnvt(h, m, r[0] || r) : at._tag(f._tag, m, m.tmpl, r, !0, s), Ue(u = c.tag), n = c.attr || n); (l = u && (!u.inline || c.fn._lr) && u.template) && ce(c, g, v), ae(r, c, n, u), c._noUpd = 0, u && (u._er = o, ke(u, e, t)) } l || ce(c, g, v), u && u._.ths && u.updateValue(u, u.bindTo ? u.bindTo.length : 1), t && (x = Me(m, Bn, u)) && x.call(u || c, e, t), m._lc = b } } function ie(e, t) { e._df = t, e[(t ? "set" : "remove") + "Attribute"](Wn, "") } function ae(n, r, i, a) { var o, s, l, d, p, c, f, u, g, v, h, _, m, b, x = !(i === qn || void 0 === n || r._noUpd || (i === Kn || i === Mt) && !a && r.elem._jsvChg), y = r.data, w = a && a.parentElem || r.elem, C = w.parentNode, k = t(w), E = r.view, j = r._val, A = a; return a && (a._.unlinked = !0, a.parentElem = a.parentElem || r.expr || a._elCnt ? w : C, s = a._prv, l = a._nxt), x ? ("visible" === i && (i = "css-display"), /^css-/.test(i) ? ("visible" === r.attr && (m = (w.currentStyle || yr.call(e, w, "")).display, n ? (n = w._jsvd || m, n !== qn || (n = lr[_ = w.nodeName]) || (h = document.createElement(_), document.body.appendChild(h), n = lr[_] = (h.currentStyle || yr.call(e, h, "")).display, document.body.removeChild(h))) : (w._jsvd = m, n = qn)), (A = A || j !== n) && t.style(w, i.slice(4), n)) : "link" !== i && (/^data-/.test(i) ? t.data(w, i.slice(5), n) : /^prop-/.test(i) ? (c = !0, i = i.slice(5)) : i === On ? (c = !0, w.name && et(n) ? (w._jsvSel = n, n = wr(w.value, n) > -1) : n = n && "false" !== n) : i === Un ? (c = !0, i = On, n = w.value === n) : "selected" === i || "disabled" === i || "multiple" === i || "readonly" === i ? n = n && "false" !== n ? i : null : i === Kn && "SELECT" === w.nodeName && (w._jsvSel = et(n) ? n : "" + n), (o = Zn[i]) ? i === Mt ? a && a.inline ? (p = a.nodes(!0), a._elCnt && (s && s !== l ? Be(s, l, w, a._tgId, "^", !0) : (f = s ? s.getAttribute(Nn) : w._df, u = a._tgId + "^", g = f.indexOf("#" + u) + 1, v = f.indexOf("/" + u), g && v > 0 && (g += u.length, v > g && (Le(f.slice(g, v)), f = f.slice(0, g) + f.slice(v), s ? s.setAttribute(Nn, f) : w._df && ie(w, f)))), s = s ? s.previousSibling : l ? l.previousSibling : w.lastChild), t(p).remove(), d = E.link(E.data, w, s, l, n, a && { tag: a._tgId })) : (x = x && j !== n, x && (k.empty(), d = E.link(y, w, s, l, n, a && { tag: a._tgId }))) : w._jsvSel ? k[o](n) : ((A = A || j !== n) && ("text" === i && w.children && !w.children[0] ? w[Pn] = null === n ? "" : n : k[o](n)), void 0 === (b = C._jsvSel) || i !== Kn && void 0 !== k.attr(Kn) || (w.selected = wr("" + n, et(b) ? b : [b]) > -1)) : (A = A || j !== n) && k[c ? "prop" : "attr"](i, void 0 !== n || c ? n : null)), r._val = n, fe(d), A) : void (r._val = n) } function oe(e, t) { var n = this, r = Me(n, Mn, n.tag), i = Me(n, Bn, n.tag); if (!r || r.call(n, e, t) !== !1) { if (t) { var a = t.change, o = t.index, s = t.items; switch (n._.srt = t.refresh, a) { case "insert": n.addViews(o, s, t._dly); break; case "remove": n.removeViews(o, s.length, void 0, t._dly); break; case "move": n.moveViews(t.oldIndex, o, s.length); break; case "refresh": n._.srt = void 0, n.fixIndex(0) } } i && i.call(n, e, t) } } function se(e) { var n, r, i = e.type, a = e.data, o = e._.bnd; !e._.useKey && o && ((r = e._.bndArr) && (t([r[1]]).off(Yt, r[0]), e._.bndArr = void 0), o !== !!o ? i ? o._.arrVws[e._.id] = e : delete o._.arrVws[e._.id] : i && a && (n = function (t) { t.data && t.data.off || oe.apply(e, arguments) }, t([a]).on(Yt, n), e._.bndArr = [n, a])) } function le(e, t, n) { var r = e.nodeName.toLowerCase(), i = st._fe[r] || e.contentEditable === Jn && { to: Mt, from: Mt }; return i ? t ? "input" === r && e.type === Un ? Un : i.to : i.from : t ? n ? "text" : Mt : "" } function de(e, n, r, i, a, o, s) { var l, d, p, c, f, u = e.parentElem, g = e._prv, v = e._nxt, h = e._elCnt; if (g && g.parentNode !== u && O("Missing parentNode"), s) { c = e.nodes(), h && g && g !== v && Be(g, v, u, e._.id, "_", !0), e.removeViews(void 0, void 0, !0), d = v, h && (g = g ? g.previousSibling : v ? v.previousSibling : u.lastChild), t(c).remove(); for (f in e._.bnds) Pe(f) } else { if (n) { if (p = i[n - 1], !p) return !1; g = p._nxt } h ? (d = g, g = d ? d.previousSibling : u.lastChild) : d = g.nextSibling } l = r.render(a, o, e._.useKey && s, e, s || n, !0), fe(e.link(a, u, g, d, l, p)) } function pe(e, t, n) { var r, i; return n ? (i = "^`", Ue(n), r = n._tgId, r || (dr[r = pr++] = n, n._tgId = "" + r)) : (i = "_`", In[r = t._.id] = t), "#" + r + i + (void 0 != e ? e : "") + "/" + r + i } function ce(e, t, n) { var r, i, a, o, s, l, p, c, f, u, g, v, h = e.tag, _ = !h, m = e.convertBack, b = e._hdl; if (t = "object" == typeof t && t, h && ((f = h.convert) && (f = f === Jn ? h.tagCtx.props.convert : f, f = e.view.getRsc("converters", f) || f, f = f && f.depends, f = f && at._dp(f, t, b)), (u = h.tagCtx.props.depends || h.depends) && (u = at._dp(u, h, b), f = f ? f.concat(u) : u), v = h.linkedElems), f = f || [], !e._depends || "" + e._depends != "" + f) { if (s = e.fn.deps.slice(), e._depends && (g = e._depends.bdId, Ze._apply(1, [t], s, e._depends, b, e._ctxCb, !0)), h) { for (i = h.boundProps.length; i--;)for (p = h.boundProps[i], a = h._.bnd.paths.length; a--;)c = h._.bnd.paths[a]["_" + p], c && c.length && c.skp && (s = s.concat(c)); _ = void 0 === h.onArrayChange || h.onArrayChange === !0 } for (i = s.length; i--;)l = s[i], l._cpfn && (s[i] = d({}, l)); if (r = Ze._apply(_ ? 0 : 1, [t], s, f, b, e._ctxCb), g || (g = e._bndId || "" + pr++, e._bndId = void 0, n._jsvBnd = (n._jsvBnd || "") + "&" + g, e.view._.bnds[g] = g), r.elem = n, r.linkCtx = e, r._tgId = g, f.bdId = g, e._depends = f, dr[g] = r, (v || void 0 !== m || h && h.bindTo) && Ie(r, h, m), v) for (i = v.length; i--;)for (o = v[i], a = o && o.length; a--;)o[a]._jsvLkEl ? o[a]._jsvBnd || (o[a]._jsvBnd = "&" + g + "+") : (o[a]._jsvLkEl = h, Ae(h, o[a]), o[a]._jsvBnd = "&" + g + "+"); else void 0 !== m && Ae(h, n); h && !h.inline && (h.flow || n.setAttribute(Nn, (n.getAttribute(Nn) || "") + "#" + g + "^/" + g + "^"), h._tgId = "" + g) } } function fe(e) { var t; if (e) for (; t = e.pop();)t._hdl() } function ue(e, t, n, r, i, a, o) { return ge(this, e, t, n, r, i, a, o) } function ge(e, n, r, i, a, o, s, l) { if (i === !0 ? (a = i, i = void 0) : i = "object" != typeof i ? void 0 : d({}, i), e && n) { n = n.jquery ? n : t(n), wn || (wn = document.body, Vn = "oninput" in wn, t(wn).on(Fn, ne).on("blur.jsv", "[contenteditable]", ne)); for (var p, c, f, u, g, v, h, _, m, b, x = pe, y = i && "replace" === i.target, w = n.length; w--;) { if (h = n[w], b = o || kn(h), "" + e === e) he(m = [], e, h, b, void 0, "expr", r, i); else { if (void 0 !== e.markup) y && (v = h.parentNode), b._.scp = !0, f = e.render(r, i, a, b, void 0, x, !0), b._.scp = void 0, v ? (s = h.previousSibling, l = h.nextSibling, t.cleanData([h], !0), v.removeChild(h), h = v) : (s = l = void 0, t(h).empty()); else { if (e !== !0 || b !== Qe) break; _ = { lnk: "top" } } if (h._df && !l) { for (u = xe(h._df, !0, ur), p = 0, c = u.length; p < c; p++)g = u[p], (g = In[g.id]) && void 0 !== g.data && g.parent.removeViews(g._.key, void 0, !0); ie(h) } m = b.link(r, h, s, l, f, _, i) } fe(m) } } return n } function ve(e, n, r, i, a, o, s, l) {
		function d(e, t, n, r, i, o, s, l, d, p, c, f, g, h) {
			var _, m, b = ""; return h ? (u = 0, e) : (v = (d || p || "").toLowerCase(), r = r || c, n = n || g, q && !n && (!e || r || v || o && !u) && (q = void 0, D = de.shift()), r = r || n, r && (r = r.toLowerCase(), u = 0, q = void 0, F && (n || g ? sr[D] || /;svg;|;math;/.test(";" + de.join(";") + ";") || (_ = "'<" + D + ".../") : sr[r] ? _ = "'</" + r : de.length && r === D || (_ = "Mismatch: '</" + r), _ && $(_ + ">' in:\n" + a)), Q = z, D = de.shift(), z = ar[D], c = c ? "</" + c + ">" : "", Q && (ae += X, X = "", z ? ae += "-" : (b = c + Qn + "@" + ae + zn + (f || ""), ae = ce.shift()))), z && !u ? (o ? X += o : t = c || g || "", v && (t += v, X && (t += " " + Nn + '="' + X + '"', X = ""))) : t = o ? t + b + i + (u ? "" : Qn + o + zn) + l + v : b || e, F && s && (u && $("{^{ within elem markup (" + u + ' ). Use data-link="..."'),
				"#" === o.charAt(0) ? de.unshift(o.slice(1)) : o.slice(1) !== (m = de.shift()) && $("Closing tag for {^{...}} under different elem: <" + m + ">")), v && (u = v, de.unshift(D), D = v.slice(1), F && de[0] && de[0] === or[D] && O("Parent of <tr> must be <tbody>"), q = sr[D], (z = ar[D]) && !Q && (ce.unshift(ae), ae = ""), Q = z, ae && z && (ae += "+")), t)
		} function p(e, t) { var r, i, a, o, s, l, d, p = []; if (e) { for ("@" === e._tkns.charAt(0) && (t = y.previousSibling, y.parentNode.removeChild(y), y = void 0), b = e.length; b--;) { if (C = e[b], a = C.ch, r = C.path) for (m = r.length - 1; i = r.charAt(m--);)"+" === i ? "-" === r.charAt(m) ? (m--, t = t.previousElementSibling) : t = t.parentNode : t = t.lastElementChild; "^" === a ? (v = dr[s = C.id]) && (d = t && (!y || y.parentNode !== t), y && !d || (v.parentElem = t), C.elCnt && d && ie(t, (C.open ? "#" : "/") + s + a + (t._df || "")), p.push([d ? null : y, C])) : (w = In[s = C.id]) && (w.parentElem || (w.parentElem = t || y && y.parentNode || n, w._.onRender = pe, w._.onArrayChange = oe, se(w)), o = w.parentElem, C.open ? (w._elCnt = C.elCnt, t && !y ? ie(t, "#" + s + a + (t._df || "")) : (w._prv || ie(o, me(o._df, "#" + s + a)), w._prv = y)) : (!t || y && y.parentNode === t ? y && (w._nxt || ie(o, me(o._df, "/" + s + a)), w._nxt = y) : (ie(t, "/" + s + a + (t._df || "")), w._nxt = void 0), (l = Me(w, Ln) || ue) && l.call(w.ctx.tag, w))) } for (b = p.length; b--;)le.push(p[b]) } return !e || e.elCnt } function c(e) { var t, n, r; if (e) for (b = e.length, m = 0; m < b; m++)if (C = e[m], v = dr[C.id], !v._is && v.linkCtx && (n = v = v.linkCtx.tag, r = v.tagName === P, !v.flow || r)) { if (!S) { for (t = 1; n = n.parent;)t++; M = M || t } !S && t !== M || P && !r || V.push(v) } } function f() { var o, l, d = "", f = {}, u = jn + (te ? ",[" + Wn + "]" : ""); for (x = ir ? n.querySelectorAll(u) : t(u, n).get(), _ = x.length, r && r.innerHTML && (E = ir ? r.querySelectorAll(u) : t(u, r).get(), r = E.length ? E[E.length - 1] : r), M = 0, h = 0; h < _; h++)if (y = x[h], r && !G) G = y === r; else { if (i && y === i) { te && (d += be(y)); break } if (y.parentNode) if (te) { if (d += be(y), y._df) { for (o = h + 1; o < _ && y.contains(x[o]);)o++; f[o - 1] = y._df } f[h] && (d += f[h] || "") } else ee && (C = xe(y, void 0, vr)) && (C = C[0]) && (Y = Y ? C.id !== Y && Y : C.open && C.id), !Y && ge(xe(y)) && y.getAttribute(En) && le.push([y]) } if (te && (d += n._df || "", (l = d.indexOf("#" + te.id) + 1) && (d = d.slice(l + te.id.length)), l = d.indexOf("/" + te.id), l + 1 && (d = d.slice(0, l)), c(xe(d, void 0, _r))), void 0 === a && n.getAttribute(En) && le.push([n]), ye(r, z), ye(i, z), !te) for (z && ae + X && (y = i, ae && (i ? p(xe(ae + "+", !0), i) : p(xe(ae, !0), n)), p(xe(X, !0), n), i && (d = i.getAttribute(Nn), (_ = d.indexOf(Z) + 1) && (d = d.slice(_ + Z.length - 1)), i.setAttribute(Nn, X + d))), _ = le.length, h = 0; h < _; h++)y = le[h], k = y[1], y = y[0], k ? (v = dr[k.id]) && ((g = v.linkCtx) && (v = g.tag, v.linkCtx = g), k.open ? (y && (v.parentElem = y.parentNode, v._prv = y), v._elCnt = k.elCnt, w = v.tagCtx.view, he(fe, void 0, v._prv, w, k.id)) : (v._nxt = y, v._.unlinked && !v._toLk && (N = v.tagCtx, w = N.view, ke(v)))) : he(fe, y.getAttribute(En), y, kn(y), void 0, ee, e, s) } var u, g, v, h, _, m, b, x, y, w, C, k, E, j, A, I, T, V, S, P, N, F, M, B, L, U, R, D, q, K, H, J, z, Q, W, X, Z, G, Y, ee, te, ne = this, re = ne._.id + "_", ae = "", le = [], de = [], ce = [], fe = [], ue = Me(ne, Ln), ge = p; if (o && (o.tmpl ? A = "/" + o._.id + "_" : (ee = o.lnk, o.tag && (re = o.tag + "^", o = !0), (te = o.get) && (ge = c, V = te.tags, S = te.deep, P = te.name)), o = o === !0), n = n ? "" + n === n ? t(n)[0] : n.jquery ? n[0] : n : ne.parentElem || document.body, F = !st.noValidate && n.contentEditable !== Jn, D = n.tagName.toLowerCase(), z = !!ar[D], r = r && we(r, z), i = i && we(i, z) || null, void 0 != a) { if (H = document.createElement("div"), K = H, Z = X = "", W = "http://www.w3.org/2000/svg" === n.namespaceURI ? "svg_ns" : (R = Ct.exec(a)) && R[1] || "", z) { for (T = i; T && !(I = xe(T));)T = T.nextSibling; (J = I ? I._tkns : n._df) && (j = A || "", !o && A || (j += "#" + re), m = J.indexOf(j), m + 1 && (m += j.length, Z = X = J.slice(0, m), J = J.slice(m), I ? T.setAttribute(Nn, J) : ie(n, J))) } if (q = void 0, a = ("" + a).replace(fr, d), F && de.length && $("Mismatched '<" + D + "...>' in:\n" + a), l) return; for (rr.appendChild(H), W = An[W] || An.div, B = W[0], K.innerHTML = W[1] + a + W[2]; B--;)K = K.lastChild; for (rr.removeChild(H), L = document.createDocumentFragment(); U = K.firstChild;)L.appendChild(U); n.insertBefore(L, i) } return f(), fe
	} function he(e, t, n, r, i, a, o, s) { var l, d, p, c, f, u, g, v, h, _, m, b = []; if (i) v = dr[i], v = v.linkCtx ? v.linkCtx.tag : v, g = v.linkCtx || { type: "inline", data: r.data, elem: v._elCnt ? v.parentElem : n, view: r, ctx: r.ctx, attr: Mt, fn: v._.bnd, tag: v, _bndId: i }, v.linkCtx = g, _e(g, e), v._toLk = g._bndId; else if (t && n) { for (o = a ? o : r.data, l = r.tmpl, t = Ce(t, le(n)), m = Cn.lastIndex = 0; d = Cn.exec(t);)b.push(d), m = Cn.lastIndex; for (m < t.length && $(t); d = b.shift();) { for (h = Cn.lastIndex, p = d[1], f = d[3]; b[0] && "else" === b[0][4];)f += ft + dt + b.shift()[3], _ = !0; _ && (f += ft + dt + pt + "/" + d[4] + ct), g = { type: a || "link", data: o, elem: n, view: r, ctx: s, attr: p, _toLk: 1, _noUpd: d[2] }, c = void 0, d[6] && (c = d[10] || void 0, g.convert = d[5] || "", void 0 !== c && le(n) && (p && $(f + "- Remove target: " + p), g.convertBack = c = c.slice(1))), g.expr = p + f, u = nr[f], u || (nr[f] = u = at.tmplFn(f.replace(xt, "\\$&"), l, !0, c, _)), g.fn = u, _e(g, e), Cn.lastIndex = h } } } function _e(e, n) { function r(t, n) { n && n.refresh || re.call(e, t, n) } var i, a = e.type; if ("top" !== a && "expr" !== a || (e.view = new at.View(at.extendCtx(e.ctx, e.view.ctx), "link", e.view, e.data, e.expr, (void 0), pe)), e._ctxCb = at._gccb(i = e.view), e._hdl = r, "SELECT" === e.elem.nodeName && (e.elem._jsvLkEl || "link" === a && !e.attr && void 0 !== e.convert)) { var o, s = e.elem, l = t(s); l.on("jsv-domchange", function () { arguments[3].refresh || (s._jsvLkEl ? l.val(s._jsvLkEl.cvtArgs(s._jsvElse, 1)[s._jsvInd]) : e.tag ? l.val(e.tag.cvtArgs(0, 1)) : (o = e.fn(i.data, i, at), l.val(e.convert || e.convertBack ? at._cnvt(e.convert, i, o) : o))) }) } e.fn._lr ? (e._toLk = 1, n.push(e)) : r(!0) } function me(e, t) { var n; return e ? (n = e.indexOf(t), n + 1 ? e.slice(0, n) + e.slice(n + t.length) : e) : "" } function be(e) { return e && ("" + e === e ? e : e.tagName === Hn ? e.type.slice(3) : 1 === e.nodeType && e.getAttribute(Nn) || "") } function xe(e, t, n) { function r(e, t, n, r, a, s) { o.push({ elCnt: i, id: r, ch: a, open: t, close: n, path: s, token: e }) } var i, a, o = []; if (a = t ? e : be(e)) return i = o.elCnt = e.tagName !== Hn, i = "@" === a.charAt(0) || i, o._tkns = a, a.replace(n || mr, r), o } function ye(e, t) { e && ("jsv" === e.type ? e.parentNode.removeChild(e) : t && "" === e.getAttribute(En) && e.removeAttribute(En)) } function we(e, t) { for (var n = e; t && n && 1 !== n.nodeType;)n = n.previousSibling; return n && (1 !== n.nodeType ? (n = document.createElement(Hn), n.type = "jsv", e.parentNode.insertBefore(n, e)) : be(n) || n.getAttribute(En) || n.setAttribute(En, "")), n } function Ce(e, n) { return e = t.trim(e), e.slice(-1) !== ct ? e = pt + ":" + e + (n ? ":" : "") + ct : e } function ke(e, n, r) { function i() { a = w.linkedElems || e.linkedElems || e.linkedElem && [e.linkedElem], a && (e.linkedElems = w.linkedElems = a, e.linkedElem = a[0] = e.linkedElem || a[0]), (s = w.mainElem || e.mainElem) && (w.mainElem = e.mainElem = s), (s = w.displayElem || e.displayElem) && (w.displayElem = e.displayElem = s) } var a, o, s, l, d, p, c, f, u, g, v, h, _, m, b, x, y, w = e.tagCtx, C = e.tagCtxs, k = C && C.length, E = e.linkCtx, j = e.bindTo || {}; if (e._.unlinked) { if (p = t(E.elem), e.linkedElement || e.mainElement || e.displayElement) { if (o = e.linkedElement) for (e.linkedElem = void 0, l = o.length; l--;)if (o[l]) for (c = !e.inline && p.filter(o[l]), d = k; d--;)g = C[d], a = g.linkedElems = g.linkedElems || new Array(l), s = c[0] ? c : g.contents(!0, o[l]), s[0] && s[0].type !== Un && (a[l] = s.eq(0)); if (o = e.mainElement) for (c = !e.inline && p.filter(o), d = k; d--;)g = C[d], s = c[0] ? c : g.contents(!0, o).eq(0), s[0] && (g.mainElem = s); if (o = e.displayElement) for (c = !e.inline && p.filter(o), d = k; d--;)g = C[d], s = c[0] ? c : g.contents(!0, o).eq(0), s[0] && (g.displayElem = s); i() } e.onBind && (e.onBind(w, E, e.ctx, n, r), i()) } for (d = k; d--;) { if (g = C[d], v = g.props, e._.unlinked && g.map && e.mapProps) { for (b = e.mapProps.length, x = v.mapDepends || e.mapDepends || [], x = et(x) ? x : [x]; b--;) { var A = e.mapProps[b]; y = e._.bnd.paths[d]["_" + A], y && y.length && y.skp && (x = x.concat(y)) } x.length && g.map.observe(x, E) } (s = g.mainElem || !e.mainElement && g.linkedElems && g.linkedElems[0]) && (s[0] && v.id && !s[0].id && (s[0].id = v.id), e.setSize && ((h = !j.height && v.height || e.height) && s.height(h), (h = !j.width && v.width || e.width) && s.width(h))), (h = (s = g.displayElem || s) && (!j["class"] && v["class"] || e.className)) && (_ = s[0]._jsvCl, h !== _ && (s.hasClass(_) && s.removeClass(_), s.addClass(h), s[0]._jsvCl = h)) } if (e.onAfterLink && (e.onAfterLink(w, E, e.ctx, n, r), i()), !e.flow && !e._.chg) for (e._tgId && e._.unlinked && (e.linkedElems || e.bindTo) && Ie(dr[e._tgId], e), d = C.length; d--;) { for (v = e.cvtArgs(d, 1), l = v.length; l--;)e.setValue(v[l], l, d, n, r); if (e._.unlinked) for (w = C[d], a = w.linkedElems || !d && e.linkedElem && [e.linkedElem], m = (e.bindTo || [0]).length; m--;)if ((s = a && a[m]) && (l = s.length)) for (; l--;)f = s[l], u = f._jsvLkEl, u && u === e || (f._jsvLkEl = e, f._jsvInd = m, f._jsvElse = d, Ae(e, f), e._tgId && (f._jsvBnd = "&" + e._tgId + "+")) } e._.unlinked = void 0, e._.lt && e.refresh() } function Ee(e) { var t = e.which; t > 15 && t < 21 || t > 32 && t < 41 || t > 111 && t < 131 || 27 === t || 144 === t || setTimeout(function () { ne(e) }) } function je(e, t, n) { t !== !0 || !Vn || Sn && e[0].contentEditable === Jn ? (t = "" + t === t ? t : "keydown.jsv", e[n](t, t.indexOf("keydown") >= 0 ? Ee : ne)) : e[n]("input.jsv", ne) } function Ae(e, n) { var r, i, a = n._jsvTr || !1; e && (i = e.tagCtx.props.trigger, void 0 === i && (i = e.trigger)), void 0 === i && (i = ot.trigger), i = i && ("INPUT" === n.tagName && n.type !== $n && n.type !== Un || "textarea" === n.type || n.contentEditable === Jn) && i || !1, a !== i && (r = t(n), je(r, a, "off"), je(r, n._jsvTr = i, "on")) } function Ie(e, t, n) { var r, i, a, o, s, l, d, p, c, f, u, g, v, h, _, m = 1, b = [], x = e.linkCtx, y = x.data, w = x.fn.paths; if (e && !e.to) { for (t && (t.convertBack || (t.convertBack = n), l = t.bindTo, m = t.tagCtxs ? t.tagCtxs.length : 1); m--;) { if (v = [], g = w[m]) for (l = g._jsvto ? ["jsvto"] : l || [0], !m && t && t._.ths && (l = l.concat("this")), p = l.length; p--;) { if (i = "", u = x._ctxCb, d = l[p], d = g[+d === d ? d : "_" + d], r = d && d.length) { if (a = d[r - 1], a._cpfn) { for (o = a; a.sb && a.sb._cpfn;)i = a = a.sb; i = a.sb || i && i.path, _ = a._cpfn && !a.sb, a = i ? i.slice(1) : o.path } s = i ? [o, a] : Te(a, y, u) } else f = t.linkedCtxParam, s = [], h = t._.fromIndex, h && f && f[h[p]] && (s = [t.tagCtxs[m].ctx[f[h[p]]][0], _t]); (c = s._cxp) && c.tag && a.indexOf(".") < 0 && (s = c), s.isCpfn = _, v.unshift(s) } b.unshift(v) } e.to = b } } function Te(e, t, n) { for (var r, i, a, o, s, l, d, p; e && e !== _t && (a = n(r = e.split("^").join("."))) && (o = a.length);) { if (s = a[0]._cxp) if (d = d || s, l = a[0][0], _t in l ? (p = l, l = l._vw) : p = l.data, d.path = e = a[0][1], a = [d.data = p, e], n = at._gccb(l), e._cpfn) { for (i = e, i.data = a[0], i._cpCtx = n; e.sb && e.sb._cpfn;)r = e = e.sb; r = e.sb || r && r.path, e = r ? r.slice(1) : i.path, a = [i, e] } else s.tag && s.path === _t && (a = s); else a = o > 1 ? [a[o - 2], a[o - 1]] : [a[o - 1]]; t = a[0], e = a[1] } return a = a || [t, r], a._cxp = d, a } function Ve(e, t, n) { var r, i, a = e.tagCtx.view, o = e.tagCtxs || [e.tagCtx], s = o.length, l = !t; if (l) { if (t = e._.bnd.call(a.tmpl, (e.linkCtx || a).data, a, at), t.lt) return; e._.lt = void 0, t = et(t) ? t : [t] } if (n) o = e.tagCtxs = t, e.tagCtx = o[0], Ue(e); else for (; s--;)r = o[s], i = t[s], d(r.ctx, i.ctx), r.args = i.args, l && (r.tmpl = i.tmpl), Ze(r.props).setProperty(i.props); return at._thp(e, o[0]), o } function Se(e) { for (var t, n, r, i = [], a = e.length, o = a; o--;)i.push(e[o]); for (o = a; o--;)if (n = i[o], n.parentNode) { if (r = n._jsvBnd) for (r = r.slice(1).split("&"), n._jsvBnd = "", t = r.length; t--;)Pe(r[t], n._jsvLkEl, n); Le(be(n) + (n._df || ""), n) } } function Pe(e, n, r) { var i, a, o, s, l, d, p, c, f, u, g, v, h, _, m = dr[e]; if (n) r._jsvLkEl = void 0; else if (m && (!r || r === m.elem)) { delete dr[e]; for (i in m.bnd) (s = m.bnd[i]) && (l = m.cbId, et(s) ? t([s]).off(Yt + l).off(Gt + l) : t(s).off(Gt + l), delete m.bnd[i]); if (a = m.linkCtx) { if (o = a.tag) { if (d = o.tagCtxs) for (p = d.length; p--;)v = d[p], (c = v.map) && c.unmap(), (h = v.linkedElems) && (_ = (_ || []).concat(h)); o.onUnbind && o.onUnbind(o.tagCtx, a, o.ctx), o.onDispose && o.onDispose(), o._elCnt || (o._prv && o._prv.parentNode.removeChild(o._prv), o._nxt && o._nxt.parentNode.removeChild(o._nxt)) } for (h = _ || [t(a.elem)], p = h.length; p--;)f = h[p], (u = f && f[0] && f[0]._jsvTr) && (je(f, u, "off"), f[0]._jsvTr = void 0); g = a.view, "link" === g.type ? g.parent.removeViews(g._.key, void 0, !0) : delete g._.bnds[e] } delete en[m.cbId] } } function Ne(e) { e ? (e = e.jquery ? e : t(e), e.each(function () { for (var e; (e = kn(this, !0)) && e.parent;)e.parent.removeViews(e._.key, void 0, !0); Se(this.getElementsByTagName("*")) }), Se(e)) : (wn && (t(wn).off(Fn, ne).off("blur.jsv", "[contenteditable]", ne), wn = void 0), Qe.removeViews(), Se(document.body.getElementsByTagName("*"))) } function Fe(e) { return e.type === $n ? e[On] : e.value } function Me(e, t, n) { return n && n[t] || e.ctx[t] && e.ctxPrm(t) || We.helpers[t] } function Be(e, t, n, r, i, a) { var o, s, l, d, p, c, f, u = 0, g = e === t; if (e) { for (l = xe(e) || [], o = 0, s = l.length; o < s; o++) { if (d = l[o], c = d.id, c === r && d.ch === i) { if (!a) break; s = 0 } g || (p = "_" === d.ch ? In[c] : dr[c].linkCtx.tag, p && (d.open ? p._prv = t : d.close && (p._nxt = t))), u += c.length + 2 } u && e.setAttribute(Nn, e.getAttribute(Nn).slice(u)), f = t ? t.getAttribute(Nn) : n._df, (s = f.indexOf("/" + r + i) + 1) && (f = l._tkns.slice(0, u) + f.slice(s + (a ? -1 : r.length + 1))), f && (t ? t.setAttribute(Nn, f) : ie(n, f)) } else ie(n, me(n._df, "#" + r + i)), a || t || ie(n, me(n._df, "/" + r + i)) } function Le(e, t) { var n, r, i, a; if (a = xe(e, !0, gr)) for (n = 0, r = a.length; n < r; n++)i = a[n], "_" === i.ch ? !(i = In[i.id]) || !i.type || t && i._prv !== t && i.parentElem !== t || i.parent.removeViews(i._.key, void 0, !0) : Pe(i.id, void 0, t) } function Oe(e, t, n, r, i, a) { var o = this, s = []; return o && o._tgId && (i = o), arguments.length < 4 && (+t !== t ? (r = t, n = t = 0) : +n !== n && (r = n, n = 0)), s[t || 0] = e, te(s, n, r, i, a), o } function $e() { for (var e = this.tag.bindTo.length, t = arguments[e], n = arguments[e + 1]; e--;)this.tag.setValue(arguments[e], e, this.index, t, n) } function Ue(e) { var n, r, i, a, o, s, l, d; if (e.contents = function (e, n) { e !== !!e && (n = e, e = void 0); var r, i = t(this.nodes()); return i[0] && (n = e ? n || "*" : n, r = n ? i.filter(n) : i, i = e ? r.add(i.find(n)) : r), i }, e.nodes = function (e, t, n) { var r, i = this.contentView || this, a = i._elCnt, o = !t && a, s = []; if (!i.args) for (t = t || i._prv, n = n || i._nxt, r = o ? t === i._nxt ? i.parentElem.lastSibling : t : i.inline === !1 ? t || i.linkCtx.elem.firstChild : t && t.nextSibling; r && (!n || r !== n);)(e || a || r.tagName !== Hn) && s.push(r), r = r.nextSibling; return s }, e.childTags = function (e, t) { e !== !!e && (t = e, e = void 0); var n = this.contentView || this, r = n.link ? n : n.tagCtx.view, i = n._prv, a = n._elCnt, o = []; return n.args || r.link(void 0, n.parentElem, a ? i && i.previousSibling : i, n._nxt, void 0, { get: { tags: o, deep: e, name: t, id: n.link ? n._.id + "_" : n._tgId + "^" } }), o }, "tag" === e._is) { for (l = e, r = l.tagCtxs.length; r--;)i = l.tagCtxs[r], i.setValues = $e, i.contents = e.contents, i.childTags = e.childTags, i.nodes = e.nodes; if (a = l.boundProps = l.boundProps || [], o = l.bindFrom) for (n = o.length; n--;)s = o[n], s + "" === s && (o[s] = 1, wr(s, a) < 0 && a.push(s)); l.setValue = at._gm(l.constructor.prototype.setValue || function (e) { return e }, function (e, r, i, a, o) { r = r || 0, i = i || 0; var s, d, p, c, f, u, g = l.tagCtxs[i]; if (!g._bdArgs || !o && void 0 === e || g._bdArgs[r] !== e || o && "set" === o.change && (a.target === e || o.value === e) ? (g._bdArgs = g._bdArgs || [], g._bdArgs[r] = e, u = l.base.call(l, e, r, i, a, o), void 0 !== u && (g._bdVals = g._bdVals || [], g._bdVals[r] = u, e = u)) : g._bdVals && (e = g._bdVals[r]), void 0 !== e && (p = l.linkedCtxParam) && p[r] && g.ctxPrm(p[r], e), c = l._.toIndex[r], void 0 !== c && (f = g.linkedElems || l.linkedElem && [l.linkedElem]) && (s = f[c]) && (n = s.length)) for (; n--;)d = s[n], void 0 === e || d._jsvChg || l.linkCtx._val === e || (void 0 !== d.value ? d.type === $n ? d[On] = t.isArray(e) ? t.inArray(d.value, e) > -1 : e && "false" !== e : d.type === Un ? d[On] = d.value === e : t(d).val(e) : d[d.contentEditable === Jn ? "innerHTML" : Pn] = e), g.props.name && (d.name = d.name || g.props.name); return l }), l.updateValue = Oe, l.updateValues = function () { var e, t, n = this, r = n.bindTo ? n.bindTo.length : 1, i = arguments.length - r; return i && (e = arguments[r], i > 1 ? t = i > 1 ? arguments[r + 1] : void 0 : +e !== e && (t = e, e = 0)), te(arguments, e, t, this) }, l.setValues = function () { return $e.apply(l.tagCtx, arguments), l }, l.refresh = function () { var e, t, n = l.linkCtx, r = l.tagCtx.view; if (t = Ve(l)) return l.onUnbind && (l.onUnbind(l.tagCtx, n, l.ctx), l._.unlinked = !0), e = l.inline ? Mt : n.attr || le(l.parentElem, !0), t = ":" === l.tagName ? at._cnvt(l.convert, r, l.tagCtx) : at._tag(l, r, r.tmpl, t, !0), ce(n, n.data, n.elem), ae(t, n, e, l), ke(l), l }, l.domChange = function () { var e = this.parentElem, n = t._data(e).events, r = "jsv-domchange"; n && n[r] && t(e).triggerHandler(r, arguments) } } else d = e, d.addViews = function (e, t, n) { var r, i = this, a = t.length, o = i.views; !i._.useKey && a && (r = o.length + a, !n && r !== i.data.length || de(i, e, i.tmpl, o, t, i.ctx) === !1 || i._.srt || i.fixIndex(e + a)) }, d.removeViews = function (e, n, r, i) { function a(e) { var n, i, a, o, s, l, d = c[e]; if (d && d.link) { n = d._.id, r || (l = d.nodes()), d.removeViews(void 0, void 0, !0), d.type = void 0, o = d._prv, s = d._nxt, a = d.parentElem, r || (d._elCnt && Be(o, s, a, n, "_"), t(l).remove()), !d._elCnt && o && (o.parentNode.removeChild(o), s.parentNode.removeChild(s)), se(d); for (i in d._.bnds) Pe(i); delete In[n] } } var o, s, l, d = this, p = !d._.useKey, c = d.views; if (p && (l = c.length), void 0 === e) if (p) { for (o = l; o--;)a(o); d.views = [] } else { for (s in c) a(s); d.views = {} } else if (void 0 === n && (p ? n = 1 : (a(e), delete c[e])), p && n && (i || l - n === d.data.length)) { for (o = e + n; o-- > e;)a(o); c.splice(e, n), d._.srt || d.fixIndex(e) } }, d.moveViews = function (e, n, r) { function i(e, t) { return RegExp("^(.*)(" + (t ? "\\/" : "#") + e._.id + "_.*)$").exec(t || e._prv.getAttribute(Nn)) } function a(e, t) { var n, r = e._prv; r.setAttribute(Nn, t), t.replace(hr, function (e, t, i, a) { n = dr[a].linkCtx.tag, n.inline && (n[t ? "_prv" : "_nxt"] = r) }), t.replace(vr, function (e, t, n, i) { In[i][t ? "_prv" : "_nxt"] = r }) } var o, s, l, d = this, p = d._nxt, c = d.views, f = n < e, u = f ? n : e, g = f ? e : n, v = n, h = [], _ = c.splice(e, r); for (n > c.length && (n = c.length), c.splice.apply(c, [n, 0].concat(_)), r = _.length, l = n + r, g += r, v; v < l; v++)s = c[v], o = s.nodes(!0), h = d._elCnt ? h.concat(o) : h.concat(s._prv, o, s._nxt); if (h = t(h), l < c.length ? h.insertBefore(c[l]._prv) : p ? h.insertBefore(p) : h.appendTo(d.parentElem), d._elCnt) { var m, b = f ? u + r : g - r, x = (c[u - 1], c[u]), y = c[b], w = c[g], C = i(x), k = i(y); a(x, k[1] + C[2]), w ? (m = i(w), a(w, C[1] + m[2])) : (c[g - 1]._nxt = p, p ? (m = i(d, p.getAttribute(Nn)), p.setAttribute(Nn, C[1] + m[2])) : (m = i(d, d.parentElem._df), ie(d.parentElem, C[1] + m[2]))), a(y, m[1] + k[2]) } d.fixIndex(u) }, d.refresh = function () { var e = this, t = e.parent; return t && (de(e, e.index, e.tmpl, t.views, e.data, void 0, !0), se(e)), e }, d.fixIndex = function (e) { for (var t = this.views, n = t.length; e < n--;)t[n].index !== n && Ze(t[n]).setProperty("index", n) }, d.link = ve } function Re(e, t, n) { var r, i, a = e.options.props; if (qe(e.propsArr, n.path, n.value, n.remove), void 0 !== a.sort || void 0 !== a.start || void 0 !== a.end || void 0 !== a.step || a.filter || a.reverse) e.update(); else if ("set" === n.change) { for (r = e.tgt, i = r.length; i-- && r[i].key !== n.path;); i === -1 ? n.path && !n.remove && Ze(r).insert({ key: n.path, prop: n.value }) : n.remove ? Ze(r).remove(i) : Ze(r[i]).setProperty("prop", n.value) } } function De(e, t, n) { var r, i, a, o, s = e.src, l = n.change; if ("set" === l) "prop" === n.path ? Ze(s).setProperty(t.target.key, n.value) : (Ze(s).removeProperty(n.oldValue), Ze(s).setProperty(n.value, t.target.prop)); else if ("insert" === l || (o = "remove" === l)) for (r = n.items, i = r.length; i--;)(a = r[i].key) && (qe(e.propsArr, a, r[i].prop, o), o ? (Ze(s).removeProperty(a), delete s[a]) : Ze(s).setProperty(a, r[i].prop)) } function qe(e, t, n, r) { for (var i = e.length; i-- && e[i].key !== t;); i === -1 ? t && !r && e.push({ key: t, prop: n }) : r && e.splice(i, 1) } function Ke(e) { return xr.test(e) } var He = t === !1; if (t = t || e.jQuery, !t || !t.fn) throw "JsViews requires jQuery"; var Je, ze, Qe, We, Xe, Ze, Ge, Ye, et, tt, nt, rt, it, at, ot, st, lt, dt, pt, ct, ft, ut, gt, vt, ht = "v1.0.11", _t = "_ocp", mt = /[ \t]*(\r\n|\n|\r)/g, bt = /\\(['"\\])/g, xt = /['"\\]/g, yt = /(?:\x08|^)(onerror:)?(?:(~?)(([\w$.]+):)?([^\x08]+))\x08(,)?([^\x08]+)/gi, wt = /^if\s/, Ct = /<(\w+)[>\s]/, kt = /[\x00`><"'&=]/g, Et = /[\x00`><\"'&=]/, jt = /^on[A-Z]|^convert(Back)?$/, At = /^\#\d+_`[\s\S]*\/\d+_`$/, It = kt, Tt = /[&<>]/g, Vt = /&(amp|gt|lt);/g, St = /\[['"]?|['"]?\]/g, Pt = 0, Nt = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\0": "&#0;", "'": "&#39;", '"': "&#34;", "`": "&#96;", "=": "&#61;" }, Ft = { amp: "&", gt: ">", lt: "<" }, Mt = "html", Bt = "object", Lt = "data-jsv-tmpl", Ot = "jsvTmpl", $t = "For #index in nested block use #getIndex().", Ut = {}, Rt = {}, Dt = e.jsrender, qt = Dt && t && !t.render, Kt = { template: { compile: A }, tag: { compile: E }, viewModel: { compile: V }, helper: {}, converter: {} }; if (We = { jsviews: ht, sub: { rPath: /^(!*?)(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g, rPrm: /(\()(?=\s*\()|(?:([([])\s*)?(?:(\^?)(~?[\w$.^]+)?\s*((\+\+|--)|\+|-|~(?![\w$])|&&|\|\||===|!==|==|!=|<=|>=|[<>%*:?\/]|(=))\s*|(!*?(@)?[#~]?[\w$.^]+)([([])?)|(,\s*)|(?:(\()\s*)?\\?(?:(')|("))|(?:\s*(([)\]])(?=[.^]|\s*$|[^([])|[)\]])([([]?))|(\s+)/g, View: C, Err: l, tmplFn: U, parse: K, extend: d, extendCtx: J, syntaxErr: $, onStore: { template: function (e, t) { null === t ? delete Rt[e] : e && (Rt[e] = t) } }, addSetting: N, settings: { allowCode: !1 }, advSet: o, _thp: i, _gm: r, _tg: function () { }, _cnvt: _, _tag: w, _er: O, _err: L, _cp: a, _sq: function (e) { return "constructor" === e && $(""), e } }, settings: { delimiters: p, advanced: function (e) { return e ? (d(st, e), at.advSet(), lt) : st } }, map: F }, (l.prototype = new Error).constructor = l, f.depends = function () { return [this.get("item"), "index"] }, u.depends = "index", C.prototype = { get: c, getIndex: u, ctxPrm: v, getRsc: y, _getTmpl: h, _getOb: g, getCache: function (e) { return ot._cchCt > this.cache._ct && (this.cache = { _ct: ot._cchCt }), void 0 !== this.cache[e] ? this.cache[e] : this.cache[e] = Ut[e](this.data, this, at) }, _is: "view" }, at = We.sub, lt = We.settings, !t.link) { for (Je in Kt) P(Je, Kt[Je]); if (nt = We.converters, rt = We.helpers, it = We.tags, at._tg.prototype = { baseApply: j, cvtArgs: m, bndArgs: x, ctxPrm: v }, Qe = at.topView = new C, t) { if (t.fn.render = W, Ge = t.expando, t.observable) { if (ht !== (ht = t.views.jsviews)) throw "jquery.observable.js requires jsrender.js " + ht; d(at, t.views.sub), We.map = t.views.map } } else t = {}, He && (e.jsrender = t), t.renderFile = t.__express = t.compile = function () { throw "Node.js: use npm jsrender, or jsrender-node.js" }, t.isFunction = function (e) { return "function" == typeof e }, t.isArray = Array.isArray || function (e) { return "[object Array]" === {}.toString.call(e) }, at._jq = function (e) { e !== t && (d(e, t), t = e, t.fn.render = W, delete t.jsrender, Ge = t.expando) }, t.jsrender = ht; ot = at.settings, ot.allowCode = !1, Ye = t.isFunction, t.render = Rt, t.views = We, t.templates = tt = We.templates; for (gt in ot) N(gt); (lt.debugMode = function (e) { return void 0 === e ? ot.debugMode : (ot._clFns && ot._clFns(), ot.debugMode = e, ot.onError = e + "" === e ? function () { return e } : Ye(e) ? e : void 0, lt) })(!1), st = ot.advanced = { cache: !0, useViews: !1, _jsv: !1 }, it({ "if": { render: function (e) { var t = this, n = t.tagCtx, r = t.rendering.done || !e && (n.args.length || !n.index) ? "" : (t.rendering.done = !0, void (t.selected = n.index)); return r }, contentCtx: !0, flow: !0 }, "for": { sortDataMap: F(Q), init: function (e, t) { this.setDataMap(this.tagCtxs) }, render: function (e) { var t, n, r, i, a, o = this, s = o.tagCtx, l = s.argDefault === !1, d = s.props, p = l || s.args.length, c = "", f = 0; if (!o.rendering.done) { if (t = p ? e : s.view.data, l) for (l = d.reverse ? "unshift" : "push", i = +d.end, a = +d.step || 1, t = [], r = +d.start || 0; (i - r) * a > 0; r += a)t[l](r); void 0 !== t && (n = et(t), c += s.render(t, !p || d.noIteration), f += n ? t.length : 1), (o.rendering.done = f) && (o.selected = s.index) } return c }, setDataMap: function (e) { for (var t, n, r, i = this, a = e.length; a--;)t = e[a], n = t.props, r = t.params.props, t.argDefault = void 0 === n.end || t.args.length > 0, n.dataMap = t.argDefault !== !1 && et(t.args[0]) && (r.sort || r.start || r.end || r.step || r.filter || r.reverse || n.sort || n.start || n.end || n.step || n.filter || n.reverse) && i.sortDataMap }, flow: !0 }, props: { baseTag: "for", dataMap: F(z), init: o, flow: !0 }, include: { flow: !0 }, "*": { render: a, flow: !0 }, ":*": { render: a, flow: !0 }, dbg: rt.dbg = nt.dbg = s }), nt({ html: G, attr: G, encode: Y, unencode: ee, url: function (e) { return void 0 != e ? encodeURI("" + e) : null === e ? e : "" } }) } if (ot = at.settings, et = (t || Dt).isArray, lt.delimiters("{{", "}}", "^"), qt && Dt.views.sub._jq(t), We = t.views, at = We.sub, Ye = t.isFunction, et = t.isArray, Ge = t.expando, !t.observe) {
		var Ht = t.event.special, Jt = [].slice, zt = [].splice, Qt = [].concat, Wt = parseInt, Xt = /\S+/g, Zt = /^[^.[]*$/, Gt = at.propChng = at.propChng || "propertyChange", Yt = at.arrChng = at.arrChng || "arrayChange", en = {}, tn = Gt + ".observe", nn = 1, rn = 1, an = 1, on = t.data, sn = {}, ln = [], dn = function (e) { return e ? e._cId = e._cId || ".obs" + rn++ : "" }, pn = function (e, t) { return this._data = t, this._ns = e, this }, cn = function (e, t) { return this._data = t, this._ns = e, this }, fn = function (e) { return et(e) ? [e] : e }, un = function (e, t, n) { e = e ? et(e) ? e : [e] : []; var r, i, a, o, s = a = t, l = e && e.length, d = []; for (r = 0; r < l; r++)i = e[r], Ye(i) ? (o = t.tagName ? t.linkCtx.data : t, d = d.concat(un(i.call(t, o, n), o, n))) : "" + i === i ? (s !== a && d.push(a = s), d.push(i)) : (t = s = i = void 0 === i ? null : i, s !== a && d.push(a = s)); return d.length && (d.unshift({ _ar: 1 }), d.push({ _ar: -1 })), d }, gn = function (e, t) { function n(e) { return typeof e === Bt && (f[0] || !c && et(e)) } if (!e.data || !e.data.off) { var r, i, a, o = t.oldValue, s = t.value, l = e.data, d = l.observeAll, p = l.cb, c = l._arOk ? 0 : 1, f = l.paths, u = l.ns; e.type === Yt ? (p.array || p).call(l, e, t) : l.prop !== t.path && "*" !== l.prop || (d ? (r = d._path + "." + t.path, i = d.filter, a = [e.target].concat(d.parents()), n(o) && vn(void 0, u, [o], f, p, !0, i, [a], r), n(s) && vn(void 0, u, [s], f, p, void 0, i, [a], r)) : (n(o) && vn(c, u, [o], f, p, !0), n(s) && vn(c, u, [s], f, p)), l.cb(e, t)) } }, vn = function () { var e = Qt.apply([], arguments); return Xe.apply(e.shift(), e) }, hn = function (e, t, n) { mn(this._ns, this._data, e, t, [], "root", n) }, _n = function (e, t) { hn.call(this, e, t, !0) }, mn = function (e, n, r, i, a, o, s, l) { function d(e, t) { for (f = e.length, g = o + "[]"; f--;)p(e, f, t, 1) } function p(t, n, a, o) { var s, d; +n !== n && n === Ge || !(s = Ze._fltr(g, t[n], v, i)) || (d = v.slice(), o && h && d[0] !== h && d.unshift(h), mn(e, s, r, i || (o ? void 0 : 0), d, g, a, l)) } function c(e, t) { switch (o = e.data.observeAll._path, h = e.target, t.change) { case "insert": d(t.items); break; case "remove": d(t.items, !0); break; case "set": g = o + "." + t.path, p(t, "oldValue", !0), p(t, "value") }h = void 0, r.apply(this, arguments) } c._wrp = 1; var f, u, g, v, h, _, m = !l || l.un || !s; if (n && typeof n === Bt) { if (v = [n].concat(a), u = et(n) ? "" : "*", l && m && t.hasData(n) && l[_ = on(n).obId]) return void l[_]++; if (l || (l = { un: s }), r) { if (u || 0 !== i) if (c._cId = dn(r), m) Xe(e, n, u, c, s, i, v, o), _ = on(n).obId, l[_] = (l[_] || 0) + 1; else { if (--l[on(n).obId]) return; Xe(e, n, u, c, s, i, v, o) } } else l && (l[on(n).obId] = 1), Xe(e, n, u, void 0, s, i, v, o); if (u) for (f in n) g = o + "." + f, p(n, f, s); else d(n, s) } }, bn = function (e) { return Zt.test(e) }, xn = function () { return [].push.call(arguments, !0), Xe.apply(void 0, arguments) }, yn = function (e) { var t, n = this.slice(); for (this.length = 0, this._go = 0; t = n.shift();)t.skip || t[0]._trigger(t[1], t[2], !0); this.paths = {} }; Xe = function () { function e() { function i(e, t) { var n; for (g in t) n = t[g], et(n) ? o(e, n, p, p) : a(e, n, void 0, I, "") } function a(e, i, a, o, s, l, d) { var c, f, u, v = fn(i), h = b, m = x; if (o = n ? o + "." + n : o, !p && (d || l)) for (j = t._data(i).events, j = j && j[l ? Yt : Gt], A = j && j.length; A--;)if (g = j[A] && j[A].data, g && (d && g.ns !== n || !d && g.ns === n && g.cb && g.cb._cId === e._cId && (!e._wrp || g.cb._wrp))) return; p || d ? t(v).off(o, gn) : (f = l ? {} : { fullPath: a, paths: s ? [s] : [], prop: E, _arOk: r }, f.ns = n, f.cb = e, x && (f.observeAll = { _path: m, path: function () { return c = h.length, m.replace(/[[.]/g, function (e) { return c--, "[" === e ? "[" + t.inArray(h[c - 1], h[c]) : "." }) }, parents: function () { return h }, filter: y }), t(v).on(o, null, f, gn), _ && (u = on(i), u = u.obId || (u.obId = nn++), _[u] = _[u] || (_.len++, i))) } function o(e, t, n, i, o) { if (r) { var s, l = x; s = t, o && (s = t[o], x = x ? x + "." + o : x), y && s && (s = Ze._fltr(x, s, o ? [t].concat(b) : b, y)), s && (i || et(s)) && a(e, s, void 0, Yt + ".observe" + dn(e), void 0, !0, n), x = l } } function s(i) { function l(i, c, f, u) { function v(t) { return t.ob = u(t), t.cb = function (n, i) { var a = t.ob, s = t.sb, l = u(t); l !== a && (typeof a === Bt && (o(f, a, !0), (s || r && et(a)) && e([a], s, f, u, !0)), t.ob = l, typeof l === Bt && (o(f, l), (s || r && et(l)) && e([l], s, f, u))), f(n, i) } } function _(e, i) { function d(e, t) { var n; if ("insert" === t.change || (p = "remove" === t.change)) { for (n = t.items.length; n--;)_(t.items[n], i.slice()); p = !1 } } f && (d._cId = dn(f)); var c, v, h, m, b, C, k, T = e; if (e && e._cxp) return l(e[0], [e[1]], f, u); for (; void 0 !== (E = i.shift());) { if (T && typeof T === Bt && "" + E === E) { if ("" === E) continue; if ("()" === E.slice(-2) && (E = E.slice(0, -2), k = !0), i.length < w + 1 && !T.nodeType) { if (!p && (j = t._data(T).events)) { for (j = j && j[Gt], A = j && j.length, v = 0; A--;)g = j[A].data, !g || g.ns !== n || g.cb._cId !== f._cId || g.cb._inId !== f._inId || !g._arOk != !r || g.prop !== E && "*" !== g.prop && "**" !== g.prop || ((b = i.join(".")) && g.paths.push(b), v++); if (v) { T = T[E]; continue } } if ("*" === E || "**" === E) { if (!p && j && j.length && a(f, T, y, I, "", !1, !0), "*" === E) { a(f, T, y, I, ""); for (b in T) b !== Ge && o(f, T, p, void 0, b) } else t.observable(n, T)[(p ? "un" : "") + "observeAll"](f); break } "[]" == E ? et(T) && (p ? a(f, T, y, Yt + dn(f), void 0, p, p) : Xe(n, T, d, p)) : E && a(f, T, y, I + ".p_" + E, i.join("^")) } if (x && (x += "." + E), "[]" === E) { for (et(T) && (m = T, c = T.length); c--;)T = m[c], _(T, i.slice()); return } E = T[E], i[0] || o(f, E, p) } if (Ye(E) && (C = E, (h = C.depends) && (T._vw && T._ocp && (T = T._vw, T._tgId && (T = T.tagCtx.view), T = T.data), s(Qt.apply([], [[T], un(h, T, f)]))), k)) { if (!i[0]) { o(f, C.call(T), p); break } if (E = C.call(T), !E) break } T = E } } var b, y, w = 0, C = c.length; for (!i || u || !(k = "view" === i._is) && "tag" !== i._is || (u = at._gccb(k ? i : i.tagCtx.contentView), f && !p && !function () { var e = i, t = f; f = function (n, r) { t.call(e, n, r) }, f._cId = t._cId, f._inId = t._inId }(), i = k ? i.data : i), c[0] || (et(i) ? o(f, i, p, !0) : p && a(f, i, void 0, I, "")), b = 0; b < C; b++)if (y = c[b], "" !== y) if (y && y._ar) r += y._ar; else if ("" + y === y) if (d = y.split("^"), d[1] && (w = d[0].split(".").length, y = d.join("."), w = y.split(".").length - w), u && (h = u(y, w))) { if (h.length) { var T = h[0], V = h[1]; if (T && T._cxp && (V = T[1], T = T[0], "view" === T._is)) { l(T, [V], f); continue } V + "" === V ? _(T, V.split(".")) : l(h.shift(), h, f, u) } } else _(i, y.split(".")); else !Ye(y) && y && y._cpfn && (m = p ? y.cb : v(y), m._cId = f._cId, m._inId = m._inId || ".obIn" + an++, (y.bnd || y.prm && y.prm.length || !y.sb) && e([i], y.path, y.prm.length ? [y.root || i] : [], y.prm, m, u, p), y.sb && (y.sb.prm && (y.sb.root = i), l(y.ob, [y.sb], f, u))) } for (var f, u = [], _ = i.length; _--;)f = i[_], f + "" === f || f && (f._ar || f._cpfn) ? u.unshift(f) : (l(f, u, c, v), u = []) } var l, d, p, c, f, u, g, v, h, _, m, b, x, y, w, C, k, E, j, A, I = tn, T = 1 != this ? Qt.apply([], arguments) : Jt.call(arguments), V = T.pop() || !1, S = T.length; if (V + "" === V && (x = V, b = T.pop(), y = T.pop(), V = !!T.pop(), S -= 3), V === !!V && (p = V, V = T[S - 1], V = !S || V + "" === V || V && !Ye(V) ? void 0 : (S--, T.pop()), p && !S && Ye(T[0]) && (V = T.shift())), c = V, S && Ye(T[S - 1]) && (v = c, V = c = T.pop(), S--), !p || !c || c._cId) { for (I += c ? (u = c._inId || "", p ? c._cId + u : (f = dn(c)) + u) : "", f && !p && (_ = en[f] = en[f] || { len: 0 }), w = n && n.match(Xt) || [""], C = w.length; C--;) { if (n = w[C], p && arguments.length < 3) if (c) i(c, en[c._cId]); else if (!T[0]) for (l in en) i(c, en[l]); s(T) } return f && !_.len && delete en[f], { cbId: f, bnd: _ } } } var n, r = 1 == this ? 0 : 1, i = Jt.call(arguments), a = i[0]; return a + "" === a && (n = a, i.shift()), e.apply(1, i) }, ln.wait = function () { var e = this; e._go = 1, setTimeout(function () { e.trigger(!0), e._go = 0, e.paths = {} }) }, Ze = function (e, t, n) { e + "" !== e && (n = t, t = e, e = ""), n = void 0 === n ? st.asyncObserve : n; var r = et(t) ? new cn(e, t) : new pn(e, t); return n && (n === !0 && (r.async = !0, n = ln), n.trigger || (et(n) ? (n.trigger = yn, n.paths = {}) : n = void 0), r._batch = n), r }, t.observable = Ze, Ze._fltr = function (e, t, n, r) { if (!r || !Ye(r) || r(e, t, n)) return t = Ye(t) ? t.set && t.call(n[0]) : t, typeof t === Bt && t }, Ze.Object = pn, Ze.Array = cn, t.observe = Ze.observe = Xe, t.unobserve = Ze.unobserve = xn, Ze._apply = vn, pn.prototype = { _data: null, observeAll: hn, unobserveAll: _n, data: function () { return this._data }, setProperty: function (e, t, n, r) { e = e || ""; var i, a, o, s, l = e + "" !== e, d = this, p = d._data, c = d._batch; if (p) if (l) if (n = t, et(e)) for (i = e.length; i--;)a = e[i], d.setProperty(a.name, a.value, void 0 === n || n); else { c || (d._batch = s = [], s.trigger = yn, s.paths = {}); for (i in e) d.setProperty(i, e[i], n); s && (d._batch.trigger(), d._batch = void 0) } else if (e !== Ge) { for (o = e.split(/[.^]/); p && o.length > 1;)p = p[o.shift()]; p && d._setProperty(p, o[0], t, n, r) } return d }, removeProperty: function (e) { return this.setProperty(e, sn), this }, _setProperty: function (e, t, n, r, i) { var a, o, s, l, d, p = t ? e[t] : e; if (Ye(p) && !Ye(n)) { if (i && !p.set) return; p.set && (d = e._vw || e, o = p, a = o.set === !0 ? o : o.set, p = o.call(d)) } (p !== n || r && p != n) && (!(p instanceof Date && n instanceof Date) || p > n || p < n) && (a ? (a.call(d, n), n = o.call(d)) : (s = n === sn) ? void 0 !== p ? (delete e[t], n = void 0) : t = void 0 : t && (e[t] = n), t && (l = { change: "set", path: t, value: n, oldValue: p, remove: s }, e._ocp && (l.ctxPrm = e._key), this._trigger(e, l))) }, _trigger: function (e, n, r) { ot._cchCt++; var i, a, o, s = this; t.hasData(e) && (!r && (a = s._batch) ? (s.async && !a._go && a.wait(), a.push([s, e, n]), i = on(e).obId + n.path, (o = a.paths[i]) && (a[o - 1].skip = 1), a.paths[i] = a.length) : (t(e).triggerHandler(Gt + (this._ns ? "." + /^\S+/.exec(this._ns)[0] : ""), n), n.oldValue = null)) } }, cn.prototype = {
			_data: null, observeAll: hn, unobserveAll: _n, data: function () { return this._data }, insert: function (e, t) { var n = this._data; return 1 === arguments.length && (t = e, e = n.length), e = Wt(e), e > -1 && (t = et(t) ? t : [t], t.length && this._insert(e, t)), this }, _insert: function (e, t) { var n = this._data, r = n.length; e > r && (e = r), zt.apply(n, [e, 0].concat(t)), this._trigger({ change: "insert", index: e, items: t }, r) }, remove: function (e, t) { var n, r = this._data; return void 0 === e && (e = r.length - 1), e = Wt(e), t = t ? Wt(t) : 0 === t ? 0 : 1, t > 0 && e > -1 && (n = r.slice(e, e + t), (t = n.length) && this._remove(e, t, n)), this }, _remove: function (e, t, n) { var r = this._data, i = r.length; r.splice(e, t), this._trigger({ change: "remove", index: e, items: n }, i) }, move: function (e, t, n) { return n = n ? Wt(n) : 0 === n ? 0 : 1, e = Wt(e), t = Wt(t), n > 0 && e > -1 && t > -1 && e !== t && this._move(e, t, n), this }, _move: function (e, t, n) { var r, i = this._data, a = i.length, o = e + n - a; o > 0 && (n -= o), n && (r = i.splice(e, n), t > i.length && (t = i.length), zt.apply(i, [t, 0].concat(r)), t !== e && this._trigger({ change: "move", oldIndex: e, index: t, items: r }, a)) }, refresh: function (e) { function t() { i && (s.insert(r - i, l), f += i, n += i, i = 0, l = []) } var n, r, i, a, o, s = this, l = [], d = s._data, p = d.slice(), c = d.length, f = c, u = e.length; for (s._srt = !0, r = i = 0; r < u; r++)if ((a = e[r]) === d[r - i]) t(); else { for (n = r - i; n < f && a !== d[n]; n++); if (n < f) { for (t(), o = 0; o++ < u - n && e[r + o] === d[n + o];); s.move(n, r, o), r += o - 1 } else i++, l.push(a) } return t(), f > r && s.remove(r, f - r), s._srt = void 0, (c || u) && s._trigger({ change: "refresh", oldItems: p }, c), s }, _trigger: function (e, n, r) {
				ot._cchCt++; var i, a, o, s = this;
				t.hasData(a = s._data) && (!r && (o = s._batch) ? (e._dly = !0, o.push([s, e, n]), s.async && !o._go && o.wait()) : (i = a.length, a = t([a]), s._srt ? e.refresh = !0 : i !== n && a.triggerHandler(Gt, { change: "set", path: "length", value: i, oldValue: n }), a.triggerHandler(Yt + (s._ns ? "." + /^\S+/.exec(s._ns)[0] : ""), e)))
			}
		}, Ht[Gt] = Ht[Yt] = { remove: function (e) { var n, r, i, a, o, s = e.data; if (s && (s.off = !0, s = s.cb) && (n = en[s._cId])) { for (i = t._data(this).events[e.type], a = i.length; a-- && !r;)r = (o = i[a].data) && o.cb && o.cb._cId === s._cId; r || (--n.len ? delete n[on(this).obId] : delete en[s._cId]) } } }, We.map = function (e) { function n(t, n, r, i) { var a, o, s = this; s.src && s.unmap(), n && (n.map = s), (typeof t === Bt || Ye(t)) && (s.src = t, i ? s.tgt = e.getTgt(t, n) : (r && (s.tgt = r.tgt || et(r) && r), s.tgt = s.tgt || [], s.options = n || s.options, (o = s.update()) ? s = o : (e.obsSrc && Ze(s.src).observeAll(s.obs = function (t, n) { a || n.refresh || (a = !0, e.obsSrc(s, t, n), a = void 0) }, s.srcFlt), e.obsTgt && Ze(s.tgt).observeAll(s.obt = function (t, n) { a || s.tgt._updt || (a = !0, e.obsTgt(s, t, n), a = void 0) }, s.tgtFlt)))) } return Ye(e) && (e = { getTgt: e }), e.baseMap && (e = t.extend({}, e.baseMap, e)), e.map = function (e, t, r, i) { return new n(e, t, r, i) }, (n.prototype = { srcFlt: e.srcFlt || bn, tgtFlt: e.tgtFlt || bn, update: function (t) { var n, r, i = this, a = i.tgt; if (!a._updt && (a._updt = !0, n = i.options && i.options.map, Ze(a).refresh(e.getTgt(i.src, i.options = t || i.options)), a._updt = !1, r = i.options && i.options.map, r && n !== r)) return r }, observe: function (e, n) { var r = this, i = r.options; r.obmp && xn(r.obmp), r.obmp = function () { var e = n.fn(n.data, n.view, at)[i.index]; t.extend(i.props, e.props), i.args = e.args, r.update() }, Ze._apply(1, n.data, un(e, n.tag, r.obmp), r.obmp, n._ctxCb) }, unmap: function () { var e = this; e.src && e.obs && Ze(e.src).unobserveAll(e.obs, e.srcFlt), e.tgt && e.obt && Ze(e.tgt).unobserveAll(e.obt, e.tgtFlt), e.obmp && xn(e.obmp), e.src = void 0 }, map: n, _def: e }).constructor = n, e }, at.advSet = function () { at = this, st = ot.advanced, e._jsv = st._jsv ? { cbBindings: en } : void 0 }, at._dp = un, at._gck = dn, at._obs = Xe, ot._cchCt = 0, st = ot.advanced = st || { useViews: !1, _jsv: !1 }
	} if (lt = We.settings, ot = at.settings, st = ot.advanced, nt = We.converters, t.templates = tt = We.templates, it = We.tags, Ct = /<(?!script)(\w+)[>\s]/, t.link) return t; ot.trigger = !0; var wn, Cn, kn, En, jn, An, In, Tn, Vn, Sn = window.navigator.userAgent, Pn = void 0 !== document.textContent ? "textContent" : "innerText", Nn = "data-jsv", Fn = "change.jsv", Mn = "onBeforeChange", Bn = "onAfterChange", Ln = "onAfterCreate", On = "checked", $n = "checkbox", Un = "radio", Rn = "input[type=", Dn = Rn + $n + "]", qn = "none", Kn = "value", Hn = "SCRIPT", Jn = "true", zn = '"></script>', Qn = '<script type="jsv', Wn = Nn + "-df", Xn = "script,[" + Nn + "]", Zn = { value: "val", input: "val", html: Mt, text: "text" }, Gn = { from: Kn, to: Kn }, Yn = 0, er = t.cleanData, tr = lt.delimiters, nr = {}, rr = document.createDocumentFragment(), ir = document.querySelector, ar = { ol: 1, ul: 1, table: 1, tbody: 1, thead: 1, tfoot: 1, tr: 1, colgroup: 1, dl: 1, select: 1, optgroup: 1, svg: 1, svg_ns: 1 }, or = { tr: "table" }, sr = { br: 1, img: 1, input: 1, hr: 1, area: 1, base: 1, col: 1, link: 1, meta: 1, command: 1, embed: 1, keygen: 1, param: 1, source: 1, track: 1, wbr: 1 }, lr = {}, dr = {}, pr = 1, cr = /^#(view\.?)?/, fr = /((\/>)|<\/(\w+)>|)(\s*)([#\/]\d+(?:_|(\^)))`(\s*)(<\w+(?=[\s\/>]))?|\s*(?:(<\w+(?=[\s\/>]))|<\/(\w+)>(\s*)|(\/>)\s*|(>)|$)/g, ur = /(#)()(\d+)(_)/g, gr = /(#)()(\d+)([_^])/g, vr = /(?:(#)|(\/))(\d+)(_)/g, hr = /(?:(#)|(\/))(\d+)(\^)/g, _r = /(#)()(\d+)(\^)/g, mr = /(?:(#)|(\/))(\d+)([_^])([-+@\d]+)?/g, br = /&(\d+)\+?/g, xr = /^[^.]*$/, yr = e.getComputedStyle, wr = t.inArray; if (Rn += Un + "]", Sn = Sn.indexOf("MSIE ") > 0 || Sn.indexOf("Trident/") > 0, Ze = t.observable, !Ze) throw requiresStr + "jquery.observable.js"; return Xe = Ze.observe, ot._clFns = function () { nr = {} }, Ue(at.View.prototype), at.onStore.template = function (e, n, r) { null === n ? (delete t.link[e], delete t.render[e]) : (n.link = ue, e && !r && "jsvTmpl" !== e && (t.render[e] = n, t.link[e] = function () { return ue.apply(n, arguments) })) }, at.viewInfos = xe, (lt.delimiters = function () { var e = tr.apply(0, arguments); return tr !== p && (e = p.apply(0, arguments)), Cn = new RegExp("(?:^|\\s*)([\\w-]*)(\\" + ut + ")?(\\" + pt + at.rTag + "(:\\w*)?\\" + ct + ")", "g"), e })(), at.addSetting("trigger"), nt.merge = function (e) { var t, n = this.linkCtx.elem.className, r = this.tagCtx.props.toggle; return r && (t = r.replace(/[\\^$.|?*+()[{]/g, "\\$&"), t = "(\\s(?=" + t + "$)|(\\s)|^)(" + t + "(\\s|$))", n = n.replace(new RegExp(t), "$2"), e = n + (e ? (n && " ") + r : "")), e }, it({ on: { attr: qn, bindTo: [], init: function (e) { for (var n, r = this, i = 0, a = e.args, o = a.length; i < o && !Ye(a[i]); i++); r._hi = o > i && i + 1, r.inline && (at.rTmpl.exec(n = t.trim(e.tmpl.markup)) || (r.template = "<button>" + (n || e.params.args[i] || "noop") + "</button>"), r.attr = Mt) }, onBind: function () { this.template && (this.mainElem = this.contents("button")) }, onAfterLink: function (e, n) { var r, i, a, o = this, s = o._hi, l = e.args, d = l.length, p = e.props, c = p.data, f = e.view, u = p.context; s && (r = l[s - 1], i = l.slice(s), l = l.slice(0, s - 1), o._sel = l[1], a = o.activeElem = o.activeElem || t(o.inline ? (o._sel = l[1] || "*", o.parentElem) : n.elem), u || (u = /^(.*)[.^][\w$]+$/.exec(e.params.args.slice(-i.length - 1)[0]), u = u && at.tmplFn(pt + ":" + u[1] + ct, f.tmpl, !0)(n.data, f, at)), o._evs && o.onUnbind(e, n, o.ctx), a.on(o._evs = l[0] || "click", o._sel, void 0 == c ? null : c, o._hlr = function (e) { var t, a = !o.inline; if (!a) for (t = o.contents("*"), d = t.length; !a && d--;)t[d].contains(e.target) && (a = !0); if (a) return r.apply(u || n.data, [].concat(i, e, { change: e.type, view: f, linkCtx: n }, i.slice.call(arguments, 1))) })) }, onUpdate: !1, onArrayChange: !1, onUnbind: function () { var e = this, t = Yn; e.activeElem && (Yn = 0, e.activeElem.off(e._evs, e._sel, e._hlr), Yn = t) }, contentCtx: !0, setSize: !0, dataBoundOnly: !0 }, radiogroup: { boundProps: ["disabled"], init: function (e) { this.name = e.props.name || (Math.random() + "jsv").slice(9) }, onBind: function (e, n) { var r, i, a, o = this, s = e.params.props; for (s = s && s.disabled, o.inline ? (r = o.contents("*")[0], r = r && kn(r).ctx.tag === o.parent ? r : o.parentElem, i = o.contents(!0, Rn)) : (r = n.elem, i = t(Rn, n.elem)), o.linkedElem = i, a = i.length; a--;)i[a].name = i[a].name || o.name; t(r).on("jsv-domchange", o._dmChg = function (t, n, l, d) { var p, c, f = n.ctx.parentTags; if (!d.refresh && (!o.inline || r !== o.parentElem || f && f[o.tagName] === o)) { for (c = o.cvtArgs()[0], i = o.linkedElem = o.contents(!0, Rn), a = i.length; a--;)p = i[a], p._jsvLkEl = o, p.name = p.name || o.name, p._jsvBnd = "&" + o._tgId + "+", p.checked = c === p.value, s && (p.disabled = !!e.props.disabled); o.linkedElems = e.linkedElems = [i] } }), o._dmChg.tgt = r }, onAfterLink: function (e, t, n, r, i) { var a = e.params.props; a && a.disabled && this.linkedElem.prop("disabled", !!e.props.disabled) }, onUnbind: function () { var e = this; e._dmChg && (t(e._dmChg.tgt).off("jsv-domchange", e._dmChg), e._dmChg = void 0) }, onUpdate: !1, contentCtx: !0, dataBoundOnly: !0 }, checkboxgroup: { boundProps: ["disabled"], init: function (e) { this.name = e.props.name || (Math.random() + "jsv").slice(9) }, onBind: function (e, n) { for (var r, i = this, a = e.params.props, o = a && a.disabled, s = e.params.args[0], l = i.contents(!0, Dn), d = l.length; d--;)l[d].name = l[d].name || i.name, l[d]._jsvLkEl = i; for (d in a) s += " " + d + "=" + a[d]; l.link(s, n.data, void 0, void 0, n.view), i.linkedElem = l, i.inline ? (r = i.contents("*")[0], r = r && t.view(r).ctx.tag === i.parent ? r : i.parentElem) : r = n.elem, t(r).on("jsv-domchange", i._dmChg = function (n, a, p, c) { var f, u = a.ctx.parentTags; if (!c.refresh && (!i.inline || r !== i.parentElem || u && u[i.tagName] === i)) for (l = i.contents(!0, Dn), d = l.length; d--;)f = l[d], f._jsvSel || (f.name = f.name || i.name, t.link(s, f, p.data), o && (f.disabled = !!e.props.disabled)) }), i._dmChg.tgt = r }, onAfterLink: function (e, t, n, r, i) { var a = e.params.props; a && a.disabled && this.contents(!0, Dn).prop("disabled", !!e.props.disabled) }, onUnbind: function () { var e = this; e._dmChg && (t(e._dmChg.tgt).off("jsv-domchange", e._dmChg), e._dmChg = void 0) }, onUpdate: !1, contentCtx: !0, dataBoundOnly: !0 } }), d(it["for"], { sortDataMap: We.map({ getTgt: it["for"].sortDataMap.getTgt, obsSrc: function (e, t, n) { e.update() }, obsTgt: function (e, t, n) { var r, i = n.items, a = e.src; if ("remove" === n.change) for (r = i.length; r--;)Ze(a).remove(wr(i[r], a)); else "insert" === n.change && Ze(a).insert(i) } }), mapProps: ["filter", "sort", "reverse", "start", "end", "step"], bindTo: ["paged", "sorted"], bindFrom: [0], onArrayChange: function (e, t, n, r) { var i, a, o = e.target.length, s = this; if (!s.rendering) if (s._.noVws || s.tagCtxs[1] && ("insert" === t.change && o === t.items.length || "remove" === t.change && !o)) a = n.map && n.map.propsArr, s.refresh(), a && (n.map.propsArr = a); else for (i in s._.arrVws) i = s._.arrVws[i], i.data === e.target && oe.apply(i, arguments); s.domChange(n, r, t), e.done = !0 }, onUpdate: function (e, t, n) { this.setDataMap(n) }, onBind: function (e, t, n, r, i) { for (var a, o = this, s = 0, l = o._ars = o._ars || {}, d = o.tagCtxs, p = d.length, c = o.selected || 0; s <= c; s++)e = d[s], a = e.map ? e.map.tgt : e.args.length ? e.args[0] : e.view.data, l[s] && (Xe(l[s], !0), delete l[s]), !l[s] && et(a) && !function () { var n = e; Xe(a, l[s] = function (e, r) { o.onArrayChange(e, r, n, t) }) }(); for (s = c + 1; s < p; s++)l[s] && (Xe(l[s], !0), delete l[s]); i && o.domChange(e, t, i) }, onAfterLink: function (e) { for (var n, r, i, a = this, o = 0, s = a.tagCtxs, l = (s.length, a.selected || 0); o <= l; o++)e = s[o], r = e.map, n = e.map ? r.tgt : e.args.length ? e.args[0] : e.view.data, et(n) && (i = e.params.props) && (i.paged && !a.paged && (t.observable(a).setProperty("paged", n.slice()), a.updateValue(a.paged, 0, o, !0)), i.sorted && !a.sorted && (t.observable(a).setProperty("sorted", r && r.sorted || n.slice()), a.updateValue(a.sorted, 1, o, !0))) }, onDispose: function () { var e, t = this; for (e in t._ars) Xe(t._ars[e], !0) } }), d(it["if"], { onUpdate: function (e, t, n) { for (var r, i, a = 0; r = this.tagCtxs[a]; a++)if (i = r.props.tmpl !== n[a].props.tmpl || r.args.length && !(r = r.args[0]) != !n[a].args[0], !this.convert && r || i) return i; return !1 }, onAfterLink: function (e, t, n, r, i) { i && this.domChange(e, t, i) } }), it("props", { baseTag: "for", dataMap: We.map({ getTgt: it.props.dataMap.getTgt, obsSrc: Re, obsTgt: De, tgtFlt: Ke }), flow: !0 }), d(t, { view: kn = function (e, n, r) { function i(e, t) { if (e) for (o = xe(e, t, ur), l = 0, d = o.length; l < d && (!(a = In[o[l].id]) || !(a = a && r ? a.get(!0, r) : a)); l++); } n !== !!n && (r = n, n = void 0); var a, o, s, l, d, p, c, f = 0, u = document.body; if (e && e !== u && Qe._.useKey > 1 && (e = "" + e === e ? t(e)[0] : e.jquery ? e[0] : e)) { if (n) { if (i(e._df, !0), !a && e.tagName) for (c = ir ? e.querySelectorAll(Xn) : t(Xn, e).get(), p = c.length, s = 0; !a && s < p; s++)i(c[s]); return a } for (; e;) { if (o = xe(e, void 0, vr)) for (p = o.length; p--;)if (a = o[p], a.open) { if (f < 1) return a = In[a.id], a && r ? a.get(r) : a || Qe; f-- } else f++; e = e.previousSibling || e.parentNode } } return Qe }, link: ge, unlink: Ne, cleanData: function (e) { e.length && Yn && Se(e), er.apply(t, arguments) } }), d(t.fn, { link: function (e, t, n, r, i, a, o) { return ge(e, this, t, n, r, i, a, o) }, unlink: function () { return Ne(this) }, view: function (e, t) { return kn(this[0], e, t) } }), t.each([Mt, "replaceWith", "empty", "remove"], function (e, n) { var r = t.fn[n]; t.fn[n] = function () { var e; Yn++; try { e = r.apply(this, arguments) } finally { Yn-- } return e } }), d(Qe = at.topView, { tmpl: { links: {} } }), In = { 0: Qe }, at._glt = function (e) { for (var t, n = /#(\d*)\^\/\1\^/g, r = [], i = be(e); t = n.exec(i);)(t = dr[t[1]]) && r.push(t.linkCtx.tag); return r }, at._gccb = function (e) { return function (t, n) { var r, i, a, o, s, l, d, p, c, f, u; if (e && t) { if (t._cpfn) try { return st.cache ? e.getCache(t._cpKey) : t._cpfn.call(e.tmpl, e.data, e, at) } catch (g) { return } if ("~" === t.charAt(0)) { if ("~tag" === t.slice(0, 4) && (i = e.ctx, "." === t.charAt(4) ? (r = t.slice(5), i = i.tag) : "~tagCtx." === t.slice(0, 8) && (r = t.slice(8), i = i.tagCtx), r)) return i ? [i, r] : []; if (t = t.slice(1).split("."), o = e.ctxPrm(s = t.shift(), void 0, !0)) if (p = o._cxp) { if (t.length && (l = "." + t.join("."), s = o[d = o.length - 1], s._cpfn ? (s.sb = l, s.bnd = !!n) : (o[d] = (s + l).replace("#data.", ""), "#view" === s.slice(0, 5) && (o[d] = o[d].slice(6), o.splice(d, 0, e)))), a = [o], (i = p.tag) && i.convert) for (u = i.bindTo || [0], d = u.length; d--;)void 0 !== n && d !== p.ind && (f = u[d], c = [o[0], i.tagCtx.params[+f === f ? "args" : "props"]], c._cxp = p, a.push(c)) } else (t.length || Ye(o)) && (a = [o, t.join(".")]); return a || [] } if ("#" === t.charAt(0)) return "#data" === t ? [] : [e, t.replace(cr, "")] } } }, at._cp = function (e, n, r, i) { if (r.linked) { if (i && (i.cvt || void 0 === i.tag._.toIndex[i.ind])) e = [{ _ocp: e }], i.updateValue = function (n) { return t.observable(e._cxp.data).setProperty(_t, n), this }; else if (n) { var a = pt + ":" + n + ct, o = nr[a]; o || (nr[a] = o = at.tmplFn(a.replace(xt, "\\$&"), r.tmpl, !0)), e = o.deps[0] ? [r, o] : [{ _ocp: i ? e : o() }] } else e = [{ _ocp: e }]; e._cxp = i || { updateValue: function (t) { return Ze(e._cxp.data).setProperty(e._cxp.path, t), this } } } return e }, at._ucp = function (e, t, n, r) { var i = r.tag, a = i ? wr(e, i.linkedCtxParam) : 0; return r.path || Te("~" + e, n.data, at._gccb(n)), (r.updateValue || i.updateValue)(t, a, r.tagElse, void 0, i) }, at._ceo = function Cr(e) { for (var t, n = [], r = e.length; r--;)t = e[r], t._cpfn && (t = d({}, t), t.prm = Cr(t.prm)), n.unshift(t); return n }, Tn = at.advSet, at.advSet = function () { Tn.call(at), e._jsv = st._jsv ? d(e._jsv || {}, { views: In, bindings: dr }) : void 0, En = st.linkAttr, jn = Xn + ",[" + En + "]", An = st._wm, An.optgroup = An.option, An.tbody = An.tfoot = An.colgroup = An.caption = An.thead, An.th = An.td }, lt.advanced({ linkAttr: "data-link", useViews: !1, noValidate: !1, _wm: { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], svg_ns: [1, "<svg>", "</svg>"], div: t.support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, _fe: { input: { from: Fe, to: Kn }, textarea: Gn, select: Gn, optgroup: { to: "label" } } }), t
}, window);
//# sourceMappingURL=jsviews.min.js.map;
/*!
 * Amplify 1.1.2
 *
 * Copyright 2011 - 2013 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 *
 * http://amplifyjs.com
 */
(function(e,t){var n=[].slice,r={},i=e.amplify={publish:function(e){if(typeof e!="string")throw new Error("You must provide a valid topic to publish.");var t=n.call(arguments,1),i,s,o,u=0,a;if(!r[e])return!0;i=r[e].slice();for(o=i.length;u<o;u++){s=i[u],a=s.callback.apply(s.context,t);if(a===!1)break}return a!==!1},subscribe:function(e,t,n,i){if(typeof e!="string")throw new Error("You must provide a valid topic to create a subscription.");arguments.length===3&&typeof n=="number"&&(i=n,n=t,t=null),arguments.length===2&&(n=t,t=null),i=i||10;var s=0,o=e.split(/\s/),u=o.length,a;for(;s<u;s++){e=o[s],a=!1,r[e]||(r[e]=[]);var f=r[e].length-1,l={callback:n,context:t,priority:i};for(;f>=0;f--)if(r[e][f].priority<=i){r[e].splice(f+1,0,l),a=!0;break}a||r[e].unshift(l)}return n},unsubscribe:function(e,t,n){if(typeof e!="string")throw new Error("You must provide a valid topic to remove a subscription.");arguments.length===2&&(n=t,t=null);if(!r[e])return;var i=r[e].length,s=0;for(;s<i;s++)r[e][s].callback===n&&(!t||r[e][s].context===t)&&(r[e].splice(s,1),s--,i--)}}})(this),function(e,t){function i(e,i){n.addType(e,function(s,o,u){var a,f,l,c,h=o,p=(new Date).getTime();if(!s){h={},c=[],l=0;try{s=i.length;while(s=i.key(l++))r.test(s)&&(f=JSON.parse(i.getItem(s)),f.expires&&f.expires<=p?c.push(s):h[s.replace(r,"")]=f.data);while(s=c.pop())i.removeItem(s)}catch(d){}return h}s="__amplify__"+s;if(o===t){a=i.getItem(s),f=a?JSON.parse(a):{expires:-1};if(!(f.expires&&f.expires<=p))return f.data;i.removeItem(s)}else if(o===null)i.removeItem(s);else{f=JSON.stringify({data:o,expires:u.expires?p+u.expires:null});try{i.setItem(s,f)}catch(d){n[e]();try{i.setItem(s,f)}catch(d){throw n.error()}}}return h})}var n=e.store=function(e,t,r){var i=n.type;return r&&r.type&&r.type in n.types&&(i=r.type),n.types[i](e,t,r||{})};n.types={},n.type=null,n.addType=function(e,t){n.type||(n.type=e),n.types[e]=t,n[e]=function(t,r,i){return i=i||{},i.type=e,n(t,r,i)}},n.error=function(){return"amplify.store quota exceeded"};var r=/^__amplify__/;for(var s in{localStorage:1,sessionStorage:1})try{window[s].setItem("__amplify__","x"),window[s].removeItem("__amplify__"),i(s,window[s])}catch(o){}if(!n.types.localStorage&&window.globalStorage)try{i("globalStorage",window.globalStorage[window.location.hostname]),n.type==="sessionStorage"&&(n.type="globalStorage")}catch(o){}(function(){if(n.types.localStorage)return;var e=document.createElement("div"),r="amplify";e.style.display="none",document.getElementsByTagName("head")[0].appendChild(e);try{e.addBehavior("#default#userdata"),e.load(r)}catch(i){e.parentNode.removeChild(e);return}n.addType("userData",function(i,s,o){e.load(r);var u,a,f,l,c,h=s,p=(new Date).getTime();if(!i){h={},c=[],l=0;while(u=e.XMLDocument.documentElement.attributes[l++])a=JSON.parse(u.value),a.expires&&a.expires<=p?c.push(u.name):h[u.name]=a.data;while(i=c.pop())e.removeAttribute(i);return e.save(r),h}i=i.replace(/[^\-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g,"-"),i=i.replace(/^-/,"_-");if(s===t){u=e.getAttribute(i),a=u?JSON.parse(u):{expires:-1};if(!(a.expires&&a.expires<=p))return a.data;e.removeAttribute(i)}else s===null?e.removeAttribute(i):(f=e.getAttribute(i),a=JSON.stringify({data:s,expires:o.expires?p+o.expires:null}),e.setAttribute(i,a));try{e.save(r)}catch(d){f===null?e.removeAttribute(i):e.setAttribute(i,f),n.userData();try{e.setAttribute(i,a),e.save(r)}catch(d){throw f===null?e.removeAttribute(i):e.setAttribute(i,f),n.error()}}return h})})(),function(){function i(e){return e===t?t:JSON.parse(JSON.stringify(e))}var e={},r={};n.addType("memory",function(n,s,o){return n?s===t?i(e[n]):(r[n]&&(clearTimeout(r[n]),delete r[n]),s===null?(delete e[n],null):(e[n]=s,o.expires&&(r[n]=setTimeout(function(){delete e[n],delete r[n]},o.expires)),s)):i(e)})}()}(this.amplify=this.amplify||{}),function(e,t){"use strict";function n(){}function r(e){return{}.toString.call(e)==="[object Function]"}function i(e){var t=!1;return setTimeout(function(){t=!0},1),function(){var n=this,r=arguments;t?e.apply(n,r):setTimeout(function(){e.apply(n,r)},1)}}e.request=function(t,s,o){var u=t||{};typeof u=="string"&&(r(s)&&(o=s,s={}),u={resourceId:t,data:s||{},success:o});var a={abort:n},f=e.request.resources[u.resourceId],l=u.success||n,c=u.error||n;u.success=i(function(t,n){n=n||"success",e.publish("request.success",u,t,n),e.publish("request.complete",u,t,n),l(t,n)}),u.error=i(function(t,n){n=n||"error",e.publish("request.error",u,t,n),e.publish("request.complete",u,t,n),c(t,n)});if(!f)throw u.resourceId?"amplify.request: unknown resourceId: "+u.resourceId:"amplify.request: no resourceId provided";if(!e.publish("request.before",u)){u.error(null,"abort");return}return e.request.resources[u.resourceId](u,a),a},e.request.types={},e.request.resources={},e.request.define=function(t,n,r){if(typeof n=="string"){if(!(n in e.request.types))throw"amplify.request.define: unknown type: "+n;r.resourceId=t,e.request.resources[t]=e.request.types[n](r)}else e.request.resources[t]=n}}(amplify),function(e,t,n){"use strict";var r=["status","statusText","responseText","responseXML","readyState"],i=/\{([^\}]+)\}/g;e.request.types.ajax=function(i){return i=t.extend({type:"GET"},i),function(s,o){var u,a,f=i.url,l=o.abort,c=t.extend(!0,{},i,{data:s.data}),h=!1,p={readyState:0,setRequestHeader:function(e,t){return u.setRequestHeader(e,t)},getAllResponseHeaders:function(){return u.getAllResponseHeaders()},getResponseHeader:function(e){return u.getResponseHeader(e)},overrideMimeType:function(e){return u.overrideMimeType(e)},abort:function(){h=!0;try{u.abort()}catch(e){}a(null,"abort")},success:function(e,t){s.success(e,t)},error:function(e,t){s.error(e,t)}};a=function(e,i){t.each(r,function(e,t){try{p[t]=u[t]}catch(n){}}),/OK$/.test(p.statusText)&&(p.statusText="success"),e===n&&(e=null),h&&(i="abort"),/timeout|error|abort/.test(i)?p.error(e,i):p.success(e,i),a=t.noop},e.publish("request.ajax.preprocess",i,s,c,p),t.extend(c,{isJSONP:function(){return/jsonp/gi.test(this.dataType)},cacheURL:function(){if(!this.isJSONP())return this.url;var e="callback";this.hasOwnProperty("jsonp")&&(this.jsonp!==!1?e=this.jsonp:this.hasOwnProperty("jsonpCallback")&&(e=this.jsonpCallback));var t=new RegExp("&?"+e+"=[^&]*&?","gi");return this.url.replace(t,"")},success:function(e,t){a(e,t)},error:function(e,t){a(null,t)},beforeSend:function(t,n){u=t,c=n;var r=i.beforeSend?i.beforeSend.call(this,p,c):!0;return r&&e.publish("request.before.ajax",i,s,c,p)}}),c.cache&&c.isJSONP()&&t.extend(c,{cache:!0}),t.ajax(c),o.abort=function(){p.abort(),l.call(this)}}},e.subscribe("request.ajax.preprocess",function(e,n,r){var s=[],o=r.data;if(typeof o=="string")return;o=t.extend(!0,{},e.data,o),r.url=r.url.replace(i,function(e,t){if(t in o)return s.push(t),o[t]}),t.each(s,function(e,t){delete o[t]}),r.data=o}),e.subscribe("request.ajax.preprocess",function(e,n,r){var i=r.data,s=e.dataMap;if(!s||typeof i=="string")return;t.isFunction(s)?r.data=s(i):(t.each(e.dataMap,function(e,t){e in i&&(i[t]=i[e],delete i[e])}),r.data=i)});var s=e.request.cache={_key:function(e,t,n){function s(){return n.charCodeAt(i++)<<24|n.charCodeAt(i++)<<16|n.charCodeAt(i++)<<8|n.charCodeAt(i++)<<0}n=t+n;var r=n.length,i=0,o=s();while(i<r)o^=s();return"request-"+e+"-"+o},_default:function(){var e={};return function(t,n,r,i){var o=s._key(n.resourceId,r.cacheURL(),r.data),u=t.cache;if(o in e)return i.success(e[o]),!1;var a=i.success;i.success=function(t){e[o]=t,typeof u=="number"&&setTimeout(function(){delete e[o]},u),a.apply(this,arguments)}}}()};e.store&&(t.each(e.store.types,function(t){s[t]=function(n,r,i,o){var u=s._key(r.resourceId,i.cacheURL(),i.data),a=e.store[t](u);if(a)return i.success(a),!1;var f=o.success;o.success=function(r){e.store[t](u,r,{expires:n.cache.expires}),f.apply(this,arguments)}}}),s.persist=s[e.store.type]),e.subscribe("request.before.ajax",function(e){var t=e.cache;if(t)return t=t.type||t,s[t in s?t:"_default"].apply(this,arguments)}),e.request.decoders={jsend:function(e,t,n,r,i){e.status==="success"?r(e.data):e.status==="fail"?i(e.data,"fail"):e.status==="error"?(delete e.status,i(e,"error")):i(null,"error")}},e.subscribe("request.before.ajax",function(n,r,i,s){function f(e,t){o(e,t)}function l(e,t){u(e,t)}var o=s.success,u=s.error,a=t.isFunction(n.decoder)?n.decoder:n.decoder in e.request.decoders?e.request.decoders[n.decoder]:e.request.decoders._default;if(!a)return;s.success=function(e,t){a(e,t,s,f,l)},s.error=function(e,t){a(e,t,s,f,l)}})}(amplify,jQuery);
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
//# sourceMappingURL=underscore.min.map;
(function(n,t,i,r){"use strict";function c(n){return(typeof n=="string"||n instanceof String)&&(n=n.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g,"")),n}var f=function(t){for(var i=t.length,r=n("head");i--;)r.has("."+t[i]).length===0&&r.append('<meta class="'+t[i]+'" />')};f(["foundation-mq-small","foundation-mq-small-only","foundation-mq-medium","foundation-mq-medium-only","foundation-mq-large","foundation-mq-large-only","foundation-mq-xlarge","foundation-mq-xlarge-only","foundation-mq-xxlarge","foundation-data-attribute-namespace"]);n(function(){typeof FastClick!="undefined"&&typeof i.body!="undefined"&&FastClick.attach(i.body)});var u=function(t,r){if(typeof t=="string"){if(r){var u;if(r.jquery){if(u=r[0],!u)return r}else u=r;return n(u.querySelectorAll(t))}return n(i.querySelectorAll(t))}return n(t,r)},e=function(n){var t=[];return n||t.push("data"),this.namespace.length>0&&t.push(this.namespace),t.push(this.name),t.join("-")},o=function(n){for(var i=n.split("-"),t=i.length,r=[];t--;)t!==0?r.push(i[t]):this.namespace.length>0?r.push(this.namespace,i[t]):r.push(i[t]);return r.reverse().join("-")},s=function(t,i){var r=this,f=function(){var f=u(this),e=!f.data(r.attr_name(!0)+"-init");f.data(r.attr_name(!0)+"-init",n.extend({},r.settings,i||t,r.data_options(f)));e&&r.events(this)};return u(this.scope).is("["+this.attr_name()+"]")?f.call(this.scope):u("["+this.attr_name()+"]",this.scope).each(f),typeof t=="string"?this[t].call(this,i):void 0},h=function(n,t){function i(){t(n[0])}function r(){this.one("load",i);if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){var n=this.attr("src"),t=n.match(/\?/)?"&":"?";t+="random="+(new Date).getTime();this.attr("src",n+t)}}if(!n.attr("src")){i();return}n[0].complete||n[0].readyState===4?i():r.call(n)};t.matchMedia=t.matchMedia||function(n){var u,i=n.documentElement,f=i.firstElementChild||i.firstChild,r=n.createElement("body"),t=n.createElement("div");return t.id="mq-test-1",t.style.cssText="position:absolute;top:-100em",r.style.background="none",r.appendChild(t),function(n){return t.innerHTML='&shy;<style media="'+n+'"> #mq-test-1 { width: 42px; }<\/style>',i.insertBefore(r,f),u=t.offsetWidth===42,i.removeChild(r),{matches:u,media:n}}}(i),function(n){function s(){u&&(r(s),o&&n.fx.tick())}for(var u,i=0,f=["webkit","moz"],r=t.requestAnimationFrame,e=t.cancelAnimationFrame,o="undefined"!=typeof n.fx;i<f.length&&!r;i++)r=t[f[i]+"RequestAnimationFrame"],e=e||t[f[i]+"CancelAnimationFrame"]||t[f[i]+"CancelRequestAnimationFrame"];r?(t.requestAnimationFrame=r,t.cancelAnimationFrame=e,o&&(n.fx.timer=function(t){t()&&n.timers.push(t)&&!u&&(u=!0,s())},n.fx.stop=function(){u=!1})):(t.requestAnimationFrame=function(n){var r=(new Date).getTime(),u=Math.max(0,16-(r-i)),f=t.setTimeout(function(){n(r+u)},u);return i=r+u,f},t.cancelAnimationFrame=function(n){clearTimeout(n)})}(n);t.Foundation={name:"Foundation",version:"5.5.1",media_queries:{small:u(".foundation-mq-small").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),"small-only":u(".foundation-mq-small-only").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),medium:u(".foundation-mq-medium").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),"medium-only":u(".foundation-mq-medium-only").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),large:u(".foundation-mq-large").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),"large-only":u(".foundation-mq-large-only").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),xlarge:u(".foundation-mq-xlarge").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),"xlarge-only":u(".foundation-mq-xlarge-only").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,""),xxlarge:u(".foundation-mq-xxlarge").css("font-family").replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g,"")},stylesheet:n("<style><\/style>").appendTo("head")[0].sheet,global:{namespace:r},init:function(n,i,r,f,e){var h=[n,r,f,e],o=[],s;if(this.rtl=/rtl/i.test(u("html").attr("dir")),this.scope=n||this.scope,this.set_namespace(),i&&typeof i=="string"&&!/reflow/i.test(i))this.libs.hasOwnProperty(i)&&o.push(this.init_lib(i,h));else for(s in this.libs)o.push(this.init_lib(s,i));u(t).on("load",function(){u(t).trigger("resize.fndtn.clearing").trigger("resize.fndtn.dropdown").trigger("resize.fndtn.equalizer").trigger("resize.fndtn.interchange").trigger("resize.fndtn.joyride").trigger("resize.fndtn.magellan").trigger("resize.fndtn.topbar").trigger("resize.fndtn.slider")});return n},init_lib:function(t,i){return this.libs.hasOwnProperty(t)?(this.patch(this.libs[t]),i&&i.hasOwnProperty(t))?(typeof this.libs[t].settings!="undefined"?n.extend(!0,this.libs[t].settings,i[t]):typeof this.libs[t].defaults!="undefined"&&n.extend(!0,this.libs[t].defaults,i[t]),this.libs[t].init.apply(this.libs[t],[this.scope,i[t]])):(i=i instanceof Array?i:new Array(i),this.libs[t].init.apply(this.libs[t],i)):function(){}},patch:function(n){n.scope=this.scope;n.namespace=this.global.namespace;n.rtl=this.rtl;n.data_options=this.utils.data_options;n.attr_name=e;n.add_namespace=o;n.bindings=s;n.S=this.utils.S},inherit:function(n,t){for(var i=t.split(" "),r=i.length;r--;)this.utils.hasOwnProperty(i[r])&&(n[i[r]]=this.utils[i[r]])},set_namespace:function(){var t=this.global.namespace===r?n(".foundation-data-attribute-namespace").css("font-family"):this.global.namespace;this.global.namespace=t===r||/false/i.test(t)?"":t},libs:{},utils:{S:u,throttle:function(n,t){var i=null;return function(){var r=this,u=arguments;i==null&&(i=setTimeout(function(){n.apply(r,u);i=null},t))}},debounce:function(n,t,i){var r,u;return function(){var f=this,e=arguments,o=function(){r=null;i||(u=n.apply(f,e))},s=i&&!r;return clearTimeout(r),r=setTimeout(o,t),s&&(u=n.apply(f,e)),u}},data_options:function(t,i){function c(n){return!isNaN(+n)&&n!==null&&n!==""&&n!==!1&&n!==!0}function s(t){return typeof t=="string"?n.trim(t):t}i=i||"options";var o={},u,r,f,h=function(n){var t=Foundation.global.namespace;return t.length>0?n.data(t+"-"+i):n.data(i)},e=h(t);if(typeof e=="object")return e;for(f=(e||":").split(";"),u=f.length;u--;)r=f[u].split(":"),r=[r[0],r.slice(1).join(":")],/true/i.test(r[1])&&(r[1]=!0),/false/i.test(r[1])&&(r[1]=!1),c(r[1])&&(r[1]=r[1].indexOf(".")===-1?parseInt(r[1],10):parseFloat(r[1])),r.length===2&&r[0].length>0&&(o[s(r[0])]=s(r[1]));return o},register_media:function(t,i){Foundation.media_queries[t]===r&&(n("head").append('<meta class="'+i+'"/>'),Foundation.media_queries[t]=c(n("."+i).css("font-family")))},add_custom_rule:function(n,t){if(t===r&&Foundation.stylesheet)Foundation.stylesheet.insertRule(n,Foundation.stylesheet.cssRules.length);else{var i=Foundation.media_queries[t];i!==r&&Foundation.stylesheet.insertRule("@media "+Foundation.media_queries[t]+"{ "+n+" }")}},image_loaded:function(n,t){var r=this,i=n.length;i===0&&t(n);n.each(function(){h(r.S(this),function(){i-=1;i===0&&t(n)})})},random_str:function(){return this.fidx||(this.fidx=0),this.prefix=this.prefix||[this.name||"F",(+new Date).toString(36)].join("-"),this.prefix+(this.fidx++).toString(36)},match:function(n){return t.matchMedia(n).matches},is_small_up:function(){return this.match(Foundation.media_queries.small)},is_medium_up:function(){return this.match(Foundation.media_queries.medium)},is_large_up:function(){return this.match(Foundation.media_queries.large)},is_xlarge_up:function(){return this.match(Foundation.media_queries.xlarge)},is_xxlarge_up:function(){return this.match(Foundation.media_queries.xxlarge)},is_small_only:function(){return!this.is_medium_up()&&!this.is_large_up()&&!this.is_xlarge_up()&&!this.is_xxlarge_up()},is_medium_only:function(){return this.is_medium_up()&&!this.is_large_up()&&!this.is_xlarge_up()&&!this.is_xxlarge_up()},is_large_only:function(){return this.is_medium_up()&&this.is_large_up()&&!this.is_xlarge_up()&&!this.is_xxlarge_up()},is_xlarge_only:function(){return this.is_medium_up()&&this.is_large_up()&&this.is_xlarge_up()&&!this.is_xxlarge_up()},is_xxlarge_only:function(){return this.is_medium_up()&&this.is_large_up()&&this.is_xlarge_up()&&this.is_xxlarge_up()}}};n.fn.foundation=function(){var n=Array.prototype.slice.call(arguments,0);return this.each(function(){return Foundation.init.apply(Foundation,[this].concat(n)),this})}})(jQuery,window,window.document),function(n,t){"use strict";Foundation.libs.slider={name:"slider",version:"5.5.1",settings:{start:0,end:100,step:1,precision:null,initial:null,display_selector:"",vertical:!1,trigger_input_change:!1,on_change:function(){}},cache:{},init:function(n,t,i){Foundation.inherit(this,"throttle");this.bindings(t,i);this.reflow()},events:function(){var i=this;n(this.scope).off(".slider").on("mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider","["+i.attr_name()+"]:not(.disabled, [disabled]) .range-slider-handle",function(t){i.cache.active||(t.preventDefault(),i.set_active_slider(n(t.target)))}).on("mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider",function(r){if(!!i.cache.active)if(r.preventDefault(),n.data(i.cache.active[0],"settings").vertical){var u=0;r.pageY||(u=t.scrollY);i.calculate_position(i.cache.active,i.get_cursor_position(r,"y")+u)}else i.calculate_position(i.cache.active,i.get_cursor_position(r,"x"))}).on("mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider",function(){i.remove_active_slider()}).on("change.fndtn.slider",function(){i.settings.on_change()});i.S(t).on("resize.fndtn.slider",i.throttle(function(){i.reflow()},300))},get_cursor_position:function(n,t){var u="page"+t.toUpperCase(),r="client"+t.toUpperCase(),i;return typeof n[u]!="undefined"?i=n[u]:typeof n.originalEvent[r]!="undefined"?i=n.originalEvent[r]:n.originalEvent.touches&&n.originalEvent.touches[0]&&typeof n.originalEvent.touches[0][r]!="undefined"?i=n.originalEvent.touches[0][r]:n.currentPoint&&typeof n.currentPoint[t]!="undefined"&&(i=n.currentPoint[t]),i},set_active_slider:function(n){this.cache.active=n},remove_active_slider:function(){this.cache.active=null},calculate_position:function(t,i){var u=this,r=n.data(t[0],"settings"),o=n.data(t[0],"handle_l"),s=n.data(t[0],"handle_o"),f=n.data(t[0],"bar_l"),e=n.data(t[0],"bar_o");requestAnimationFrame(function(){var n,o;n=Foundation.rtl&&!r.vertical?u.limit_to((e+f-i)/f,0,1):u.limit_to((i-e)/f,0,1);n=r.vertical?1-n:n;o=u.normalized_value(n,r.start,r.end,r.step,r.precision);u.set_ui(t,o)})},set_ui:function(t,i){var r=n.data(t[0],"settings"),f=n.data(t[0],"handle_l"),e=n.data(t[0],"bar_l"),o=this.normalized_percentage(i,r.start,r.end),u=o*(e-f)-1,s=o*100,c=t.parent(),h=t.parent().children("input[type=hidden]");Foundation.rtl&&!r.vertical&&(u=-u);u=r.vertical?-u+e-f+1:u;this.set_translate(t,u,r.vertical);r.vertical?t.siblings(".range-slider-active-segment").css("height",s+"%"):t.siblings(".range-slider-active-segment").css("width",s+"%");c.attr(this.attr_name(),i).trigger("change").trigger("change.fndtn.slider");h.val(i);r.trigger_input_change&&h.trigger("change");t[0].hasAttribute("aria-valuemin")||t.attr({"aria-valuemin":r.start,"aria-valuemax":r.end});t.attr("aria-valuenow",i);r.display_selector!=""&&n(r.display_selector).each(function(){this.hasOwnProperty("value")?n(this).val(i):n(this).text(i)})},normalized_percentage:function(n,t,i){return Math.min(1,(n-t)/(i-t))},normalized_value:function(n,t,i,r,u){var e=i-t,f=n*e,o=(f-f%r)/r,s=f%r,h=s>=r*.5?r:0;return(o*r+h+t).toFixed(u)},set_translate:function(t,i,r){r?n(t).css("-webkit-transform","translateY("+i+"px)").css("-moz-transform","translateY("+i+"px)").css("-ms-transform","translateY("+i+"px)").css("-o-transform","translateY("+i+"px)").css("transform","translateY("+i+"px)"):n(t).css("-webkit-transform","translateX("+i+"px)").css("-moz-transform","translateX("+i+"px)").css("-ms-transform","translateX("+i+"px)").css("-o-transform","translateX("+i+"px)").css("transform","translateX("+i+"px)")},limit_to:function(n,t,i){return Math.min(Math.max(n,t),i)},initialize_settings:function(t){var i=n.extend({},this.settings,this.data_options(n(t).parent())),r;i.precision===null&&(r=(""+i.step).match(/\.([\d]*)/),i.precision=r&&r[1]?r[1].length:0);i.vertical?(n.data(t,"bar_o",n(t).parent().offset().top),n.data(t,"bar_l",n(t).parent().outerHeight()),n.data(t,"handle_o",n(t).offset().top),n.data(t,"handle_l",n(t).outerHeight())):(n.data(t,"bar_o",n(t).parent().offset().left),n.data(t,"bar_l",n(t).parent().outerWidth()),n.data(t,"handle_o",n(t).offset().left),n.data(t,"handle_l",n(t).outerWidth()));n.data(t,"bar",n(t).parent());n.data(t,"settings",i)},set_initial_position:function(t){var i=n.data(t.children(".range-slider-handle")[0],"settings"),r=typeof i.initial=="number"&&!isNaN(i.initial)?i.initial:Math.floor((i.end-i.start)*.5/i.step)*i.step+i.start,u=t.children(".range-slider-handle");this.set_ui(u,r)},set_value:function(t){var i=this;n("["+i.attr_name()+"]",this.scope).each(function(){n(this).attr(i.attr_name(),t)});!n(this.scope).attr(i.attr_name())||n(this.scope).attr(i.attr_name(),t);i.reflow()},reflow:function(){var t=this;t.S("["+this.attr_name()+"]").each(function(){var i=n(this).children(".range-slider-handle")[0],r=n(this).attr(t.attr_name());t.initialize_settings(i);r?t.set_ui(n(i),parseFloat(r)):t.set_initial_position(n(this))})}}}(jQuery,window,window.document),function(n,t,i,r){"use strict";var u=u||!1;Foundation.libs.joyride={name:"joyride",version:"5.5.1",defaults:{expose:!1,modal:!0,keyboard:!0,tip_location:"bottom",nub_position:"auto",scroll_speed:1500,scroll_animation:"linear",timer:0,start_timer_on_click:!0,start_offset:0,next_button:!0,prev_button:!0,tip_animation:"fade",pause_after:[],exposed:[],tip_animation_fade_speed:300,cookie_monster:!1,cookie_name:"joyride",cookie_domain:!1,cookie_expires:365,tip_container:"body",abort_on_close:!0,tip_location_patterns:{top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},post_ride_callback:function(){},post_step_callback:function(){},pre_step_callback:function(){},pre_ride_callback:function(){},post_expose_callback:function(){},template:{link:'<a href="#close" class="joyride-close-tip">&times;<\/a>',timer:'<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"><\/span><\/div>',tip:'<div class="joyride-tip-guide"><span class="joyride-nub"><\/span><\/div>',wrapper:'<div class="joyride-content-wrapper"><\/div>',button:'<a href="#" class="small button joyride-next-tip"><\/a>',prev_button:'<a href="#" class="small button joyride-prev-tip"><\/a>',modal:'<div class="joyride-modal-bg"><\/div>',expose:'<div class="joyride-expose-wrapper"><\/div>',expose_cover:'<div class="joyride-expose-cover"><\/div>'},expose_add_class:""},init:function(t,i,r){Foundation.inherit(this,"throttle random_str");this.settings=this.settings||n.extend({},this.defaults,r||i);this.bindings(i,r)},go_next:function(){this.settings.$li.next().length<1?this.end():this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(),this.startTimer()):(this.hide(),this.show())},go_prev:function(){this.settings.$li.prev().length<1||(this.settings.timer>0?(clearTimeout(this.settings.automate),this.hide(),this.show(null,!0),this.startTimer()):(this.hide(),this.show(null,!0)))},events:function(){var i=this;n(this.scope).off(".joyride").on("click.fndtn.joyride",".joyride-next-tip, .joyride-modal-bg",function(n){n.preventDefault();this.go_next()}.bind(this)).on("click.fndtn.joyride",".joyride-prev-tip",function(n){n.preventDefault();this.go_prev()}.bind(this)).on("click.fndtn.joyride",".joyride-close-tip",function(n){n.preventDefault();this.end(this.settings.abort_on_close)}.bind(this)).on("keyup.fndtn.joyride",function(n){if(this.settings.keyboard&&this.settings.riding)switch(n.which){case 39:n.preventDefault();this.go_next();break;case 37:n.preventDefault();this.go_prev();break;case 27:n.preventDefault();this.end(this.settings.abort_on_close)}}.bind(this));n(t).off(".joyride").on("resize.fndtn.joyride",i.throttle(function(){if(n("["+i.attr_name()+"]").length>0&&i.settings.$next_tip&&i.settings.riding){if(i.settings.exposed.length>0){var t=n(i.settings.exposed);t.each(function(){var t=n(this);i.un_expose(t);i.expose(t)})}i.is_phone()?i.pos_phone():i.pos_default(!1)}},100))},start:function(){var t=this,i=n("["+this.attr_name()+"]",this.scope),r=["timer","scrollSpeed","startOffset","tipAnimationFadeSpeed","cookieExpires"],u=r.length;!i.length>0||(this.settings.init||this.events(),this.settings=i.data(this.attr_name(!0)+"-init"),this.settings.$content_el=i,this.settings.$body=n(this.settings.tip_container),this.settings.body_offset=n(this.settings.tip_container).position(),this.settings.$tip_content=this.settings.$content_el.find("> li"),this.settings.paused=!1,this.settings.attempts=0,this.settings.riding=!0,typeof n.cookie!="function"&&(this.settings.cookie_monster=!1),this.settings.cookie_monster&&(!this.settings.cookie_monster||n.cookie(this.settings.cookie_name))||(this.settings.$tip_content.each(function(i){var e=n(this),f;for(this.settings=n.extend({},t.defaults,t.data_options(e)),f=u;f--;)t.settings[r[f]]=parseInt(t.settings[r[f]],10);t.create({$li:e,index:i})}),!this.settings.start_timer_on_click&&this.settings.timer>0?(this.show("init"),this.startTimer()):this.show("init")))},resume:function(){this.set_li();this.show()},tip_template:function(t){var i,r;return t.tip_class=t.tip_class||"",i=n(this.settings.template.tip).addClass(t.tip_class),r=n.trim(n(t.li).html())+this.prev_button_text(t.prev_button_text,t.index)+this.button_text(t.button_text)+this.settings.template.link+this.timer_instance(t.index),i.append(n(this.settings.template.wrapper)),i.first().attr(this.add_namespace("data-index"),t.index),n(".joyride-content-wrapper",i).append(r),i[0]},timer_instance:function(t){return t===0&&this.settings.start_timer_on_click&&this.settings.timer>0||this.settings.timer===0?"":n(this.settings.template.timer)[0].outerHTML},button_text:function(t){return this.settings.tip_settings.next_button?(t=n.trim(t)||"Next",t=n(this.settings.template.button).append(t)[0].outerHTML):t="",t},prev_button_text:function(t,i){return this.settings.tip_settings.prev_button?(t=n.trim(t)||"Previous",t=i==0?n(this.settings.template.prev_button).append(t).addClass("disabled")[0].outerHTML:n(this.settings.template.prev_button).append(t)[0].outerHTML):t="",t},create:function(t){this.settings.tip_settings=n.extend({},this.settings,this.data_options(t.$li));var i=t.$li.attr(this.add_namespace("data-button"))||t.$li.attr(this.add_namespace("data-text")),r=t.$li.attr(this.add_namespace("data-button-prev"))||t.$li.attr(this.add_namespace("data-prev-text")),u=t.$li.attr("class"),f=n(this.tip_template({tip_class:u,index:t.index,button_text:i,prev_button_text:r,li:t.$li}));n(this.settings.tip_container).append(f)},show:function(t,i){var u=null,f;this.settings.$li===r||n.inArray(this.settings.$li.index(),this.settings.pause_after)===-1?(this.settings.paused?this.settings.paused=!1:this.set_li(t,i),this.settings.attempts=0,this.settings.$li.length&&this.settings.$target.length>0?(t&&(this.settings.pre_ride_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.show_modal()),this.settings.pre_step_callback(this.settings.$li.index(),this.settings.$next_tip),this.settings.modal&&this.settings.expose&&this.expose(),this.settings.tip_settings=n.extend({},this.settings,this.data_options(this.settings.$li)),this.settings.timer=parseInt(this.settings.timer,10),this.settings.tip_settings.tip_location_pattern=this.settings.tip_location_patterns[this.settings.tip_settings.tip_location],/body/i.test(this.settings.$target.selector)||(f=n(".joyride-modal-bg"),/pop/i.test(this.settings.tipAnimation)?f.hide():f.fadeOut(this.settings.tipAnimationFadeSpeed),this.scroll_to()),this.is_phone()?this.pos_phone(!0):this.pos_default(!0),u=this.settings.$next_tip.find(".joyride-timer-indicator"),/pop/i.test(this.settings.tip_animation)?(u.width(0),this.settings.timer>0?(this.settings.$next_tip.show(),setTimeout(function(){u.animate({width:u.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.show()):/fade/i.test(this.settings.tip_animation)&&(u.width(0),this.settings.timer>0?(this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed).show(),setTimeout(function(){u.animate({width:u.parent().width()},this.settings.timer,"linear")}.bind(this),this.settings.tip_animation_fade_speed)):this.settings.$next_tip.fadeIn(this.settings.tip_animation_fade_speed)),this.settings.$current_tip=this.settings.$next_tip):this.settings.$li&&this.settings.$target.length<1?this.show(t,i):this.end()):this.settings.paused=!0},is_phone:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},hide:function(){this.settings.modal&&this.settings.expose&&this.un_expose();this.settings.modal||n(".joyride-modal-bg").hide();this.settings.$current_tip.css("visibility","hidden");setTimeout(n.proxy(function(){this.hide();this.css("visibility","visible")},this.settings.$current_tip),0);this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip)},set_li:function(n,t){n?(this.settings.$li=this.settings.$tip_content.eq(this.settings.start_offset),this.set_next_tip(),this.settings.$current_tip=this.settings.$next_tip):(this.settings.$li=t?this.settings.$li.prev():this.settings.$li.next(),this.set_next_tip());this.set_target()},set_next_tip:function(){this.settings.$next_tip=n(".joyride-tip-guide").eq(this.settings.$li.index());this.settings.$next_tip.data("closed","")},set_target:function(){var t=this.settings.$li.attr(this.add_namespace("data-class")),r=this.settings.$li.attr(this.add_namespace("data-id")),u=function(){return r?n(i.getElementById(r)):t?n("."+t).first():n("body")};this.settings.$target=u()},scroll_to:function(){var r,i;r=n(t).height()/2;i=Math.ceil(this.settings.$target.offset().top-r+this.settings.$next_tip.outerHeight());i!=0&&n("html, body").stop().animate({scrollTop:i},this.settings.scroll_speed,"swing")},paused:function(){return n.inArray(this.settings.$li.index()+1,this.settings.pause_after)===-1},restart:function(){this.hide();this.settings.$li=r;this.show("init")},pos_default:function(n){var t=this.settings.$next_tip.find(".joyride-nub"),f=Math.ceil(t.outerWidth()/2),u=Math.ceil(t.outerHeight()/2),e=n||!1,i,r;e&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show());/body/i.test(this.settings.$target.selector)?this.settings.$li.length&&this.pos_modal(t):(i=this.settings.tip_settings.tipAdjustmentY?parseInt(this.settings.tip_settings.tipAdjustmentY):0,r=this.settings.tip_settings.tipAdjustmentX?parseInt(this.settings.tip_settings.tipAdjustmentX):0,this.bottom()?(this.rtl?this.settings.$next_tip.css({top:this.settings.$target.offset().top+u+this.settings.$target.outerHeight()+i,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()+r}):this.settings.$next_tip.css({top:this.settings.$target.offset().top+u+this.settings.$target.outerHeight()+i,left:this.settings.$target.offset().left+r}),this.nub_position(t,this.settings.tip_settings.nub_position,"top")):this.top()?(this.rtl?this.settings.$next_tip.css({top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-u+i,left:this.settings.$target.offset().left+this.settings.$target.outerWidth()-this.settings.$next_tip.outerWidth()}):this.settings.$next_tip.css({top:this.settings.$target.offset().top-this.settings.$next_tip.outerHeight()-u+i,left:this.settings.$target.offset().left+r}),this.nub_position(t,this.settings.tip_settings.nub_position,"bottom")):this.right()?(this.settings.$next_tip.css({top:this.settings.$target.offset().top+i,left:this.settings.$target.outerWidth()+this.settings.$target.offset().left+f+r}),this.nub_position(t,this.settings.tip_settings.nub_position,"left")):this.left()&&(this.settings.$next_tip.css({top:this.settings.$target.offset().top+i,left:this.settings.$target.offset().left-this.settings.$next_tip.outerWidth()-f+r}),this.nub_position(t,this.settings.tip_settings.nub_position,"right")),!this.visible(this.corners(this.settings.$next_tip))&&this.settings.attempts<this.settings.tip_settings.tip_location_pattern.length&&(t.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),this.settings.tip_settings.tip_location=this.settings.tip_settings.tip_location_pattern[this.settings.attempts],this.settings.attempts++,this.pos_default()));e&&(this.settings.$next_tip.hide(),this.settings.$next_tip.css("visibility","visible"))},pos_phone:function(t){var f=this.settings.$next_tip.outerHeight(),o=this.settings.$next_tip.offset(),e=this.settings.$target.outerHeight(),i=n(".joyride-nub",this.settings.$next_tip),r=Math.ceil(i.outerHeight()/2),u=t||!1;i.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left");u&&(this.settings.$next_tip.css("visibility","hidden"),this.settings.$next_tip.show());/body/i.test(this.settings.$target.selector)?this.settings.$li.length&&this.pos_modal(i):this.top()?(this.settings.$next_tip.offset({top:this.settings.$target.offset().top-f-r}),i.addClass("bottom")):(this.settings.$next_tip.offset({top:this.settings.$target.offset().top+e+r}),i.addClass("top"));u&&(this.settings.$next_tip.hide(),this.settings.$next_tip.css("visibility","visible"))},pos_modal:function(n){this.center();n.hide();this.show_modal()},show_modal:function(){var t;this.settings.$next_tip.data("closed")||(t=n(".joyride-modal-bg"),t.length<1&&(t=n(this.settings.template.modal),t.appendTo("body")),/pop/i.test(this.settings.tip_animation)?t.show():t.fadeIn(this.settings.tip_animation_fade_speed))},expose:function(){var r,u,i,f,e,o="expose-"+this.random_str(6);if(arguments.length>0&&arguments[0]instanceof n)i=arguments[0];else if(this.settings.$target&&!/body/i.test(this.settings.$target.selector))i=this.settings.$target;else return!1;if(i.length<1)return t.console&&console.error("element not valid",i),!1;r=n(this.settings.template.expose);this.settings.$body.append(r);r.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)});u=n(this.settings.template.expose_cover);f={zIndex:i.css("z-index"),position:i.css("position")};e=i.attr("class")==null?"":i.attr("class");i.css("z-index",parseInt(r.css("z-index"))+1);f.position=="static"&&i.css("position","relative");i.data("expose-css",f);i.data("orig-class",e);i.attr("class",e+" "+this.settings.expose_add_class);u.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)});this.settings.modal&&this.show_modal();this.settings.$body.append(u);r.addClass(o);u.addClass(o);i.data("expose",o);this.settings.post_expose_callback(this.settings.$li.index(),this.settings.$next_tip,i);this.add_exposed(i)},un_expose:function(){var u,i,f,r,e,o=!1;if(arguments.length>0&&arguments[0]instanceof n)i=arguments[0];else if(this.settings.$target&&!/body/i.test(this.settings.$target.selector))i=this.settings.$target;else return!1;if(i.length<1)return t.console&&console.error("element not valid",i),!1;u=i.data("expose");f=n("."+u);arguments.length>1&&(o=arguments[1]);o===!0?n(".joyride-expose-wrapper,.joyride-expose-cover").remove():f.remove();r=i.data("expose-css");r.zIndex=="auto"?i.css("z-index",""):i.css("z-index",r.zIndex);r.position!=i.css("position")&&(r.position=="static"?i.css("position",""):i.css("position",r.position));e=i.data("orig-class");i.attr("class",e);i.removeData("orig-classes");i.removeData("expose");i.removeData("expose-z-index");this.remove_exposed(i)},add_exposed:function(t){this.settings.exposed=this.settings.exposed||[];t instanceof n||typeof t=="object"?this.settings.exposed.push(t[0]):typeof t=="string"&&this.settings.exposed.push(t)},remove_exposed:function(t){var r,i;for(t instanceof n?r=t[0]:typeof t=="string"&&(r=t),this.settings.exposed=this.settings.exposed||[],i=this.settings.exposed.length;i--;)if(this.settings.exposed[i]==r){this.settings.exposed.splice(i,1);return}},center:function(){var i=n(t);return this.settings.$next_tip.css({top:(i.height()-this.settings.$next_tip.outerHeight())/2+i.scrollTop(),left:(i.width()-this.settings.$next_tip.outerWidth())/2+i.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(this.settings.tip_settings.tip_location)},top:function(){return/top/i.test(this.settings.tip_settings.tip_location)},right:function(){return/right/i.test(this.settings.tip_settings.tip_location)},left:function(){return/left/i.test(this.settings.tip_settings.tip_location)},corners:function(i){var r=n(t),s=r.height()/2,u=Math.ceil(this.settings.$target.offset().top-s+this.settings.$next_tip.outerHeight()),h=r.width()+r.scrollLeft(),o=r.height()+u,f=r.height()+r.scrollTop(),e=r.scrollTop();return u<e&&(e=u<0?0:u),o>f&&(f=o),[i.offset().top<e,h<i.offset().left+i.outerWidth(),f<i.offset().top+i.outerHeight(),r.scrollLeft()>i.offset().left]},visible:function(n){for(var t=n.length;t--;)if(n[t])return!1;return!0},nub_position:function(n,t,i){t==="auto"?n.addClass(i):n.addClass(t)},startTimer:function(){this.settings.$li.length?this.settings.automate=setTimeout(function(){this.hide();this.show();this.startTimer()}.bind(this),this.settings.timer):clearTimeout(this.settings.automate)},end:function(t){this.settings.cookie_monster&&n.cookie(this.settings.cookie_name,"ridden",{expires:this.settings.cookie_expires,domain:this.settings.cookie_domain});this.settings.timer>0&&clearTimeout(this.settings.automate);this.settings.modal&&this.settings.expose&&this.un_expose();n(this.scope).off("keyup.joyride");this.settings.$next_tip.data("closed",!0);this.settings.riding=!1;n(".joyride-modal-bg").hide();this.settings.$current_tip.hide();(typeof t=="undefined"||t===!1)&&(this.settings.post_step_callback(this.settings.$li.index(),this.settings.$current_tip),this.settings.post_ride_callback(this.settings.$li.index(),this.settings.$current_tip));n(".joyride-tip-guide").remove()},off:function(){n(this.scope).off(".joyride");n(t).off(".joyride");n(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride");n(".joyride-tip-guide, .joyride-modal-bg").remove();clearTimeout(this.settings.automate);this.settings={}},reflow:function(){}}}(jQuery,window,window.document),function(n,t){"use strict";Foundation.libs.equalizer={name:"equalizer",version:"5.5.1",settings:{use_tallest:!0,before_height_change:n.noop,after_height_change:n.noop,equalize_on_stack:!1},init:function(n,t,i){Foundation.inherit(this,"image_loaded");this.bindings(t,i);this.reflow()},events:function(){this.S(t).off(".equalizer").on("resize.fndtn.equalizer",function(){this.reflow()}.bind(this))},equalize:function(t){var f=!1,r=t.find("["+this.attr_name()+"-watch]:visible"),i=t.data(this.attr_name(!0)+"-init")||this.settings,e,u,o,s;r.length!==0&&((e=r.first().offset().top,i&&i.before_height_change&&i.before_height_change(),t.trigger("before-height-change").trigger("before-height-change.fndth.equalizer"),r.height("inherit"),r.each(function(){var t=n(this);t.offset().top!==e&&(f=!0)}),i.equalize_on_stack===!1&&f)||(u=r.map(function(){return n(this).outerHeight(!1)}).get(),i&&i.use_tallest?(o=Math.max.apply(null,u),r.css("height",o)):(s=Math.min.apply(null,u),r.css("height",s)),i&&i.after_height_change(),t.trigger("after-height-change").trigger("after-height-change.fndtn.equalizer")))},reflow:function(){var t=this;this.S("["+this.attr_name()+"]",this.scope).each(function(){var i=n(this);t.image_loaded(t.S("img",this),function(){t.equalize(i)})})}}}(jQuery,window,window.document),function(n,t,i){"use strict";Foundation.libs.dropdown={name:"dropdown",version:"5.5.1",settings:{active_class:"open",disabled_class:"disabled",mega_class:"mega",align:"bottom",is_hover:!1,hover_timeout:150,opened:function(){},closed:function(){}},init:function(t,i,r){Foundation.inherit(this,"throttle");n.extend(!0,this.settings,i,r);this.bindings(i,r)},events:function(){var r=this,u=r.S;u(this.scope).off(".dropdown").on("click.fndtn.dropdown","["+this.attr_name()+"]",function(t){var i=u(this).data(r.attr_name(!0)+"-init")||r.settings;(!i.is_hover||Modernizr.touch)&&(t.preventDefault(),u(this).parent("[data-reveal-id]")&&t.stopPropagation(),r.toggle(n(this)))}).on("mouseenter.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(n){var t=u(this),i,f,e;clearTimeout(r.timeout);t.data(r.data_attr())?(i=u("#"+t.data(r.data_attr())),f=t):(i=t,f=u("["+r.attr_name()+'="'+i.attr("id")+'"]'));e=f.data(r.attr_name(!0)+"-init")||r.settings;u(n.currentTarget).data(r.data_attr())&&e.is_hover&&r.closeall.call(r);e.is_hover&&r.open.apply(r,[i,f])}).on("mouseleave.fndtn.dropdown","["+this.attr_name()+"], ["+this.attr_name()+"-content]",function(){var n=u(this),i,t;n.data(r.data_attr())?t=n.data(r.data_attr(!0)+"-init")||r.settings:(i=u("["+r.attr_name()+'="'+u(this).attr("id")+'"]'),t=i.data(r.attr_name(!0)+"-init")||r.settings);r.timeout=setTimeout(function(){n.data(r.data_attr())?t.is_hover&&r.close.call(r,u("#"+n.data(r.data_attr()))):t.is_hover&&r.close.call(r,n)}.bind(this),t.hover_timeout)}).on("click.fndtn.dropdown",function(t){var f=u(t.target).closest("["+r.attr_name()+"-content]"),e=f.find("a");if((e.length>0&&f.attr("aria-autoclose")!=="false"&&r.close.call(r,u("["+r.attr_name()+"-content]")),t.target===i||n.contains(i.documentElement,t.target))&&!(u(t.target).closest("["+r.attr_name()+"]").length>0)){if(!u(t.target).data("revealId")&&f.length>0&&(u(t.target).is("["+r.attr_name()+"-content]")||n.contains(f.first()[0],t.target))){t.stopPropagation();return}r.close.call(r,u("["+r.attr_name()+"-content]"))}}).on("opened.fndtn.dropdown","["+r.attr_name()+"-content]",function(){r.settings.opened.call(this)}).on("closed.fndtn.dropdown","["+r.attr_name()+"-content]",function(){r.settings.closed.call(this)});u(t).off(".dropdown").on("resize.fndtn.dropdown",r.throttle(function(){r.resize.call(r)},50));this.resize()},close:function(t){var i=this;t.each(function(){var r=n("["+i.attr_name()+"="+t[0].id+"]")||n("aria-controls="+t[0].id+"]");r.attr("aria-expanded","false");i.S(this).hasClass(i.settings.active_class)&&(i.S(this).css(Foundation.rtl?"right":"left","-99999px").attr("aria-hidden","true").removeClass(i.settings.active_class).prev("["+i.attr_name()+"]").removeClass(i.settings.active_class).removeData("target"),i.S(this).trigger("closed").trigger("closed.fndtn.dropdown",[t]))});t.removeClass("f-open-"+this.attr_name(!0))},closeall:function(){var t=this;n.each(t.S(".f-open-"+this.attr_name(!0)),function(){t.close.call(t,t.S(this))})},open:function(n,t){this.css(n.addClass(this.settings.active_class),t);n.prev("["+this.attr_name()+"]").addClass(this.settings.active_class);n.data("target",t.get(0)).trigger("opened").trigger("opened.fndtn.dropdown",[n,t]);n.attr("aria-hidden","false");t.attr("aria-expanded","true");n.focus();n.addClass("f-open-"+this.attr_name(!0))},data_attr:function(){return this.namespace.length>0?this.namespace+"-"+this.name:this.name},toggle:function(n){if(!n.hasClass(this.settings.disabled_class)){var t=this.S("#"+n.data(this.data_attr()));t.length!==0&&(this.close.call(this,this.S("["+this.attr_name()+"-content]").not(t)),t.hasClass(this.settings.active_class)?(this.close.call(this,t),t.data("target")!==n.get(0)&&this.open.call(this,t,n)):this.open.call(this,t,n))}},resize:function(){var t=this.S("["+this.attr_name()+"-content].open"),i=n(t.data("target"));t.length&&i.length&&this.css(t,i)},css:function(n,t){var u=Math.max((t.width()-n.width())/2,8),i=t.data(this.attr_name(!0)+"-init")||this.settings,r;return this.clear_idx(),this.small()?(r=this.dirs.bottom.call(n,t,i),n.attr("style","").removeClass("drop-left drop-right drop-top").css({position:"absolute",width:"95%","max-width":"none",top:r.top}),n.css(Foundation.rtl?"right":"left",u)):this.style(n,t,i),n},style:function(t,i,r){var u=n.extend({position:"absolute"},this.dirs[r.align].call(t,i,r));t.attr("style","").css(u)},dirs:{_base:function(n){var s=this.offsetParent(),e=s.offset(),r=n.offset(),f,u,o;return r.top-=e.top,r.left-=e.left,r.missRight=!1,r.missTop=!1,r.missLeft=!1,r.leftRightFlag=!1,f=i.getElementsByClassName("row")[0]?i.getElementsByClassName("row")[0].clientWidth:t.outerWidth,u=(t.outerWidth-f)/2,o=f,this.hasClass("mega")||(n.offset().top<=this.outerHeight()&&(r.missTop=!0,o=t.outerWidth-u,r.leftRightFlag=!0),n.offset().left+this.outerWidth()>n.offset().left+u&&n.offset().left-u>this.outerWidth()&&(r.missRight=!0,r.missLeft=!1),n.offset().left-this.outerWidth()<=0&&(r.missLeft=!0,r.missRight=!1)),r},top:function(n,t){var r=Foundation.libs.dropdown,i=r.dirs._base.call(this,n);return(this.addClass("drop-top"),i.missTop==!0&&(i.top=i.top+n.outerHeight()+this.outerHeight(),this.removeClass("drop-top")),i.missRight==!0&&(i.left=i.left-this.outerWidth()+n.outerWidth()),(n.outerWidth()<this.outerWidth()||r.small()||this.hasClass(t.mega_menu))&&r.adjust_pip(this,n,t,i),Foundation.rtl)?{left:i.left-this.outerWidth()+n.outerWidth(),top:i.top-this.outerHeight()}:{left:i.left,top:i.top-this.outerHeight()}},bottom:function(n,t){var r=Foundation.libs.dropdown,i=r.dirs._base.call(this,n);return(i.missRight==!0&&(i.left=i.left-this.outerWidth()+n.outerWidth()),(n.outerWidth()<this.outerWidth()||r.small()||this.hasClass(t.mega_menu))&&r.adjust_pip(this,n,t,i),r.rtl)?{left:i.left-this.outerWidth()+n.outerWidth(),top:i.top+n.outerHeight()}:{left:i.left,top:i.top+n.outerHeight()}},left:function(n){var t=Foundation.libs.dropdown.dirs._base.call(this,n);return this.addClass("drop-left"),t.missLeft==!0&&(t.left=t.left+this.outerWidth(),t.top=t.top+n.outerHeight(),this.removeClass("drop-left")),{left:t.left-this.outerWidth(),top:t.top}},right:function(n,t){var i=Foundation.libs.dropdown.dirs._base.call(this,n),r;return this.addClass("drop-right"),i.missRight==!0?(i.left=i.left-this.outerWidth(),i.top=i.top+n.outerHeight(),this.removeClass("drop-right")):i.triggeredRight=!0,r=Foundation.libs.dropdown,(n.outerWidth()<this.outerWidth()||r.small()||this.hasClass(t.mega_menu))&&r.adjust_pip(this,n,t,i),{left:i.left+n.outerWidth(),top:i.top}}},adjust_pip:function(n,t,i,r){var f=Foundation.stylesheet,u=8;n.hasClass(i.mega_class)?u=r.left+t.outerWidth()/2-8:this.small()&&(u+=r.left-8);this.rule_idx=f.cssRules.length;var e=".f-dropdown.open:before",o=".f-dropdown.open:after",s="left: "+u+"px;",h="left: "+(u-1)+"px;";r.missRight==!0&&(u=n.outerWidth()-23,e=".f-dropdown.open:before",o=".f-dropdown.open:after",s="left: "+u+"px;",h="left: "+(u-1)+"px;");r.triggeredRight==!0&&(e=".f-dropdown.open:before",o=".f-dropdown.open:after",s="left:-12px;",h="left:-14px;");f.insertRule?(f.insertRule([e,"{",s,"}"].join(" "),this.rule_idx),f.insertRule([o,"{",h,"}"].join(" "),this.rule_idx+1)):(f.addRule(e,s,this.rule_idx),f.addRule(o,h,this.rule_idx+1))},clear_idx:function(){var n=Foundation.stylesheet;typeof this.rule_idx!="undefined"&&(n.deleteRule(this.rule_idx),n.deleteRule(this.rule_idx),delete this.rule_idx)},small:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},off:function(){this.S(this.scope).off(".fndtn.dropdown");this.S("html, body").off(".fndtn.dropdown");this.S(t).off(".fndtn.dropdown");this.S("[data-dropdown-content]").off(".fndtn.dropdown")},reflow:function(){}}}(jQuery,window,window.document),function(n,t,i,r){"use strict";Foundation.libs.clearing={name:"clearing",version:"5.5.1",settings:{templates:{viewing:'<a href="#" class="clearing-close">&times;<\/a><div class="visible-img" style="display: none"><div class="clearing-touch-label"><\/div><img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" alt="" /><p class="clearing-caption"><\/p><a href="#" class="clearing-main-prev"><span><\/span><\/a><a href="#" class="clearing-main-next"><span><\/span><\/a><\/div>'},close_selectors:".clearing-close, div.clearing-blackout",open_selectors:"",skip_selector:"",touch_label:"",init:!1,locked:!1},init:function(n,t,i){var r=this;Foundation.inherit(this,"throttle image_loaded");this.bindings(t,i);r.S(this.scope).is("["+this.attr_name()+"]")?this.assemble(r.S("li",this.scope)):r.S("["+this.attr_name()+"]",this.scope).each(function(){r.assemble(r.S("li",this))})},events:function(r){var u=this,f=u.S,e=n(".scroll-container");e.length>0&&(this.scope=e);f(this.scope).off(".clearing").on("click.fndtn.clearing","ul["+this.attr_name()+"] li "+this.settings.open_selectors,function(n,t,i){var t=t||f(this),i=i||t,r=t.next("li"),e=t.closest("["+u.attr_name()+"]").data(u.attr_name(!0)+"-init"),o=f(n.target);n.preventDefault();e||(u.init(),e=t.closest("["+u.attr_name()+"]").data(u.attr_name(!0)+"-init"));i.hasClass("visible")&&t[0]===i[0]&&r.length>0&&u.is_open(t)&&(i=r,o=f("img",i));u.open(o,t,i);u.update_paddles(i)}).on("click.fndtn.clearing",".clearing-main-next",function(n){u.nav(n,"next")}).on("click.fndtn.clearing",".clearing-main-prev",function(n){u.nav(n,"prev")}).on("click.fndtn.clearing",this.settings.close_selectors,function(n){Foundation.libs.clearing.close(n,this)});n(i).on("keydown.fndtn.clearing",function(n){u.keydown(n)});f(t).off(".clearing").on("resize.fndtn.clearing",function(){u.resize()});this.swipe_events(r)},swipe_events:function(){var t=this,n=t.S;n(this.scope).on("touchstart.fndtn.clearing",".visible-img",function(t){t.touches||(t=t.originalEvent);var i={start_page_x:t.touches[0].pageX,start_page_y:t.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};n(this).data("swipe-transition",i);t.stopPropagation()}).on("touchmove.fndtn.clearing",".visible-img",function(i){var r,u;(i.touches||(i=i.originalEvent),i.touches.length>1||i.scale&&i.scale!==1)||(r=n(this).data("swipe-transition"),typeof r=="undefined"&&(r={}),r.delta_x=i.touches[0].pageX-r.start_page_x,Foundation.rtl&&(r.delta_x=-r.delta_x),typeof r.is_scrolling=="undefined"&&(r.is_scrolling=!!(r.is_scrolling||Math.abs(r.delta_x)<Math.abs(i.touches[0].pageY-r.start_page_y))),r.is_scrolling||r.active||(i.preventDefault(),u=r.delta_x<0?"next":"prev",r.active=!0,t.nav(i,u)))}).on("touchend.fndtn.clearing",".visible-img",function(t){n(this).data("swipe-transition",{});t.stopPropagation()})},assemble:function(t){var i=t.parent(),r,u;if(!i.parent().hasClass("carousel")&&(i.after('<div id="foundationClearingHolder"><\/div>'),r=i.detach(),u="",r[0]!=null)){u=r[0].outerHTML;var o=this.S("#foundationClearingHolder"),s=i.data(this.attr_name(!0)+"-init"),e={grid:'<div class="carousel">'+u+"<\/div>",viewing:s.templates.viewing},f='<div class="clearing-assembled"><div>'+e.viewing+e.grid+"<\/div><\/div>",h=this.settings.touch_label;Modernizr.touch&&(f=n(f).find(".clearing-touch-label").html(h).end());o.after(f).remove()}},open:function(t,r,u){function l(){setTimeout(function(){this.image_loaded(o,function(){o.outerWidth()!==1||c?y.call(this,o):l.call(this)}.bind(this))}.bind(this),100)}function y(t){var i=n(t);i.css("visibility","visible");a.css("overflow","hidden");h.addClass("clearing-blackout");s.addClass("clearing-container");e.show();this.fix_height(u).caption(f.S(".clearing-caption",e),f.S("img",u)).center_and_label(t,v).shift(r,u,function(){u.closest("li").siblings().removeClass("visible");u.closest("li").addClass("visible")});e.trigger("opened.fndtn.clearing")}var f=this,a=n(i.body),h=u.closest(".clearing-assembled"),s=f.S("div",h).first(),e=f.S(".visible-img",s),o=f.S("img",e).not(t),v=f.S(".clearing-touch-label",s),c=!1;n("body").on("touchmove",function(n){n.preventDefault()});o.error(function(){c=!0});this.locked()||(e.trigger("open.fndtn.clearing"),o.attr("src",this.load(t)).css("visibility","hidden"),l.call(this))},close:function(t,r){t.preventDefault();var f=function(n){return/blackout/.test(n.selector)?n:n.closest(".clearing-blackout")}(n(r)),o=n(i.body),e,u;return r===t.target&&f&&(o.css("overflow",""),e=n("div",f).first(),u=n(".visible-img",e),u.trigger("close.fndtn.clearing"),this.settings.prev_index=0,n("ul["+this.attr_name()+"]",f).attr("style","").closest(".clearing-blackout").removeClass("clearing-blackout"),e.removeClass("clearing-container"),u.hide(),u.trigger("closed.fndtn.clearing")),n("body").off("touchmove"),!1},is_open:function(n){return n.parent().prop("style").length>0},keydown:function(t){var i=n(".clearing-blackout ul["+this.attr_name()+"]"),r=this.rtl?37:39,u=this.rtl?39:37;t.which===r&&this.go(i,"next");t.which===u&&this.go(i,"prev");t.which===27&&this.S("a.clearing-close").trigger("click").trigger("click.fndtn.clearing")},nav:function(t,i){var r=n("ul["+this.attr_name()+"]",".clearing-blackout");t.preventDefault();this.go(r,i)},resize:function(){var t=n("img",".clearing-blackout .visible-img"),i=n(".clearing-touch-label",".clearing-blackout");t.length&&(this.center_and_label(t,i),t.trigger("resized.fndtn.clearing"))},fix_height:function(n){var t=n.parent().children(),i=this;return t.each(function(){var n=i.S(this),t=n.find("img");n.height()>t.outerHeight()&&n.addClass("fix-height")}).closest("ul").width(t.length*100+"%"),this},update_paddles:function(n){n=n.closest("li");var t=n.closest(".carousel").siblings(".visible-img");n.next().length>0?this.S(".clearing-main-next",t).removeClass("disabled"):this.S(".clearing-main-next",t).addClass("disabled");n.prev().length>0?this.S(".clearing-main-prev",t).removeClass("disabled"):this.S(".clearing-main-prev",t).addClass("disabled")},center_and_label:function(n,t){return!this.rtl&&t.length>0?t.css({marginLeft:-(t.outerWidth()/2),marginTop:-(n.outerHeight()/2)-t.outerHeight()-10}):t.css({marginRight:-(t.outerWidth()/2),marginTop:-(n.outerHeight()/2)-t.outerHeight()-10,left:"auto",right:"50%"}),this},load:function(n){var t;return(t=n[0].nodeName==="A"?n.attr("href"):n.closest("a").attr("href"),this.preload(n),t)?t:n.attr("src")},preload:function(n){this.img(n.closest("li").next()).img(n.closest("li").prev())},img:function(n){if(n.length){var i=new Image,t=this.S("a",n);i.src=t.length?t.attr("href"):this.S("img",n).attr("src")}return this},caption:function(n,t){var i=t.attr("data-caption");return i?n.html(i).show():n.text("").hide(),this},go:function(n,t){var r=this.S(".visible",n),i=r[t]();this.settings.skip_selector&&i.find(this.settings.skip_selector).length!=0&&(i=i[t]());i.length&&this.S("img",i).trigger("click",[r,i]).trigger("click.fndtn.clearing",[r,i]).trigger("change.fndtn.clearing")},shift:function(n,t,i){var u=t.parent(),c=this.settings.prev_index||t.index(),f=this.direction(u,n,t),e=this.rtl?"right":"left",h=parseInt(u.css("left"),10),o=t.outerWidth(),s,r={};t.index()===c||/skip/.test(f)?/skip/.test(f)&&(s=t.index()-this.settings.up_count,this.lock(),s>0?(r[e]=-(s*o),u.animate(r,300,this.unlock())):(r[e]=0,u.animate(r,300,this.unlock()))):/left/.test(f)?(this.lock(),r[e]=h+o,u.animate(r,300,this.unlock())):/right/.test(f)&&(this.lock(),r[e]=h-o,u.animate(r,300,this.unlock()));i()},direction:function(n,t,i){var u=this.S("li",n),o=u.outerWidth()+u.outerWidth()/4,f=Math.floor(this.S(".clearing-container").outerWidth()/o)-1,r=u.index(i),e;return this.settings.up_count=f,e=this.adjacent(this.settings.prev_index,r)?r>f&&r>this.settings.prev_index?"right":r>f-1&&r<=this.settings.prev_index?"left":!1:"skip",this.settings.prev_index=r,e},adjacent:function(n,t){for(var i=t+1;i>=t-1;i--)if(i===n)return!0;return!1},lock:function(){this.settings.locked=!0},unlock:function(){this.settings.locked=!1},locked:function(){return this.settings.locked},off:function(){this.S(this.scope).off(".fndtn.clearing");this.S(t).off(".fndtn.clearing")},reflow:function(){this.init()}}}(jQuery,window,window.document),function(n,t,i,r){"use strict";var u=function(){},f=function(u,f){if(u.hasClass(f.slides_container_class))return this;var h=this,c,l=u,p,y,w,v=0,b,a,k=!1;h.slides=function(){return l.children(f.slide_selector)};h.slides().first().addClass(f.active_slide_class);h.update_slide_number=function(t){f.slide_number&&(p.find("span:first").text(parseInt(t)+1),p.find("span:last").text(h.slides().length));f.bullets&&(y.children().removeClass(f.bullets_active_class),n(y.children().get(t)).addClass(f.bullets_active_class))};h.update_active_link=function(t){var i=n('[data-orbit-link="'+h.slides().eq(t).attr("data-orbit-slide")+'"]');i.siblings().removeClass(f.bullets_active_class);i.addClass(f.bullets_active_class)};h.build_markup=function(){l.wrap('<div class="'+f.container_class+'"><\/div>');c=l.parent();l.addClass(f.slides_container_class);f.stack_on_small&&c.addClass(f.stack_on_small_class);f.navigation_arrows&&(c.append(n('<a href="#"><span><\/span><\/a>').addClass(f.prev_class)),c.append(n('<a href="#"><span><\/span><\/a>').addClass(f.next_class)));f.timer&&(w=n("<div>").addClass(f.timer_container_class),w.append("<span>"),w.append(n("<div>").addClass(f.timer_progress_class)),w.addClass(f.timer_paused_class),c.append(w));f.slide_number&&(p=n("<div>").addClass(f.slide_number_class),p.append("<span><\/span> "+f.slide_number_text+" <span><\/span>"),c.append(p));f.bullets&&(y=n("<ol>").addClass(f.bullets_container_class),c.append(y),y.wrap('<div class="orbit-bullets-container"><\/div>'),h.slides().each(function(t){var i=n("<li>").attr("data-orbit-slide",t).on("click",h.link_bullet);y.append(i)}))};h._goto=function(t,i){var r,o,e,u,s,c;if(t===v)return!1;if(typeof a=="object"&&a.restart(),r=h.slides(),o="next",k=!0,t<v&&(o="prev"),t>=r.length){if(!f.circular)return!1;t=0}else if(t<0){if(!f.circular)return!1;t=r.length-1}if(e=n(r.get(v)),u=n(r.get(t)),e.css("zIndex",2),e.removeClass(f.active_slide_class),u.css("zIndex",4).addClass(f.active_slide_class),l.trigger("before-slide-change.fndtn.orbit"),f.before_slide_change(),h.update_active_link(t),s=function(){var n=function(){v=t;k=!1;i===!0&&(a=h.create_timer(),a.start());h.update_slide_number(v);l.trigger("after-slide-change.fndtn.orbit",[{slide_number:v,total_slides:r.length}]);f.after_slide_change(v,r.length)};l.outerHeight()!=u.outerHeight()&&f.variable_height?l.animate({height:u.outerHeight()},250,"linear",n):n()},r.length===1)return s(),!1;c=function(){o==="next"&&b.next(e,u,s);o==="prev"&&b.prev(e,u,s)};u.outerHeight()>l.outerHeight()&&f.variable_height?l.animate({height:u.outerHeight()},250,"linear",c):c()};h.next=function(n){n.stopImmediatePropagation();n.preventDefault();h._goto(v+1)};h.prev=function(n){n.stopImmediatePropagation();n.preventDefault();h._goto(v-1)};h.link_custom=function(t){var i,r;t.preventDefault();i=n(this).attr("data-orbit-link");typeof i=="string"&&(i=n.trim(i))!=""&&(r=c.find("[data-orbit-slide="+i+"]"),r.index()!=-1&&h._goto(r.index()))};h.link_bullet=function(){var t=n(this).attr("data-orbit-slide"),i;typeof t=="string"&&(t=n.trim(t))!=""&&(isNaN(parseInt(t))?(i=c.find("[data-orbit-slide="+t+"]"),i.index()!=-1&&h._goto(i.index()+1)):h._goto(parseInt(t)))};h.timer_callback=function(){h._goto(v+1,!0)};h.compute_dimensions=function(){var i=n(h.slides().get(v)),t=i.outerHeight();f.variable_height||h.slides().each(function(){n(this).outerHeight()>t&&(t=n(this).outerHeight())});l.height(t)};h.create_timer=function(){return new e(c.find("."+f.timer_container_class),f,h.timer_callback)};h.stop_timer=function(){typeof a=="object"&&a.stop()};h.toggle_timer=function(){var n=c.find("."+f.timer_container_class);n.hasClass(f.timer_paused_class)?(typeof a=="undefined"&&(a=h.create_timer()),a.start()):typeof a=="object"&&a.stop()};h.init=function(){h.build_markup();f.timer&&(a=h.create_timer(),Foundation.utils.image_loaded(this.slides().children("img"),a.start));b=new s(f,l);f.animation==="slide"&&(b=new o(f,l));c.on("click","."+f.next_class,h.next);c.on("click","."+f.prev_class,h.prev);if(f.next_on_click)c.on("click","."+f.slides_container_class+" [data-orbit-slide]",h.link_bullet);c.on("click",h.toggle_timer);if(f.swipe)c.on("touchstart.fndtn.orbit",function(n){n.touches||(n=n.originalEvent);var t={start_page_x:n.touches[0].pageX,start_page_y:n.touches[0].pageY,start_time:(new Date).getTime(),delta_x:0,is_scrolling:r};c.data("swipe-transition",t);n.stopPropagation()}).on("touchmove.fndtn.orbit",function(n){var t,i;(n.touches||(n=n.originalEvent),n.touches.length>1||n.scale&&n.scale!==1)||(t=c.data("swipe-transition"),typeof t=="undefined"&&(t={}),t.delta_x=n.touches[0].pageX-t.start_page_x,typeof t.is_scrolling=="undefined"&&(t.is_scrolling=!!(t.is_scrolling||Math.abs(t.delta_x)<Math.abs(n.touches[0].pageY-t.start_page_y))),t.is_scrolling||t.active||(n.preventDefault(),i=t.delta_x<0?v+1:v-1,t.active=!0,h._goto(i)))}).on("touchend.fndtn.orbit",function(n){c.data("swipe-transition",{});n.stopPropagation()});c.on("mouseenter.fndtn.orbit",function(){f.timer&&f.pause_on_hover&&h.stop_timer()}).on("mouseleave.fndtn.orbit",function(){f.timer&&f.resume_on_mouseout&&a.start()});n(i).on("click","[data-orbit-link]",h.link_custom);n(t).on("load resize",h.compute_dimensions);Foundation.utils.image_loaded(this.slides().children("img"),h.compute_dimensions);Foundation.utils.image_loaded(this.slides().children("img"),function(){c.prev("."+f.preloader_class).css("display","none");h.update_slide_number(0);h.update_active_link(0);l.trigger("ready.fndtn.orbit")})};h.init()},e=function(n,t,i){var f=this,o=t.timer_speed,u=n.find("."+t.timer_progress_class),s,e,r=-1;this.update_progress=function(n){var t=u.clone();t.attr("style","");t.css("width",n+"%");u.replaceWith(t);u=t};this.restart=function(){clearTimeout(e);n.addClass(t.timer_paused_class);r=-1;f.update_progress(0)};this.start=function(){if(!n.hasClass(t.timer_paused_class))return!0;r=r===-1?o:r;n.removeClass(t.timer_paused_class);s=(new Date).getTime();u.animate({width:"100%"},r,"linear");e=setTimeout(function(){f.restart();i()},r);n.trigger("timer-started.fndtn.orbit")};this.stop=function(){var i,u;if(n.hasClass(t.timer_paused_class))return!0;clearTimeout(e);n.addClass(t.timer_paused_class);i=(new Date).getTime();r=r-(i-s);u=100-r/o*100;f.update_progress(u);n.trigger("timer-stopped.fndtn.orbit")}},o=function(t){var i=t.animation_speed,f=n("html[dir=rtl]").length===1,r=f?"marginRight":"marginLeft",u={};u[r]="0%";this.next=function(n,t,f){n.animate({marginLeft:"-100%"},i);t.animate(u,i,function(){n.css(r,"100%");f()})};this.prev=function(n,t,f){n.animate({marginLeft:"100%"},i);t.css(r,"-100%");t.animate(u,i,function(){n.css(r,"100%");f()})}},s=function(t){var i=t.animation_speed,r=n("html[dir=rtl]").length===1,u=r?"marginRight":"marginLeft";this.next=function(n,t,r){t.css({margin:"0%",opacity:"0.01"});t.animate({opacity:"1"},i,"linear",function(){n.css("margin","100%");r()})};this.prev=function(n,t,r){t.css({margin:"0%",opacity:"0.01"});t.animate({opacity:"1"},i,"linear",function(){n.css("margin","100%");r()})}};Foundation.libs=Foundation.libs||{};Foundation.libs.orbit={name:"orbit",version:"5.5.1",settings:{animation:"slide",timer_speed:1e4,pause_on_hover:!0,resume_on_mouseout:!1,next_on_click:!0,animation_speed:500,stack_on_small:!1,navigation_arrows:!0,slide_number:!0,slide_number_text:"of",container_class:"orbit-container",stack_on_small_class:"orbit-stack-on-small",next_class:"orbit-next",prev_class:"orbit-prev",timer_container_class:"orbit-timer",timer_paused_class:"paused",timer_progress_class:"orbit-progress",slides_container_class:"orbit-slides-container",preloader_class:"preloader",slide_selector:"*",bullets_container_class:"orbit-bullets",bullets_active_class:"active",slide_number_class:"orbit-slide-number",caption_class:"orbit-caption",active_slide_class:"active",orbit_transition_class:"orbit-transitioning",bullets:!0,circular:!0,timer:!0,variable_height:!1,swipe:!0,before_slide_change:u,after_slide_change:u},init:function(n,t,i){var r=this;this.bindings(t,i)},events:function(n){var t=new f(this.S(n),this.S(n).data("orbit-init"));this.S(n).data(this.name+"-instance",t)},reflow:function(){var n=this,t,i;n.S(n.scope).is("[data-orbit]")?(t=n.S(n.scope),i=t.data(n.name+"-instance"),i.compute_dimensions()):n.S("[data-orbit]",n.scope).each(function(t,i){var r=n.S(i),f=n.data_options(r),u=r.data(n.name+"-instance");u.compute_dimensions()})}}}(jQuery,window,window.document),function(n){"use strict";Foundation.libs.offcanvas={name:"offcanvas",version:"5.5.1",settings:{open_method:"move",close_on_click:!1},init:function(n,t,i){this.bindings(t,i)},events:function(){var i=this,f=i.S,t="",r="",u="";this.settings.open_method==="move"?(t="move-",r="right",u="left"):this.settings.open_method==="overlap_single"?(t="offcanvas-overlap-",r="right",u="left"):this.settings.open_method==="overlap"&&(t="offcanvas-overlap");f(this.scope).off(".offcanvas").on("click.fndtn.offcanvas",".left-off-canvas-toggle",function(u){i.click_toggle_class(u,t+r);i.settings.open_method!=="overlap"&&f(".left-submenu").removeClass(t+r);n(".left-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".left-off-canvas-menu a",function(u){var o=i.get_settings(u),e=f(this).parent();!o.close_on_click||e.hasClass("has-submenu")||e.hasClass("back")?f(this).parent().hasClass("has-submenu")?(u.preventDefault(),f(this).siblings(".left-submenu").toggleClass(t+r)):e.hasClass("back")&&(u.preventDefault(),e.parent().removeClass(t+r)):(i.hide.call(i,t+r,i.get_wrapper(u)),e.parent().removeClass(t+r));n(".left-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".right-off-canvas-toggle",function(r){i.click_toggle_class(r,t+u);i.settings.open_method!=="overlap"&&f(".right-submenu").removeClass(t+u);n(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".right-off-canvas-menu a",function(r){var o=i.get_settings(r),e=f(this).parent();!o.close_on_click||e.hasClass("has-submenu")||e.hasClass("back")?f(this).parent().hasClass("has-submenu")?(r.preventDefault(),f(this).siblings(".right-submenu").toggleClass(t+u)):e.hasClass("back")&&(r.preventDefault(),e.parent().removeClass(t+u)):(i.hide.call(i,t+u,i.get_wrapper(r)),e.parent().removeClass(t+u));n(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".exit-off-canvas",function(e){i.click_remove_class(e,t+u);f(".right-submenu").removeClass(t+u);r&&(i.click_remove_class(e,t+r),f(".left-submenu").removeClass(t+u));n(".right-off-canvas-toggle").attr("aria-expanded","true")}).on("click.fndtn.offcanvas",".exit-off-canvas",function(f){i.click_remove_class(f,t+u);n(".left-off-canvas-toggle").attr("aria-expanded","false");r&&(i.click_remove_class(f,t+r),n(".right-off-canvas-toggle").attr("aria-expanded","false"))})},toggle:function(n,t){t=t||this.get_wrapper();t.is("."+n)?this.hide(n,t):this.show(n,t)},show:function(n,t){t=t||this.get_wrapper();t.trigger("open").trigger("open.fndtn.offcanvas");t.addClass(n)},hide:function(n,t){t=t||this.get_wrapper();t.trigger("close").trigger("close.fndtn.offcanvas");t.removeClass(n)},click_toggle_class:function(n,t){n.preventDefault();var i=this.get_wrapper(n);this.toggle(t,i)},click_remove_class:function(n,t){n.preventDefault();var i=this.get_wrapper(n);this.hide(t,i)},get_settings:function(n){var t=this.S(n.target).closest("["+this.attr_name()+"]");return t.data(this.attr_name(!0)+"-init")||this.settings},get_wrapper:function(n){var t=this.S(n?n.target:this.scope).closest(".off-canvas-wrap");return t.length===0&&(t=this.S(".off-canvas-wrap")),t},reflow:function(){}}}(jQuery,window,window.document),function(n){"use strict";Foundation.libs.alert={name:"alert",version:"5.5.1",settings:{callback:function(){}},init:function(n,t,i){this.bindings(t,i)},events:function(){var t=this,i=this.S;n(this.scope).off(".alert").on("click.fndtn.alert","["+this.attr_name()+"] .close",function(n){var r=i(this).closest("["+t.attr_name()+"]"),u=r.data(t.attr_name(!0)+"-init")||t.settings;if(n.preventDefault(),Modernizr.csstransitions){r.addClass("alert-close");r.on("transitionend webkitTransitionEnd oTransitionEnd",function(){i(this).trigger("close").trigger("close.fndtn.alert").remove();u.callback()})}else r.fadeOut(300,function(){i(this).trigger("close").trigger("close.fndtn.alert").remove();u.callback()})})},reflow:function(){}}}(jQuery,window,window.document),function(n,t,i,r){"use strict";function u(n){var t=/fade/i.test(n),i=/pop/i.test(n);return{animate:t||i,pop:i,fade:t}}Foundation.libs.reveal={name:"reveal",version:"5.5.1",locked:!1,settings:{animation:"fadeAndPop",animation_speed:250,close_on_background_click:!0,close_on_esc:!0,dismiss_modal_class:"close-reveal-modal",multiple_opened:!1,bg_class:"reveal-modal-bg",root_element:"body",open:function(){},opened:function(){},close:function(){},closed:function(){},bg:n(".reveal-modal-bg"),css:{open:{opacity:0,visibility:"visible",display:"block"},close:{opacity:1,visibility:"hidden",display:"none"}}},init:function(t,i,r){n.extend(!0,this.settings,i,r);this.bindings(i,r)},events:function(){var n=this,t=n.S;t(this.scope).off(".reveal").on("click.fndtn.reveal","["+this.add_namespace("data-reveal-id")+"]:not([disabled])",function(i){var r,u,f;i.preventDefault();n.locked||(r=t(this),u=r.data(n.data_attr("reveal-ajax")),n.locked=!0,typeof u=="undefined"?n.open.call(n,r):(f=u===!0?r.attr("href"):u,n.open.call(n,r,{url:f})))});t(i).on("click.fndtn.reveal",this.close_targets(),function(i){if(i.preventDefault(),!n.locked){var r=t("["+n.attr_name()+"].open").data(n.attr_name(!0)+"-init")||n.settings,u=t(i.target)[0]===t("."+r.bg_class)[0];if(u)if(r.close_on_background_click)i.stopPropagation();else return;n.locked=!0;n.close.call(n,u?t("["+n.attr_name()+"].open"):t(this).closest("["+n.attr_name()+"]"))}});if(t("["+n.attr_name()+"]",this.scope).length>0)t(this.scope).on("open.fndtn.reveal",this.settings.open).on("opened.fndtn.reveal",this.settings.opened).on("opened.fndtn.reveal",this.open_video).on("close.fndtn.reveal",this.settings.close).on("closed.fndtn.reveal",this.settings.closed).on("closed.fndtn.reveal",this.close_video);else t(this.scope).on("open.fndtn.reveal","["+n.attr_name()+"]",this.settings.open).on("opened.fndtn.reveal","["+n.attr_name()+"]",this.settings.opened).on("opened.fndtn.reveal","["+n.attr_name()+"]",this.open_video).on("close.fndtn.reveal","["+n.attr_name()+"]",this.settings.close).on("closed.fndtn.reveal","["+n.attr_name()+"]",this.settings.closed).on("closed.fndtn.reveal","["+n.attr_name()+"]",this.close_video);return!0},key_up_on:function(){var n=this;n.S("body").off("keyup.fndtn.reveal").on("keyup.fndtn.reveal",function(t){var i=n.S("["+n.attr_name()+"].open"),r=i.data(n.attr_name(!0)+"-init")||n.settings;r&&t.which===27&&r.close_on_esc&&!n.locked&&n.close.call(n,i)});return!0},key_up_off:function(){return this.S("body").off("keyup.fndtn.reveal"),!0},open:function(i,r){var f=this,u,e,o,s;if(i?typeof i.selector!="undefined"?u=f.S("#"+i.data(f.data_attr("reveal-id"))).first():(u=f.S(this.scope),r=i):u=f.S(this.scope),e=u.data(f.attr_name(!0)+"-init"),e=e||this.settings,u.hasClass("open")&&i.attr("data-reveal-id")==u.attr("id"))return f.close(u);u.hasClass("open")||(o=f.S("["+f.attr_name()+"].open"),typeof u.data("css-top")=="undefined"&&u.data("css-top",parseInt(u.css("top"),10)).data("offset",this.cache_offset(u)),this.key_up_on(u),u.on("open.fndtn.reveal").trigger("open.fndtn.reveal"),o.length<1&&this.toggle_bg(u,!0),typeof r=="string"&&(r={url:r}),typeof r!="undefined"&&r.url?(s=typeof r.success!="undefined"?r.success:null,n.extend(r,{success:function(t,i,r){if(n.isFunction(s)){var h=s(t,i,r);typeof h=="string"&&(t=h)}u.html(t);f.S(u).foundation("section","reflow");f.S(u).children().foundation();o.length>0&&(e.multiple_opened?this.to_back(o):this.hide(o,e.css.close));f.show(u,e.css.open)}}),n.ajax(r)):(o.length>0&&(e.multiple_opened?this.to_back(o):this.hide(o,e.css.close)),this.show(u,e.css.open)));f.S(t).trigger("resize")},close:function(t){var t=t&&t.length?t:this.S(this.scope),r=this.S("["+this.attr_name()+"].open"),i=t.data(this.attr_name(!0)+"-init")||this.settings;r.length>0&&(this.locked=!0,this.key_up_off(t),t.trigger("close").trigger("close.fndtn.reveal"),(i.multiple_opened&&r.length===1||!i.multiple_opened||t.length>1)&&(this.toggle_bg(t,!1),this.to_front(t)),i.multiple_opened?(this.hide(t,i.css.close,i),this.to_front(n(n.makeArray(r).reverse()[1]))):this.hide(r,i.css.close,i))},close_targets:function(){var n="."+this.settings.dismiss_modal_class;return this.settings.close_on_background_click?n+", ."+this.settings.bg_class:n},toggle_bg:function(t,i){this.S("."+this.settings.bg_class).length===0&&(this.settings.bg=n("<div />",{"class":this.settings.bg_class}).appendTo("body").hide());var u=this.settings.bg.filter(":visible").length>0;i!=u&&((i==r?u:!i)?this.hide(this.settings.bg):this.show(this.settings.bg))},show:function(i,r){var s,h,e,o,f;if(r){if(f=i.data(this.attr_name(!0)+"-init")||this.settings,s=f.root_element,i.parent(s).length===0){h=i.wrap('<div style="display: none;" />').parent();i.on("closed.fndtn.reveal.wrapped",function(){i.detach().appendTo(h);i.unwrap().unbind("closed.fndtn.reveal.wrapped")});i.detach().appendTo(s)}return(e=u(f.animation),e.animate||(this.locked=!1),e.pop)?(r.top=n(t).scrollTop()-i.data("offset")+"px",o={top:n(t).scrollTop()+i.data("css-top")+"px",opacity:1},setTimeout(function(){return i.css(r).animate(o,f.animation_speed,"linear",function(){this.locked=!1;i.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),f.animation_speed/2)):e.fade?(r.top=n(t).scrollTop()+i.data("css-top")+"px",o={opacity:1},setTimeout(function(){return i.css(r).animate(o,f.animation_speed,"linear",function(){this.locked=!1;i.trigger("opened").trigger("opened.fndtn.reveal")}.bind(this)).addClass("open")}.bind(this),f.animation_speed/2)):i.css(r).show().css({opacity:1}).addClass("open").trigger("opened").trigger("opened.fndtn.reveal")}return(f=this.settings,u(f.animation).fade)?i.fadeIn(f.animation_speed/2):(this.locked=!1,i.show())},to_back:function(n){n.addClass("toback")},to_front:function(n){n.removeClass("toback")},hide:function(i,r){var e,o,f;return r?(f=i.data(this.attr_name(!0)+"-init"),f=f||this.settings,e=u(f.animation),e.animate||(this.locked=!1),e.pop)?(o={top:-n(t).scrollTop()-i.data("offset")+"px",opacity:0},setTimeout(function(){return i.animate(o,f.animation_speed,"linear",function(){this.locked=!1;i.css(r).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),f.animation_speed/2)):e.fade?(o={opacity:0},setTimeout(function(){return i.animate(o,f.animation_speed,"linear",function(){this.locked=!1;i.css(r).trigger("closed").trigger("closed.fndtn.reveal")}.bind(this)).removeClass("open")}.bind(this),f.animation_speed/2)):i.hide().css(r).removeClass("open").trigger("closed").trigger("closed.fndtn.reveal"):(f=this.settings,u(f.animation).fade)?i.fadeOut(f.animation_speed/2):i.hide()},close_video:function(t){var r=n(".flex-video",t.target),i=n("iframe",r);i.length>0&&(i.attr("data-src",i[0].src),i.attr("src",i.attr("src")),r.hide())},open_video:function(t){var u=n(".flex-video",t.target),i=u.find("iframe"),f,e;i.length>0&&(f=i.attr("data-src"),typeof f=="string"?i[0].src=i.attr("data-src"):(e=i[0].src,i[0].src=r,i[0].src=e),u.show())},data_attr:function(n){return this.namespace.length>0?this.namespace+"-"+n:n},cache_offset:function(n){var t=n.show().height()+parseInt(n.css("top"),10);return n.hide(),t},off:function(){n(this.scope).off(".fndtn.reveal")},reflow:function(){}}}(jQuery,window,window.document),function(n,t){"use strict";Foundation.libs.interchange={name:"interchange",version:"5.5.1",cache:{},images_loaded:!1,nodes_loaded:!1,settings:{load_attr:"interchange",named_queries:{"default":"only screen",small:Foundation.media_queries.small,"small-only":Foundation.media_queries["small-only"],medium:Foundation.media_queries.medium,"medium-only":Foundation.media_queries["medium-only"],large:Foundation.media_queries.large,"large-only":Foundation.media_queries["large-only"],xlarge:Foundation.media_queries.xlarge,"xlarge-only":Foundation.media_queries["xlarge-only"],xxlarge:Foundation.media_queries.xxlarge,landscape:"only screen and (orientation: landscape)",portrait:"only screen and (orientation: portrait)",retina:"only screen and (-webkit-min-device-pixel-ratio: 2),only screen and (min--moz-device-pixel-ratio: 2),only screen and (-o-min-device-pixel-ratio: 2/1),only screen and (min-device-pixel-ratio: 2),only screen and (min-resolution: 192dpi),only screen and (min-resolution: 2dppx)"},directives:{replace:function(t,i,r){var u,f,e;return/IMG/.test(t[0].nodeName)?(u=t[0].src,new RegExp(i,"i").test(u))?void 0:(t[0].src=i,r(t[0].src)):(f=t.data(this.data_attr+"-last-path"),e=this,f==i)?void 0:/\.(gif|jpg|jpeg|tiff|png)([?#].*)?/i.test(i)?(n(t).css("background-image","url("+i+")"),t.data("interchange-last-path",i),r(i)):n.get(i,function(n){t.html(n);t.data(e.data_attr+"-last-path",i);r()})}}},init:function(t,i,r){Foundation.inherit(this,"throttle random_str");this.data_attr=this.set_data_attr();n.extend(!0,this.settings,i,r);this.bindings(i,r);this.load("images");this.load("nodes")},get_media_hash:function(){var n="";for(var t in this.settings.named_queries)n+=matchMedia(this.settings.named_queries[t]).matches.toString();return n},events:function(){var i=this,r;n(t).off(".interchange").on("resize.fndtn.interchange",i.throttle(function(){var n=i.get_media_hash();n!==r&&i.resize();r=n},50));return this},resize:function(){var r=this.cache,i,t;if(!this.images_loaded||!this.nodes_loaded){setTimeout(n.proxy(this.resize,this),50);return}for(i in r)r.hasOwnProperty(i)&&(t=this.results(i,r[i]),t&&this.settings.directives[t.scenario[1]].call(this,t.el,t.scenario[0],function(n){var t;return t=arguments[0]instanceof Array?arguments[0]:Array.prototype.slice.call(arguments,0),function(){n.el.trigger(n.scenario[1],t)}}(t)))},results:function(n,t){var i=t.length,u,f,r;if(i>0)for(u=this.S("["+this.add_namespace("data-uuid")+'="'+n+'"]');i--;)if(r=t[i][2],f=this.settings.named_queries.hasOwnProperty(r)?matchMedia(this.settings.named_queries[r]):matchMedia(r),f.matches)return{el:u,scenario:t[i]};return!1},load:function(n,t){return(typeof this["cached_"+n]=="undefined"||t)&&this["update_"+n](),this["cached_"+n]},update_images:function(){var n=this.S("img["+this.data_attr+"]"),i=n.length,t=i,r=0,f=this.data_attr,u;for(this.cache={},this.cached_images=[],this.images_loaded=i===0;t--;)r++,n[t]&&(u=n[t].getAttribute(f)||"",u.length>0&&this.cached_images.push(n[t])),r===i&&(this.images_loaded=!0,this.enhance("images"));return this},update_nodes:function(){var n=this.S("["+this.data_attr+"]").not("img"),t=n.length,i=t,r=0,f=this.data_attr,u;for(this.cached_nodes=[],this.nodes_loaded=t===0;i--;)r++,u=n[i].getAttribute(f)||"",u.length>0&&this.cached_nodes.push(n[i]),r===t&&(this.nodes_loaded=!0,this.enhance("nodes"));return this},enhance:function(i){for(var r=this["cached_"+i].length;r--;)this.object(n(this["cached_"+i][r]));return n(t).trigger("resize").trigger("resize.fndtn.interchange")},convert_directive:function(n){var t=this.trim(n);return t.length>0?t:"replace"},parse_scenario:function(n){var t=n[0].match(/(.+),\s*(\w+)\s*$/),u=n[1],i,r;if(t)i=t[1],r=t[2];else var f=n[0].split(/,\s*$/),i=f[0],r="";return[this.trim(i),this.convert_directive(r),this.trim(u)]},object:function(n){var r=this.parse_data_attr(n),u=[],t=r.length,i,f;if(t>0)while(t--)i=r[t].split(/\(([^\)]*?)(\))$/),i.length>1&&(f=this.parse_scenario(i),u.push(f));return this.store(n,u)},store:function(n,t){var i=this.random_str(),r=n.data(this.add_namespace("uuid",!0));return this.cache[r]?this.cache[r]:(n.attr(this.add_namespace("data-uuid"),i),this.cache[i]=t)},trim:function(t){return typeof t=="string"?n.trim(t):t},set_data_attr:function(n){return n?this.namespace.length>0?this.namespace+"-"+this.settings.load_attr:this.settings.load_attr:this.namespace.length>0?"data-"+this.namespace+"-"+this.settings.load_attr:"data-"+this.settings.load_attr},parse_data_attr:function(n){for(var t=n.attr(this.attr_name()).split(/\[(.*?)\]/),i=t.length,r=[];i--;)t[i].replace(/[\W\d]+/,"").length>4&&r.push(t[i]);return r},reflow:function(){this.load("images",!0);this.load("nodes",!0)}}}(jQuery,window,window.document),function(n,t){"use strict";Foundation.libs["magellan-expedition"]={name:"magellan-expedition",version:"5.5.1",settings:{active_class:"active",threshold:0,destination_threshold:20,throttle_delay:30,fixed_top:0,offset_by_height:!0,duration:700,easing:"swing"},init:function(n,t,i){Foundation.inherit(this,"throttle");this.bindings(t,i)},events:function(){var i=this,u=i.S,r=i.settings;i.set_expedition_position();u(i.scope).off(".magellan").on("click.fndtn.magellan","["+i.add_namespace("data-magellan-arrival")+'] a[href^="#"]',function(t){var f;t.preventDefault();var o=n(this).closest("["+i.attr_name()+"]"),r=o.data("magellan-expedition-init"),u=this.hash.split("#").join(""),e=n('a[name="'+u+'"]');e.length===0&&(e=n("#"+u));f=e.offset().top-r.destination_threshold+1;r.offset_by_height&&(f=f-o.outerHeight());n("html, body").stop().animate({scrollTop:f},r.duration,r.easing,function(){history.pushState?history.pushState(null,null,"#"+u):location.hash="#"+u})}).on("scroll.fndtn.magellan",i.throttle(this.check_for_arrivals.bind(this),r.throttle_delay));n(t).on("resize.fndtn.magellan",i.throttle(this.set_expedition_position.bind(this),r.throttle_delay))},check_for_arrivals:function(){var n=this;n.update_arrivals();n.update_expedition_positions()},set_expedition_position:function(){var t=this;n("["+this.attr_name()+"=fixed]",t.scope).each(function(){var i=n(this),f=i.data("magellan-expedition-init"),e=i.attr("styles"),u,r;i.attr("style","");u=i.offset().top+f.threshold;r=parseInt(i.data("magellan-fixed-top"));isNaN(r)||(t.settings.fixed_top=r);i.data(t.data_attr("magellan-top-offset"),u);i.attr("style",e)})},update_expedition_positions:function(){var i=this,r=n(t).scrollTop();n("["+this.attr_name()+"=fixed]",i.scope).each(function(){var t=n(this),f=t.data("magellan-expedition-init"),e=t.attr("style"),o=t.data("magellan-top-offset"),u;r+i.settings.fixed_top>=o?(u=t.prev("["+i.add_namespace("data-magellan-expedition-clone")+"]"),u.length===0&&(u=t.clone(),u.removeAttr(i.attr_name()),u.attr(i.add_namespace("data-magellan-expedition-clone"),""),t.before(u)),t.css({position:"fixed",top:f.fixed_top}).addClass("fixed")):(t.prev("["+i.add_namespace("data-magellan-expedition-clone")+"]").remove(),t.attr("style",e).css("position","").css("top","").removeClass("fixed"))})},update_arrivals:function(){var i=this,r=n(t).scrollTop();n("["+this.attr_name()+"]",i.scope).each(function(){var t=n(this),u=t.data(i.attr_name(!0)+"-init"),e=i.offsets(t,r),o=t.find("["+i.add_namespace("data-magellan-arrival")+"]"),f=!1;e.each(function(n,r){if(r.viewport_offset>=r.top_offset){var e=t.find("["+i.add_namespace("data-magellan-arrival")+"]");return e.not(r.arrival).removeClass(u.active_class),r.arrival.addClass(u.active_class),f=!0,!0}});f||o.removeClass(u.active_class)})},offsets:function(t,i){var r=this,u=t.data(r.attr_name(!0)+"-init"),f=i;return t.find("["+r.add_namespace("data-magellan-arrival")+"]").map(function(){var o=n(this).data(r.data_attr("magellan-arrival")),e=n("["+r.add_namespace("data-magellan-destination")+"="+o+"]"),i;if(e.length>0)return i=e.offset().top-u.destination_threshold,u.offset_by_height&&(i=i-t.outerHeight()),i=Math.floor(i),{destination:e,arrival:n(this),top_offset:i,viewport_offset:f}}).sort(function(n,t){return n.top_offset<t.top_offset?-1:n.top_offset>t.top_offset?1:0})},data_attr:function(n){return this.namespace.length>0?this.namespace+"-"+n:n},off:function(){this.S(this.scope).off(".magellan");this.S(t).off(".magellan")},reflow:function(){var t=this;n("["+t.add_namespace("data-magellan-expedition-clone")+"]",t.scope).remove()}}}(jQuery,window,window.document),function(n){"use strict";Foundation.libs.accordion={name:"accordion",version:"5.5.1",settings:{content_class:"content",active_class:"active",multi_expand:!1,toggleable:!0,callback:function(){}},init:function(n,t,i){this.bindings(t,i)},events:function(){var t=this,i=this.S;i(this.scope).off(".fndtn.accordion").on("click.fndtn.accordion","["+this.attr_name()+"] > .accordion-navigation > a",function(r){var e=i(this).closest("["+t.attr_name()+"]"),h=t.attr_name()+"="+e.attr(t.attr_name()),u=e.data(t.attr_name(!0)+"-init")||t.settings,f=i("#"+this.href.split("#")[1]),o=n("> .accordion-navigation",e),s=o.children("."+u.content_class),c=s.filter("."+u.active_class);if(r.preventDefault(),e.attr(t.attr_name())&&(s=s.add("["+h+"] dd > ."+u.content_class),o=o.add("["+h+"] .accordion-navigation")),u.toggleable&&f.is(c)){f.parent(".accordion-navigation").toggleClass(u.active_class,!1);f.toggleClass(u.active_class,!1);u.callback(f);f.triggerHandler("toggled",[e]);e.triggerHandler("toggled",[f]);return}u.multi_expand||(s.removeClass(u.active_class),o.removeClass(u.active_class));f.addClass(u.active_class).parent().addClass(u.active_class);u.callback(f);f.triggerHandler("toggled",[e]);e.triggerHandler("toggled",[f])})},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(n,t,i){"use strict";Foundation.libs.topbar={name:"topbar",version:"5.5.1",settings:{index:0,sticky_class:"sticky",custom_back_text:!0,back_text:"Back",mobile_show_parent_link:!0,is_hover:!0,scrolltop:!0,sticky_on:"all"},init:function(t,i,r){Foundation.inherit(this,"add_custom_rule register_media throttle");var u=this;u.register_media("topbar","foundation-mq-topbar");this.bindings(i,r);u.S("["+this.attr_name()+"]",this.scope).each(function(){var t=n(this),r=t.data(u.attr_name(!0)+"-init"),f=u.S("section, .top-bar-section",this),i;t.data("index",0);i=t.parent();i.hasClass("fixed")||u.is_sticky(t,i,r)?(u.settings.sticky_class=r.sticky_class,u.settings.sticky_topbar=t,t.data("height",i.outerHeight()),t.data("stickyoffset",i.offset().top)):t.data("height",t.outerHeight());r.assembled||u.assemble(t);r.is_hover?u.S(".has-dropdown",t).addClass("not-click"):u.S(".has-dropdown",t).removeClass("not-click");u.add_custom_rule(".f-topbar-fixed { padding-top: "+t.data("height")+"px }");i.hasClass("fixed")&&u.S("body").addClass("f-topbar-fixed")})},is_sticky:function(n,t,i){var r=t.hasClass(i.sticky_class),u=matchMedia(Foundation.media_queries.small).matches,f=matchMedia(Foundation.media_queries.medium).matches,e=matchMedia(Foundation.media_queries.large).matches;return r&&i.sticky_on==="all"?!0:r&&this.small()&&i.sticky_on.indexOf("small")!==-1&&u&&!f&&!e?!0:r&&this.medium()&&i.sticky_on.indexOf("medium")!==-1&&u&&f&&!e?!0:r&&this.large()&&i.sticky_on.indexOf("large")!==-1&&u&&f&&e?!0:!1},toggle:function(i){var u=this,r,e,f;r=i?u.S(i).closest("["+this.attr_name()+"]"):u.S("["+this.attr_name()+"]");e=r.data(this.attr_name(!0)+"-init");f=u.S("section, .top-bar-section",r);u.breakpoint()&&(u.rtl?(f.css({right:"0%"}),n(">.name",f).css({right:"100%"})):(f.css({left:"0%"}),n(">.name",f).css({left:"100%"})),u.S("li.moved",f).removeClass("moved"),r.data("index",0),r.toggleClass("expanded").css("height",""));e.scrolltop?r.hasClass("expanded")?r.parent().hasClass("fixed")&&(e.scrolltop?(r.parent().removeClass("fixed"),r.addClass("fixed"),u.S("body").removeClass("f-topbar-fixed"),t.scrollTo(0,0)):r.parent().removeClass("expanded")):r.hasClass("fixed")&&(r.parent().addClass("fixed"),r.removeClass("fixed"),u.S("body").addClass("f-topbar-fixed")):(u.is_sticky(r,r.parent(),e)&&r.parent().addClass("fixed"),r.parent().hasClass("fixed")&&(r.hasClass("expanded")?(r.addClass("fixed"),r.parent().addClass("expanded"),u.S("body").addClass("f-topbar-fixed")):(r.removeClass("fixed"),r.parent().removeClass("expanded"),u.update_sticky_positioning())))},timer:null,events:function(){var i=this,r=this.S;r(this.scope).off(".topbar").on("click.fndtn.topbar","["+this.attr_name()+"] .toggle-topbar",function(n){n.preventDefault();i.toggle(this)}).on("click.fndtn.topbar",'.top-bar .top-bar-section li a[href^="#"],['+this.attr_name()+'] .top-bar-section li a[href^="#"]',function(){var t=n(this).closest("li");!i.breakpoint()||t.hasClass("back")||t.hasClass("has-dropdown")||i.toggle()}).on("click.fndtn.topbar","["+this.attr_name()+"] li.has-dropdown",function(t){var u=r(this),f=r(t.target),e=u.closest("["+i.attr_name()+"]"),o=e.data(i.attr_name(!0)+"-init");if(f.data("revealId")){i.toggle();return}i.breakpoint()||(!o.is_hover||Modernizr.touch)&&(t.stopImmediatePropagation(),u.hasClass("hover")?(u.removeClass("hover").find("li").removeClass("hover"),u.parents("li.hover").removeClass("hover")):(u.addClass("hover"),n(u).siblings().removeClass("hover"),f[0].nodeName==="A"&&f.parent().hasClass("has-dropdown")&&t.preventDefault()))}).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown>a",function(n){if(i.breakpoint()){n.preventDefault();var u=r(this),t=u.closest("["+i.attr_name()+"]"),f=t.find("section, .top-bar-section"),o=u.next(".dropdown").outerHeight(),e=u.closest("li");t.data("index",t.data("index")+1);e.addClass("moved");i.rtl?(f.css({right:-(100*t.data("index"))+"%"}),f.find(">.name").css({right:100*t.data("index")+"%"})):(f.css({left:-(100*t.data("index"))+"%"}),f.find(">.name").css({left:100*t.data("index")+"%"}));t.css("height",u.siblings("ul").outerHeight(!0)+t.data("height"))}});r(t).off(".topbar").on("resize.fndtn.topbar",i.throttle(function(){i.resize.call(i)},50)).trigger("resize").trigger("resize.fndtn.topbar").on("load",function(){r(this).trigger("resize.fndtn.topbar")});r("body").off(".topbar").on("click.fndtn.topbar",function(n){var t=r(n.target).closest("li").closest("li.hover");t.length>0||r("["+i.attr_name()+"] li.hover").removeClass("hover")});r(this.scope).on("click.fndtn.topbar","["+this.attr_name()+"] .has-dropdown .back",function(n){n.preventDefault();var f=r(this),t=f.closest("["+i.attr_name()+"]"),u=t.find("section, .top-bar-section"),s=t.data(i.attr_name(!0)+"-init"),e=f.closest("li.moved"),o=e.parent();t.data("index",t.data("index")-1);i.rtl?(u.css({right:-(100*t.data("index"))+"%"}),u.find(">.name").css({right:100*t.data("index")+"%"})):(u.css({left:-(100*t.data("index"))+"%"}),u.find(">.name").css({left:100*t.data("index")+"%"}));t.data("index")===0?t.css("height",""):t.css("height",o.outerHeight(!0)+t.data("height"));setTimeout(function(){e.removeClass("moved")},300)});r(this.scope).find(".dropdown a").focus(function(){n(this).parents(".has-dropdown").addClass("hover")}).blur(function(){n(this).parents(".has-dropdown").removeClass("hover")})},resize:function(){var n=this;n.S("["+this.attr_name()+"]").each(function(){var t=n.S(this),e=t.data(n.attr_name(!0)+"-init"),r=t.parent("."+n.settings.sticky_class),u,f;n.breakpoint()||(f=t.hasClass("expanded"),t.css("height","").removeClass("expanded").find("li").removeClass("hover"),f&&n.toggle(t));n.is_sticky(t,r,e)&&(r.hasClass("fixed")?(r.removeClass("fixed"),u=r.offset().top,n.S(i.body).hasClass("f-topbar-fixed")&&(u-=t.data("height")),t.data("stickyoffset",u),r.addClass("fixed")):(u=r.offset().top,t.data("stickyoffset",u)))})},breakpoint:function(){return!matchMedia(Foundation.media_queries.topbar).matches},small:function(){return matchMedia(Foundation.media_queries.small).matches},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},assemble:function(t){var i=this,r=t.data(this.attr_name(!0)+"-init"),u=i.S("section, .top-bar-section",t);u.detach();i.S(".has-dropdown>a",u).each(function(){var t=i.S(this),f=t.siblings(".dropdown"),e=t.attr("href"),u;f.find(".title.back").length||(u=r.mobile_show_parent_link==!0&&e?n('<li class="title back js-generated"><h5><a href="javascript:void(0)"><\/a><\/h5><\/li><li class="parent-link hide-for-large-up"><a class="parent-link js-generated" href="'+e+'">'+t.html()+"<\/a><\/li>"):n('<li class="title back js-generated"><h5><a href="javascript:void(0)"><\/a><\/h5>'),r.custom_back_text==!0?n("h5>a",u).html(r.back_text):n("h5>a",u).html("&laquo; "+t.html()),f.prepend(u))});u.appendTo(t);this.sticky();this.assembled(t)},assembled:function(t){t.data(this.attr_name(!0),n.extend({},t.data(this.attr_name(!0)),{assembled:!0}))},height:function(t){var i=0,r=this;return n("> li",t).each(function(){i+=r.S(this).outerHeight(!0)}),i},sticky:function(){var n=this;this.S(t).on("scroll",function(){n.update_sticky_positioning()})},update_sticky_positioning:function(){var i="."+this.settings.sticky_class,u=this.S(t),n=this,r;n.settings.sticky_topbar&&n.is_sticky(this.settings.sticky_topbar,this.settings.sticky_topbar.parent(),this.settings)&&(r=this.settings.sticky_topbar.data("stickyoffset"),n.S(i).hasClass("expanded")||(u.scrollTop()>r?n.S(i).hasClass("fixed")||(n.S(i).addClass("fixed"),n.S("body").addClass("f-topbar-fixed")):u.scrollTop()<=r&&n.S(i).hasClass("fixed")&&(n.S(i).removeClass("fixed"),n.S("body").removeClass("f-topbar-fixed"))))},off:function(){this.S(this.scope).off(".fndtn.topbar");this.S(t).off(".fndtn.topbar")},reflow:function(){}}}(jQuery,window,window.document),function(n,t,i,r){"use strict";Foundation.libs.tab={name:"tab",version:"5.5.1",settings:{active_class:"active",callback:function(){},deep_linking:!1,scroll_to_content:!0,is_hover:!1},default_tab_hashes:[],init:function(n,i,r){var u=this,f=this.S;this.bindings(i,r);u.entry_location=t.location.href;this.handle_location_hash_change();f("["+this.attr_name()+"] > .active > a",this.scope).each(function(){u.default_tab_hashes.push(this.hash)})},events:function(){var n=this,i=this.S,r=function(t){var r=i(this).closest("["+n.attr_name()+"]").data(n.attr_name(!0)+"-init");(!r.is_hover||Modernizr.touch)&&(t.preventDefault(),t.stopPropagation(),n.toggle_active_tab(i(this).parent()))};i(this.scope).off(".tab").on("focus.fndtn.tab","["+this.attr_name()+"] > * > a",r).on("click.fndtn.tab","["+this.attr_name()+"] > * > a",r).on("mouseenter.fndtn.tab","["+this.attr_name()+"] > * > a",function(){var t=i(this).closest("["+n.attr_name()+"]").data(n.attr_name(!0)+"-init");t.is_hover&&n.toggle_active_tab(i(this).parent())});i(t).on("hashchange.fndtn.tab",function(t){t.preventDefault();n.handle_location_hash_change()})},handle_location_hash_change:function(){var t=this,i=this.S;i("["+this.attr_name()+"]",this.scope).each(function(){var s=i(this).data(t.attr_name(!0)+"-init"),u,f,o,e;if(s.deep_linking)if(u=s.scroll_to_content?t.scope.location.hash:t.scope.location.hash.replace("fndtn-",""),u!="")f=i(u),f.hasClass("content")&&f.parent().hasClass("tabs-content")?t.toggle_active_tab(n("["+t.attr_name()+"] > * > a[href="+u+"]").parent()):(o=f.closest(".content").attr("id"),o!=r&&t.toggle_active_tab(n("["+t.attr_name()+"] > * > a[href=#"+o+"]").parent(),u));else for(e=0;e<t.default_tab_hashes.length;e++)t.toggle_active_tab(n("["+t.attr_name()+"] > * > a[href="+t.default_tab_hashes[e]+"]").parent())})},toggle_active_tab:function(u,f){var c=this,s=c.S,a=u.closest("["+this.attr_name()+"]"),v=u.find("a"),p=u.children("a").first(),o="#"+p.attr("href").split("#")[1],h=s(o),y=u.siblings(),e=a.data(this.attr_name(!0)+"-init"),w=function(t){var u=n(this),f=n(this).parents("li").prev().children('[role="tab"]'),e=n(this).parents("li").next().children('[role="tab"]'),r;switch(t.keyCode){case 37:r=f;break;case 39:r=e;break;default:r=!1}r.length&&(u.attr({tabindex:"-1","aria-selected":null}),r.attr({tabindex:"0","aria-selected":!0}).focus());n('[role="tabpanel"]').attr("aria-hidden","true");n("#"+n(i.activeElement).attr("href").substring(1)).attr("aria-hidden",null)},l=function(n){var i=t.location.href===c.entry_location,r=e.scroll_to_content?c.default_tab_hashes[0]:i?t.location.hash:"fndtn-"+c.default_tab_hashes[0].replace("#","");i&&n===r||(t.location.hash=n)};s(this).data(this.data_attr("tab-content"))&&(o="#"+s(this).data(this.data_attr("tab-content")).split("#")[1],h=s(o));e.deep_linking&&(e.scroll_to_content?(l(f||o),f==r||f==o?u.parent()[0].scrollIntoView():s(o)[0].scrollIntoView()):f!=r?l("fndtn-"+f.replace("#","")):l("fndtn-"+o.replace("#","")));u.addClass(e.active_class).triggerHandler("opened");v.attr({"aria-selected":"true",tabindex:0});y.removeClass(e.active_class);y.find("a").attr({"aria-selected":"false",tabindex:-1});h.siblings().removeClass(e.active_class).attr({"aria-hidden":"true",tabindex:-1});h.addClass(e.active_class).attr("aria-hidden","false").removeAttr("tabindex");e.callback(u);h.triggerHandler("toggled",[u]);a.triggerHandler("toggled",[h]);v.off("keydown").on("keydown",w)},data_attr:function(n){return this.namespace.length>0?this.namespace+"-"+n:n},off:function(){},reflow:function(){}}}(jQuery,window,window.document),function(n,t,i){"use strict";Foundation.libs.abide={name:"abide",version:"5.5.1",settings:{live_validate:!0,validate_on_blur:!0,focus_on_invalid:!0,error_labels:!0,error_class:"error",timeout:1e3,patterns:{alpha:/^[a-zA-Z]+$/,alpha_numeric:/^[a-zA-Z0-9]+$/,integer:/^[-+]?\d+$/,number:/^[-+]?\d*(?:[\.\,]\d+)?$/,card:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,cvv:/^([0-9]){3,4}$/,email:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,url:/^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,domain:/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,8}$/,datetime:/^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,date:/(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/,time:/^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/,dateISO:/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,month_day_year:/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/,day_month_year:/^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.]\d{4}$/,color:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/},validators:{equalTo:function(n){var t=i.getElementById(n.getAttribute(this.add_namespace("data-equalto"))).value,r=n.value;return t===r}}},timer:null,init:function(n,t,i){this.bindings(t,i)},events:function(t){var i=this,u=i.S(t).attr("novalidate","novalidate"),r=u.data(this.attr_name(!0)+"-init")||{};this.invalid_attr=this.add_namespace("data-invalid");u.off(".abide").on("submit.fndtn.abide validate.fndtn.abide",function(n){var t=/ajax/i.test(i.S(this).attr(i.attr_name()));return i.validate(i.S(this).find("input, textarea, select").get(),n,t)}).on("reset",function(){return i.reset(n(this))}).find("input, textarea, select").off(".abide").on("blur.fndtn.abide change.fndtn.abide",function(n){r.validate_on_blur===!0&&i.validate([this],n)}).on("keydown.fndtn.abide",function(n){r.live_validate===!0&&n.which!=9&&(clearTimeout(i.timer),i.timer=setTimeout(function(){i.validate([this],n)}.bind(this),r.timeout))})},reset:function(t){t.removeAttr(this.invalid_attr);n(this.invalid_attr,t).removeAttr(this.invalid_attr);n("."+this.settings.error_class,t).not("small").removeClass(this.settings.error_class)},validate:function(n,t,i){for(var f=this.parse_patterns(n),o=f.length,u=this.S(n[0]).closest("form"),e=/submit/.test(t.type),r=0;r<o;r++)if(!f[r]&&(e||i))return this.settings.focus_on_invalid&&n[r].focus(),u.trigger("invalid").trigger("invalid.fndtn.abide"),this.S(n[r]).closest("form").attr(this.invalid_attr,""),!1;return((e||i)&&u.trigger("valid").trigger("valid.fndtn.abide"),u.removeAttr(this.invalid_attr),i)?!1:!0},parse_patterns:function(n){for(var t=n.length,i=[];t--;)i.push(this.pattern(n[t]));return this.check_validation_and_apply_styles(i)},pattern:function(n){var r=n.getAttribute("type"),i=typeof n.getAttribute("required")=="string",t=n.getAttribute("pattern")||"";return this.settings.patterns.hasOwnProperty(t)&&t.length>0?[n,this.settings.patterns[t],i]:t.length>0?[n,new RegExp(t),i]:this.settings.patterns.hasOwnProperty(r)?[n,this.settings.patterns[r],i]:(t=/.*/,[n,t,i])},check_validation_and_apply_styles:function(t){for(var e=t.length,a=[],y=this.S(t[0][0]).closest("[data-"+this.attr_name(!0)+"]"),d=y.data(this.attr_name(!0)+"-init")||{},c,l;e--;){var i=t[e][0],u=t[e][2],p=i.value.trim(),s=this.S(i).parent(),h=i.getAttribute(this.add_namespace("data-abide-validator")),w=i.type==="radio",b=i.type==="checkbox",o=this.S('label[for="'+i.getAttribute("id")+'"]'),k=u?i.value.length>0:!0,r=[],f,v;i.getAttribute(this.add_namespace("data-equalto"))&&(h="equalTo");f=s.is("label")?s.parent():s;h&&(v=this.settings.validators[h].apply(this,[i,u,f]),r.push(v));w&&u?r.push(this.valid_radio(i,u)):b&&u?r.push(this.valid_checkbox(i,u)):(t[e][1].test(p)&&k||!u&&i.value.length<1||n(i).attr("disabled")?r.push(!0):r.push(!1),r=[r.every(function(n){return n})],r[0]?(this.S(i).removeAttr(this.invalid_attr),i.setAttribute("aria-invalid","false"),i.removeAttribute("aria-describedby"),f.removeClass(this.settings.error_class),o.length>0&&this.settings.error_labels&&o.removeClass(this.settings.error_class).removeAttr("role"),n(i).triggerHandler("valid")):(this.S(i).attr(this.invalid_attr,""),i.setAttribute("aria-invalid","true"),c=f.find("small."+this.settings.error_class,"span."+this.settings.error_class),l=c.length>0?c[0].id:"",l.length>0&&i.setAttribute("aria-describedby",l),f.addClass(this.settings.error_class),o.length>0&&this.settings.error_labels&&o.addClass(this.settings.error_class).attr("role","alert"),n(i).triggerHandler("invalid")));a.push(r[0])}return[a.every(function(n){return n})]},valid_checkbox:function(n,t){var n=this.S(n),i=n.is(":checked")||!t||n.get(0).getAttribute("disabled");return i?n.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):n.attr(this.invalid_attr,"").parent().addClass(this.settings.error_class),i},valid_radio:function(n){for(var e=n.getAttribute("name"),i=this.S(n).closest("[data-"+this.attr_name(!0)+"]").find("[name='"+e+"']"),u=i.length,r=!1,f=!1,t=0;t<u;t++)i[t].getAttribute("disabled")?(f=!0,r=!0):i[t].checked?r=!0:f&&(r=!1);for(t=0;t<u;t++)r?this.S(i[t]).removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):this.S(i[t]).attr(this.invalid_attr,"").parent().addClass(this.settings.error_class);return r},valid_equal:function(n,t,r){var f=i.getElementById(n.getAttribute(this.add_namespace("data-equalto"))).value,e=n.value,u=f===e;return u?(this.S(n).removeAttr(this.invalid_attr),r.removeClass(this.settings.error_class),label.length>0&&settings.error_labels&&label.removeClass(this.settings.error_class)):(this.S(n).attr(this.invalid_attr,""),r.addClass(this.settings.error_class),label.length>0&&settings.error_labels&&label.addClass(this.settings.error_class)),u},valid_oneof:function(n,t,i,r){var n=this.S(n),f=this.S("["+this.add_namespace("data-oneof")+"]"),e=f.filter(":checked").length>0,u;return e?n.removeAttr(this.invalid_attr).parent().removeClass(this.settings.error_class):n.attr(this.invalid_attr,"").parent().addClass(this.settings.error_class),r||(u=this,f.each(function(){u.valid_oneof.call(u,this,null,null,!0)})),e}}}(jQuery,window,window.document),function(n,t){"use strict";Foundation.libs.tooltip={name:"tooltip",version:"5.5.1",settings:{additional_inheritable_classes:[],tooltip_class:".tooltip",append_to:"body",touch_close_text:"Tap To Close",disable_for_touch:!1,hover_delay:200,show_on:"all",tip_template:function(n,t){return'<span data-selector="'+n+'" id="'+n+'" class="'+Foundation.libs.tooltip.settings.tooltip_class.substring(1)+'" role="tooltip">'+t+'<span class="nub"><\/span><\/span>'}},cache:{},init:function(n,t,i){Foundation.inherit(this,"random_str");this.bindings(t,i)},should_show:function(t){var i=n.extend({},this.settings,this.data_options(t));return i.show_on==="all"?!0:this.small()&&i.show_on==="small"||this.medium()&&i.show_on==="medium"||this.large()&&i.show_on==="large"?!0:!1},medium:function(){return matchMedia(Foundation.media_queries.medium).matches},large:function(){return matchMedia(Foundation.media_queries.large).matches},events:function(t){var i=this,r=i.S;i.create(this.S(t));n(this.scope).off(".tooltip").on("mouseenter.fndtn.tooltip mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"]",function(t){var u=r(this),f=n.extend({},i.settings,i.data_options(u)),e=!1;if(Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&r(t.target).is("a")||/mouse/i.test(t.type)&&i.ie_touch(t))return!1;if(u.hasClass("open"))Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&t.preventDefault(),i.hide(u);else{if(f.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type))return;!f.disable_for_touch&&Modernizr.touch&&/touchstart|MSPointerDown/i.test(t.type)&&(t.preventDefault(),r(f.tooltip_class+".open").hide(),e=!0);/enter|over/i.test(t.type)?this.timer=setTimeout(function(){var n=i.showTip(u)}.bind(this),i.settings.hover_delay):t.type==="mouseout"||t.type==="mouseleave"?(clearTimeout(this.timer),i.hide(u)):i.showTip(u)}}).on("mouseleave.fndtn.tooltip touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip","["+this.attr_name()+"].open",function(t){if(/mouse/i.test(t.type)&&i.ie_touch(t))return!1;(n(this).data("tooltip-open-event-type")!="touch"||t.type!="mouseleave")&&(n(this).data("tooltip-open-event-type")=="mouse"&&/MSPointerDown|touchstart/i.test(t.type)?i.convert_to_touch(n(this)):i.hide(n(this)))}).on("DOMNodeRemoved DOMAttrModified","["+this.attr_name()+"]:not(a)",function(){i.hide(r(this))})},ie_touch:function(){return!1},showTip:function(n){var t=this.getTip(n);if(this.should_show(n,t))return this.show(n)},getTip:function(t){var r=this.selector(t),u=n.extend({},this.settings,this.data_options(t)),i=null;return r&&(i=this.S('span[data-selector="'+r+'"]'+u.tooltip_class)),typeof i=="object"?i:!1},selector:function(n){var t=n.attr("id"),i=n.attr(this.attr_name())||n.attr("data-selector");return(t&&t.length<1||!t)&&typeof i!="string"&&(i=this.random_str(6),n.attr("data-selector",i).attr("aria-describedby",i)),t&&t.length>0?t:i},create:function(i){var o=this,r=n.extend({},this.settings,this.data_options(i)),f=this.settings.tip_template,u,e;if(typeof r.tip_template=="string"&&t.hasOwnProperty(r.tip_template)&&(f=t[r.tip_template]),u=n(f(this.selector(i),n("<div><\/div>").html(i.attr("title")).html())),e=this.inheritable_classes(i),u.addClass(e).appendTo(r.append_to),Modernizr.touch){u.append('<span class="tap-to-close">'+r.touch_close_text+"<\/span>");u.on("touchstart.fndtn.tooltip MSPointerDown.fndtn.tooltip",function(){o.hide(i)})}i.removeAttr("title").attr("title","")},reposition:function(t,i,r){var s,u,e,h,f,o;i.css("visibility","hidden").show();s=t.data("width");u=i.children(".nub");e=u.outerHeight();h=u.outerHeight();this.small()?i.css({width:"100%"}):i.css({width:s?s:"auto"});f=function(n,t,i,r,u){return n.css({top:t?t:"auto",bottom:r?r:"auto",left:u?u:"auto",right:i?i:"auto"}).end()};f(i,t.offset().top+t.outerHeight()+10,"auto","auto",t.offset().left);this.small()?(f(i,t.offset().top+t.outerHeight()+10,"auto","auto",12.5,n(this.scope).width()),i.addClass("tip-override"),f(u,-e,"auto","auto",t.offset().left)):(o=t.offset().left,Foundation.rtl&&(u.addClass("rtl"),o=t.offset().left+t.outerWidth()-i.outerWidth()),f(i,t.offset().top+t.outerHeight()+10,"auto","auto",o),i.removeClass("tip-override"),r&&r.indexOf("tip-top")>-1?(Foundation.rtl&&u.addClass("rtl"),f(i,t.offset().top-i.outerHeight(),"auto","auto",o).removeClass("tip-override")):r&&r.indexOf("tip-left")>-1?(f(i,t.offset().top+t.outerHeight()/2-i.outerHeight()/2,"auto","auto",t.offset().left-i.outerWidth()-e).removeClass("tip-override"),u.removeClass("rtl")):r&&r.indexOf("tip-right")>-1&&(f(i,t.offset().top+t.outerHeight()/2-i.outerHeight()/2,"auto","auto",t.offset().left+t.outerWidth()+e).removeClass("tip-override"),u.removeClass("rtl")));i.css("visibility","visible").hide()},small:function(){return matchMedia(Foundation.media_queries.small).matches&&!matchMedia(Foundation.media_queries.medium).matches},inheritable_classes:function(t){var r=n.extend({},this.settings,this.data_options(t)),u=["tip-top","tip-left","tip-bottom","tip-right","radius","round"].concat(r.additional_inheritable_classes),i=t.attr("class"),f=i?n.map(i.split(" "),function(t){if(n.inArray(t,u)!==-1)return t}).join(" "):"";return n.trim(f)},convert_to_touch:function(t){var i=this,r=i.getTip(t),u=n.extend({},i.settings,i.data_options(t));if(r.find(".tap-to-close").length===0){r.append('<span class="tap-to-close">'+u.touch_close_text+"<\/span>");r.on("click.fndtn.tooltip.tapclose touchstart.fndtn.tooltip.tapclose MSPointerDown.fndtn.tooltip.tapclose",function(){i.hide(t)})}t.data("tooltip-open-event-type","touch")},show:function(n){var t=this.getTip(n);n.data("tooltip-open-event-type")=="touch"&&this.convert_to_touch(n);this.reposition(n,t,n.attr("class"));n.addClass("open");t.fadeIn(150)},hide:function(n){var t=this.getTip(n);t.fadeOut(150,function(){t.find(".tap-to-close").remove();t.off("click.fndtn.tooltip.tapclose MSPointerDown.fndtn.tapclose");n.removeClass("open")})},off:function(){var t=this;this.S(this.scope).off(".fndtn.tooltip");this.S(this.settings.tooltip_class).each(function(i){n("["+t.attr_name()+"]").eq(i).attr("title",n(this).text())}).remove()},reflow:function(){}}}(jQuery,window,window.document);;
/*!
 * accounting.js v0.4.2, copyright 2014 Open Exchange Rates, MIT license, http://openexchangerates.github.io/accounting.js
 */
(function(p,z){function q(a){return!!(""===a||a&&a.charCodeAt&&a.substr)}function m(a){return u?u(a):"[object Array]"===v.call(a)}function r(a){return"[object Object]"===v.call(a)}function s(a,b){var d,a=a||{},b=b||{};for(d in b)b.hasOwnProperty(d)&&null==a[d]&&(a[d]=b[d]);return a}function j(a,b,d){var c=[],e,h;if(!a)return c;if(w&&a.map===w)return a.map(b,d);for(e=0,h=a.length;e<h;e++)c[e]=b.call(d,a[e],e,a);return c}function n(a,b){a=Math.round(Math.abs(a));return isNaN(a)?b:a}function x(a){var b=c.settings.currency.format;"function"===typeof a&&(a=a());return q(a)&&a.match("%v")?{pos:a,neg:a.replace("-","").replace("%v","-%v"),zero:a}:!a||!a.pos||!a.pos.match("%v")?!q(b)?b:c.settings.currency.format={pos:b,neg:b.replace("%v","-%v"),zero:b}:a}var c={version:"0.4.1",settings:{currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}}},w=Array.prototype.map,u=Array.isArray,v=Object.prototype.toString,o=c.unformat=c.parse=function(a,b){if(m(a))return j(a,function(a){return o(a,b)});a=a||0;if("number"===typeof a)return a;var b=b||".",c=RegExp("[^0-9-"+b+"]",["g"]),c=parseFloat((""+a).replace(/\((.*)\)/,"-$1").replace(c,"").replace(b,"."));return!isNaN(c)?c:0},y=c.toFixed=function(a,b){var b=n(b,c.settings.number.precision),d=Math.pow(10,b);return(Math.round(c.unformat(a)*d)/d).toFixed(b)},t=c.formatNumber=c.format=function(a,b,d,i){if(m(a))return j(a,function(a){return t(a,b,d,i)});var a=o(a),e=s(r(b)?b:{precision:b,thousand:d,decimal:i},c.settings.number),h=n(e.precision),f=0>a?"-":"",g=parseInt(y(Math.abs(a||0),h),10)+"",l=3<g.length?g.length%3:0;return f+(l?g.substr(0,l)+e.thousand:"")+g.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+e.thousand)+(h?e.decimal+y(Math.abs(a),h).split(".")[1]:"")},A=c.formatMoney=function(a,b,d,i,e,h){if(m(a))return j(a,function(a){return A(a,b,d,i,e,h)});var a=o(a),f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format);return(0<a?g.pos:0>a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal))};c.formatColumn=function(a,b,d,i,e,h){if(!a)return[];var f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format),l=g.pos.indexOf("%s")<g.pos.indexOf("%v")?!0:!1,k=0,a=j(a,function(a){if(m(a))return c.formatColumn(a,f);a=o(a);a=(0<a?g.pos:0>a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal));if(a.length>k)k=a.length;return a});return j(a,function(a){return q(a)&&a.length<k?l?a.replace(f.symbol,f.symbol+Array(k-a.length+1).join(" ")):Array(k-a.length+1).join(" ")+a:a})};if("undefined"!==typeof exports){if("undefined"!==typeof module&&module.exports)exports=module.exports=c;exports.accounting=c}else"function"===typeof define&&define.amd?define([],function(){return c}):(c.noConflict=function(a){return function(){p.accounting=a;c.noConflict=z;return c}}(p.accounting),p.accounting=c)})(this);
;
document.addEventListener("DOMContentLoaded",function(){function t(n){var i,r,t;try{i=n.selectionStart;r=n.selectionEnd}catch(u){}return(t=document.selection,t&&t.createRange().text.length!=0)?!0:!t&&n.value.substring(i,r).length!=0?!0:!1}$(".gn-form-buttons label").wrapInner("<div class='inner-fix form-control'><\/div>");var n=$(".gn-ehance");n.length>0&&$(".gn-ehance").prettyCheckable();$(".gn-password-textbox").each(function(){var n=$(this),t=$('<div class="tooltip-requirements color-black rounded"><span>Requirements<\/span><ul><li>Must be 10 characters<\/li><li>No spaces<\/li><li>Must contain one letter<\/li><li>Must contain one number<\/li><\/ul><\/div>');n.after(t);n.focus(function(){var i=n.position().top+n.outerHeight(),r=n.position().left;t.css({display:"block",top:i,left:r})});n.focusout(function(){t.css("display","none")})});$("input[type=text], input[type=password], input[type=number], input[type=tel],input[type=email], textarea").focus(function(){$(this).select()}).mousedown(function(){if(t($(this)[0])){var n=window.getSelection?window.getSelection():document.selection;n&&(n.removeAllRanges?n.removeAllRanges():n.empty&&n.empty())}})});;
(function ($) {
    Array.prototype.anyContains = function (strToCompare) {
        for (var i = 0; i < this.length; i++)
            if (strToCompare.toLocaleLowerCase().indexOf(this[i]) > -1)
                return true;
        
        return false;
    }
    
    $.fn.gnCookiePolicy = function (options) {
    	var that = this;
        var settings = $.extend({
            cookiePolicyUrl: '/cookie-policy'
        });
        
        var expirationDays = 90;
        var cacheName = 'GolfNow.Web.CookiePolicy';
        var _expiration = expirationDays * 24 * 60 * 60 * 1000; //90 day expiration

        var policyAgreed = GolfNow.Web.Cache.GetValue(cacheName) || false;
        GolfNow.Web.Domains.RequiresDomainCookiePolicy().done(function (isCookiePolicyDomain) {
            if (!policyAgreed && isCookiePolicyDomain) {
                return that.each(function () {
                    var $that = $(that);
                    $that.load(settings.cookiePolicyUrl, null, function () {
                    	$that.show('slow');
                    	$that.find('a.agree').on('click', function () {
                            GolfNow.Web.Cache.SetLocalStorageValue(cacheName, true, _expiration);
                            $that.hide('fast');
                        });
                    });
                });
            }
        });
    }
})(jQuery);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Currency=function(n,t){function r(n){var u=t.findWhere(i,{code:n}),r,f;return u===undefined?"$":(r="",f=u.font.split(","),t.forEach(f,function(n){r+=("000"+n.trim()).slice(-4)}),r.hexDecode())}var i=[{code:"AFN",font:"60b"},{code:"ARS",font:"24"},{code:"AWG",font:"192"},{code:"AUD",font:"24"},{code:"AZN",font:"43c, 430, 43d"},{code:"BSD",font:"24"},{code:"BBD",font:"24"},{code:"BYR",font:"70, 2e"},{code:"BZD",font:"42, 5a, 24"},{code:"BMD",font:"24"},{code:"BOB",font:"24, 62"},{code:"BAM",font:"4b, 4d"},{code:"BWP",font:"50"},{code:"BGN",font:"43b, 432"},{code:"BRL",font:"52, 24"},{code:"BND",font:"24"},{code:"KHR",font:"17db"},{code:"CAD",font:"24"},{code:"KYD",font:"24"},{code:"CLP",font:"24"},{code:"CNY",font:"a5"},{code:"COP",font:"24"},{code:"CRC",font:"20a1"},{code:"HRK",font:"6b, 6e"},{code:"CUP",font:"20b1"},{code:"CZK",font:"4b, 10d"},{code:"DKK",font:"6b, 72"},{code:"DOP",font:"52, 44, 24"},{code:"XCD",font:"24"},{code:"EGP",font:"a3"},{code:"SVC",font:"24"},{code:"EUR",font:"20ac"},{code:"FKP",font:"a3"},{code:"FJD",font:"24"},{code:"GHS",font:"a2"},{code:"GIP",font:"a3"},{code:"GTQ",font:"51"},{code:"GGP",font:"a3"},{code:"GYD",font:"24"},{code:"HNL",font:"4c"},{code:"HKD",font:"24"},{code:"HUF",font:"46, 74"},{code:"ISK",font:"6b, 72"},{code:"INR",font:""},{code:"IDR",font:"52, 70"},{code:"IRR",font:"fdfc"},{code:"IMP",font:"a3"},{code:"ILS",font:"20aa"},{code:"JMD",font:"4a, 24"},{code:"JPY",font:"a5"},{code:"JEP",font:"a3"},{code:"KZT",font:"43b, 432"},{code:"KPW",font:"20a9"},{code:"KRW",font:"20a9"},{code:"KGS",font:"43b, 432"},{code:"LAK",font:"20ad"},{code:"LBP",font:"a3"},{code:"LRD",font:"24"},{code:"MKD",font:"434, 435, 43d"},{code:"MYR",font:"52, 4d"},{code:"MUR",font:"20a8"},{code:"MXN",font:"24"},{code:"MNT",font:"20ae"},{code:"MZN",font:"4d, 54"},{code:"NAD",font:"24"},{code:"NPR",font:"20a8"},{code:"ANG",font:"192"},{code:"NZD",font:"24"},{code:"NIO",font:"43, 24"},{code:"NGN",font:"20a6"},{code:"KPW",font:"20a9"},{code:"NOK",font:"6b, 72"},{code:"OMR",font:"fdfc"},{code:"PKR",font:"20a8"},{code:"PAB",font:"42, 2f, 2e"},{code:"PYG",font:"47, 73"},{code:"PEN",font:"53, 2f, 2e"},{code:"PHP",font:"20b1"},{code:"PLN",font:"7a, 142"},{code:"QAR",font:"fdfc"},{code:"RON",font:"6c, 65, 69"},{code:"RUB",font:"440, 443, 431"},{code:"SHP",font:"a3"},{code:"SAR",font:"fdfc"},{code:"RSD",font:"414, 438, 43d, 2e"},{code:"SCR",font:"20a8"},{code:"SGD",font:"24"},{code:"SBD",font:"24"},{code:"SOS",font:"53"},{code:"ZAR",font:"52"},{code:"KRW",font:"20a9"},{code:"LKR",font:"20a8"},{code:"SEK",font:"6b, 72"},{code:"CHF",font:"43, 48, 46"},{code:"SRD",font:"24"},{code:"SYP",font:"a3"},{code:"TWD",font:"4e, 54, 24"},{code:"THB",font:"e3f"},{code:"TTD",font:"54, 54, 24"},{code:"TRY",font:""},{code:"TVD",font:"24"},{code:"UAH",font:"20b4"},{code:"GBP",font:"a3"},{code:"USD",font:"24"},{code:"UYU",font:"24, 55"},{code:"UZS",font:"43b, 432"},{code:"VEF",font:"42, 73"},{code:"VND",font:"20ab"},{code:"YER",font:"fdfc"},{code:"ZWD",font:"5a, 24"}];return{getSymbol:r}}(jQuery,_);String.prototype.hexEncode=function(){for(var t,i="",n=0;n<this.length;n++)t=this.charCodeAt(n).toString(16),i+=("000"+t).slice(-4);return i};String.prototype.hexDecode=function(){for(var t=this.match(/.{1,4}/g)||[],i="",n=0;n<t.length;n++)i+=String.fromCharCode(parseInt(t[n],16));return i};
/*
//# sourceMappingURL=gn-currency-mapping.min.js.map
*/;
(function(){"use strict";function t(n){return n.split("").reverse().join("")}function i(n,t){return n.substring(0,t.length)===t}function o(n,t){return n.slice(-1*t.length)===t}function r(n,t,i){if((n[t]||n[i])&&n[t]===n[i])throw new Error(t);}function f(n){return typeof n=="number"&&isFinite(n)}function s(n,t){var i=Math.pow(10,t);return(Math.round(n*i)/i).toFixed(t)}function h(n,i,r,u,e,o,h,c,l,a,v,y){var g=y,b,k,w,d="",p="";return(o&&(y=o(y)),!f(y))?!1:(n!==!1&&parseFloat(y.toFixed(n))===0&&(y=0),y<0&&(b=!0,y=Math.abs(y)),n!==!1&&(y=s(y,n)),y=y.toString(),y.indexOf(".")!==-1?(k=y.split("."),w=k[0],r&&(d=r+k[1])):w=y,i&&(w=t(w).match(/.{1,3}/g),w=t(w.join(t(i)))),b&&c&&(p+=c),u&&(p+=u),b&&l&&(p+=l),p+=w,p+=d,e&&(p+=e),a&&(p=a(p,g)),p)}function c(n,t,r,u,e,s,h,c,l,a,v,y){var b=y,w,p="";return(v&&(y=v(y)),!y||typeof y!="string")?!1:(c&&i(y,c)&&(y=y.replace(c,""),w=!0),u&&i(y,u)&&(y=y.replace(u,"")),l&&i(y,l)&&(y=y.replace(l,""),w=!0),e&&o(y,e)&&(y=y.slice(0,-1*e.length)),t&&(y=y.split(t).join("")),r&&(y=y.replace(r,".")),w&&(p+="-"),p+=y,p=p.replace(/[^0-9\.\-.]/g,""),p==="")?!1:(p=Number(p),h&&(p=h(p)),!f(p))?!1:p}function l(t){for(var i,f,u={},e=0;e<n.length;e+=1)if(i=n[e],f=t[i],f===undefined)u[i]=i!=="negative"||u.negativeBefore?i==="mark"&&u.thousand!=="."?".":!1:"-";else if(i==="decimals")if(f>=0&&f<8)u[i]=f;else throw new Error(i);else if(i==="encoder"||i==="decoder"||i==="edit"||i==="undo")if(typeof f=="function")u[i]=f;else throw new Error(i);else if(typeof f=="string")u[i]=f;else throw new Error(i);return r(u,"mark","thousand"),r(u,"prefix","negative"),r(u,"prefix","negativeBefore"),u}function e(t,i,r){for(var f=[],u=0;u<n.length;u+=1)f.push(t[n[u]]);return f.push(r),i.apply("",f)}function u(n){if(!(this instanceof u))return new u(n);typeof n=="object"&&(n=l(n),this.to=function(t){return e(n,h,t)},this.from=function(t){return e(n,c,t)})}var n=["decimals","thousand","mark","prefix","postfix","encoder","decoder","negativeBefore","negative","edit","undo"];window.wNumb=u})();
/*
//# sourceMappingURL=wNumb.min.js.map
*/;
(function(n){typeof define=="function"&&define.amd?define([],n):typeof exports=="object"?module.exports=n():window.noUiSlider=n()})(function(){"use strict";function d(n){return typeof n=="object"&&typeof n.to=="function"&&typeof n.from=="function"}function c(n){n.parentElement.removeChild(n)}function l(n){return n!==null&&n!==undefined}function a(n){n.preventDefault()}function g(n){return n.filter(function(n){return this[n]?!1:this[n]=!0},{})}function nt(n,t){return Math.round(n/t)*t}function tt(n,t){var r=n.getBoundingClientRect(),u=n.ownerDocument,f=u.documentElement,i=p(u);return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(i.x=0),t?r.top+i.y-f.clientTop:r.left+i.x-f.clientLeft}function r(n){return typeof n=="number"&&!isNaN(n)&&isFinite(n)}function v(n,i,r){r>0&&(t(n,i),setTimeout(function(){f(n,i)},r))}function y(n){return Math.max(Math.min(n,100),0)}function e(n){return Array.isArray(n)?n:[n]}function it(n){n=String(n);var t=n.split(".");return t.length>1?t[1].length:0}function t(n,t){n.classList?n.classList.add(t):n.className+=" "+t}function f(n,t){n.classList?n.classList.remove(t):n.className=n.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")}function rt(n,t){return n.classList?n.classList.contains(t):new RegExp("\\b"+t+"\\b").test(n.className)}function p(n){var t=window.pageXOffset!==undefined,i=(n.compatMode||"")==="CSS1Compat",r=t?window.pageXOffset:i?n.documentElement.scrollLeft:n.body.scrollLeft,u=t?window.pageYOffset:i?n.documentElement.scrollTop:n.body.scrollTop;return{x:r,y:u}}function ut(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}function ft(){var n=!1,t;try{t=Object.defineProperty({},"passive",{get:function(){n=!0}});window.addEventListener("test",null,t)}catch(i){}return n}function et(){return window.CSS&&CSS.supports&&CSS.supports("touch-action","none")}function o(n,t){return 100/(t-n)}function s(n,t){return t*100/(n[1]-n[0])}function ot(n,t){return s(n,n[0]<0?t+Math.abs(n[0]):t-n[0])}function st(n,t){return t*(n[1]-n[0])/100+n[0]}function u(n,t){for(var i=1;n>=t[i];)i+=1;return i}function ht(n,t,i){if(i>=n.slice(-1)[0])return 100;var r=u(i,n),e=n[r-1],s=n[r],f=t[r-1],h=t[r];return f+ot([e,s],i)/o(f,h)}function ct(n,t,i){if(i>=100)return n.slice(-1)[0];var r=u(i,t),e=n[r-1],s=n[r],f=t[r-1],h=t[r];return st([e,s],(i-f)*o(f,h))}function lt(n,t,i,r){if(r===100)return r;var f=u(r,n),e=n[f-1],o=n[f];return i?r-e>(o-e)/2?o:e:t[f-1]?n[f-1]+nt(r-n[f-1],t[f-1]):r}function at(t,i,u){var f;if(typeof i=="number"&&(i=[i]),!Array.isArray(i))throw new Error("noUiSlider ("+n+"): 'range' contains invalid value.");if(f=t==="min"?0:t==="max"?100:parseFloat(t),!r(f)||!r(i[0]))throw new Error("noUiSlider ("+n+"): 'range' value isn't numeric.");u.xPct.push(f);u.xVal.push(i[0]);f?u.xSteps.push(isNaN(i[1])?!1:i[1]):isNaN(i[1])||(u.xSteps[0]=i[1]);u.xHighestCompleteStep.push(0)}function vt(n,t,i){if(t){if(i.xVal[n]===i.xVal[n+1]){i.xSteps[n]=i.xHighestCompleteStep[n]=i.xVal[n];return}i.xSteps[n]=s([i.xVal[n],i.xVal[n+1]],t)/o(i.xPct[n],i.xPct[n+1]);var r=(i.xVal[n+1]-i.xVal[n])/i.xNumSteps[n],u=Math.ceil(Number(r.toFixed(3))-1),f=i.xVal[n]+i.xNumSteps[n]*u;i.xHighestCompleteStep[n]=f}}function i(n,t,i){this.xPct=[];this.xVal=[];this.xSteps=[i||!1];this.xNumSteps=[!1];this.xHighestCompleteStep=[];this.snap=t;var r,u=[];for(r in n)n.hasOwnProperty(r)&&u.push([n[r],r]);for(u.length&&typeof u[0][0]=="object"?u.sort(function(n,t){return n[0][0]-t[0][0]}):u.sort(function(n,t){return n[0]-t[0]}),r=0;r<u.length;r++)at(u[r][1],u[r][0],this);for(this.xNumSteps=this.xSteps.slice(0),r=0;r<this.xNumSteps.length;r++)vt(r,this.xNumSteps[r],this)}function w(t){if(d(t))return!0;throw new Error("noUiSlider ("+n+"): 'format' requires 'to' and 'from' methods.");}function yt(t,i){if(!r(i))throw new Error("noUiSlider ("+n+"): 'step' is not numeric.");t.singleStep=i}function pt(t,r){if(typeof r!="object"||Array.isArray(r))throw new Error("noUiSlider ("+n+"): 'range' is not an object.");if(r.min===undefined||r.max===undefined)throw new Error("noUiSlider ("+n+"): Missing 'min' or 'max' in 'range'.");if(r.min===r.max)throw new Error("noUiSlider ("+n+"): 'range' 'min' and 'max' cannot be equal.");t.spectrum=new i(r,t.snap,t.singleStep)}function wt(t,i){if(i=e(i),!Array.isArray(i)||!i.length)throw new Error("noUiSlider ("+n+"): 'start' option is incorrect.");t.handles=i.length;t.start=i}function bt(t,i){if(t.snap=i,typeof i!="boolean")throw new Error("noUiSlider ("+n+"): 'snap' option must be a boolean.");}function kt(t,i){if(t.animate=i,typeof i!="boolean")throw new Error("noUiSlider ("+n+"): 'animate' option must be a boolean.");}function dt(t,i){if(t.animationDuration=i,typeof i!="number")throw new Error("noUiSlider ("+n+"): 'animationDuration' option must be a number.");}function gt(t,i){var r=[!1],u;if(i==="lower"?i=[!0,!1]:i==="upper"&&(i=[!1,!0]),i===!0||i===!1){for(u=1;u<t.handles;u++)r.push(i);r.push(!1)}else if(Array.isArray(i)&&i.length&&i.length===t.handles+1)r=i;else throw new Error("noUiSlider ("+n+"): 'connect' option doesn't match handle count.");t.connect=r}function ni(t,i){switch(i){case"horizontal":t.ort=0;break;case"vertical":t.ort=1;break;default:throw new Error("noUiSlider ("+n+"): 'orientation' option is invalid.");}}function b(t,i){if(!r(i))throw new Error("noUiSlider ("+n+"): 'margin' option must be numeric.");if(i!==0&&(t.margin=t.spectrum.getMargin(i),!t.margin))throw new Error("noUiSlider ("+n+"): 'margin' option is only supported on linear sliders.");}function ti(t,i){if(!r(i))throw new Error("noUiSlider ("+n+"): 'limit' option must be numeric.");if(t.limit=t.spectrum.getMargin(i),!t.limit||t.handles<2)throw new Error("noUiSlider ("+n+"): 'limit' option is only supported on linear sliders with 2 or more handles.");}function ii(t,i){if(!r(i)&&!Array.isArray(i))throw new Error("noUiSlider ("+n+"): 'padding' option must be numeric or array of exactly 2 numbers.");if(Array.isArray(i)&&!(i.length===2||r(i[0])||r(i[1])))throw new Error("noUiSlider ("+n+"): 'padding' option must be numeric or array of exactly 2 numbers.");if(i!==0){if(Array.isArray(i)||(i=[i,i]),t.padding=[t.spectrum.getMargin(i[0]),t.spectrum.getMargin(i[1])],t.padding[0]===!1||t.padding[1]===!1)throw new Error("noUiSlider ("+n+"): 'padding' option is only supported on linear sliders.");if(t.padding[0]<0||t.padding[1]<0)throw new Error("noUiSlider ("+n+"): 'padding' option must be a positive number(s).");if(t.padding[0]+t.padding[1]>100)throw new Error("noUiSlider ("+n+"): 'padding' option must not exceed 100% of the range.");}}function ri(t,i){switch(i){case"ltr":t.dir=0;break;case"rtl":t.dir=1;break;default:throw new Error("noUiSlider ("+n+"): 'direction' option was not recognized.");}}function ui(t,i){if(typeof i!="string")throw new Error("noUiSlider ("+n+"): 'behaviour' must be a string containing options.");var e=i.indexOf("tap")>=0,o=i.indexOf("drag")>=0,r=i.indexOf("fixed")>=0,u=i.indexOf("snap")>=0,s=i.indexOf("hover")>=0,f=i.indexOf("unconstrained")>=0;if(r){if(t.handles!==2)throw new Error("noUiSlider ("+n+"): 'fixed' behaviour must be used with 2 handles");b(t,t.start[1]-t.start[0])}if(f&&(t.margin||t.limit))throw new Error("noUiSlider ("+n+"): 'unconstrained' behaviour cannot be used with margin or limit");t.events={tap:e||u,drag:o,fixed:r,snap:u,hover:s,unconstrained:f}}function fi(t,i){if(i!==!1)if(i===!0){t.tooltips=[];for(var r=0;r<t.handles;r++)t.tooltips.push(!0)}else{if(t.tooltips=e(i),t.tooltips.length!==t.handles)throw new Error("noUiSlider ("+n+"): must pass a formatter for all handles.");t.tooltips.forEach(function(t){if(typeof t!="boolean"&&(typeof t!="object"||typeof t.to!="function"))throw new Error("noUiSlider ("+n+"): 'tooltips' must be passed a formatter or 'false'.");})}}function ei(n,t){n.ariaFormat=t;w(t)}function oi(n,t){n.format=t;w(t)}function si(t,i){if(t.keyboardSupport=i,typeof i!="boolean")throw new Error("noUiSlider ("+n+"): 'keyboardSupport' option must be a boolean.");}function hi(n,t){n.documentElement=t}function ci(t,i){if(typeof i!="string"&&i!==!1)throw new Error("noUiSlider ("+n+"): 'cssPrefix' must be a string or `false`.");t.cssPrefix=i}function li(t,i){if(typeof i!="object")throw new Error("noUiSlider ("+n+"): 'cssClasses' must be an object.");if(typeof t.cssPrefix=="string"){t.cssClasses={};for(var r in i)i.hasOwnProperty(r)&&(t.cssClasses[r]=t.cssPrefix+i[r])}else t.cssClasses=i}function k(t){var i={margin:0,limit:0,padding:0,animate:!0,animationDuration:300,ariaFormat:h,format:h},r={step:{r:!1,t:yt},start:{r:!0,t:wt},connect:{r:!0,t:gt},direction:{r:!0,t:ri},snap:{r:!1,t:bt},animate:{r:!1,t:kt},animationDuration:{r:!1,t:dt},range:{r:!0,t:pt},orientation:{r:!1,t:ni},margin:{r:!1,t:b},limit:{r:!1,t:ti},padding:{r:!1,t:ii},behaviour:{r:!0,t:ui},ariaFormat:{r:!1,t:ei},format:{r:!1,t:oi},tooltips:{r:!1,t:fi},keyboardSupport:{r:!0,t:si},documentElement:{r:!1,t:hi},cssPrefix:{r:!0,t:ci},cssClasses:{r:!0,t:li}},u={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal",keyboardSupport:!0,cssPrefix:"noUi-",cssClasses:{target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",touchArea:"touch-area",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",connects:"connects",ltr:"ltr",rtl:"rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"}},e;t.format&&!t.ariaFormat&&(t.ariaFormat=t.format);Object.keys(r).forEach(function(f){if(!l(t[f])&&u[f]===undefined){if(r[f].r)throw new Error("noUiSlider ("+n+"): '"+f+"' is required.");return!0}r[f].t(i,l(t[f])?t[f]:u[f])});i.pips=t.pips;var f=document.createElement("div"),o=f.style.msTransform!==undefined,s=f.style.transform!==undefined;return i.transformRule=s?"transform":o?"msTransform":"webkitTransform",e=[["left","top"],["right","bottom"]],i.style=e[i.dir][i.ort],i}function ai(i,r,u){function d(n,i){var r=at.createElement("div");return i&&t(r,i),n.appendChild(r),r}function sr(n,i){var f=d(n,r.cssClasses.origin),u=d(f,r.cssClasses.handle);return d(u,r.cssClasses.touchArea),u.setAttribute("data-handle",i),r.keyboardSupport&&(u.setAttribute("tabindex","0"),u.addEventListener("keydown",function(n){return tu(n,i)})),u.setAttribute("role","slider"),u.setAttribute("aria-orientation",r.ort?"vertical":"horizontal"),i===0?t(u,r.cssClasses.handleLower):i===r.handles-1&&t(u,r.cssClasses.handleUpper),f}function vi(n,t){return t?d(n,r.cssClasses.connect):!1}function hr(n,t){var u=d(t,r.cssClasses.connects),i;for(s=[],it=[],it.push(vi(u,n[0])),i=0;i<r.handles;i++)s.push(sr(t,i)),ot[i]=i,it.push(vi(u,n[i+1]))}function cr(n){return t(n,r.cssClasses.target),r.dir===0?t(n,r.cssClasses.ltr):t(n,r.cssClasses.rtl),r.ort===0?t(n,r.cssClasses.horizontal):t(n,r.cssClasses.vertical),d(n,r.cssClasses.base)}function lr(n,t){return r.tooltips[t]?d(n.firstChild,r.cssClasses.tooltip):!1}function yi(){return w.hasAttribute("disabled")}function ri(n){var t=s[n];return t.hasAttribute("disabled")}function ui(){ct&&(ki("update.tooltips"),ct.forEach(function(n){n&&c(n)}),ct=null)}function pi(){ui();ct=s.map(lr);hi("update.tooltips",function(n,t,i){if(ct[t]){var u=n[t];r.tooltips[t]!==!0&&(u=r.tooltips[t].to(i[t]));ct[t].innerHTML=u}})}function ar(){hi("update",function(n,t,i,u,f){ot.forEach(function(n){var t=s[n],u=kt(h,n,0,!0,!0,!0),e=kt(h,n,100,!0,!0,!0),c=f[n],l=r.ariaFormat.to(i[n]);u=o.fromStepping(u).toFixed(1);e=o.fromStepping(e).toFixed(1);c=o.fromStepping(c).toFixed(1);t.children[0].setAttribute("aria-valuemin",u);t.children[0].setAttribute("aria-valuemax",e);t.children[0].setAttribute("aria-valuenow",c);t.children[0].setAttribute("aria-valuetext",l)})})}function vr(t,i,r){if(t==="range"||t==="steps")return o.xVal;if(t==="count"){if(i<2)throw new Error("noUiSlider ("+n+"): 'values' (>= 2) required for mode 'count'.");var u=i-1,f=100/u;for(i=[];u--;)i[u]=u*f;i.push(100);t="positions"}return t==="positions"?i.map(function(n){return o.fromStepping(r?o.getStep(n):n)}):t==="values"?r?i.map(function(n){return o.fromStepping(o.getStep(o.toStepping(n)))}):i:void 0}function yr(n,t,i){function c(n,t){return(n+t).toFixed(7)/1}var r={},f=o.xVal[0],e=o.xVal[o.xVal.length-1],s=!1,h=!1,u=0;return i=g(i.slice().sort(function(n,t){return n-t})),i[0]!==f&&(i.unshift(f),s=!0),i[i.length-1]!==e&&(i.push(e),h=!0),i.forEach(function(f,e){var a,l,v,w=f,y=i[e+1],p,b,k,d,nt,g,tt,it=t==="steps";if(it&&(a=o.xNumSteps[e]),a||(a=y-w),w!==!1&&y!==undefined)for(a=Math.max(a,1e-7),l=w;l<=y;l=c(l,a)){for(p=o.toStepping(l),b=p-u,nt=b/n,g=Math.round(nt),tt=b/g,v=1;v<=g;v+=1)k=u+v*tt,r[k.toFixed(5)]=[o.fromStepping(k),0];d=i.indexOf(l)>-1?ti:it?ii:bt;!e&&s&&(d=0);l===y&&h||(r[p.toFixed(5)]=[l,d]);u=p}}),r}function pr(n,i,u){function c(n,t){var i=t===r.cssClasses.value,u=i?s:h,f=i?o:e;return t+" "+u[r.ort]+" "+f[n]}function l(n,t,e){if(e=i?i(t,e):e,e!==er){var o=d(f,!1);o.className=c(e,r.cssClasses.marker);o.style[r.style]=n+"%";e>bt&&(o=d(f,!1),o.className=c(e,r.cssClasses.value),o.setAttribute("data-value",t),o.style[r.style]=n+"%",o.innerHTML=u.to(t))}}var f=at.createElement("div"),o=[],e,s,h;return o[bt]=r.cssClasses.valueNormal,o[ti]=r.cssClasses.valueLarge,o[ii]=r.cssClasses.valueSub,e=[],e[bt]=r.cssClasses.markerNormal,e[ti]=r.cssClasses.markerLarge,e[ii]=r.cssClasses.markerSub,s=[r.cssClasses.valueHorizontal,r.cssClasses.valueVertical],h=[r.cssClasses.markerHorizontal,r.cssClasses.markerVertical],t(f,r.cssClasses.pips),t(f,r.ort===0?r.cssClasses.pipsHorizontal:r.cssClasses.pipsVertical),Object.keys(n).forEach(function(t){l(t,n[t][0],n[t][1])}),f}function fi(){vt&&(c(vt),vt=null)}function ei(n){fi();var t=n.mode,i=n.density||1,r=n.filter||!1,u=n.values||!1,f=n.stepped||!1,e=vr(t,u,f),o=yr(i,t,e),s=n.format||{to:Math.round};return vt=w.appendChild(pr(o,r,s))}function wi(){var n=nt.getBoundingClientRect(),t="offset"+["Width","Height"][r.ort];return r.ort===0?n.width||nt[t]:n.height||nt[t]}function ht(n,t,i,u){var f=function(f){if((f=wr(f,u.pageOffset,u.target||t),!f)||yi()&&!u.doNotReject||rt(w,r.cssClasses.tap)&&!u.doNotReject||n===st.start&&f.buttons!==undefined&&f.buttons>1||u.hover&&f.buttons)return!1;ai||f.preventDefault();f.calcPoint=f.points[r.ort];i(f,u)},e=[];return n.split(" ").forEach(function(n){t.addEventListener(n,f,ai?{passive:!0}:!1);e.push([n,f])}),e}function wr(n,t,i){var c=n.type.indexOf("touch")===0,h=n.type.indexOf("mouse")===0,o=n.type.indexOf("pointer")===0,r,u,s,f,e;if(n.type.indexOf("MSPointer")===0&&(o=!0),c)if(s=function(n){return n.target===i||i.contains(n.target)},n.type==="touchstart"){if(f=Array.prototype.filter.call(n.touches,s),f.length>1)return!1;r=f[0].pageX;u=f[0].pageY}else{if(e=Array.prototype.find.call(n.changedTouches,s),!e)return!1;r=e.pageX;u=e.pageY}return t=t||p(at),(h||o)&&(r=n.clientX+t.x,u=n.clientY+t.y),n.pageOffset=t,n.points=[r,u],n.cursor=h||o,n}function bi(n){var i=n-tt(nt,r.ort),t=i*100/wi();return t=y(t),r.dir?100-t:t}function br(n){var t=100,i=!1;return s.forEach(function(r,u){if(!ri(u)){var f=Math.abs(h[u]-n);(f<t||f===100&&t===100)&&(i=u,t=f)}}),i}function kr(n,t){n.type==="mouseout"&&n.target.nodeName==="HTML"&&n.relatedTarget===null&&oi(n,t)}function dr(n,t){if(navigator.appVersion.indexOf("MSIE 9")===-1&&n.buttons===0&&t.buttonsProperty!==0)return oi(n,t);var i=(r.dir?-1:1)*(n.calcPoint-t.startCalcPoint),u=i*100/t.baseSize;di(i>0,u,t.locations,t.handleNumbers)}function oi(n,t){t.handle&&(f(t.handle,r.cssClasses.active),gt-=1);t.listeners.forEach(function(n){pt.removeEventListener(n[0],n[1])});gt===0&&(f(w,r.cssClasses.drag),li(),n.cursor&&(wt.style.cursor="",wt.removeEventListener("selectstart",a)));t.handleNumbers.forEach(function(n){l("change",n);l("set",n);l("end",n)})}function si(n,i){var u,e;if(i.handleNumbers.some(ri))return!1;i.handleNumbers.length===1&&(e=s[i.handleNumbers[0]],u=e.children[0],gt+=1,t(u,r.cssClasses.active));n.stopPropagation();var f=[],o=ht(st.move,pt,dr,{target:n.target,handle:u,listeners:f,startCalcPoint:n.calcPoint,baseSize:wi(),pageOffset:n.pageOffset,handleNumbers:i.handleNumbers,buttonsProperty:n.buttons,locations:h.slice()}),c=ht(st.end,pt,oi,{target:n.target,handle:u,listeners:f,doNotReject:!0,handleNumbers:i.handleNumbers}),v=ht("mouseout",pt,kr,{target:n.target,handle:u,listeners:f,doNotReject:!0,handleNumbers:i.handleNumbers});f.push.apply(f,o.concat(c,v));n.cursor&&(wt.style.cursor=getComputedStyle(n.target).cursor,s.length>1&&t(w,r.cssClasses.drag),wt.addEventListener("selectstart",a,!1));i.handleNumbers.forEach(function(n){l("start",n)})}function gr(n){n.stopPropagation();var i=bi(n.calcPoint),t=br(i);if(t===!1)return!1;r.events.snap||v(w,r.cssClasses.tap,r.animationDuration);yt(t,i,!0,!0);li();l("slide",t,!0);l("update",t,!0);l("change",t,!0);l("set",t,!0);r.events.snap&&si(n,{handleNumbers:[t]})}function nu(n){var t=bi(n.calcPoint),i=o.getStep(t),r=o.fromStepping(i);Object.keys(b).forEach(function(n){"hover"===n.split(".")[0]&&b[n].forEach(function(n){n.call(ni,r)})})}function tu(n,t){var u,f;if(yi()||ri(t))return!1;u=["Left","Right"];f=["Down","Up"];r.dir&&!r.ort?u.reverse():r.ort&&!r.dir&&f.reverse();var e=n.key.replace("Arrow",""),s=e===f[0]||e===u[0],c=e===f[1]||e===u[1];if(!s&&!c)return!0;n.preventDefault();var l=s?0:1,a=ur(t),i=a[l];return i===null?!1:(i===!1&&(i=o.getDefaultStep(h[t],s,10)),i=Math.max(i,1e-7),i=(s?-1:1)*i,ir(t,lt[t]+i,!0),!1)}function iu(n){n.fixed||s.forEach(function(n,t){ht(st.start,n.children[0],si,{handleNumbers:[t]})});n.tap&&ht(st.start,nt,gr,{});n.hover&&ht(st.move,nt,nu,{hover:!0});n.drag&&it.forEach(function(i,u){if(i!==!1&&u!==0&&u!==it.length-1){var e=s[u-1],o=s[u],f=[i];t(i,r.cssClasses.draggable);n.fixed&&(f.push(e.children[0]),f.push(o.children[0]));f.forEach(function(n){ht(st.start,n,si,{handles:[e,o],handleNumbers:[u-1,u]})})}})}function hi(n,t){b[n]=b[n]||[];b[n].push(t);n.split(".")[0]==="update"&&s.forEach(function(n,t){l("update",t)})}function ki(n){var t=n&&n.split(".")[0],i=t&&n.substring(t.length);Object.keys(b).forEach(function(n){var r=n.split(".")[0],u=n.substring(r.length);t&&t!==r||i&&i!==u||delete b[n]})}function l(n,t,i){Object.keys(b).forEach(function(u){var f=u.split(".")[0];n===f&&b[u].forEach(function(n){n.call(ni,lt.map(r.format.to),t,lt.slice(),i||!1,h.slice())})})}function kt(n,t,i,u,f,e){return(s.length>1&&!r.events.unconstrained&&(u&&t>0&&(i=Math.max(i,n[t-1]+r.margin)),f&&t<s.length-1&&(i=Math.min(i,n[t+1]-r.margin))),s.length>1&&r.limit&&(u&&t>0&&(i=Math.min(i,n[t-1]+r.limit)),f&&t<s.length-1&&(i=Math.max(i,n[t+1]-r.limit))),r.padding&&(t===0&&(i=Math.max(i,r.padding[0])),t===s.length-1&&(i=Math.min(i,100-r.padding[1]))),i=o.getStep(i),i=y(i),i===n[t]&&!e)?!1:i}function ci(n,t){var i=r.ort;return(i?t:n)+", "+(i?n:t)}function di(n,t,i,r){var u=i.slice(),e=[!n,n],o=[n,!n],f;r=r.slice();n&&r.reverse();r.length>1?r.forEach(function(n,i){var r=kt(u,n,u[n]+t,e[i],o[i],!1);r===!1?t=0:(t=r-u[n],u[n]=r)}):e=o=[!0];f=!1;r.forEach(function(n,r){f=yt(n,i[n]+t,e[r],o[r])||f});f&&r.forEach(function(n){l("update",n);l("slide",n)})}function gi(n,t){return r.dir?100-n-t:n}function ru(n,t){h[n]=t;lt[n]=o.fromStepping(t);var i="translate("+ci(gi(t,0)-or+"%","0")+")";s[n].style[r.transformRule]=i;nr(n);nr(n+1)}function li(){ot.forEach(function(n){var t=h[n]>50?-1:1,i=3+(s.length+t*n);s[n].style.zIndex=i})}function yt(n,t,i,r){return(t=kt(h,n,t,i,r,!1),t===!1)?!1:(ru(n,t),!0)}function nr(n){var t,i;if(it[n]){t=0;i=100;n!==0&&(t=h[n-1]);n!==it.length-1&&(i=h[n]);var u=i-t,f="translate("+ci(gi(t,u)+"%","0")+")",e="scale("+ci(u/100,"1")+")";it[n].style[r.transformRule]=f+" "+e}}function tr(n,t){return n===null||n===!1||n===undefined?h[t]:(typeof n=="number"&&(n=String(n)),n=r.format.from(n),n=o.toStepping(n),n===!1||isNaN(n))?h[t]:n}function dt(n,t){var i=e(n),u=h[0]===undefined;t=t===undefined?!0:!!t;r.animate&&!u&&v(w,r.cssClasses.tap,r.animationDuration);ot.forEach(function(n){yt(n,tr(i[n],n),!0,!1)});ot.forEach(function(n){yt(n,h[n],!0,!0)});li();ot.forEach(function(n){l("update",n);i[n]!==null&&t&&l("set",n)})}function uu(n){dt(r.start,n)}function ir(t,i,r){if(t=Number(t),!(t>=0&&t<ot.length))throw new Error("noUiSlider ("+n+"): invalid handle number, got: "+t);yt(t,tr(i,t),!0,!0);l("update",t);r&&l("set",t)}function rr(){var n=lt.map(r.format.to);return n.length===1?n[0]:n}function fu(){for(var n in r.cssClasses)r.cssClasses.hasOwnProperty(n)&&f(w,r.cssClasses[n]);while(w.firstChild)w.removeChild(w.firstChild);delete w.noUiSlider}function ur(n){var e=h[n],t=o.getNearbySteps(e),f=lt[n],i=t.thisStep.step,u=null,s;return r.snap?[f-t.stepBefore.startValue||null,t.stepAfter.startValue-f||null]:(i!==!1&&f+i>t.stepAfter.startValue&&(i=t.stepAfter.startValue-f),u=f>t.thisStep.startValue?t.thisStep.step:t.stepBefore.step===!1?!1:f-t.stepBefore.highestStep,e===100?i=null:e===0&&(u=null),s=o.countStepDecimals(),i!==null&&i!==!1&&(i=Number(i.toFixed(s))),u!==null&&u!==!1&&(u=Number(u.toFixed(s))),[u,i])}function eu(){return ot.map(ur)}function ou(n,t){var e=rr(),f=["margin","limit","padding","range","animate","snap","step","format","pips","tooltips"],i;f.forEach(function(t){n[t]!==undefined&&(u[t]=n[t])});i=k(u);f.forEach(function(t){n[t]!==undefined&&(r[t]=i[t])});o=i.spectrum;r.margin=i.margin;r.limit=i.limit;r.padding=i.padding;r.pips?ei(r.pips):fi();r.tooltips?pi():ui();h=[];dt(n.start||e,t)}function su(){nt=cr(w);hr(r.connect,nt);iu(r.events);dt(r.start);r.pips&&ei(r.pips);r.tooltips&&pi();ar()}var st=ut(),fr=et(),ai=fr&&ft(),w=i,nt,s,it,vt,ct,o=r.spectrum,lt=[],h=[],ot=[],gt=0,b={},ni,at=i.ownerDocument,pt=r.documentElement||at.documentElement,wt=at.body,er=-1,bt=0,ti=1,ii=2,or=at.dir==="rtl"||r.ort===1?0:100;return su(),ni={destroy:fu,steps:eu,on:hi,off:ki,get:rr,set:dt,setHandle:ir,reset:uu,__moveHandles:function(n,t,i){di(n,t,h,i)},options:u,updateOptions:ou,target:w,removePips:fi,removeTooltips:ui,pips:ei}}function vi(t,i){if(!t||!t.nodeName)throw new Error("noUiSlider ("+n+"): create requires a single element, got: "+t);if(t.noUiSlider)throw new Error("noUiSlider ("+n+"): Slider was already initialized.");var u=k(i,t),r=ai(t,u,i);return t.noUiSlider=r,r}var n="%%REPLACE_THIS_WITH_VERSION%%",h;return i.prototype.getMargin=function(t){var i=this.xNumSteps[0];if(i&&t/i%1!=0)throw new Error("noUiSlider ("+n+"): 'limit', 'margin' and 'padding' must be divisible by step.");return this.xPct.length===2?s(this.xVal,t):!1},i.prototype.toStepping=function(n){return ht(this.xVal,this.xPct,n)},i.prototype.fromStepping=function(n){return ct(this.xVal,this.xPct,n)},i.prototype.getStep=function(n){return lt(this.xPct,this.xSteps,this.snap,n)},i.prototype.getDefaultStep=function(n,t,i){var r=u(n,this.xPct);return(n===100||t&&n===this.xPct[r-1])&&(r=Math.max(r-1,1)),(this.xVal[r]-this.xVal[r-1])/i},i.prototype.getNearbySteps=function(n){var t=u(n,this.xPct);return{stepBefore:{startValue:this.xVal[t-2],step:this.xNumSteps[t-2],highestStep:this.xHighestCompleteStep[t-2]},thisStep:{startValue:this.xVal[t-1],step:this.xNumSteps[t-1],highestStep:this.xHighestCompleteStep[t-1]},stepAfter:{startValue:this.xVal[t],step:this.xNumSteps[t],highestStep:this.xHighestCompleteStep[t]}}},i.prototype.countStepDecimals=function(){var n=this.xNumSteps.map(it);return Math.max.apply(null,n)},i.prototype.convert=function(n){return this.getStep(this.toStepping(n))},h={to:function(n){return n!==undefined&&n.toFixed(2)},from:Number},{__spectrum:i,version:n,create:vi}});;
/*!
* jquery.inputmask.bundle.js
* https://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2016 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.3.4-108
*/
!function(n){function t(i,r){return this instanceof t?(n.isPlainObject(i)?r=i:(r=r||{},r.alias=i),this.el=void 0,this.opts=n.extend(!0,{},this.defaults,r),this.noMasksCache=r&&void 0!==r.definitions,this.userOptions=r||{},this.events={},this.dataAttribute="data-inputmask",void this.resolveAlias(this.opts.alias,r,this.opts)):new t(i,r)}function r(i,r){function f(i,u,f){var o,e;if(null!==i&&""!==i)return(1===i.length&&f.greedy===!1&&0!==f.repeat&&(f.placeholder=""),f.repeat>0||"*"===f.repeat||"+"===f.repeat)&&(o="*"===f.repeat?0:"+"===f.repeat?1:f.repeat,i=f.groupmarker.start+i+f.groupmarker.end+f.quantifiermarker.start+o+","+f.repeat+f.quantifiermarker.end),void 0===t.prototype.masksCache[i]||r===!0?(e={mask:i,maskToken:t.prototype.analyseMask(i,f),validPositions:{},_buffer:void 0,buffer:void 0,tests:{},metadata:u,maskLength:void 0},r!==!0&&(t.prototype.masksCache[f.numericInput?i.split("").reverse().join(""):i]=e,e=n.extend(!0,{},t.prototype.masksCache[f.numericInput?i.split("").reverse().join(""):i]))):e=n.extend(!0,{},t.prototype.masksCache[f.numericInput?i.split("").reverse().join(""):i]),e}var e,u;if(n.isFunction(i.mask)&&(i.mask=i.mask(i)),n.isArray(i.mask)){if(i.mask.length>1)return i.keepStatic=null===i.keepStatic||i.keepStatic,u=i.groupmarker.start,n.each(i.numericInput?i.mask.reverse():i.mask,function(t,r){u.length>1&&(u+=i.groupmarker.end+i.alternatormarker+i.groupmarker.start);u+=void 0===r.mask||n.isFunction(r.mask)?r:r.mask}),u+=i.groupmarker.end,f(u,i.mask,i);i.mask=i.mask.pop()}return i.mask&&(e=void 0===i.mask.mask||n.isFunction(i.mask.mask)?f(i.mask,i.mask,i):f(i.mask.mask,i.mask,i)),e}function i(r,u,h){function ni(n,t,i){t=t||0;var o,u,f,e=[],r=0,s=v();lt=void 0!==l?l.maxLength:void 0;lt===-1&&(lt=void 0);do n===!0&&c().validPositions[r]?(f=c().validPositions[r],u=f.match,o=f.locator.slice(),e.push(i===!0?f.input:i===!1?u.nativeDef:it(r,u))):(f=ot(r,o,r-1),u=f.match,o=f.locator.slice(),(h.jitMasking===!1||r<s||Number.isFinite(h.jitMasking)&&h.jitMasking>r)&&e.push(i===!1?u.nativeDef:it(r,u))),r++;while((void 0===lt||r<lt)&&(null!==u.fn||""!==u.def)||t>r);return""===e[e.length-1]&&e.pop(),c().maskLength=r+1,e}function c(){return u}function nt(n){var t=c();t.buffer=void 0;n!==!0&&(t._buffer=void 0,t.validPositions={},t.p=0)}function v(n,t,i){var u=-1,f=-1,e=i||c().validPositions,o,r;void 0===n&&(n=-1);for(o in e)r=parseInt(o),e[r]&&(t||null!==e[r].match.fn)&&(r<=n&&(u=r),r>=n&&(f=r));return u!==-1&&n-u>1||f<n?u:f}function li(t,i,r,u){function y(n){var t=c().validPositions[n],i,r;return void 0!==t&&null===t.match.fn?(i=c().validPositions[n-1],r=c().validPositions[n+1],void 0!==i&&void 0!==r):!1}var f,e=t,s=n.extend(!0,{},c().validPositions),l=!1,a,o;for(c().p=t,f=i-1;f>=e;f--)void 0!==c().validPositions[f]&&(r!==!0&&(!c().validPositions[f].match.optionality&&y(f)||h.canClearPosition(c(),f,v(),u,h)===!1)||delete c().validPositions[f]);for(nt(!0),f=e+1;f<=v();){for(;void 0!==c().validPositions[e];)e++;a=c().validPositions[e];(f<e&&(f=e+1),void 0===c().validPositions[f]&&d(f)||void 0!==a)?f++:(o=ot(f),l===!1&&s[e]&&s[e].match.def===o.match.def?(c().validPositions[e]=n.extend(!0,{},s[e]),c().validPositions[e].input=o.input,delete c().validPositions[f],f++):ai(e,o.match.def)?et(e,o.input||it(f),!0)!==!1&&(delete c().validPositions[f],f++,l=!0):d(f)||(f++,e--),e++)}nt(!0)}function vt(n,t){for(var i,f=n,e=v(),r=c().validPositions[e]||tt(0)[0],o=void 0!==r.alternation?r.locator[r.alternation].toString().split(","):[],u=0;u<f.length&&(i=f[u],!(i.match&&(h.greedy&&i.match.optionalQuantifier!==!0||(i.match.optionality===!1||i.match.newBlockMarker===!1)&&i.match.optionalQuantifier!==!0)&&(void 0===r.alternation||r.alternation!==i.alternation||void 0!==i.locator[r.alternation]&&ti(i.locator[r.alternation].toString().split(","),o)))||t===!0&&(null!==i.match.fn||/[0-9a-bA-Z]/.test(i.match.def)));u++);return i}function ot(n,t,i){return c().validPositions[n]||vt(tt(n,t?t.slice():t,i))}function st(n){return c().validPositions[n]?c().validPositions[n]:tt(n)[0]}function ai(n,t){for(var u=!1,r=tt(n),i=0;i<r.length;i++)if(r[i].match&&r[i].match.def===t){u=!0;break}return u}function tt(t,i,r){function y(i,r,e,s){function l(e,s,p){function ht(t,i){var r=0===n.inArray(t,i.matches);return r||n.each(i.matches,function(n,u){if(u.isQuantifier===!0&&(r=ht(t,i.matches[n-1])))return!1}),r}function at(t,i,r){var u,f;return(c().tests[t]||c().validPositions[t])&&n.each(c().tests[t]||[c().validPositions[t]],function(n,t){var o=void 0!==r?r:t.alternation,e=t.locator[o]?t.locator[o].toString().indexOf(i):-1;(void 0===f||e<f)&&e!==-1&&(u=t,f=e)}),u?u.locator.slice(u.alternation+1):void 0!==r?at(t,i):void 0}function wt(n,i){return null===n.match.fn&&null!==i.match.fn&&i.match.fn.test(n.match.def,c(),t,!1,h,!1)}var vt,ft,rt,et,w,lt,ot,b,it,nt,st;if(f>1e4)throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+c().mask;if(f===t&&void 0===e.matches)return u.push({match:e,locator:s.reverse(),cd:v}),!0;if(void 0!==e.matches){if(e.isGroup&&p!==e){if(e=l(i.matches[n.inArray(e,i.matches)+1],s))return!0}else if(e.isOptional){if(vt=e,e=y(e,r,s,p)){if(o=u[u.length-1].match,!ht(o,vt))return!0;a=!0;f=t}}else if(e.isAlternator){var ct,ut=e,tt=[],bt=u.slice(),yt=s.length,k=r.length>0?r.shift():-1;if(k===-1||"string"==typeof k){var d,kt=f,pt=r.slice(),g=[];if("string"==typeof k)g=k.split(",");else for(d=0;d<ut.matches.length;d++)g.push(d);for(ft=0;ft<g.length;ft++)for((d=parseInt(g[ft]),u=[],r=at(f,d,yt)||pt.slice(),e=l(ut.matches[d]||i.matches[d],[d].concat(s),p)||e,e!==!0&&void 0!==e&&g[g.length-1]<ut.matches.length)&&(rt=n.inArray(e,i.matches)+1,i.matches.length>rt&&(e=l(i.matches[rt],[rt].concat(s.slice(1,s.length)),p),e&&(g.push(rt.toString()),n.each(u,function(n,t){t.alternation=s.length-1})))),ct=u.slice(),f=kt,u=[],et=0;et<ct.length;et++){for(w=ct[et],lt=!1,w.alternation=w.alternation||yt,ot=0;ot<tt.length;ot++)if(b=tt[ot],("string"!=typeof k||n.inArray(w.locator[w.alternation].toString(),g)!==-1)&&(w.match.def===b.match.def||wt(w,b))){lt=w.match.nativeDef===b.match.nativeDef;w.alternation==b.alternation&&b.locator[b.alternation].toString().indexOf(w.locator[w.alternation])===-1&&(b.locator[b.alternation]=b.locator[b.alternation]+","+w.locator[w.alternation],b.alternation=w.alternation,null==w.match.fn&&(b.na=b.na||w.locator[w.alternation].toString(),b.na.indexOf(w.locator[w.alternation])===-1&&(b.na=b.na+","+w.locator[w.alternation])));break}lt||tt.push(w)}"string"==typeof k&&(tt=n.map(tt,function(t,i){var e,r,f,u;if(isFinite(i)){for(r=t.alternation,f=t.locator[r].toString().split(","),t.locator[r]=void 0,t.alternation=void 0,u=0;u<f.length;u++)e=n.inArray(f[u],g)!==-1,e&&(void 0!==t.locator[r]?(t.locator[r]+=",",t.locator[r]+=f[u]):t.locator[r]=parseInt(f[u]),t.alternation=r);if(void 0!==t.locator[r])return t}}));u=bt.concat(tt);f=t;a=u.length>0;r=pt.slice()}else e=l(ut.matches[k]||i.matches[k],[k].concat(s),p);if(e)return!0}else if(e.isQuantifier&&p!==i.matches[n.inArray(e,i.matches)-1]){for(it=e,nt=r.length>0?r.shift():0;nt<(isNaN(it.quantifier.max)?nt+1:it.quantifier.max)&&f<=t;nt++)if(st=i.matches[n.inArray(it,i.matches)-1],e=l(st,[nt].concat(s),st)){if(o=u[u.length-1].match,o.optionalQuantifier=nt>it.quantifier.min-1,ht(o,st)){if(nt>it.quantifier.min-1){a=!0;f=t;break}return!0}return!0}}else if(e=y(e,r,s,p))return!0}else f++}for(var w,p=r.length>0?r.shift():0;p<i.matches.length;p++)if(i.matches[p].isQuantifier!==!0){if(w=l(i.matches[p],[p].concat(e),s),w&&f===t)return w;if(f>t)break}}function d(t){var i=[];return n.isArray(t)||(t=[t]),t.length>0&&(void 0===t[0].alternation?(i=vt(t.slice()).locator.slice(),0===i.length&&(i=t[0].locator.slice())):n.each(t,function(n,t){if(""!==t.def)if(0===i.length)i=t.locator.slice();else for(var r=0;r<i.length;r++)t.locator[r]&&i[r].toString().indexOf(t.locator[r])===-1&&(i[r]+=","+t.locator[r])})),i}function p(n){return h.keepStatic&&t>0&&n.length>1+(""===n[n.length-1].match.def?1:0)&&n[0].match.optionality!==!0&&n[0].match.optionalQuantifier!==!0&&null===n[0].match.fn&&!/[0-9a-bA-Z]/.test(n[0].match.def)?[vt(n)]:n}var o,b=c().maskToken,f=i?r:0,l=i?i.slice():[0],u=[],a=!1,v=i?i.join(""):"",w,e,s,k;if(t>-1){if(void 0===i){for(e=t-1;void 0===(w=c().validPositions[e]||c().tests[e])&&e>-1;)e--;void 0!==w&&e>-1&&(l=d(w),v=l.join(""),f=e)}if(c().tests[t]&&c().tests[t][0].cd===v)return p(c().tests[t]);for(s=l.shift();s<b.length;s++)if(k=y(b[s],l,[s]),k&&f===t||f>t)break}return(0===u.length||a)&&u.push({match:{fn:null,cardinality:0,optionality:!0,casing:null,def:"",placeholder:""},locator:[],cd:v}),void 0!==i&&c().tests[t]?p(n.extend(!0,[],u)):(c().tests[t]=n.extend(!0,[],u),p(c().tests[t]))}function k(){return void 0===c()._buffer&&(c()._buffer=ni(!1,1),void 0===c().buffer&&c()._buffer.slice()),c()._buffer}function a(n){return void 0!==c().buffer&&n!==!0||(c().buffer=ni(!0,v(),!0)),c().buffer}function wt(n,t,i){var r;if(n===!0)nt(),n=0,t=i.length;else for(r=n;r<t;r++)delete c().validPositions[r];for(r=n;r<t;r++)nt(!0),i[r]!==h.skipOptionalPartCharacter&&et(r,i[r],!0,!0)}function ki(n,i,r){switch(h.casing||i.casing){case"upper":n=n.toUpperCase();break;case"lower":n=n.toLowerCase();break;case"title":var u=c().validPositions[r-1];n=0===r||u&&u.input===String.fromCharCode(t.keyCode.SPACE)?n.toUpperCase():n.toLowerCase()}return n}function ti(t,i){for(var f=h.greedy?i:i.slice(0,1),u=!1,r=0;r<t.length;r++)if(n.inArray(t[r],f)!==-1){u=!0;break}return u}function et(i,r,u,f,e){function k(n){var t=y?n.begin-n.end>1||n.begin-n.end==1&&h.insertMode:n.end-n.begin>1||n.end-n.begin==1&&h.insertMode;return t&&0===n.begin&&n.end===c().maskLength?"full":t}function g(t,r,u){var e=!1;return n.each(tt(t),function(o,s){for(var p,y,g,w,l=s.match,tt=r?1:0,b="",d=l.cardinality;d>tt;d--)b+=di(t-(d-1));if(r&&(b+=r),a(!0),e=null!=l.fn?l.fn.test(b,c(),t,u,h,k(i)):(r===l.def||r===h.skipOptionalPartCharacter)&&""!==l.def&&{c:l.placeholder||l.def,pos:t},e!==!1){if(p=void 0!==e.c?e.c:r,p=p===h.skipOptionalPartCharacter&&null===l.fn?l.placeholder||l.def:p,y=t,g=a(),void 0!==e.remove&&(n.isArray(e.remove)||(e.remove=[e.remove]),n.each(e.remove.sort(function(n,t){return t-n}),function(n,t){li(t,t+1,!0)})),void 0!==e.insert&&(n.isArray(e.insert)||(e.insert=[e.insert]),n.each(e.insert.sort(function(n,t){return n-t}),function(n,t){et(t.pos,t.c,!0,f)})),e.refreshFromBuffer){if(w=e.refreshFromBuffer,u=!0,wt(w===!0?w:w.start,w.end,g),void 0===e.pos&&void 0===e.c)return e.pos=v(),!1;if(y=void 0!==e.pos?e.pos:t,y!==t)return e=n.extend(e,et(y,p,!0,f)),!1}else if(e!==!0&&void 0!==e.pos&&e.pos!==t&&(y=e.pos,wt(t,y,a().slice()),y!==t))return e=n.extend(e,et(y,p,!0)),!1;return(e===!0||void 0!==e.pos||void 0!==e.c)&&(o>0&&nt(!0),ut(y,n.extend({},s,{input:ki(p,l,y)}),f,k(i))||(e=!1),!1)}}),e}function ct(t,i,r){for(var d,s,l,e,o,y,u,it=n.extend(!0,{},c().validPositions),p=!1,w=v(),b,k,g,a=c().validPositions[w];w>=0;w--)if(l=c().validPositions[w],l&&void 0!==l.alternation){if(d=w,s=c().validPositions[d].alternation,a.locator[l.alternation]!==l.locator[l.alternation])break;a=l}return void 0!==s&&(u=parseInt(d),b=void 0!==a.locator[a.alternation||s]?a.locator[a.alternation||s]:y[0],b.length>0&&(b=b.split(",")[0]),k=c().validPositions[u],g=c().validPositions[u-1],n.each(tt(u,g?g.locator:void 0,u-1),function(l,a){var w,ot,rt,ut;for(y=a.locator[s]?a.locator[s].toString().split(","):[],w=0;w<y.length;w++){var d=[],tt=0,g=0,ft=!1;if(b<y[w]&&(void 0===a.na||n.inArray(y[w],a.na.split(","))===-1)){for(c().validPositions[u]=n.extend(!0,{},a),ot=c().validPositions[u].locator,c().validPositions[u].locator[s]=parseInt(y[w]),null==a.match.fn?(k.input!==a.match.def&&(ft=!0,k.generatedInput!==!0&&d.push(k.input)),g++,c().validPositions[u].generatedInput=!/[0-9a-bA-Z]/.test(a.match.def),c().validPositions[u].input=a.match.def):c().validPositions[u].input=k.input,e=u+1;e<v(void 0,!0)+1;e++)o=c().validPositions[e],o&&o.generatedInput!==!0&&/[0-9a-bA-Z]/.test(o.input)?d.push(o.input):e<t&&tt++,delete c().validPositions[e];for(ft&&d[0]===a.match.def&&d.shift(),nt(!0),p=!0;d.length>0;)if(rt=d.shift(),rt!==h.skipOptionalPartCharacter&&!(p=et(v(void 0,!0)+1,rt,!1,f,!0)))break;if(p){for(c().validPositions[u].locator=ot,ut=v(t)+1,e=u+1;e<v()+1;e++)o=c().validPositions[e],(void 0===o||null==o.match.fn)&&e<t+(g-tt)&&g++;t+=g-tt;p=et(t>ut?ut:t,i,r,f,!0)}if(p)return!1;nt();c().validPositions=n.extend(!0,{},it)}}})),p}function lt(t,i){var f=c().validPositions[i];if(f)for(var e=f.locator,h=e.length,r=t;r<i;r++)if(void 0===c().validPositions[r]&&!d(r,!0)){var o=tt(r),u=o[0],s=-1;n.each(o,function(n,t){for(var i=0;i<h&&void 0!==t.locator[i]&&ti(t.locator[i].toString().split(","),e[i].toString().split(","));i++)s<i&&(s=i,u=t)});ut(r,n.extend({},u,{input:u.match.placeholder||u.match.def}),!0)}}function ut(t,i,r,u){var e,s,p,o,f,y;if(u||h.insertMode&&void 0!==c().validPositions[t]&&void 0===r){for(s=n.extend(!0,{},c().validPositions),p=v(void 0,!0),e=t;e<=p;e++)delete c().validPositions[e];c().validPositions[t]=n.extend(!0,{},i);var a,l=!0,w=c().validPositions,b=!1,k=c().maskLength;for(e=a=t;e<=p;e++){if(o=s[e],void 0!==o)for(f=a;f<c().maskLength&&(null==o.match.fn&&w[e]&&(w[e].match.optionalQuantifier===!0||w[e].match.optionality===!0)||null!=o.match.fn);)if((f++,b===!1&&s[f]&&s[f].match.def===o.match.def)?(c().validPositions[f]=n.extend(!0,{},s[f]),c().validPositions[f].input=o.input,ft(f),a=f,l=!0):ai(f,o.match.def)?(y=et(f,o.input,!0,!0),l=y!==!1,a=y.caret||y.insert?v():f,b=!0):l=o.generatedInput===!0,c().maskLength<k&&(c().maskLength=k),l)break;if(!l)break}if(!l)return c().validPositions=n.extend(!0,{},s),nt(!0),!1}else c().validPositions[t]=n.extend(!0,{},i);return nt(!0),!0}function ft(t){for(var r,u,i=t-1;i>-1&&!c().validPositions[i];i--);for(i++;i<t;i++)void 0===c().validPositions[i]&&(h.jitMasking===!1||h.jitMasking>i)&&(u=tt(i,ot(i-1).locator,i-1).slice(),""===u[u.length-1].match.def&&u.pop(),r=vt(u),r&&(r.match.def===h.radixPointDefinitionSymbol||!d(i,!0)||n.inArray(h.radixPoint,a())<i&&r.match.fn&&r.match.fn.test(it(i),c(),i,!1,h))&&(o=g(i,r.match.placeholder||(null==r.match.fn?r.match.def:""!==it(i)?it(i):a()[i]),!0),o!==!1&&(c().validPositions[o.pos||i].generatedInput=!0)))}var s,o,st,rt,b,l,w,ht;if(u=u===!0,s=i,void 0!==i.begin&&(s=y&&!k(i)?i.end:i.begin),o=!1,st=n.extend(!0,{},c().validPositions),ft(s),k(i)&&(ri(void 0,t.keyCode.DELETE,i),s=c().p),s<c().maskLength&&(o=g(s,r,u),(!u||f===!0)&&o===!1))if(rt=c().validPositions[s],rt&&null===rt.match.fn&&(rt.match.def===r||r===h.skipOptionalPartCharacter))o={caret:p(s)};else if((h.insertMode||void 0===c().validPositions[p(s)])&&!d(s,!0))for(b=tt(s).slice(),""===b[b.length-1].match.def&&b.pop(),l=vt(b,!0),l&&null===l.match.fn&&(l=l.match.placeholder||l.match.def,g(s,l,u),c().validPositions[s].generatedInput=!0),w=s+1,ht=p(s);w<=ht;w++)if(o=g(w,r,u),o!==!1){lt(s,void 0!==o.pos?o.pos:w);s=w;break}return o===!1&&h.keepStatic&&!u&&e!==!0&&(o=ct(s,r,u)),o===!0&&(o={pos:s}),n.isFunction(h.postValidation)&&o!==!1&&!u&&f!==!0&&(o=!!h.postValidation(a(!0),o,h)&&o),void 0===o.pos&&(o.pos=s),o===!1&&(nt(!0),c().validPositions=n.extend(!0,{},st)),o}function d(n,t){var i,r;return(t?(i=ot(n).match,""===i.def&&(i=st(n).match)):i=st(n).match,null!=i.fn)?i.fn:t!==!0&&n>-1?(r=tt(n),r.length>1+(""===r[r.length-1].match.def?1:0)):!1}function p(n,t){var r=c().maskLength,i;if(n>=r)return r;for(i=n;++i<r&&(t===!0&&(st(i).match.newBlockMarker!==!0||!d(i))||t!==!0&&!d(i)););return i}function at(n,t){var r,i=n;if(i<=0)return 0;for(;--i>0&&(t===!0&&st(i).match.newBlockMarker!==!0||t!==!0&&!d(i)&&(r=tt(i),r.length<2||2===r.length&&""===r[1].match.def)););return i}function di(n){return void 0===c().validPositions[n]?it(n):c().validPositions[n].input}function ut(t,i,r,u,f){var e,o;u&&n.isFunction(h.onBeforeWrite)&&(e=h.onBeforeWrite(u,i,r,h),e&&(e.refreshFromBuffer&&(o=e.refreshFromBuffer,wt(o===!0?o:o.start,o.end,e.buffer||i),i=a(!0)),void 0!==r&&(r=void 0!==e.caret?e.caret:r)));t.inputmask._valueSet(i.join(""));void 0===r||void 0!==u&&"blur"===u.type?ei(t,i,r):w(t,r);f===!0&&(kt=!0,n(t).trigger("input"))}function it(n,t){var f,i,u,r;if(t=t||st(n).match,void 0!==t.placeholder)return t.placeholder;if(null===t.fn){if(n>-1&&void 0===c().validPositions[n]&&(i=tt(n),u=[],i.length>1+(""===i[i.length-1].match.def?1:0)))for(r=0;r<i.length;r++)if(i[r].match.optionality!==!0&&i[r].match.optionalQuantifier!==!0&&(null===i[r].match.fn||void 0===f||i[r].match.fn.test(f.match.def,c(),n,!0,h)!==!1)&&(u.push(i[r]),null===i[r].match.fn&&(f=i[r]),u.length>1&&/[0-9a-bA-Z]/.test(u[0].match.def)))return h.placeholder.charAt(n%h.placeholder.length);return t.def}return h.placeholder.charAt(n%h.placeholder.length)}function ht(i,r,u,f,e,o){function ft(){var t=!1,r=k().slice(l,p(l)).join("").indexOf(tt),i,n;if(r!==-1&&!d(l))for(t=!0,i=k().slice(l,l+r),n=0;n<i.length;n++)if(" "!==i[n]){t=!1;break}return t}var g=f.slice(),tt="",l=0,s=void 0,it,b,y,rt;(nt(),c().p=p(-1),u)||(h.autoUnmask!==!0?(it=k().slice(0,p(-1)).join(""),b=g.join("").match(new RegExp("^"+t.escapeRegex(it),"g")),b&&b.length>0&&(g.splice(0,b.length*it.length),l=p(l))):l=p(l));(n.each(g,function(t,r){var e,y,o;if(void 0!==r){e=new n.Event("keypress");e.which=r.charCodeAt(0);tt+=r;var f=v(void 0,!0),p=c().validPositions[f],w=ot(f+1,p?p.locator.slice():void 0,f);!ft()||u||h.autoUnmask?(y=u?t:null==w.match.fn&&w.match.optionality&&f+1<c().p?f+1:c().p,s=pt.call(i,e,!0,!1,u,y),l=y+1,tt=""):s=pt.call(i,e,!0,!1,!0,f+1);!u&&n.isFunction(h.onBeforeWrite)&&(s=h.onBeforeWrite(e,a(),s.forwardPosition,h),s&&s.refreshFromBuffer)&&(o=s.refreshFromBuffer,wt(o===!0?o:o.start,o.end,s.buffer),nt(!0),s.caret&&(c().p=s.caret))}}),r)&&(y=void 0,rt=v(),document.activeElement===i&&(e||s)&&(y=w(i).begin,e&&s===!1&&(y=p(v(y))),s&&o!==!0&&(y<rt+1||rt===-1)&&(y=h.numericInput&&void 0===s.caret?at(s.forwardPosition):s.forwardPosition)),ut(i,a(),y,e||new n.Event("checkval")))}function vi(t){var i,r,f,u,e;if(t&&void 0===t.inputmask)return t.value;i=[];r=c().validPositions;for(f in r)r[f].match&&null!=r[f].match.fn&&i.push(r[f].input);return u=0===i.length?"":(y?i.reverse():i).join(""),n.isFunction(h.onUnMask)&&(e=(y?a().slice().reverse():a()).join(""),u=h.onUnMask(e,u,h)||u),u}function w(n,t,i,r){function f(n){if(r!==!0&&y&&"number"==typeof n&&(!h.greedy||""!==h.placeholder)){var t=a().join("").length;n=t-n}return n}var u,e,c,s;if("number"!=typeof t)return n.setSelectionRange?(t=n.selectionStart,i=n.selectionEnd):window.getSelection?(u=window.getSelection().getRangeAt(0),u.commonAncestorContainer.parentNode!==n&&u.commonAncestorContainer!==n||(t=u.startOffset,i=u.endOffset)):document.selection&&document.selection.createRange&&(u=document.selection.createRange(),t=0-u.duplicate().moveStart("character",-n.inputmask._valueGet().length),i=t+u.text.length),{begin:f(t),end:f(i)};t=f(t);i=f(i);i="number"==typeof i?i:t;e=parseInt(((n.ownerDocument.defaultView||window).getComputedStyle?(n.ownerDocument.defaultView||window).getComputedStyle(n,null):n.currentStyle).fontSize)*i;(n.scrollLeft=e>n.scrollWidth?e:0,o||h.insertMode!==!1||t!==i||i++,n.setSelectionRange)?(n.selectionStart=t,n.selectionEnd=i):window.getSelection?((u=document.createRange(),void 0===n.firstChild||null===n.firstChild)&&(c=document.createTextNode(""),n.appendChild(c)),u.setStart(n.firstChild,t<n.inputmask._valueGet().length?t:n.inputmask._valueGet().length),u.setEnd(n.firstChild,i<n.inputmask._valueGet().length?i:n.inputmask._valueGet().length),u.collapse(!0),s=window.getSelection(),s.removeAllRanges(),s.addRange(u)):n.createTextRange&&(u=n.createTextRange(),u.collapse(!0),u.moveEnd("character",i),u.moveStart("character",t),u.select());ei(n,void 0,{begin:t,end:i})}function ii(t){for(var r,s=a(),f=s.length,h=v(),e={},u=c().validPositions[h],l=void 0!==u?u.locator.slice():void 0,o,i=h+1;i<s.length;i++)r=ot(i,l,i-1),l=r.locator.slice(),e[i]=n.extend(!0,{},r);for(o=u&&void 0!==u.alternation?u.locator[u.alternation]:void 0,i=f-1;i>h&&(r=e[i],(r.match.optionality||r.match.optionalQuantifier||o&&(o!==e[i].locator[u.alternation]&&null!=r.match.fn||null===r.match.fn&&r.locator[u.alternation]&&ti(r.locator[u.alternation].toString().split(","),o.toString().split(","))&&""!==tt(i)[0].def))&&s[i]===it(i,r.match));i--)f--;return t?{l:f,def:e[f]?e[f].match:void 0}:f}function yt(n){for(var i=ii(),t=n.length-1;t>i&&!d(t);t--);return n.splice(i,t+1-i),n}function ct(t){var i,r;if(n.isFunction(h.isComplete))return h.isComplete(t,h);if("*"!==h.repeat){var f=!1,u=ii(!0),e=at(u.l);if(void 0===u.def||u.def.newBlockMarker||u.def.optionality||u.def.optionalQuantifier)for(f=!0,i=0;i<=e;i++)if(r=ot(i).match,null!==r.fn&&void 0===c().validPositions[i]&&r.optionality!==!0&&r.optionalQuantifier!==!0||null===r.fn&&t[i]!==it(i,r)){f=!1;break}return f}}function gi(t){function o(t){if(n.valHooks&&(void 0===n.valHooks[t]||n.valHooks[t].inputmaskpatch!==!0)){var i=n.valHooks[t]&&n.valHooks[t].get?n.valHooks[t].get:function(n){return n.value},r=n.valHooks[t]&&n.valHooks[t].set?n.valHooks[t].set:function(n,t){return n.value=t,n};n.valHooks[t]={get:function(n){if(n.inputmask){if(n.inputmask.opts.autoUnmask)return n.inputmask.unmaskedvalue();var t=i(n);return v(void 0,void 0,n.inputmask.maskset.validPositions)!==-1||h.nullable!==!0?t:""}return i(n)},set:function(t,i){var u,f=n(t);return u=r(t,i),t.inputmask&&f.trigger("setvalue"),u},inputmaskpatch:!0}}}function f(){return this.inputmask?this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():v()!==-1||h.nullable!==!0?document.activeElement===this&&h.clearMaskOnLostFocus?(y?yt(a().slice()).reverse():yt(a().slice())).join(""):i.call(this):"":i.call(this)}function e(t){r.call(this,t);this.inputmask&&n(this).trigger("setvalue")}function s(t){b.on(t,"mouseenter",function(){var t=n(this),i=this,r=i.inputmask._valueGet();r!==a().join("")&&t.trigger("setvalue")})}var i,r,u;t.inputmask.__valueGet||(h.noValuePatching!==!0&&(Object.getOwnPropertyDescriptor?("function"!=typeof Object.getPrototypeOf&&(Object.getPrototypeOf="object"==typeof"test".__proto__?function(n){return n.__proto__}:function(n){return n.constructor.prototype}),u=Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value"):void 0,u&&u.get&&u.set?(i=u.get,r=u.set,Object.defineProperty(t,"value",{get:f,set:e,configurable:!0})):"INPUT"!==t.tagName&&(i=function(){return this.textContent},r=function(n){this.textContent=n},Object.defineProperty(t,"value",{get:f,set:e,configurable:!0}))):document.__lookupGetter__&&t.__lookupGetter__("value")&&(i=t.__lookupGetter__("value"),r=t.__lookupSetter__("value"),t.__defineGetter__("value",f),t.__defineSetter__("value",e)),t.inputmask.__valueGet=i,t.inputmask.__valueSet=r),t.inputmask._valueGet=function(n){return y&&n!==!0?i.call(this.el).split("").reverse().join(""):i.call(this.el)},t.inputmask._valueSet=function(n,t){r.call(this.el,null===n||void 0===n?"":t!==!0&&y?n.split("").reverse().join(""):n)},void 0===i&&(i=function(){return this.value},r=function(n){this.value=n},o(t.type),s(t)))}function ri(i,r,u,f){function s(){var t,f;if(h.keepStatic){for(var u=[],r=v(-1,!0),o=n.extend(!0,{},c().validPositions),e=c().validPositions[r];r>=0;r--)if(t=c().validPositions[r],t){if(t.generatedInput!==!0&&/[0-9a-bA-Z]/.test(t.input)&&u.push(t.input),delete c().validPositions[r],void 0!==t.alternation&&t.locator[t.alternation]!==e.locator[t.alternation])break;e=t}if(r>-1)for(c().p=p(v(-1,!0));u.length>0;)f=new n.Event("keypress"),f.which=u.pop().charCodeAt(0),pt.call(i,f,!0,!1,!1,c().p);else c().validPositions=n.extend(!0,{},o)}}var o,e;(h.numericInput||y)&&(r===t.keyCode.BACKSPACE?r=t.keyCode.DELETE:r===t.keyCode.DELETE&&(r=t.keyCode.BACKSPACE),y)&&(o=u.end,u.end=u.begin,u.begin=o);r===t.keyCode.BACKSPACE&&(u.end-u.begin<1||h.insertMode===!1)?(u.begin=at(u.begin),void 0===c().validPositions[u.begin]||c().validPositions[u.begin].input!==h.groupSeparator&&c().validPositions[u.begin].input!==h.radixPoint||u.begin--):r===t.keyCode.DELETE&&u.begin===u.end&&(u.end=d(u.end,!0)?u.end+1:p(u.end)+1,void 0===c().validPositions[u.begin]||c().validPositions[u.begin].input!==h.groupSeparator&&c().validPositions[u.begin].input!==h.radixPoint||u.end++);li(u.begin,u.end,!1,f);f!==!0&&s();e=v(u.begin,!0);e<u.begin?c().p=p(e):f!==!0&&(c().p=u.begin)}function yi(i){function l(n){var t=document.createElement("input"),i="on"+n,r=i in t;return r||(t.setAttribute(i,"return;"),r="function"==typeof t[i]),t=null,r}var u=this,s=n(u),f=i.keyCode,r=w(u),o;f===t.keyCode.BACKSPACE||f===t.keyCode.DELETE||e&&f===t.keyCode.BACKSPACE_SAFARI||i.ctrlKey&&f===t.keyCode.X&&!l("cut")?(i.preventDefault(),ri(u,f,r),ut(u,a(!0),c().p,i,u.inputmask._valueGet()!==a().join("")),u.inputmask._valueGet()===k().join("")?s.trigger("cleared"):ct(a())===!0&&s.trigger("complete"),h.showTooltip&&(u.title=h.tooltip||c().mask)):f===t.keyCode.END||f===t.keyCode.PAGE_DOWN?(i.preventDefault(),o=p(v()),h.insertMode||o!==c().maskLength||i.shiftKey||o--,w(u,i.shiftKey?r.begin:o,o,!0)):f===t.keyCode.HOME&&!i.shiftKey||f===t.keyCode.PAGE_UP?(i.preventDefault(),w(u,0,i.shiftKey?r.begin:0,!0)):(h.undoOnEscape&&f===t.keyCode.ESCAPE||90===f&&i.ctrlKey)&&i.altKey!==!0?(ht(u,!0,!1,ft.split("")),s.trigger("click")):f!==t.keyCode.INSERT||i.shiftKey||i.ctrlKey?h.tabThrough===!0&&f===t.keyCode.TAB?(i.shiftKey===!0?(null===st(r.begin).match.fn&&(r.begin=p(r.begin)),r.end=at(r.begin,!0),r.begin=at(r.end,!0)):(r.begin=p(r.begin,!0),r.end=p(r.begin,!0),r.end<c().maskLength&&r.end--),r.begin<c().maskLength&&(i.preventDefault(),w(u,r.begin,r.end))):i.shiftKey||(h.insertMode===!1?f===t.keyCode.RIGHT?setTimeout(function(){var n=w(u);w(u,n.begin)},0):f===t.keyCode.LEFT&&setTimeout(function(){var n=w(u);w(u,y?n.begin+1:n.begin-1)},0):setTimeout(function(){ei(u)},0)):(h.insertMode=!h.insertMode,w(u,h.insertMode||r.begin!==c().maskLength?r.begin:r.begin-1));h.onKeyDown.call(this,i,a(),w(u).begin,h);wi=n.inArray(f,h.ignorables)!==-1}function pt(i,r,u,f,e){var v=this,b=n(v),s=i.which||i.charCode||i.keyCode,l,k,d,o,g,y;return!(r===!0||i.ctrlKey&&i.altKey)&&(i.ctrlKey||i.metaKey||wi)?(s===t.keyCode.ENTER&&ft!==a().join("")&&(ft=a().join(""),setTimeout(function(){b.trigger("change")},0)),!0):s&&(46===s&&i.shiftKey===!1&&","===h.radixPoint&&(s=44),k=r?{begin:e,end:e}:w(v),d=String.fromCharCode(s),c().writeOutBuffer=!0,o=et(k,d,f),(o!==!1&&(nt(!0),l=void 0!==o.caret?o.caret:r?o.pos+1:p(o.pos),c().p=l),u!==!1)&&(g=this,(setTimeout(function(){h.onKeyValidation.call(g,s,o,h)},0),c().writeOutBuffer&&o!==!1)&&(y=a(),ut(v,y,h.numericInput&&void 0===o.caret?at(l):l,i,r!==!0),r!==!0&&setTimeout(function(){ct(y)===!0&&b.trigger("complete")},0))),h.showTooltip&&(v.title=h.tooltip||c().mask),i.preventDefault(),r)?(o.forwardPosition=l,o):void 0}function ui(t){var s,o=this,c=t.originalEvent||t,l=n(o),i=o.inputmask._valueGet(!0),r=w(o),u,f,e;if(y&&(s=r.end,r.end=r.begin,r.begin=s),u=i.substr(0,r.begin),f=i.substr(r.end,i.length),u===(y?k().reverse():k()).slice(0,r.begin).join("")&&(u=""),f===(y?k().reverse():k()).slice(r.end).join("")&&(f=""),y&&(s=u,u=f,f=s),window.clipboardData&&window.clipboardData.getData)i=u+window.clipboardData.getData("Text")+f;else{if(!c.clipboardData||!c.clipboardData.getData)return!0;i=u+c.clipboardData.getData("text/plain")+f}if(e=i,n.isFunction(h.onBeforePaste)){if(e=h.onBeforePaste(i,h),e===!1)return t.preventDefault();e||(e=i)}return ht(o,!1,!1,y?e.split("").reverse():e.toString().split("")),ut(o,a(),p(v()),t,ft!==a().join("")),ct(a())===!0&&l.trigger("complete"),t.preventDefault()}function nr(i){var e=this,r=e.inputmask._valueGet(),u,s,h,l,o;if(a().join("")!==r){if(u=w(e),(r=r.replace(new RegExp("("+t.escapeRegex(k().join(""))+")*"),""),f)&&(s=r.replace(a().join(""),""),1===s.length))return h=new n.Event("keypress"),h.which=s.charCodeAt(0),pt.call(e,h,!0,!0,!1,c().validPositions[u.begin-1]?u.begin:u.begin-1),!1;if(u.begin>r.length&&(w(e,r.length),u=w(e)),a().length-r.length!=1||r.charAt(u.begin)===a()[u.begin]||r.charAt(u.begin+1)===a()[u.begin]||d(u.begin)){for(l=v()+1,o=k().join("");null===r.match(t.escapeRegex(o)+"$");)o=o.slice(1);r=r.replace(o,"");r=r.split("");ht(e,!0,!1,r,i,u.begin<l);ct(a())===!0&&n(e).trigger("complete")}else i.keyCode=t.keyCode.BACKSPACE,yi.call(e,i);i.preventDefault()}}function tr(){var t=this,i=t.inputmask._valueGet();ht(t,!0,!1,(n.isFunction(h.onBeforeMask)?h.onBeforeMask(i,h)||i:i).split(""));ft=a().join("");(h.clearMaskOnLostFocus||h.clearIncomplete)&&t.inputmask._valueGet()===k().join("")&&t.inputmask._valueSet("")}function ir(n){var t=this,i=t.inputmask._valueGet();h.showMaskOnFocus&&(!h.showMaskOnHover||h.showMaskOnHover&&""===i)&&(t.inputmask._valueGet()!==a().join("")?ut(t,a(),p(v())):si===!1&&w(t,p(v())));h.positionCaretOnTab===!0&&setTimeout(function(){fi.apply(this,[n])},0);ft=a().join("")}function rr(){var n=this,t,i;(si=!1,h.clearMaskOnLostFocus&&document.activeElement!==n)&&(t=a().slice(),i=n.inputmask._valueGet(),i!==n.getAttribute("placeholder")&&""!==i&&(v()===-1&&i===k().join("")?t=[]:yt(t),ut(n,t)))}function fi(){function i(t){var i,u,r;if(""!==h.radixPoint&&(i=c().validPositions,void 0===i[t]||i[t].input===it(t))){if(t<p(-1))return!0;if(u=n.inArray(h.radixPoint,a()),u!==-1){for(r in i)if(u<r&&i[r].input!==it(r))return!1;return!0}}return!1}var t=this;setTimeout(function(){var f,o,e;if(document.activeElement===t&&(f=w(t),f.begin===f.end))switch(h.positionCaretOnClick){case"none":break;case"radixFocus":if(i(f.begin)){o=n.inArray(h.radixPoint,a().join(""));w(t,h.numericInput?p(o):o);break}default:var u=f.begin,s=v(u,!0),r=p(s);u<r?w(t,d(u)||d(u-1)?u:p(u)):(e=it(r),(""===e||a()[r]===e||st(r).match.optionalQuantifier===!0)&&(d(r)||st(r).match.def!==e)||(r=p(r)),w(t,r))}},0)}function ur(){var n=this;setTimeout(function(){w(n,0,p(v()))},0)}function fr(i){var r=this,e=n(r),u=w(r),o=i.originalEvent||i,s=window.clipboardData||o.clipboardData,f=y?a().slice(u.end,u.begin):a().slice(u.begin,u.end);s.setData("text",y?f.reverse().join(""):f.join(""));document.execCommand&&document.execCommand("copy");ri(r,t.keyCode.DELETE,u);ut(r,a(),c().p,i,ft!==a().join(""));r.inputmask._valueGet()===k().join("")&&e.trigger("cleared");h.showTooltip&&(r.title=h.tooltip||c().mask)}function er(t){var f=n(this),r=this,u,i;r.inputmask&&(u=r.inputmask._valueGet(),i=a().slice(),ft!==i.join("")&&setTimeout(function(){f.trigger("change");ft=i.join("")},0),""!==u&&(h.clearMaskOnLostFocus&&(v()===-1&&u===k().join("")?i=[]:yt(i)),ct(i)===!1&&(setTimeout(function(){f.trigger("incomplete")},0),h.clearIncomplete&&(nt(),i=h.clearMaskOnLostFocus?[]:k().slice())),ut(r,i,void 0,t)))}function or(){var n=this;si=!0;document.activeElement!==n&&h.showMaskOnHover&&n.inputmask._valueGet()!==a().join("")&&ut(n,a())}function sr(){ft!==a().join("")&&bt.trigger("change");h.clearMaskOnLostFocus&&v()===-1&&l.inputmask._valueGet&&l.inputmask._valueGet()===k().join("")&&l.inputmask._valueSet("");h.removeMaskOnSubmit&&(l.inputmask._valueSet(l.inputmask.unmaskedvalue(),!0),setTimeout(function(){ut(l,a())},0))}function hr(){setTimeout(function(){bt.trigger("setvalue")},0)}function pi(t){function e(n){var u,r=document.createElement("span"),f,h,e,o,s,c;for(f in i)isNaN(f)&&f.indexOf("font")!==-1&&(r.style[f]=i[f]);for(r.style.textTransform=i.textTransform,r.style.letterSpacing=i.letterSpacing,r.style.position="absolute",r.style.height="auto",r.style.width="auto",r.style.visibility="hidden",r.style.whiteSpace="nowrap",document.body.appendChild(r),e=t.inputmask._valueGet(),o=0,u=0,h=e.length;u<=h;u++){if(r.innerHTML+=e.charAt(u)||"_",r.offsetWidth>=n){s=n-o;c=r.offsetWidth-n;r.innerHTML=e.charAt(u);s-=r.offsetWidth/3;u=s<c?u-1:u;break}o=r.offsetWidth}return document.body.removeChild(r),u}function f(){g.style.position="absolute";g.style.top=u.top+"px";g.style.left=u.left+"px";g.style.width=parseInt(t.offsetWidth)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth)+"px";g.style.height=parseInt(t.offsetHeight)-parseInt(i.paddingTop)-parseInt(i.paddingBottom)-parseInt(i.borderTopWidth)-parseInt(i.borderBottomWidth)+"px";g.style.lineHeight=g.style.height;g.style.zIndex=isNaN(i.zIndex)?-1:i.zIndex-1;g.style.webkitAppearance="textfield";g.style.mozAppearance="textfield";g.style.Appearance="textfield"}var u=n(t).position(),i=(t.ownerDocument.defaultView||window).getComputedStyle(t,null),r;t.parentNode;g=document.createElement("div");document.body.appendChild(g);for(r in i)isNaN(r)&&"cssText"!==r&&r.indexOf("webkit")==-1&&(g.style[r]=i[r]);t.style.backgroundColor="transparent";t.style.color="transparent";t.style.webkitAppearance="caret";t.style.mozAppearance="caret";t.style.Appearance="caret";f();n(window).on("resize",function(){u=n(t).position();i=(t.ownerDocument.defaultView||window).getComputedStyle(t,null);f()});n(t).on("click",function(n){return w(t,e(n.clientX)),fi.call(this,[n])})}function ei(n,t,i){function y(){o||null!==e.fn&&void 0!==u.input?o&&null!==e.fn&&void 0!==u.input&&(o=!1,f+="<\/span>"):(o=!0,f+="<span class='im-static''>")}var f,o,s,e,u,r,l;if(void 0!==g){if(t=t||a(),void 0===i?i=w(n):void 0===i.begin&&(i={begin:i,end:i}),f="",o=!1,""!=t){r=0;l=v();do r===i.begin&&document.activeElement===n&&(f+="<span class='im-caret' style='border-right-width: 1px;border-right-style: solid;'><\/span>"),c().validPositions[r]?(u=c().validPositions[r],e=u.match,s=u.locator.slice(),y(),f+=u.input):(u=ot(r,s,r-1),e=u.match,s=u.locator.slice(),(h.jitMasking===!1||r<l||Number.isFinite(h.jitMasking)&&h.jitMasking>r)&&(y(),f+=it(r,e))),r++;while((void 0===lt||r<lt)&&(null!==e.fn||""!==e.def)||l>r)}g.innerHTML=f}}function cr(t){function u(t,i){var f=t.getAttribute("type"),u="INPUT"===t.tagName&&n.inArray(f,i.supportsInputType)!==-1||t.isContentEditable||"TEXTAREA"===t.tagName,r;return u||"INPUT"!==t.tagName||(r=document.createElement("input"),r.setAttribute("type",f),u="text"===r.type,r=null),u}var r,i;u(t,h)&&(l=t,bt=n(l),h.showTooltip&&(l.title=h.tooltip||c().mask),("rtl"===l.dir||h.rightAlign)&&(l.style.textAlign="right"),("rtl"===l.dir||h.numericInput)&&(l.dir="ltr",l.removeAttribute("dir"),l.inputmask.isRTL=!0,y=!0),h.colorMask===!0&&pi(l),s&&(l.hasOwnProperty("inputmode")&&(l.inputmode=h.inputmode,l.setAttribute("inputmode",h.inputmode)),"rtfm"===h.androidHack&&(h.colorMask!==!0&&pi(l),l.type="password")),b.off(l),gi(l),b.on(l,"submit",sr),b.on(l,"reset",hr),b.on(l,"mouseenter",or),b.on(l,"blur",er),b.on(l,"focus",ir),b.on(l,"mouseleave",rr),h.colorMask!==!0&&b.on(l,"click",fi),b.on(l,"dblclick",ur),b.on(l,"paste",ui),b.on(l,"dragdrop",ui),b.on(l,"drop",ui),b.on(l,"cut",fr),b.on(l,"complete",h.oncomplete),b.on(l,"incomplete",h.onincomplete),b.on(l,"cleared",h.oncleared),h.inputEventOnly!==!0&&(b.on(l,"keydown",yi),b.on(l,"keypress",pt)),b.on(l,"compositionstart",n.noop),b.on(l,"compositionupdate",n.noop),b.on(l,"compositionend",n.noop),b.on(l,"keyup",n.noop),b.on(l,"input",nr),b.on(l,"setvalue",tr),k(),""!==l.inputmask._valueGet()||h.clearMaskOnLostFocus===!1||document.activeElement===l)&&(r=n.isFunction(h.onBeforeMask)?h.onBeforeMask(l.inputmask._valueGet(),h)||l.inputmask._valueGet():l.inputmask._valueGet(),ht(l,!0,!1,r.split("")),i=a().slice(),ft=i.join(""),ct(i)===!1&&h.clearIncomplete&&nt(),h.clearMaskOnLostFocus&&document.activeElement!==l&&(v()===-1?i=[]:yt(i)),ut(l,i),document.activeElement===l&&w(l,p(v())))}var ft,l,bt,lt,g,rt,y=!1,oi=!1,kt=!1,wi=!1,si=!1,b={on:function(i,r,u){var o=function(i){var r,s,c,o;if(void 0===this.inputmask&&"FORM"!==this.nodeName)r=n.data(this,"_inputmask_opts"),r?new t(r).mask(this):b.off(this);else{if("setvalue"===i.type||!(this.disabled||this.readOnly&&!("keydown"===i.type&&i.ctrlKey&&67===i.keyCode||h.tabThrough===!1&&i.keyCode===t.keyCode.TAB))){switch(i.type){case"input":if(kt===!0)return kt=!1,i.preventDefault();break;case"keydown":oi=!1;kt=!1;break;case"keypress":if(oi===!0)return i.preventDefault();oi=!0;break;case"click":if(f||e)return s=this,c=arguments,setTimeout(function(){u.apply(s,c)},0),!1}return o=u.apply(this,arguments),o===!1&&(i.preventDefault(),i.stopPropagation()),o}i.preventDefault()}};i.inputmask.events[r]=i.inputmask.events[r]||[];i.inputmask.events[r].push(o);n.inArray(r,["submit","reset"])!==-1?null!=i.form&&n(i.form).on(r,o):n(i).on(r,o)},off:function(t,i){if(t.inputmask&&t.inputmask.events){var r;i?(r=[],r[i]=t.inputmask.events[i]):r=t.inputmask.events;n.each(r,function(i,r){for(;r.length>0;){var u=r.pop();n.inArray(i,["submit","reset"])!==-1?null!=t.form&&n(t.form).off(i,u):n(t).off(i,u)}delete t.inputmask.events[i]})}}},bi,gt;if(void 0!==r)switch(r.action){case"isComplete":return l=r.el,ct(a());case"unmaskedvalue":return l=r.el,void 0!==l&&void 0!==l.inputmask?(u=l.inputmask.maskset,h=l.inputmask.opts,y=l.inputmask.isRTL):(rt=r.value,h.numericInput&&(y=!0),rt=(n.isFunction(h.onBeforeMask)?h.onBeforeMask(rt,h)||rt:rt).split(""),ht(void 0,!1,!1,y?rt.reverse():rt),n.isFunction(h.onBeforeWrite)&&h.onBeforeWrite(void 0,a(),0,h)),vi(l);case"mask":l=r.el;u=l.inputmask.maskset;h=l.inputmask.opts;y=l.inputmask.isRTL;cr(l);break;case"format":return h.numericInput&&(y=!0),rt=(n.isFunction(h.onBeforeMask)?h.onBeforeMask(r.value,h)||r.value:r.value).split(""),ht(void 0,!1,!1,y?rt.reverse():rt),n.isFunction(h.onBeforeWrite)&&h.onBeforeWrite(void 0,a(),0,h),r.metadata?{value:y?a().slice().reverse().join(""):a().join(""),metadata:i({action:"getmetadata"},u,h)}:y?a().slice().reverse().join(""):a().join("");case"isValid":h.numericInput&&(y=!0);r.value?(rt=r.value.split(""),ht(void 0,!1,!0,y?rt.reverse():rt)):r.value=a().join("");for(var hi=a(),ci=ii(),dt=hi.length-1;dt>ci&&!d(dt);dt--);return hi.splice(ci,dt+1-ci),ct(hi)&&r.value===a().join("");case"getemptymask":return k().join("");case"remove":l=r.el;bt=n(l);u=l.inputmask.maskset;h=l.inputmask.opts;l.inputmask._valueSet(vi(l));b.off(l);Object.getOwnPropertyDescriptor&&Object.getPrototypeOf?(bi=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(l),"value"),bi&&l.inputmask.__valueGet&&Object.defineProperty(l,"value",{get:l.inputmask.__valueGet,set:l.inputmask.__valueSet,configurable:!0})):document.__lookupGetter__&&l.__lookupGetter__("value")&&l.inputmask.__valueGet&&(l.__defineGetter__("value",l.inputmask.__valueGet),l.__defineSetter__("value",l.inputmask.__valueSet));l.inputmask=void 0;break;case"getmetadata":return n.isArray(u.metadata)?(gt=ni(!0,0,!1).join(""),n.each(u.metadata,function(n,t){if(t.mask===gt)return gt=t,!1}),gt):u.metadata}}var u=navigator.userAgent,o=/mobile/i.test(u),f=/iemobile/i.test(u),e=/iphone/i.test(u)&&!f,s=/android/i.test(u)&&!f;return t.prototype={defaults:{placeholder:"_",optionalmarker:{start:"[",end:"]"},quantifiermarker:{start:"{",end:"}"},groupmarker:{start:"(",end:")"},alternatormarker:"|",escapeChar:"\\",mask:null,oncomplete:n.noop,onincomplete:n.noop,oncleared:n.noop,repeat:0,greedy:!0,autoUnmask:!1,removeMaskOnSubmit:!1,clearMaskOnLostFocus:!0,insertMode:!0,clearIncomplete:!1,aliases:{},alias:null,onKeyDown:n.noop,onBeforeMask:null,onBeforePaste:function(t,i){return n.isFunction(i.onBeforeMask)?i.onBeforeMask(t,i):t},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:!0,showMaskOnHover:!0,onKeyValidation:n.noop,skipOptionalPartCharacter:" ",showTooltip:!1,tooltip:void 0,numericInput:!1,rightAlign:!1,undoOnEscape:!0,radixPoint:"",radixPointDefinitionSymbol:void 0,groupSeparator:"",keepStatic:null,positionCaretOnTab:!0,tabThrough:!1,supportsInputType:["text","tel","password"],definitions:{"9":{validator:"[0-9]",cardinality:1,definitionSymbol:"*"},a:{validator:"[A-Za-zА-яЁёÀ-ÿµ]",cardinality:1,definitionSymbol:"*"},"*":{validator:"[0-9A-Za-zА-яЁёÀ-ÿµ]",cardinality:1}},ignorables:[8,9,13,19,27,33,34,35,36,37,38,39,40,45,46,93,112,113,114,115,116,117,118,119,120,121,122,123],isComplete:null,canClearPosition:n.noop,postValidation:null,staticDefinitionSymbol:void 0,jitMasking:!1,nullable:!0,inputEventOnly:!1,noValuePatching:!1,positionCaretOnClick:"lvp",casing:null,inputmode:"verbatim",colorMask:!1,androidHack:!1},masksCache:{},mask:function(u){function e(t,i,r,u){function l(n,i){i=void 0!==i?i:t.getAttribute(u+"-"+n);null!==i&&("string"==typeof i&&(0===n.indexOf("on")?i=window[i]:"false"===i?i=!1:"true"===i&&(i=!0)),r[n]=i)}var c,e,o,s,h=t.getAttribute(u);if(h&&""!==h&&(h=h.replace(new RegExp("'","g"),'"'),e=JSON.parse("{"+h+"}")),e){o=void 0;for(s in e)if("alias"===s.toLowerCase()){o=e[s];break}}l("alias",o);r.alias&&f.resolveAlias(r.alias,r,i);for(c in i){if(e){o=void 0;for(s in e)if(s.toLowerCase()===c.toLowerCase()){o=e[s];break}}l(c,o)}return n.extend(!0,i,r),i}var f=this;return"string"==typeof u&&(u=document.getElementById(u)||document.querySelectorAll(u)),u=u.nodeName?[u]:u,n.each(u,function(u,o){var s=n.extend(!0,{},f.opts),h;e(o,s,n.extend(!0,{},f.userOptions),f.dataAttribute);h=r(s,f.noMasksCache);void 0!==h&&(void 0!==o.inputmask&&o.inputmask.remove(),o.inputmask=new t,o.inputmask.opts=s,o.inputmask.noMasksCache=f.noMasksCache,o.inputmask.userOptions=n.extend(!0,{},f.userOptions),o.inputmask.el=o,o.inputmask.maskset=h,o.inputmask.isRTL=!1,n.data(o,"_inputmask_opts",s),i({action:"mask",el:o}))}),u&&u[0]?u[0].inputmask||this:this},option:function(t,i){return"string"==typeof t?this.opts[t]:"object"==typeof t?(n.extend(this.userOptions,t),this.el&&i!==!0&&this.mask(this.el),this):void 0},unmaskedvalue:function(n){return i({action:"unmaskedvalue",el:this.el,value:n},this.el&&this.el.inputmask?this.el.inputmask.maskset:r(this.opts,this.noMasksCache),this.opts)},remove:function(){if(this.el)return i({action:"remove",el:this.el}),this.el.inputmask=void 0,this.el},getemptymask:function(){return i({action:"getemptymask"},this.maskset||r(this.opts,this.noMasksCache),this.opts)},hasMaskedValue:function(){return!this.opts.autoUnmask},isComplete:function(){return i({action:"isComplete",el:this.el},this.maskset||r(this.opts,this.noMasksCache),this.opts)},getmetadata:function(){return i({action:"getmetadata"},this.maskset||r(this.opts,this.noMasksCache),this.opts)},isValid:function(n){return i({action:"isValid",value:n},this.maskset||r(this.opts,this.noMasksCache),this.opts)},format:function(n,t){return i({action:"format",value:n,metadata:t},this.maskset||r(this.opts,this.noMasksCache),this.opts)},analyseMask:function(t,i){function h(n,t,i,r){this.matches=[];this.isGroup=n||!1;this.isOptional=t||!1;this.isQuantifier=i||!1;this.isAlternator=r||!1;this.quantifier={min:1,max:1}}function g(t,r,u){var f=i.definitions[r],e;if(u=void 0!==u?u:t.matches.length,e=t.matches[u-1],f&&!p){f.placeholder=n.isFunction(f.placeholder)?f.placeholder(i):f.placeholder;for(var h=f.prevalidator,a=h?h.length:0,o=1;o<f.cardinality;o++){var c=a>=o?h[o-1]:[],s=c.validator,l=c.cardinality;t.matches.splice(u++,0,{fn:s?"string"==typeof s?new RegExp(s):new function(){this.test=s}:new RegExp("."),cardinality:l?l:1,optionality:t.isOptional,newBlockMarker:void 0===e||e.def!==(f.definitionSymbol||r),casing:f.casing,def:f.definitionSymbol||r,placeholder:f.placeholder,nativeDef:r});e=t.matches[u-1]}t.matches.splice(u++,0,{fn:f.validator?"string"==typeof f.validator?new RegExp(f.validator):new function(){this.test=f.validator}:new RegExp("."),cardinality:f.cardinality,optionality:t.isOptional,newBlockMarker:void 0===e||e.def!==(f.definitionSymbol||r),casing:f.casing,def:f.definitionSymbol||r,placeholder:f.placeholder,nativeDef:r})}else t.matches.splice(u++,0,{fn:null,cardinality:0,optionality:t.isOptional,newBlockMarker:void 0===e||e.def!==r,casing:null,def:i.staticDefinitionSymbol||r,placeholder:void 0!==i.staticDefinitionSymbol?r:void 0,nativeDef:r}),p=!1}function y(n,t){n&&n.isGroup&&(n.isGroup=!1,g(n,i.groupmarker.start,0),t!==!0&&g(n,i.groupmarker.end))}function rt(n,t,i,r){t.matches.length>0&&(void 0===r||r)&&(i=t.matches[t.matches.length-1],y(i));g(t,n)}function nt(){if(r.length>0){if(f=r[r.length-1],rt(c,f,s,!f.isAlternator),f.isAlternator){e=r.pop();for(var n=0;n<e.matches.length;n++)e.matches[n].isGroup=!1;r.length>0?(f=r[r.length-1],f.matches.push(e)):u.matches.push(e)}}else rt(c,u,s)}function ut(n){function f(n){return n===i.optionalmarker.start?n=i.optionalmarker.end:n===i.optionalmarker.end?n=i.optionalmarker.start:n===i.groupmarker.start?n=i.groupmarker.end:n===i.groupmarker.end&&(n=i.groupmarker.start),n}var t,r,u;n.matches=n.matches.reverse();for(t in n.matches)r=parseInt(t),n.matches[t].isQuantifier&&n.matches[r+1]&&n.matches[r+1].isGroup&&(u=n.matches[t],n.matches.splice(t,1),n.matches.splice(r+1,0,u)),n.matches[t]=void 0!==n.matches[t].matches?ut(n.matches[t]):f(n.matches[t]);return n}for(var w,b,d,o,c,l,f,e,s,v,ft=/(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,p=!1,u=new h,r=[],tt=[];o=ft.exec(t);)if(c=o[0],p)nt();else switch(c.charAt(0)){case i.escapeChar:p=!0;break;case i.optionalmarker.end:case i.groupmarker.end:if(l=r.pop(),void 0!==l)if(r.length>0){if(f=r[r.length-1],f.matches.push(l),f.isAlternator){for(e=r.pop(),w=0;w<e.matches.length;w++)e.matches[w].isGroup=!1;r.length>0?(f=r[r.length-1],f.matches.push(e)):u.matches.push(e)}}else u.matches.push(l);else nt();break;case i.optionalmarker.start:y(u.matches[u.matches.length-1]);r.push(new h(!1,!0));break;case i.groupmarker.start:y(u.matches[u.matches.length-1]);r.push(new h(!0));break;case i.quantifiermarker.start:b=new h(!1,!1,!0);c=c.replace(/[{}]/g,"");var a=c.split(","),it=isNaN(a[0])?a[0]:parseInt(a[0]),k=1===a.length?it:isNaN(a[1])?a[1]:parseInt(a[1]);("*"!==k&&"+"!==k||(it="*"===k?0:1),b.quantifier={min:it,max:k},r.length>0)?(d=r[r.length-1].matches,o=d.pop(),o.isGroup||(v=new h(!0),v.matches.push(o),o=v),d.push(o),d.push(b)):(o=u.matches.pop(),o.isGroup||(v=new h(!0),v.matches.push(o),o=v),u.matches.push(o),u.matches.push(b));break;case i.alternatormarker:r.length>0?(f=r[r.length-1],s=f.matches.pop()):s=u.matches.pop();s.isAlternator?r.push(s):(e=new h(!1,!1,!1,!0),e.matches.push(s),r.push(e));break;default:nt()}for(;r.length>0;)l=r.pop(),y(l,!0),u.matches.push(l);return u.matches.length>0&&(s=u.matches[u.matches.length-1],y(s),tt.push(u)),i.numericInput&&ut(tt[0]),tt},resolveAlias:function(t,i,r){var u=r.aliases[t];return u?(u.alias&&this.resolveAlias(u.alias,void 0,r),n.extend(!0,r,u),n.extend(!0,r,i),!0):(null===r.mask&&(r.mask=t),!1)}},t.extendDefaults=function(i){n.extend(!0,t.prototype.defaults,i)},t.extendDefinitions=function(i){n.extend(!0,t.prototype.defaults.definitions,i)},t.extendAliases=function(i){n.extend(!0,t.prototype.defaults.aliases,i)},t.format=function(n,i,r){return t(i).format(n,r)},t.unmask=function(n,i){return t(i).unmaskedvalue(n)},t.isValid=function(n,i){return t(i).isValid(n)},t.remove=function(t){n.each(t,function(n,t){t.inputmask&&t.inputmask.remove()})},t.escapeRegex=function(n){return n.replace(new RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^)","gim"),"\\$1")},t.keyCode={ALT:18,BACKSPACE:8,BACKSPACE_SAFARI:127,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91,X:88},window.Inputmask=t,t}(jQuery),function(n,t){return void 0===n.fn.inputmask&&(n.fn.inputmask=function(i,r){var f,u=this[0];if(void 0===r&&(r={}),"string"==typeof i)switch(i){case"unmaskedvalue":return u&&u.inputmask?u.inputmask.unmaskedvalue():n(u).val();case"remove":return this.each(function(){this.inputmask&&this.inputmask.remove()});case"getemptymask":return u&&u.inputmask?u.inputmask.getemptymask():"";case"hasMaskedValue":return!(!u||!u.inputmask)&&u.inputmask.hasMaskedValue();case"isComplete":return!u||!u.inputmask||u.inputmask.isComplete();case"getmetadata":return u&&u.inputmask?u.inputmask.getmetadata():void 0;case"setvalue":n(u).val(r);u&&void 0===u.inputmask&&n(u).triggerHandler("setvalue");break;case"option":if("string"!=typeof r)return this.each(function(){if(void 0!==this.inputmask)return this.inputmask.option(r)});if(u&&void 0!==u.inputmask)return u.inputmask.option(r);break;default:return r.alias=i,f=new t(r),this.each(function(){f.mask(this)})}else{if("object"==typeof i)return f=new t(i),void 0===i.mask&&void 0===i.alias?this.each(function(){return void 0!==this.inputmask?this.inputmask.option(i):void f.mask(this)}):this.each(function(){f.mask(this)});if(void 0===i)return this.each(function(){f=new t(r);f.mask(this)})}}),n.fn.inputmask}(jQuery,Inputmask),function(){}(jQuery,Inputmask),function(n,t){function i(n){return isNaN(n)||29===new Date(n,2,0).getDate()}return t.extendAliases({"dd/mm/yyyy":{mask:"1/2/y",placeholder:"dd/mm/yyyy",regex:{val1pre:new RegExp("[0-3]"),val1:new RegExp("0[1-9]|[12][0-9]|3[01]"),val2pre:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|[12][0-9]|3[01])"+i+"[01])")},val2:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|[12][0-9])"+i+"(0[1-9]|1[012]))|(30"+i+"(0[13-9]|1[012]))|(31"+i+"(0[13578]|1[02]))")}},leapday:"29/02/",separator:"/",yearrange:{minyear:1900,maxyear:2099},isInYearRange:function(n,t,i){if(isNaN(n))return!1;var r=parseInt(n.concat(t.toString().slice(n.length))),u=parseInt(n.concat(i.toString().slice(n.length)));return!isNaN(r)&&t<=r&&r<=i||!isNaN(u)&&t<=u&&u<=i},determinebaseyear:function(n,t,i){var r=(new Date).getFullYear(),u,s,e,f,o;if(n>r)return n;if(t<r){for(u=t.toString().slice(0,2),s=t.toString().slice(2,4);t<u+i;)u--;return e=u+s,n>e?n:e}if(n<=r&&r<=t){for(f=r.toString().slice(0,2);t<f+i;)f--;return o=f+i,o<n?n:o}return r},onKeyDown:function(i){var u=n(this),r;i.ctrlKey&&i.keyCode===t.keyCode.RIGHT&&(r=new Date,u.val(r.getDate().toString()+(r.getMonth()+1).toString()+r.getFullYear().toString()),u.trigger("setvalue"))},getFrontValue:function(n,t,i){for(var f,e=0,r=0,u=0;u<n.length&&"2"!==n.charAt(u);u++)f=i.definitions[n.charAt(u)],f?(e+=r,r=f.cardinality):r++;return t.join("").substr(e,r)},postValidation:function(n,t,r){var f,e,u=n.join("");return 0===r.mask.indexOf("y")?(e=u.substr(0,4),f=u.substr(4,11)):(e=u.substr(6,11),f=u.substr(0,6)),t&&(f!==r.leapday||i(e))},definitions:{"1":{validator:function(n,t,i,r,u){var f=u.regex.val1.test(n);return r||f||n.charAt(1)!==u.separator&&"-./".indexOf(n.charAt(1))===-1||!(f=u.regex.val1.test("0"+n.charAt(0)))?f:(t.buffer[i-1]="0",{refreshFromBuffer:{start:i-1,end:i},pos:i,c:n.charAt(0)})},cardinality:2,prevalidator:[{validator:function(n,t,i,r,u){var e=n,f;if(isNaN(t.buffer[i+1])||(e+=t.buffer[i+1]),f=1===e.length?u.regex.val1pre.test(e):u.regex.val1.test(e),!r&&!f){if(f=u.regex.val1.test(n+"0"))return t.buffer[i]=n,t.buffer[++i]="0",{pos:i,c:"0"};if(f=u.regex.val1.test("0"+n))return t.buffer[i]="0",i++,{pos:i}}return f},cardinality:1}]},"2":{validator:function(n,t,i,r,u){var f=u.getFrontValue(t.mask,t.buffer,u),e;return f.indexOf(u.placeholder[0])!==-1&&(f="01"+u.separator),e=u.regex.val2(u.separator).test(f+n),r||e||n.charAt(1)!==u.separator&&"-./".indexOf(n.charAt(1))===-1||!(e=u.regex.val2(u.separator).test(f+"0"+n.charAt(0)))?e:(t.buffer[i-1]="0",{refreshFromBuffer:{start:i-1,end:i},pos:i,c:n.charAt(0)})},cardinality:2,prevalidator:[{validator:function(n,t,i,r,u){var f,e;return isNaN(t.buffer[i+1])||(n+=t.buffer[i+1]),f=u.getFrontValue(t.mask,t.buffer,u),f.indexOf(u.placeholder[0])!==-1&&(f="01"+u.separator),e=1===n.length?u.regex.val2pre(u.separator).test(f+n):u.regex.val2(u.separator).test(f+n),r||e||!(e=u.regex.val2(u.separator).test(f+"0"+n))?e:(t.buffer[i]="0",i++,{pos:i})},cardinality:1}]},y:{validator:function(n,t,i,r,u){return u.isInYearRange(n,u.yearrange.minyear,u.yearrange.maxyear)},cardinality:4,prevalidator:[{validator:function(n,t,i,r,u){var e=u.isInYearRange(n,u.yearrange.minyear,u.yearrange.maxyear),f;if(!r&&!e){if(f=u.determinebaseyear(u.yearrange.minyear,u.yearrange.maxyear,n+"0").toString().slice(0,1),e=u.isInYearRange(f+n,u.yearrange.minyear,u.yearrange.maxyear))return t.buffer[i++]=f.charAt(0),{pos:i};if(f=u.determinebaseyear(u.yearrange.minyear,u.yearrange.maxyear,n+"0").toString().slice(0,2),e=u.isInYearRange(f+n,u.yearrange.minyear,u.yearrange.maxyear))return t.buffer[i++]=f.charAt(0),t.buffer[i++]=f.charAt(1),{pos:i}}return e},cardinality:1},{validator:function(n,t,i,r,u){var e=u.isInYearRange(n,u.yearrange.minyear,u.yearrange.maxyear),f;if(!r&&!e){if(f=u.determinebaseyear(u.yearrange.minyear,u.yearrange.maxyear,n).toString().slice(0,2),e=u.isInYearRange(n[0]+f[1]+n[1],u.yearrange.minyear,u.yearrange.maxyear))return t.buffer[i++]=f.charAt(1),{pos:i};if(f=u.determinebaseyear(u.yearrange.minyear,u.yearrange.maxyear,n).toString().slice(0,2),e=u.isInYearRange(f+n,u.yearrange.minyear,u.yearrange.maxyear))return t.buffer[i-1]=f.charAt(0),t.buffer[i++]=f.charAt(1),t.buffer[i++]=n.charAt(0),{refreshFromBuffer:{start:i-3,end:i},pos:i}}return e},cardinality:2},{validator:function(n,t,i,r,u){return u.isInYearRange(n,u.yearrange.minyear,u.yearrange.maxyear)},cardinality:3}]}},insertMode:!1,autoUnmask:!1},"mm/dd/yyyy":{placeholder:"mm/dd/yyyy",alias:"dd/mm/yyyy",regex:{val2pre:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[13-9]|1[012])"+i+"[0-3])|(02"+i+"[0-2])")},val2:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|1[012])"+i+"(0[1-9]|[12][0-9]))|((0[13-9]|1[012])"+i+"30)|((0[13578]|1[02])"+i+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},leapday:"02/29/",onKeyDown:function(i){var u=n(this),r;i.ctrlKey&&i.keyCode===t.keyCode.RIGHT&&(r=new Date,u.val((r.getMonth()+1).toString()+r.getDate().toString()+r.getFullYear().toString()),u.trigger("setvalue"))}},"yyyy/mm/dd":{mask:"y/1/2",placeholder:"yyyy/mm/dd",alias:"mm/dd/yyyy",leapday:"/02/29",onKeyDown:function(i){var u=n(this),r;i.ctrlKey&&i.keyCode===t.keyCode.RIGHT&&(r=new Date,u.val(r.getFullYear().toString()+(r.getMonth()+1).toString()+r.getDate().toString()),u.trigger("setvalue"))}},"dd.mm.yyyy":{mask:"1.2.y",placeholder:"dd.mm.yyyy",leapday:"29.02.",separator:".",alias:"dd/mm/yyyy"},"dd-mm-yyyy":{mask:"1-2-y",placeholder:"dd-mm-yyyy",leapday:"29-02-",separator:"-",alias:"dd/mm/yyyy"},"mm.dd.yyyy":{mask:"1.2.y",placeholder:"mm.dd.yyyy",leapday:"02.29.",separator:".",alias:"mm/dd/yyyy"},"mm-dd-yyyy":{mask:"1-2-y",placeholder:"mm-dd-yyyy",leapday:"02-29-",separator:"-",alias:"mm/dd/yyyy"},"yyyy.mm.dd":{mask:"y.1.2",placeholder:"yyyy.mm.dd",leapday:".02.29",separator:".",alias:"yyyy/mm/dd"},"yyyy-mm-dd":{mask:"y-1-2",placeholder:"yyyy-mm-dd",leapday:"-02-29",separator:"-",alias:"yyyy/mm/dd"},datetime:{mask:"1/2/y h:s",placeholder:"dd/mm/yyyy hh:mm",alias:"dd/mm/yyyy",regex:{hrspre:new RegExp("[012]"),hrs24:new RegExp("2[0-4]|1[3-9]"),hrs:new RegExp("[01][0-9]|2[0-4]"),ampm:new RegExp("^[a|p|A|P][m|M]"),mspre:new RegExp("[0-5]"),ms:new RegExp("[0-5][0-9]")},timeseparator:":",hourFormat:"24",definitions:{h:{validator:function(n,t,i,r,u){var e,f;return"24"===u.hourFormat&&24===parseInt(n,10)?(t.buffer[i-1]="0",t.buffer[i]="0",{refreshFromBuffer:{start:i-1,end:i},c:"0"}):(e=u.regex.hrs.test(n),!r&&!e&&(n.charAt(1)===u.timeseparator||"-.:".indexOf(n.charAt(1))!==-1)&&(e=u.regex.hrs.test("0"+n.charAt(0))))?(t.buffer[i-1]="0",t.buffer[i]=n.charAt(0),i++,{refreshFromBuffer:{start:i-2,end:i},pos:i,c:u.timeseparator}):e&&"24"!==u.hourFormat&&u.regex.hrs24.test(n)?(f=parseInt(n,10),24===f?(t.buffer[i+5]="a",t.buffer[i+6]="m"):(t.buffer[i+5]="p",t.buffer[i+6]="m"),f-=12,f<10?(t.buffer[i]=f.toString(),t.buffer[i-1]="0"):(t.buffer[i]=f.toString().charAt(1),t.buffer[i-1]=f.toString().charAt(0)),{refreshFromBuffer:{start:i-1,end:i+6},c:t.buffer[i]}):e},cardinality:2,prevalidator:[{validator:function(n,t,i,r,u){var f=u.regex.hrspre.test(n);return r||f||!(f=u.regex.hrs.test("0"+n))?f:(t.buffer[i]="0",i++,{pos:i})},cardinality:1}]},s:{validator:"[0-5][0-9]",cardinality:2,prevalidator:[{validator:function(n,t,i,r,u){var f=u.regex.mspre.test(n);return r||f||!(f=u.regex.ms.test("0"+n))?f:(t.buffer[i]="0",i++,{pos:i})},cardinality:1}]},t:{validator:function(n,t,i,r,u){return u.regex.ampm.test(n+"m")},casing:"lower",cardinality:1}},insertMode:!1,autoUnmask:!1},datetime12:{mask:"1/2/y h:s t\\m",placeholder:"dd/mm/yyyy hh:mm xm",alias:"datetime",hourFormat:"12"},"mm/dd/yyyy hh:mm xm":{mask:"1/2/y h:s t\\m",placeholder:"mm/dd/yyyy hh:mm xm",alias:"datetime12",regex:{val2pre:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[13-9]|1[012])"+i+"[0-3])|(02"+i+"[0-2])")},val2:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|1[012])"+i+"(0[1-9]|[12][0-9]))|((0[13-9]|1[012])"+i+"30)|((0[13578]|1[02])"+i+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},leapday:"02/29/",onKeyDown:function(i){var u=n(this),r;i.ctrlKey&&i.keyCode===t.keyCode.RIGHT&&(r=new Date,u.val((r.getMonth()+1).toString()+r.getDate().toString()+r.getFullYear().toString()),u.trigger("setvalue"))}},"hh:mm t":{mask:"h:s t\\m",placeholder:"hh:mm xm",alias:"datetime",hourFormat:"12"},"h:s t":{mask:"h:s t\\m",placeholder:"hh:mm xm",alias:"datetime",hourFormat:"12"},"hh:mm:ss":{mask:"h:s:s",placeholder:"hh:mm:ss",alias:"datetime",autoUnmask:!1},"hh:mm":{mask:"h:s",placeholder:"hh:mm",alias:"datetime",autoUnmask:!1},date:{alias:"dd/mm/yyyy"},"mm/yyyy":{mask:"1/y",placeholder:"mm/yyyy",leapday:"donotuse",separator:"/",alias:"mm/dd/yyyy"},shamsi:{regex:{val2pre:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|1[012])"+i+"[0-3])")},val2:function(n){var i=t.escapeRegex.call(this,n);return new RegExp("((0[1-9]|1[012])"+i+"(0[1-9]|[12][0-9]))|((0[1-9]|1[012])"+i+"30)|((0[1-6])"+i+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},yearrange:{minyear:1300,maxyear:1499},mask:"y/1/2",leapday:"/12/30",placeholder:"yyyy/mm/dd",alias:"mm/dd/yyyy",clearIncomplete:!0}}),t}(jQuery,Inputmask),function(n,t){return t.extendDefinitions({A:{validator:"[A-Za-zА-яЁёÀ-ÿµ]",cardinality:1,casing:"upper"},"&":{validator:"[0-9A-Za-zА-яЁёÀ-ÿµ]",cardinality:1,casing:"upper"},"#":{validator:"[0-9A-Fa-f]",cardinality:1,casing:"upper"},x:{validator:"3[47]",cardinality:2,prevalidator:[{validator:"3",cardinality:1}]},o:{validator:function(n){return/\d\d/.test(n)&&n!=="34"&&n!=="37"},cardinality:2,prevalidator:[{validator:"\\d",cardinality:1}]}}),t.extendAliases({url:{definitions:{i:{validator:".",cardinality:1}},mask:"(\\http://)|(\\http\\s://)|(ftp://)|(ftp\\s://)i{+}",insertMode:!1,autoUnmask:!1,inputmode:"url"},ip:{mask:"i[i[i]].i[i[i]].i[i[i]].i[i[i]]",definitions:{i:{validator:function(n,t,i){return i-1>-1&&"."!==t.buffer[i-1]?(n=t.buffer[i-1]+n,n=i-2>-1&&"."!==t.buffer[i-2]?t.buffer[i-2]+n:"0"+n):n="00"+n,new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(n)},cardinality:1}},onUnMask:function(n){return n},inputmode:"numeric"},email:{mask:"*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]",greedy:!1,onBeforePaste:function(n){return n=n.toLowerCase(),n.replace("mailto:","")},definitions:{"*":{validator:"[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]",cardinality:1,casing:"lower"},"-":{validator:"[0-9A-Za-z-]",cardinality:1,casing:"lower"}},onUnMask:function(n){return n},inputmode:"email"},mac:{mask:"##:##:##:##:##:##"},vin:{mask:"V{13}9{4}",definitions:{V:{validator:"[A-HJ-NPR-Za-hj-npr-z\\d]",cardinality:1,casing:"upper"}},clearIncomplete:!0,autoUnmask:!0}}),t}(jQuery,Inputmask),function(n,t){return t.extendAliases({numeric:{mask:function(n){function f(t){for(var r="",i=0;i<t.length;i++)r+=n.definitions[t.charAt(i)]||n.optionalmarker.start===t.charAt(i)||n.optionalmarker.end===t.charAt(i)||n.quantifiermarker.start===t.charAt(i)||n.quantifiermarker.end===t.charAt(i)||n.groupmarker.start===t.charAt(i)||n.groupmarker.end===t.charAt(i)||n.alternatormarker===t.charAt(i)?"\\"+t.charAt(i):t.charAt(i);return r}var u,e,i,r;return(0!==n.repeat&&isNaN(n.integerDigits)&&(n.integerDigits=n.repeat),n.repeat=0,n.groupSeparator===n.radixPoint&&(n.groupSeparator="."===n.radixPoint?",":","===n.radixPoint?".":"")," "===n.groupSeparator&&(n.skipOptionalPartCharacter=void 0),n.autoGroup=n.autoGroup&&""!==n.groupSeparator,n.autoGroup&&("string"==typeof n.groupSize&&isFinite(n.groupSize)&&(n.groupSize=parseInt(n.groupSize)),isFinite(n.integerDigits)))&&(u=Math.floor(n.integerDigits/n.groupSize),e=n.integerDigits%n.groupSize,n.integerDigits=parseInt(n.integerDigits)+(0===e?u-1:u),n.integerDigits<1&&(n.integerDigits="*")),n.placeholder.length>1&&(n.placeholder=n.placeholder.charAt(0)),"radixFocus"===n.positionCaretOnClick&&""===n.placeholder&&n.integerOptional===!1&&(n.positionCaretOnClick="lvp"),n.definitions[";"]=n.definitions["~"],n.definitions[";"].definitionSymbol="~",n.numericInput===!0&&(n.positionCaretOnClick="radixFocus"===n.positionCaretOnClick?"lvp":n.positionCaretOnClick,n.digitsOptional=!1,isNaN(n.digits)&&(n.digits=2),n.decimalProtect=!1),i="[+]",(i+=f(n.prefix),i+=n.integerOptional===!0?"~{1,"+n.integerDigits+"}":"~{"+n.integerDigits+"}",void 0!==n.digits)&&(n.decimalProtect&&(n.radixPointDefinitionSymbol=":"),r=n.digits.toString().split(","),isFinite(r[0]&&r[1]&&isFinite(r[1]))?i+=(n.decimalProtect?":":n.radixPoint)+";{"+n.digits+"}":(isNaN(n.digits)||parseInt(n.digits)>0)&&(i+=n.digitsOptional?"["+(n.decimalProtect?":":n.radixPoint)+";{1,"+n.digits+"}]":(n.decimalProtect?":":n.radixPoint)+";{"+n.digits+"}")),i+=f(n.suffix),i+="[-]",n.greedy=!1,null!==n.min&&(n.min=n.min.toString().replace(new RegExp(t.escapeRegex(n.groupSeparator),"g"),""),","===n.radixPoint&&(n.min=n.min.replace(n.radixPoint,"."))),null!==n.max&&(n.max=n.max.toString().replace(new RegExp(t.escapeRegex(n.groupSeparator),"g"),""),","===n.radixPoint&&(n.max=n.max.replace(n.radixPoint,"."))),i},placeholder:"",greedy:!1,digits:"*",digitsOptional:!0,radixPoint:".",positionCaretOnClick:"radixFocus",groupSize:3,groupSeparator:"",autoGroup:!1,allowPlus:!0,allowMinus:!0,negationSymbol:{front:"-",back:""},integerDigits:"+",integerOptional:!0,prefix:"",suffix:"",rightAlign:!0,decimalProtect:!0,min:null,max:null,step:1,insertMode:!0,autoUnmask:!1,unmaskAsNumber:!1,inputmode:"numeric",postFormat:function(i,r,u){var c,y,h,o,s,f,p,w,l,a,v,e;if(u.numericInput===!0&&(i=i.reverse(),isFinite(r)&&(r=i.join("").length-r-1)),r=r>=i.length?i.length-1:r<0?0:r,h=i[r],o=i.slice(),h===u.groupSeparator&&(o.splice(r--,1),h=o[r]),s=o.join("").match(new RegExp("^"+t.escapeRegex(u.negationSymbol.front))),s=null!==s&&1===s.length,r>(s?u.negationSymbol.front.length:0)+u.prefix.length&&r<o.length-u.suffix.length&&(o[r]="!"),f=o.join(""),p=o.join(),s&&(f=f.replace(new RegExp("^"+t.escapeRegex(u.negationSymbol.front)),""),f=f.replace(new RegExp(t.escapeRegex(u.negationSymbol.back)+"$"),"")),f=f.replace(new RegExp(t.escapeRegex(u.suffix)+"$"),""),f=f.replace(new RegExp("^"+t.escapeRegex(u.prefix)),""),f.length>0&&u.autoGroup||f.indexOf(u.groupSeparator)!==-1){if(w=t.escapeRegex(u.groupSeparator),f=f.replace(new RegExp(w,"g"),""),l=f.split(h===u.radixPoint?"!":u.radixPoint),f=""===u.radixPoint?f:l[0],h!==u.negationSymbol.front&&(f=f.replace("!","?")),f.length>u.groupSize)for(a=new RegExp("([-+]?[\\d?]+)([\\d?]{"+u.groupSize+"})");a.test(f)&&""!==u.groupSeparator;)f=f.replace(a,"$1"+u.groupSeparator+"$2"),f=f.replace(u.groupSeparator+u.groupSeparator,u.groupSeparator);f=f.replace("?","!");""!==u.radixPoint&&l.length>1&&(f+=(h===u.radixPoint?"!":u.radixPoint)+l[1])}if(f=u.prefix+f+u.suffix,s&&(f=u.negationSymbol.front+f+u.negationSymbol.back),v=p!==f.split("").join(),e=n.inArray("!",f),e===-1&&(e=r),v){for(i.length=f.length,c=0,y=f.length;c<y;c++)i[c]=f.charAt(c);i[e]=h}return e=u.numericInput&&isFinite(r)?i.join("").length-e-1:e,u.numericInput&&(i=i.reverse(),n.inArray(u.radixPoint,i)<e&&i.join("").length-u.suffix.length!==e&&(e-=1)),{pos:e,refreshFromBuffer:v,buffer:i,isNegative:s}},onBeforeWrite:function(i,r,u,f){var o,a,e,h,c,y,l,v,s;if(i&&("blur"===i.type||"checkval"===i.type||"keydown"===i.type)&&(a=f.numericInput?r.slice().reverse().join(""):r.join(""),e=a.replace(f.prefix,""),e=e.replace(f.suffix,""),e=e.replace(new RegExp(t.escapeRegex(f.groupSeparator),"g"),""),","===f.radixPoint&&(e=e.replace(f.radixPoint,".")),h=e.match(new RegExp("[-"+t.escapeRegex(f.negationSymbol.front)+"]","g")),h=null!==h&&1===h.length,e=e.replace(new RegExp("[-"+t.escapeRegex(f.negationSymbol.front)+"]","g"),""),e=e.replace(new RegExp(t.escapeRegex(f.negationSymbol.back)+"$"),""),isNaN(f.placeholder)&&(e=e.replace(new RegExp(t.escapeRegex(f.placeholder),"g"),"")),e=e===f.negationSymbol.front?e+"0":e,""!==e&&isFinite(e))){if(c=parseFloat(e),y=h?c*-1:c,null!==f.min&&isFinite(f.min)&&y<parseFloat(f.min)?(c=Math.abs(f.min),h=f.min<0,a=void 0):null!==f.max&&isFinite(f.max)&&y>parseFloat(f.max)&&(c=Math.abs(f.max),h=f.max<0,a=void 0),e=c.toString().replace(".",f.radixPoint).split(""),isFinite(f.digits)){for(l=n.inArray(f.radixPoint,e),v=n.inArray(f.radixPoint,a),l===-1&&(e.push(f.radixPoint),l=e.length-1),s=1;s<=f.digits;s++)f.digitsOptional||void 0!==e[l+s]&&e[l+s]!==f.placeholder.charAt(0)?v!==-1&&void 0!==a[v+s]&&(e[l+s]=e[l+s]||a[v+s]):e[l+s]="0";e[e.length-1]===f.radixPoint&&delete e[e.length-1]}if(c.toString()!==e&&c.toString()+"."!==e||h)return e=(f.prefix+e.join("")).split(""),!h||0===c&&"blur"===i.type||(e.unshift(f.negationSymbol.front),e.push(f.negationSymbol.back)),f.numericInput&&(e=e.reverse()),o=f.postFormat(e,f.numericInput?u:u-1,f),o.buffer&&(o.refreshFromBuffer=o.buffer.join("")!==r.join("")),o}if(f.autoGroup)return o=f.postFormat(r,f.numericInput?u:u-1,f),o.caret=u<(o.isNegative?f.negationSymbol.front.length:0)+f.prefix.length||u>o.buffer.length-(o.isNegative?f.negationSymbol.back.length:0)?o.pos:o.pos+1,o},regex:{integerPart:function(n){return new RegExp("["+t.escapeRegex(n.negationSymbol.front)+"+]?\\d+")},integerNPart:function(n){return new RegExp("[\\d"+t.escapeRegex(n.groupSeparator)+t.escapeRegex(n.placeholder.charAt(0))+"]+")}},signHandler:function(n,t,i,r,u){if(!r&&u.allowMinus&&"-"===n||u.allowPlus&&"+"===n){var f=t.buffer.join("").match(u.regex.integerPart(u));if(f&&f[0].length>0)return t.buffer[f.index]===("-"===n?"+":u.negationSymbol.front)?"-"===n?""!==u.negationSymbol.back?{pos:0,c:u.negationSymbol.front,remove:0,caret:i,insert:{pos:t.buffer.length-1,c:u.negationSymbol.back}}:{pos:0,c:u.negationSymbol.front,remove:0,caret:i}:""!==u.negationSymbol.back?{pos:0,c:"+",remove:[0,t.buffer.length-1],caret:i}:{pos:0,c:"+",remove:0,caret:i}:t.buffer[0]===("-"===n?u.negationSymbol.front:"+")?"-"===n&&""!==u.negationSymbol.back?{remove:[0,t.buffer.length-1],caret:i-1}:{remove:0,caret:i-1}:"-"===n?""!==u.negationSymbol.back?{pos:0,c:u.negationSymbol.front,caret:i+1,insert:{pos:t.buffer.length,c:u.negationSymbol.back}}:{pos:0,c:u.negationSymbol.front,caret:i+1}:{pos:0,c:n,caret:i+1}}return!1},radixHandler:function(t,i,r,u,f){if(!u&&f.numericInput!==!0&&t===f.radixPoint&&void 0!==f.digits&&(isNaN(f.digits)||parseInt(f.digits)>0)){var o=n.inArray(f.radixPoint,i.buffer),e=i.buffer.join("").match(f.regex.integerPart(f));if(o!==-1&&i.validPositions[o])return i.validPositions[o-1]?{caret:o+1}:{pos:e.index,c:e[0],caret:o+1};if(!e||"0"===e[0]&&e.index+1!==r)return i.buffer[e?e.index:r]="0",{pos:(e?e.index:r)+1,c:f.radixPoint}}return!1},leadingZeroHandler:function(t,i,r,u,f,e){var o,c,h,s,l;if(!u)if(o=i.buffer.slice(""),o.splice(0,f.prefix.length),o.splice(o.length-f.suffix.length,f.suffix.length),f.numericInput===!0){if(o=o.reverse(),c=o[0],"0"===c&&void 0===i.validPositions[r-1])return{pos:r,remove:o.length-1}}else if(r-=f.prefix.length,h=n.inArray(f.radixPoint,o),s=o.slice(0,h!==-1?h:void 0).join("").match(f.regex.integerNPart(f)),s&&(h===-1||r<=h)){if(l=h===-1?0:parseInt(o.slice(h+1).join("")),0===s[0].indexOf(""!==f.placeholder?f.placeholder.charAt(0):"0")&&(s.index+1===r||e!==!0&&0===l))return i.buffer.splice(s.index+f.prefix.length,1),{pos:s.index+f.prefix.length,remove:s.index+f.prefix.length};if("0"===t&&r<=s.index&&s[0]!==f.groupSeparator)return!1}return!0},definitions:{"~":{validator:function(i,r,u,f,e,o){var s=e.signHandler(i,r,u,f,e),h;return s||(s=e.radixHandler(i,r,u,f,e),s||(s=f?new RegExp("[0-9"+t.escapeRegex(e.groupSeparator)+"]").test(i):new RegExp("[0-9]").test(i),s!==!0||(s=e.leadingZeroHandler(i,r,u,f,e,o),s!==!0)))||(h=n.inArray(e.radixPoint,r.buffer),s=h!==-1&&(e.digitsOptional===!1||r.validPositions[u])&&e.numericInput!==!0&&u>h&&!f?{pos:u,remove:u}:{pos:u}),s},cardinality:1},"+":{validator:function(n,t,i,r,u){var f=u.signHandler(n,t,i,r,u);return!f&&(r&&u.allowMinus&&n===u.negationSymbol.front||u.allowMinus&&"-"===n||u.allowPlus&&"+"===n)&&(f=!(!r&&"-"===n)||(""!==u.negationSymbol.back?{pos:i,c:"-"===n?u.negationSymbol.front:"+",caret:i+1,insert:{pos:t.buffer.length,c:u.negationSymbol.back}}:{pos:i,c:"-"===n?u.negationSymbol.front:"+",caret:i+1})),f},cardinality:1,placeholder:""},"-":{validator:function(n,t,i,r,u){var f=u.signHandler(n,t,i,r,u);return!f&&r&&u.allowMinus&&n===u.negationSymbol.back&&(f=!0),f},cardinality:1,placeholder:""},":":{validator:function(n,i,r,u,f){var e=f.signHandler(n,i,r,u,f),o;return e||(o="["+t.escapeRegex(f.radixPoint)+"]",e=new RegExp(o).test(n),e&&i.validPositions[r]&&i.validPositions[r].match.placeholder===f.radixPoint&&(e={caret:r+1})),e},cardinality:1,placeholder:function(n){return n.radixPoint}}},onUnMask:function(n,i,r){if(""===i&&r.nullable===!0)return i;var u=n.replace(r.prefix,"");return u=u.replace(r.suffix,""),u=u.replace(new RegExp(t.escapeRegex(r.groupSeparator),"g"),""),r.unmaskAsNumber?(""!==r.radixPoint&&u.indexOf(r.radixPoint)!==-1&&(u=u.replace(t.escapeRegex.call(this,r.radixPoint),".")),Number(u)):u},isComplete:function(n,i){var u=n.join(""),f=n.slice(),r;return(i.postFormat(f,0,i),f.join("")!==u)?!1:(r=u.replace(i.prefix,""),r=r.replace(i.suffix,""),r=r.replace(new RegExp(t.escapeRegex(i.groupSeparator),"g"),""),","===i.radixPoint&&(r=r.replace(t.escapeRegex(i.radixPoint),".")),isFinite(r))},onBeforeMask:function(n,i){var r,e,u,f,s,h,o;return(i.numericInput===!0&&(n=n.split("").reverse().join("")),""!==i.radixPoint&&isFinite(n))&&(r=n.split("."),e=""!==i.groupSeparator?parseInt(i.groupSize):0,2===r.length&&(r[0].length>e||r[1].length>e)&&(n=n.toString().replace(".",i.radixPoint))),u=n.match(/,/g),f=n.match(/\./g),(f&&u?f.length>u.length?(n=n.replace(/\./g,""),n=n.replace(",",i.radixPoint)):u.length>f.length?(n=n.replace(/,/g,""),n=n.replace(".",i.radixPoint)):n=n.indexOf(".")<n.indexOf(",")?n.replace(/\./g,""):n=n.replace(/,/g,""):n=n.replace(new RegExp(t.escapeRegex(i.groupSeparator),"g"),""),0===i.digits&&(n.indexOf(".")!==-1?n=n.substring(0,n.indexOf(".")):n.indexOf(",")!==-1&&(n=n.substring(0,n.indexOf(",")))),""!==i.radixPoint&&isFinite(i.digits)&&n.indexOf(i.radixPoint)!==-1)&&(s=n.split(i.radixPoint),h=s[1].match(new RegExp("\\d*"))[0],parseInt(i.digits)<h.toString().length&&(o=Math.pow(10,parseInt(i.digits)),n=n.replace(t.escapeRegex(i.radixPoint),"."),n=Math.round(parseFloat(n)*o)/o,n=n.toString().replace(".",i.radixPoint))),i.numericInput===!0&&(n=n.split("").reverse().join("")),n.toString()},canClearPosition:function(n,t,i,r,u){var f=n.validPositions[t].input;return f!==u.radixPoint||null!==n.validPositions[t].match.fn&&u.decimalProtect===!1||isFinite(f)||t===i||f===u.groupSeparator||f===u.negationSymbol.front||f===u.negationSymbol.back},onKeyDown:function(i,r,u,f){var e=n(this);if(i.ctrlKey)switch(i.keyCode){case t.keyCode.UP:e.val(parseFloat(this.inputmask.unmaskedvalue())+parseInt(f.step));e.trigger("setvalue");break;case t.keyCode.DOWN:e.val(parseFloat(this.inputmask.unmaskedvalue())-parseInt(f.step));e.trigger("setvalue")}}},currency:{prefix:"$ ",groupSeparator:",",alias:"numeric",placeholder:"0",autoGroup:!0,digits:2,digitsOptional:!1,clearMaskOnLostFocus:!1},decimal:{alias:"numeric"},integer:{alias:"numeric",digits:0,radixPoint:""},percentage:{alias:"numeric",digits:2,radixPoint:".",placeholder:"0",autoGroup:!1,min:0,max:100,suffix:" %",allowPlus:!1,allowMinus:!1}}),t}(jQuery,Inputmask),function(n,t){function i(n,t){var u=(n.mask||n).replace(/#/g,"9").replace(/\)/,"9").replace(/[+()#-]/g,""),f=(t.mask||t).replace(/#/g,"9").replace(/\)/,"9").replace(/[+()#-]/g,""),i=(n.mask||n).split("#")[0],r=(t.mask||t).split("#")[0];return 0===r.indexOf(i)?-1:0===i.indexOf(r)?1:u.localeCompare(f)}var r=t.prototype.analyseMask;return t.prototype.analyseMask=function(t,i){function u(n,i,r){var h;i=i||"";r=r||e;""!==i&&(r[i]={});for(var s="",f=r[i]||r,o=n.length-1;o>=0;o--)t=n[o].mask||n[o],s=t.substr(0,1),f[s]=f[s]||[],f[s].unshift(t.substr(1)),n.splice(o,1);for(h in f)f[h].length>500&&u(f[h].slice(),h,f)}function f(t){var u=[];for(var r in t)n.isArray(t[r])?1===t[r].length?u.push(r+t[r]):u.push(r+i.groupmarker.start+t[r].join(i.groupmarker.end+i.alternatormarker+i.groupmarker.start)+i.groupmarker.end):u.push(r+f(t[r]));return""+(1===u.length?u[0]:i.groupmarker.start+u.join(i.groupmarker.end+i.alternatormarker+i.groupmarker.start)+i.groupmarker.end)}var e={};return i.phoneCodes&&i.phoneCodes.length>1e3&&(t=t.substr(1,t.length-2),u(t.split(i.groupmarker.end+i.alternatormarker+i.groupmarker.start)),t=f(e)),r.call(this,t,i)},t.extendAliases({abstractphone:{groupmarker:{start:"<",end:">"},countrycode:"",phoneCodes:[],mask:function(n){return n.definitions={"#":n.definitions[9]},n.phoneCodes.sort(i)},keepStatic:!0,onBeforeMask:function(n,t){var i=n.replace(/^0{1,2}/,"").replace(/[\s]/g,"");return(i.indexOf(t.countrycode)>1||i.indexOf(t.countrycode)===-1)&&(i="+"+t.countrycode+i),i},onUnMask:function(n,t){return t},inputmode:"tel"}}),t}(jQuery,Inputmask),function(n,t){return t.extendAliases({Regex:{mask:"r",greedy:!1,repeat:"*",regex:null,regexTokens:null,tokenizer:/\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,quantifierFilter:/[0-9]+[^,]/,isComplete:function(n,t){return new RegExp(t.regex).test(n.join(""))},definitions:{r:{validator:function(t,i,r,u,f){function h(n,t){this.matches=[];this.isGroup=n||!1;this.isQuantifier=t||!1;this.quantifier={min:1,max:1};this.repeaterPart=void 0}function w(){var n,i,r=new h,t=[],e,s;for(f.regexTokens=[];n=f.tokenizer.exec(f.regex);)switch(i=n[0],i.charAt(0)){case"(":t.push(new h(!0));break;case")":o=t.pop();t.length>0?t[t.length-1].matches.push(o):r.matches.push(o);break;case"{":case"+":case"*":e=new h(!1,!0);i=i.replace(/[{}]/g,"");var u=i.split(","),c=isNaN(u[0])?u[0]:parseInt(u[0]),l=1===u.length?c:isNaN(u[1])?u[1]:parseInt(u[1]);(e.quantifier={min:c,max:l},t.length>0)?(s=t[t.length-1].matches,n=s.pop(),n.isGroup||(o=new h(!0),o.matches.push(n),n=o),s.push(n),s.push(e)):(n=r.matches.pop(),n.isGroup||(o=new h(!0),o.matches.push(n),n=o),r.matches.push(n),r.matches.push(e));break;default:t.length>0?t[t.length-1].matches.push(i):r.matches.push(i)}r.matches.length>0&&f.regexTokens.push(r)}function s(t,i){var u=!1,l,r,w,k,v,f,h,d,o,y;for(i&&(e+="(",c++),l=0;l<t.matches.length;l++){if(r=t.matches[l],r.isGroup===!0)u=s(r,!0);else if(r.isQuantifier===!0){var g=n.inArray(r,t.matches),p=t.matches[g-1],b=e;if(isNaN(r.quantifier.max)){for(;r.repeaterPart&&r.repeaterPart!==e&&r.repeaterPart.length>e.length&&!(u=s(p,!0)););u=u||s(p,!0);u&&(r.repeaterPart=e);e=b+r.quantifier.max}else{for(w=0,k=r.quantifier.max-1;w<k&&!(u=s(p,!0));w++);e=b+"{"+r.quantifier.min+","+r.quantifier.max+"}"}}else if(void 0!==r.matches)for(v=0;v<r.length&&!(u=s(r[v],i));v++);else{if("["==r.charAt(0)){for(f=e,f+=r,o=0;o<c;o++)f+=")";y=new RegExp("^("+f+")$");u=y.test(a)}else for(h=0,d=r.length;h<d;h++)if("\\"!==r.charAt(h)){for(f=e,f+=r.substr(0,h+1),f=f.replace(/\|$/,""),o=0;o<c;o++)f+=")";if(y=new RegExp("^("+f+")$"),u=y.test(a))break}e+=r}if(u)break}return i&&(e+=")",c--),u}var a,o,y=i.buffer.slice(),e="",p=!1,c=0,l,v;for(null===f.regexTokens&&w(),y.splice(r,0,t),a=y.join(""),l=0;l<f.regexTokens.length;l++)if(v=f.regexTokens[l],p=s(v,v.isGroup))break;return p},cardinality:1}}}}),t}(jQuery,Inputmask);;
(function(n){"use strict";var t={item:3,autoWidth:!1,slideMove:1,slideMargin:10,addClass:"",border:0,mode:"slide",useCSS:!0,cssEasing:"ease",easing:"linear",speed:400,auto:!1,pauseOnHover:!1,loop:!1,slideEndAnimation:!0,pause:2e3,keyPress:!1,controls:!0,prevHtml:"",nextHtml:"",rtl:!1,adaptiveHeight:!1,vertical:!1,verticalHeight:500,vThumbWidth:100,thumbItem:10,pager:!0,gallery:!1,galleryMargin:5,thumbMargin:5,currentPagerPosition:"middle",enableTouch:!0,enableDrag:!0,freeMove:!0,swipeThreshold:40,responsive:[],onBeforeStart:function(){},onSliderLoad:function(){},onBeforeSlide:function(){},onAfterSlide:function(){},onBeforeNextSlide:function(){},onBeforePrevSlide:function(){}};n.fn.lightSlider=function(i){if(this.length===0)return this;if(this.length>1)return this.each(function(){n(this).lightSlider(i)}),this;var a={},r=n.extend(!0,{},t,i),p={},u=this;a.$el=this;r.mode==="fade"&&(r.vertical=!1);var s=u.children(),g=n(window).width(),ut=null,b=null,w=0,c=0,nt=!1,o=0,f="",e=0,tt=r.vertical===!0?"height":"width",it=r.vertical===!0?"margin-bottom":"margin-right",l=0,d=0,y=0,k=0,v=null,rt="ontouchstart"in document.documentElement,h={};h.chbreakpoint=function(){var f,i,t,u;if(g=n(window).width(),r.responsive.length){if(r.autoWidth===!1&&(f=r.item),g<r.responsive[0].breakpoint)for(i=0;i<r.responsive.length;i++)g<r.responsive[i].breakpoint&&(ut=r.responsive[i].breakpoint,b=r.responsive[i]);if(typeof b!="undefined"&&b!==null)for(t in b.settings)b.settings.hasOwnProperty(t)&&((typeof p[t]=="undefined"||p[t]===null)&&(p[t]=r[t]),r[t]=b.settings[t]);if(!n.isEmptyObject(p)&&g>r.responsive[0].breakpoint)for(u in p)p.hasOwnProperty(u)&&(r[u]=p[u]);r.autoWidth===!1&&l>0&&y>0&&f!==r.item&&(e=Math.round(l/((y+r.slideMargin)*r.slideMove)))}};h.calSW=function(){r.autoWidth===!1&&(y=(o-(r.item*r.slideMargin-r.slideMargin))/r.item)};h.calWidth=function(n){var i=n===!0?f.find(".lslide").length:s.length,t;if(r.autoWidth===!1)c=i*(y+r.slideMargin);else for(c=0,t=0;t<i;t++)c+=parseInt(s.eq(t).width())+r.slideMargin+r.border*2;return c};a={doCss:function(){var n=function(){for(var t=["transition","MozTransition","WebkitTransition","OTransition","msTransition","KhtmlTransition"],i=document.documentElement,n=0;n<t.length;n++)if(t[n]in i.style)return!0};return r.useCSS&&n()?!0:!1},keyPress:function(){if(r.keyPress)n(document).on("keyup.lightslider",function(t){n(":focus").is("input, textarea")||(t.preventDefault?t.preventDefault():t.returnValue=!1,t.keyCode===37?u.goToPrevSlide():t.keyCode===39&&u.goToNextSlide())})},controls:function(){if(r.controls){u.after('<div class="lSAction"><a class="lSPrev">'+r.prevHtml+'<\/a><a class="lSNext">'+r.nextHtml+"<\/a><\/div>");r.autoWidth?h.calWidth(!1)<o&&f.find(".lSAction").hide():w<=r.item&&f.find(".lSAction").hide();f.find(".lSAction a").on("click",function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,n(this).attr("class")==="lSPrev"?u.goToPrevSlide():u.goToNextSlide(),!1})}},initialStyle:function(){var n=this;r.mode==="fade"&&(r.autoWidth=!1,r.slideEndAnimation=!1);r.auto&&(r.slideEndAnimation=!1);r.autoWidth&&(r.slideMove=1,r.item=1);r.loop&&(r.slideMove=1,r.freeMove=!1);r.onBeforeStart.call(this,u);h.chbreakpoint();u.addClass("lightSlider").wrap('<div class="lSSlideOuter '+r.addClass+'"><div class="lSSlideWrapper"><\/div><\/div>');f=u.parent(".lSSlideWrapper");r.rtl===!0&&f.parent().addClass("lSrtl");r.vertical?(f.parent().addClass("vertical"),o=r.verticalHeight,f.css("height",o+"px")):o=u.outerWidth();s.addClass("lslide");r.loop===!0&&r.mode==="slide"&&(h.calSW(),h.clone=function(){var v,y,i,t,f,c,l,a;if(h.calWidth(!0)>o){for(v=0,y=0,i=0;i<s.length;i++)if(v+=parseInt(u.find(".lslide").eq(i).width())+r.slideMargin,y++,v>=o+r.slideMargin)break;if(t=r.autoWidth===!0?y:r.item,t<u.find(".clone.left").length)for(f=0;f<u.find(".clone.left").length-t;f++)s.eq(f).remove();if(t<u.find(".clone.right").length)for(c=s.length-1;c>s.length-1-u.find(".clone.right").length;c--)e--,s.eq(c).remove();for(l=u.find(".clone.right").length;l<t;l++)u.find(".lslide").eq(l).clone().removeClass("lslide").addClass("clone right").appendTo(u),e++;for(a=u.find(".lslide").length-u.find(".clone.left").length;a>u.find(".lslide").length-t;a--)u.find(".lslide").eq(a-1).clone().removeClass("lslide").addClass("clone left").prependTo(u);s=u.children()}else s.hasClass("clone")&&(u.find(".clone").remove(),n.move(u,0))},h.clone());h.sSW=function(){w=s.length;r.rtl===!0&&r.vertical===!1&&(it="margin-left");r.autoWidth===!1&&s.css(tt,y+"px");s.css(it,r.slideMargin+"px");c=h.calWidth(!1);u.css(tt,c+"px");r.loop===!0&&r.mode==="slide"&&nt===!1&&(e=u.find(".clone.left").length)};h.calL=function(){s=u.children();w=s.length};this.doCss()&&f.addClass("usingCss");h.calL();r.mode==="slide"?(h.calSW(),h.sSW(),r.loop===!0&&(l=n.slideValue(),this.move(u,l)),r.vertical===!1&&this.setHeight(u,!1)):(this.setHeight(u,!0),u.addClass("lSFade"),this.doCss()||(s.fadeOut(0),s.eq(e).fadeIn(0)));r.loop===!0&&r.mode==="slide"?s.eq(e).addClass("active"):s.first().addClass("active")},pager:function(){var i=this,n,t;h.createPager=function(){var a,w,v,t,h;k=(o-(r.thumbItem*r.thumbMargin-r.thumbMargin))/r.thumbItem;for(var p=f.find(".lslide"),b=f.find(".lslide").length,n=0,s="",l=0,n=0;n<b;n++)if(r.mode==="slide"&&(r.autoWidth?l+=(parseInt(p.eq(n).width())+r.slideMargin)*r.slideMove:l=n*(y+r.slideMargin)*r.slideMove),a=p.eq(n*r.slideMove).attr("data-thumb"),r.gallery===!0&&a?(w="src="+a,s+='<li style="width:100%;'+tt+":"+k+"px;"+it+":"+r.thumbMargin+'px"><a href="#"><img '+w+" /><\/a><\/li>"):s+='<li><a href="#">'+(n+1)+"<\/a><\/li>",r.mode==="slide"&&l>=c-o-r.slideMargin){n=n+1;v=2;r.autoWidth&&(s+='<li><a href="#">'+(n+1)+"<\/a><\/li>",v=1);n<v?(s=null,f.parent().addClass("noPager")):f.parent().removeClass("noPager");break}t=f.parent();t.find(".lSPager").html(s);r.gallery===!0&&(r.vertical===!0&&t.find(".lSPager").css("width",r.vThumbWidth+"px"),d=n*(r.thumbMargin+k)+.5,t.find(".lSPager").css({property:d+"px","transition-duration":r.speed+"ms"}),r.vertical===!0&&f.parent().css("padding-right",r.vThumbWidth+r.galleryMargin+"px"),t.find(".lSPager").css(tt,d+"px"));h=t.find(".lSPager").find("li");h.first().addClass("active");h.on("click",function(){return e=r.loop===!0&&r.mode==="slide"?e+(h.index(this)-t.find(".lSPager").find("li.active").index()):h.index(this),u.mode(!1),r.gallery===!0&&i.slideThumb(),!1})};r.pager&&(n="lSpg",r.gallery&&(n="lSGallery"),f.after('<ul class="lSPager '+n+'"><\/ul>'),t=r.vertical?"margin-left":"margin-top",f.parent().find(".lSPager").css(t,r.galleryMargin+"px"),h.createPager());setTimeout(function(){h.init()},0)},setHeight:function(n,t){var i=null,f=this,u;if(i=r.loop?n.children(".lslide ").first():n.children().first(),u=function(){var r=i.outerHeight(),u=0,f=r;t&&(r=0,u=f*100/o);n.css({height:r+"px","padding-bottom":u+"%"})},u(),i.find("img").length)if(i.find("img")[0].complete)u(),v||f.auto();else i.find("img").on("load",function(){setTimeout(function(){u();v||f.auto()},100)});else v||f.auto()},active:function(n,t){var i,o,s;this.doCss()&&r.mode==="fade"&&f.addClass("on");i=0;e*r.slideMove<w?(n.removeClass("active"),this.doCss()||r.mode!=="fade"||t!==!1||n.fadeOut(r.speed),i=t===!0?e:e*r.slideMove,t===!0&&(o=n.length,s=o-1,i+1>=o&&(i=s)),r.loop===!0&&r.mode==="slide"&&(i=t===!0?e-u.find(".clone.left").length:e*r.slideMove,t===!0&&(o=n.length,s=o-1,i+1===o?i=s:i+1>o&&(i=0))),this.doCss()||r.mode!=="fade"||t!==!1||n.eq(i).fadeIn(r.speed),n.eq(i).addClass("active")):(n.removeClass("active"),n.eq(n.length-1).addClass("active"),this.doCss()||r.mode!=="fade"||t!==!1||(n.fadeOut(r.speed),n.eq(i).fadeIn(r.speed)))},move:function(n,t){r.rtl===!0&&(t=-t);this.doCss()?r.vertical===!0?n.css({transform:"translate3d(0px, "+-t+"px, 0px)","-webkit-transform":"translate3d(0px, "+-t+"px, 0px)"}):n.css({transform:"translate3d("+-t+"px, 0px, 0px)","-webkit-transform":"translate3d("+-t+"px, 0px, 0px)"}):r.vertical===!0?n.css("position","relative").animate({top:-t+"px"},r.speed,r.easing):n.css("position","relative").animate({left:-t+"px"},r.speed,r.easing);var i=f.parent().find(".lSPager").find("li");this.active(i,!0)},fade:function(){this.active(s,!1);var n=f.parent().find(".lSPager").find("li");this.active(n,!0)},slide:function(){var n=this;h.calSlide=function(){c>o&&(l=n.slideValue(),n.active(s,!1),l>c-o-r.slideMargin?l=c-o-r.slideMargin:l<0&&(l=0),n.move(u,l),r.loop===!0&&r.mode==="slide"&&(e>=w-u.find(".clone.left").length/r.slideMove&&n.resetSlide(u.find(".clone.left").length),e===0&&n.resetSlide(f.find(".lslide").length)))};h.calSlide()},resetSlide:function(n){var t=this;f.find(".lSAction a").addClass("disabled");setTimeout(function(){e=n;f.css("transition-duration","0ms");l=t.slideValue();t.active(s,!1);a.move(u,l);setTimeout(function(){f.css("transition-duration",r.speed+"ms");f.find(".lSAction a").removeClass("disabled")},50)},r.speed+100)},slideValue:function(){var n=0,t;if(r.autoWidth===!1)n=e*(y+r.slideMargin)*r.slideMove;else for(n=0,t=0;t<e;t++)n+=parseInt(s.eq(t).width())+r.slideMargin;return n},slideThumb:function(){var i,n,s,t;switch(r.currentPagerPosition){case"left":i=0;break;case"middle":i=o/2-k/2;break;case"right":i=o-k}n=e-u.find(".clone.left").length;s=f.parent().find(".lSPager");r.mode==="slide"&&r.loop===!0&&(n>=s.children().length?n=0:n<0&&(n=s.children().length));t=n*(k+r.thumbMargin)-i;t+o>d&&(t=d-o-r.thumbMargin);t<0&&(t=0);this.move(s,t)},auto:function(){r.auto&&(clearInterval(v),v=setInterval(function(){u.goToNextSlide()},r.pause))},pauseOnHover:function(){var t=this;if(r.auto&&r.pauseOnHover){f.on("mouseenter",function(){n(this).addClass("ls-hover");u.pause();r.auto=!0});f.on("mouseleave",function(){n(this).removeClass("ls-hover");f.find(".lightSlider").hasClass("lsGrabbing")||t.auto()})}},touchMove:function(n,t){var s,i,e;f.css("transition-duration","0ms");r.mode==="slide"&&(s=n-t,i=l-s,i>=c-o-r.slideMargin?r.freeMove===!1?i=c-o-r.slideMargin:(e=c-o-r.slideMargin,i=e+(i-e)/5):i<0&&(i=r.freeMove===!1?0:i/5),this.move(u,i))},touchEnd:function(n){var i,t,h;f.css("transition-duration",r.speed+"ms");r.mode==="slide"?(i=!1,t=!0,l=l-n,l>c-o-r.slideMargin?(l=c-o-r.slideMargin,r.autoWidth===!1&&(i=!0)):l<0&&(l=0),h=function(n){var u=0,f,h,t;if(i||n&&(u=1),r.autoWidth){for(h=0,t=0;t<s.length;t++)if(h+=parseInt(s.eq(t).width())+r.slideMargin,e=t+u,h>=l)break}else f=l/((y+r.slideMargin)*r.slideMove),e=parseInt(f)+u,l>=c-o-r.slideMargin&&f%1!=0&&e++},n>=r.swipeThreshold?(h(!1),t=!1):n<=-r.swipeThreshold&&(h(!0),t=!1),u.mode(t),this.slideThumb()):n>=r.swipeThreshold?u.goToPrevSlide():n<=-r.swipeThreshold&&u.goToNextSlide()},enableDrag:function(){var e=this;if(!rt){var u=0,t=0,i=!1;f.find(".lightSlider").addClass("lsGrab");f.on("mousedown",function(t){if(c<o&&c!==0)return!1;n(t.target).attr("class")!=="lSPrev"&&n(t.target).attr("class")!=="lSNext"&&(u=r.vertical===!0?t.pageY:t.pageX,i=!0,t.preventDefault?t.preventDefault():t.returnValue=!1,f.scrollLeft+=1,f.scrollLeft-=1,f.find(".lightSlider").removeClass("lsGrab").addClass("lsGrabbing"),clearInterval(v))});n(window).on("mousemove",function(n){i&&(t=r.vertical===!0?n.pageY:n.pageX,e.touchMove(t,u))});n(window).on("mouseup",function(o){if(i){f.find(".lightSlider").removeClass("lsGrabbing").addClass("lsGrab");i=!1;t=r.vertical===!0?o.pageY:o.pageX;var s=t-u;if(Math.abs(s)>=r.swipeThreshold)n(window).on("click.ls",function(t){t.preventDefault?t.preventDefault():t.returnValue=!1;t.stopImmediatePropagation();t.stopPropagation();n(window).off("click.ls")});e.touchEnd(s)}})}},enableTouch:function(){var i=this,n,t;if(rt){n={};t={};f.on("touchstart",function(i){t=i.originalEvent.targetTouches[0];n.pageX=i.originalEvent.targetTouches[0].pageX;n.pageY=i.originalEvent.targetTouches[0].pageY;clearInterval(v)});f.on("touchmove",function(u){var s,f,e;if(c<o&&c!==0)return!1;s=u.originalEvent;t=s.targetTouches[0];f=Math.abs(t.pageX-n.pageX);e=Math.abs(t.pageY-n.pageY);r.vertical===!0?(e*3>f&&u.preventDefault(),i.touchMove(t.pageY,n.pageY)):(f*3>e&&u.preventDefault(),i.touchMove(t.pageX,n.pageX))});f.on("touchend",function(){if(c<o&&c!==0)return!1;var u;u=r.vertical===!0?t.pageY-n.pageY:t.pageX-n.pageX;i.touchEnd(u)})}},build:function(){var t=this;t.initialStyle();this.doCss()&&(r.enableTouch===!0&&t.enableTouch(),r.enableDrag===!0&&t.enableDrag());n(window).on("focus",function(){t.auto()});n(window).on("blur",function(){clearInterval(v)});t.pager();t.pauseOnHover();t.controls();t.keyPress()}};a.build();h.init=function(){h.chbreakpoint();r.vertical===!0?(o=r.item>1?r.verticalHeight:s.outerHeight(),f.css("height",o+"px")):o=f.outerWidth();r.loop===!0&&r.mode==="slide"&&h.clone();h.calL();r.mode==="slide"&&u.removeClass("lSSlide");r.mode==="slide"&&(h.calSW(),h.sSW());setTimeout(function(){r.mode==="slide"&&u.addClass("lSSlide")},1e3);r.pager&&h.createPager();r.adaptiveHeight===!0&&r.vertical===!1&&u.css("height",s.eq(e).outerHeight(!0));r.adaptiveHeight===!1&&(r.mode==="slide"?r.vertical===!1?a.setHeight(u,!1):a.auto():a.setHeight(u,!0));r.gallery===!0&&a.slideThumb();r.mode==="slide"&&a.slide();r.autoWidth===!1?s.length<=r.item?f.find(".lSAction").hide():f.find(".lSAction").show():h.calWidth(!1)<o&&c!==0?f.find(".lSAction").hide():f.find(".lSAction").show()};u.goToPrevSlide=function(){if(e>0)r.onBeforePrevSlide.call(this,u,e),e--,u.mode(!1),r.gallery===!0&&a.slideThumb();else if(r.loop===!0){if(r.onBeforePrevSlide.call(this,u,e),r.mode==="fade"){var n=w-1;e=parseInt(n/r.slideMove)}u.mode(!1);r.gallery===!0&&a.slideThumb()}else r.slideEndAnimation===!0&&(u.addClass("leftEnd"),setTimeout(function(){u.removeClass("leftEnd")},400))};u.goToNextSlide=function(){var n=!0,t;r.mode==="slide"&&(t=a.slideValue(),n=t<c-o-r.slideMargin);e*r.slideMove<w-r.slideMove&&n?(r.onBeforeNextSlide.call(this,u,e),e++,u.mode(!1),r.gallery===!0&&a.slideThumb()):r.loop===!0?(r.onBeforeNextSlide.call(this,u,e),e=0,u.mode(!1),r.gallery===!0&&a.slideThumb()):r.slideEndAnimation===!0&&(u.addClass("rightEnd"),setTimeout(function(){u.removeClass("rightEnd")},400))};u.mode=function(n){r.adaptiveHeight===!0&&r.vertical===!1&&u.css("height",s.eq(e).outerHeight(!0));nt===!1&&(r.mode==="slide"?a.doCss()&&(u.addClass("lSSlide"),r.speed!==""&&f.css("transition-duration",r.speed+"ms"),r.cssEasing!==""&&f.css("transition-timing-function",r.cssEasing)):a.doCss()&&(r.speed!==""&&u.css("transition-duration",r.speed+"ms"),r.cssEasing!==""&&u.css("transition-timing-function",r.cssEasing)));n||r.onBeforeSlide.call(this,u,e);r.mode==="slide"?a.slide():a.fade();f.hasClass("ls-hover")||a.auto();setTimeout(function(){n||r.onAfterSlide.call(this,u,e)},r.speed);nt=!0};u.play=function(){u.goToNextSlide();r.auto=!0;a.auto()};u.pause=function(){r.auto=!1;clearInterval(v)};u.refresh=function(){h.init()};u.getCurrentSlideCount=function(){var i=e,t,n;return r.loop&&(t=f.find(".lslide").length,n=u.find(".clone.left").length,i=e<=n-1?t+(e-n):e>=t+n?e-t-n:e-n),i+1};u.getTotalSlideCount=function(){return f.find(".lslide").length};u.goToSlide=function(n){e=r.loop?n+u.find(".clone.left").length-1:n;u.mode(!1);r.gallery===!0&&a.slideThumb()};u.destroy=function(){u.lightSlider&&(u.goToPrevSlide=function(){},u.goToNextSlide=function(){},u.mode=function(){},u.play=function(){},u.pause=function(){},u.refresh=function(){},u.getCurrentSlideCount=function(){},u.getTotalSlideCount=function(){},u.goToSlide=function(){},u.lightSlider=null,h={init:function(){}},u.parent().parent().find(".lSAction, .lSPager").remove(),u.removeClass("lightSlider lSFade lSSlide lsGrab lsGrabbing leftEnd right").removeAttr("style").unwrap().unwrap(),u.children().removeAttr("style"),s.removeClass("lslide active"),u.find(".clone").remove(),s=null,v=null,nt=!1,e=0)};setTimeout(function(){r.onSliderLoad.call(this,u)},10);n(window).on("resize orientationchange",function(n){setTimeout(function(){n.preventDefault?n.preventDefault():n.returnValue=!1;h.init()},200)});return this}})(jQuery);;
(function(){"use strict";function n(n,i){if(this.el=n,this.$el=$(n),this.s=$.extend({},t,i),this.s.dynamic&&this.s.dynamicEl!=="undefined"&&this.s.dynamicEl.constructor===Array&&!this.s.dynamicEl.length)throw"When using dynamic mode, you must also define dynamicEl as an Array.";return this.modules={},this.lGalleryOn=!1,this.lgBusy=!1,this.hideBartimeout=!1,this.isTouch="ontouchstart"in document.documentElement,this.s.slideEndAnimatoin&&(this.s.hideControlOnEnd=!1),this.$items=this.s.dynamic?this.s.dynamicEl:this.s.selector==="this"?this.$el:this.s.selector!==""?this.s.selectWithin?$(this.s.selectWithin).find(this.s.selector):this.$el.find($(this.s.selector)):this.$el.children(),this.$slide="",this.$outer="",this.init(),this}var t={mode:"lg-slide",cssEasing:"ease",easing:"linear",speed:600,height:"100%",width:"100%",addClass:"",startClass:"lg-start-zoom",backdropDuration:150,hideBarsDelay:6e3,useLeft:!1,closable:!0,loop:!0,escKey:!0,keyPress:!0,controls:!0,slideEndAnimatoin:!0,hideControlOnEnd:!1,mousewheel:!0,getCaptionFromTitleOrAlt:!0,appendSubHtmlTo:".lg-sub-html",subHtmlSelectorRelative:!1,preload:1,showAfterLoad:!0,selector:"",selectWithin:"",nextHtml:"",prevHtml:"",index:!1,iframeMaxWidth:"100%",download:!0,counter:!0,appendCounterTo:".lg-toolbar",swipeThreshold:50,enableSwipe:!0,enableDrag:!0,dynamic:!1,dynamicEl:[],galleryId:1};n.prototype.init=function(){var n=this,t;if(n.s.preload>n.$items.length&&(n.s.preload=n.$items.length),t=window.location.hash,t.indexOf("lg="+this.s.galleryId)>0&&(n.index=parseInt(t.split("&slide=")[1],10),$("body").addClass("lg-from-hash"),$("body").hasClass("lg-on")||(setTimeout(function(){n.build(n.index)}),$("body").addClass("lg-on"))),n.s.dynamic)n.$el.trigger("onBeforeOpen.lg"),n.index=n.s.index||0,$("body").hasClass("lg-on")||setTimeout(function(){n.build(n.index);$("body").addClass("lg-on")});else n.$items.on("click.lgcustom",function(t){try{t.preventDefault();t.preventDefault()}catch(i){t.returnValue=!1}n.$el.trigger("onBeforeOpen.lg");n.index=n.s.index||n.$items.index(this);$("body").hasClass("lg-on")||(n.build(n.index),$("body").addClass("lg-on"))})};n.prototype.build=function(n){var t=this;if(t.structure(),$.each($.fn.lightGallery.modules,function(n){t.modules[n]=new $.fn.lightGallery.modules[n](t.el)}),t.slide(n,!1,!1,!1),t.s.keyPress&&t.keyPress(),t.$items.length>1)t.arrow(),setTimeout(function(){t.enableDrag();t.enableSwipe()},50),t.s.mousewheel&&t.mousewheel();else t.$slide.on("click.lg",function(){t.$el.trigger("onSlideClick.lg")});t.counter();t.closeGallery();t.$el.trigger("onAfterOpen.lg");t.$outer.on("mousemove.lg click.lg touchstart.lg",function(){t.$outer.removeClass("lg-hide-items");clearTimeout(t.hideBartimeout);t.hideBartimeout=setTimeout(function(){t.$outer.addClass("lg-hide-items")},t.s.hideBarsDelay)});t.$outer.trigger("mousemove.lg")};n.prototype.structure=function(){var r="",u="",n=0,f="",e,t=this,i;for($("body").append('<div class="lg-backdrop"><\/div>'),$(".lg-backdrop").css("transition-duration",this.s.backdropDuration+"ms"),n=0;n<this.$items.length;n++)r+='<div class="lg-item"><\/div>';this.s.controls&&this.$items.length>1&&(u='<div class="lg-actions"><button class="lg-prev lg-icon">'+this.s.prevHtml+'<\/button><button class="lg-next lg-icon">'+this.s.nextHtml+"<\/button><\/div>");this.s.appendSubHtmlTo===".lg-sub-html"&&(f='<div class="lg-sub-html"><\/div>');e='<div class="lg-outer '+this.s.addClass+" "+this.s.startClass+'"><div class="lg" style="width:'+this.s.width+"; height:"+this.s.height+'"><div class="lg-inner">'+r+'<\/div><div class="lg-toolbar lg-group"><span class="lg-close lg-icon"><i class="fa-solid fa-xmark"><\/i><\/span><\/div>'+u+f+"<\/div><\/div>";$("body").append(e);this.$outer=$(".lg-outer");this.$slide=this.$outer.find(".lg-item");this.s.useLeft?(this.$outer.addClass("lg-use-left"),this.s.mode="lg-slide"):this.$outer.addClass("lg-use-css3");t.setTop();$(window).on("resize.lg orientationchange.lg",function(){setTimeout(function(){t.setTop()},100)});this.$slide.eq(this.index).addClass("lg-current");this.doCss()?this.$outer.addClass("lg-css3"):(this.$outer.addClass("lg-css"),this.s.speed=0);this.$outer.addClass(this.s.mode);this.s.enableDrag&&this.$items.length>1&&this.$outer.addClass("lg-grab");this.s.showAfterLoad&&this.$outer.addClass("lg-show-after-load");this.doCss()&&(i=this.$outer.find(".lg-inner"),i.css("transition-timing-function",this.s.cssEasing),i.css("transition-duration",this.s.speed+"ms"));setTimeout(function(){$(".lg-backdrop").addClass("in")});setTimeout(function(){t.$outer.addClass("lg-visible")},this.s.backdropDuration);this.s.download&&this.$outer.find(".lg-toolbar").append('<a id="lg-download" target="_blank" download class="lg-download lg-icon"><\/a>');this.prevScrollTop=$(window).scrollTop()};n.prototype.setTop=function(){if(this.s.height!=="100%"){var n=$(window).height(),i=(n-parseInt(this.s.height,10))/2,t=this.$outer.find(".lg");n>=parseInt(this.s.height,10)?t.css("top",i+"px"):t.css("top","0px")}};n.prototype.doCss=function(){var n=function(){for(var t=["transition","MozTransition","WebkitTransition","OTransition","msTransition","KhtmlTransition"],i=document.documentElement,n=0,n=0;n<t.length;n++)if(t[n]in i.style)return!0};return n()?!0:!1};n.prototype.isVideo=function(n,t){var i;if(i=this.s.dynamic?this.s.dynamicEl[t].html:this.$items.eq(t).attr("data-html"),!n)return i?{html5:!0}:(console.error("lightGallery :- data-src is not pvovided on slide item "+(t+1)+". Please make sure the selector property is properly configured. More info - http://sachinchoolur.github.io/lightGallery/demos/html-markup.html"),!1);var r=n.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com|be-nocookie\.com)\/(?:watch\?v=|embed\/)?([a-z0-9\-\_\%]+)/i),u=n.match(/\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i),f=n.match(/\/\/(?:www\.)?dai.ly\/([0-9a-z\-_]+)/i),e=n.match(/\/\/(?:www\.)?(?:vk\.com|vkontakte\.ru)\/(?:video_ext\.php\?)(.*)/i);return r?{youtube:r}:u?{vimeo:u}:f?{dailymotion:f}:e?{vk:e}:void 0};n.prototype.counter=function(){this.s.counter&&$(this.s.appendCounterTo).append('<div id="lg-counter"><span id="lg-counter-current">'+(parseInt(this.index,10)+1)+'<\/span> / <span id="lg-counter-all">'+this.$items.length+"<\/span><\/div>")};n.prototype.addHtml=function(n){var t=null,i,r,u;this.s.dynamic?this.s.dynamicEl[n].subHtmlUrl?i=this.s.dynamicEl[n].subHtmlUrl:t=this.s.dynamicEl[n].subHtml:(r=this.$items.eq(n),r.attr("data-sub-html-url")?i=r.attr("data-sub-html-url"):(t=r.attr("data-sub-html"),this.s.getCaptionFromTitleOrAlt&&!t&&(t=r.attr("title")||r.find("img").first().attr("alt"))));i||(typeof t!="undefined"&&t!==null?(u=t.substring(0,1),(u==="."||u==="#")&&(t=this.s.subHtmlSelectorRelative&&!this.s.dynamic?r.find(t).html():$(t).html())):t="");this.s.appendSubHtmlTo===".lg-sub-html"?i?this.$outer.find(this.s.appendSubHtmlTo).load(i):this.$outer.find(this.s.appendSubHtmlTo).html(t):i?this.$slide.eq(n).load(i):this.$slide.eq(n).append(t);typeof t!="undefined"&&t!==null&&(t===""?this.$outer.find(this.s.appendSubHtmlTo).addClass("lg-empty-html"):this.$outer.find(this.s.appendSubHtmlTo).removeClass("lg-empty-html"));this.$el.trigger("onAfterAppendSubHtml.lg",[n])};n.prototype.preload=function(n){for(var t=1,i=1,t=1;t<=this.s.preload;t++){if(t>=this.$items.length-n)break;this.loadContent(n+t,!1,0)}for(i=1;i<=this.s.preload;i++){if(n-i<0)break;this.loadContent(n-i,!1,0)}};n.prototype.loadContent=function(n,t,i){var r=this,e=!1,o,f,l,s,h,a,y=function(n){for(var t,o,i,r=[],e=[],u=0;u<n.length;u++)t=n[u].split(" "),t[0]===""&&t.splice(0,1),e.push(t[0]),r.push(t[1]);for(o=$(window).width(),i=0;i<r.length;i++)if(parseInt(r[i],10)>o){f=e[i];break}},p,w,c,u,v;if(r.s.dynamic?(r.s.dynamicEl[n].poster&&(e=!0,l=r.s.dynamicEl[n].poster),a=r.s.dynamicEl[n].html,f=r.s.dynamicEl[n].src,r.s.dynamicEl[n].responsive&&(p=r.s.dynamicEl[n].responsive.split(","),y(p)),s=r.s.dynamicEl[n].srcset,h=r.s.dynamicEl[n].sizes):(r.$items.eq(n).attr("data-poster")&&(e=!0,l=r.$items.eq(n).attr("data-poster")),a=r.$items.eq(n).attr("data-html"),f=r.$items.eq(n).attr("href")||r.$items.eq(n).attr("data-src"),r.$items.eq(n).attr("data-responsive")&&(w=r.$items.eq(n).attr("data-responsive").split(","),y(w)),s=r.$items.eq(n).attr("data-srcset"),h=r.$items.eq(n).attr("data-sizes")),c=!1,r.s.dynamic?r.s.dynamicEl[n].iframe&&(c=!0):r.$items.eq(n).attr("data-iframe")==="true"&&(c=!0),u=r.isVideo(f,n),!r.$slide.eq(n).hasClass("lg-loaded")){if(c?r.$slide.eq(n).prepend('<div class="lg-video-cont lg-has-iframe" style="max-width:'+r.s.iframeMaxWidth+'"><div class="lg-video"><iframe class="lg-object" frameborder="0" src="'+f+'"  allowfullscreen="true"><\/iframe><\/div><\/div>'):e?(v="",v=u&&u.youtube?"lg-has-youtube":u&&u.vimeo?"lg-has-vimeo":"lg-has-html5",r.$slide.eq(n).prepend('<div class="lg-video-cont '+v+' "><div class="lg-video"><span class="lg-video-play"><\/span><img class="lg-object lg-has-poster" src="'+l+'" /><\/div><\/div>')):u?(r.$slide.eq(n).prepend('<div class="lg-video-cont "><div class="lg-video"><\/div><\/div>'),r.$el.trigger("hasVideo.lg",[n,f,a])):r.$slide.eq(n).prepend('<div class="lg-img-wrap"><img class="lg-object lg-image" src="'+f+'" /><\/div>'),r.$el.trigger("onAferAppendSlide.lg",[n]),o=r.$slide.eq(n).find(".lg-object"),h&&o.attr("sizes",h),s){o.attr("srcset",s);try{picturefill({elements:[o[0]]})}catch(b){console.warn("lightGallery :- If you want srcset to be supported for older browser please include picturefil version 2 javascript library in your document.")}}this.s.appendSubHtmlTo!==".lg-sub-html"&&r.addHtml(n);r.$slide.eq(n).addClass("lg-loaded")}r.$slide.eq(n).find(".lg-object").on("load.lg error.lg",function(){var t=0;i&&!$("body").hasClass("lg-from-hash")&&(t=i);setTimeout(function(){r.$slide.eq(n).addClass("lg-complete");r.$el.trigger("onSlideItemLoad.lg",[n,i||0])},t)});if(u&&u.html5&&!e&&r.$slide.eq(n).addClass("lg-complete"),t===!0)if(r.$slide.eq(n).hasClass("lg-complete"))r.preload(n);else r.$slide.eq(n).find(".lg-object").on("load.lg error.lg",function(){r.preload(n)})};n.prototype.slide=function(n,t,i,r){var f=this.$outer.find(".lg-current").index(),u=this,e,c,h,o,s;u.lGalleryOn&&f===n||(e=this.$slide.length,c=u.lGalleryOn?this.s.speed:0,u.lgBusy||(this.s.download&&(h=u.s.dynamic?u.s.dynamicEl[n].downloadUrl!==!1&&(u.s.dynamicEl[n].downloadUrl||u.s.dynamicEl[n].src):u.$items.eq(n).attr("data-download-url")!=="false"&&(u.$items.eq(n).attr("data-download-url")||u.$items.eq(n).attr("href")||u.$items.eq(n).attr("data-src")),h?($("#lg-download").attr("href",h),u.$outer.removeClass("lg-hide-download")):u.$outer.addClass("lg-hide-download")),this.$el.trigger("onBeforeSlide.lg",[f,n,t,i]),u.lgBusy=!0,clearTimeout(u.hideBartimeout),this.s.appendSubHtmlTo===".lg-sub-html"&&setTimeout(function(){u.addHtml(n)},c),this.arrowDisable(n),r||(n<f?r="prev":n>f&&(r="next")),t?(this.$slide.removeClass("lg-prev-slide lg-current lg-next-slide"),e>2?(o=n-1,s=n+1,n===0&&f===e-1?(s=0,o=e-1):n===e-1&&f===0&&(s=0,o=e-1)):(o=0,s=1),r==="prev"?u.$slide.eq(s).addClass("lg-next-slide"):u.$slide.eq(o).addClass("lg-prev-slide"),u.$slide.eq(n).addClass("lg-current")):(u.$outer.addClass("lg-no-trans"),this.$slide.removeClass("lg-prev-slide lg-next-slide"),r==="prev"?(this.$slide.eq(n).addClass("lg-prev-slide"),this.$slide.eq(f).addClass("lg-next-slide")):(this.$slide.eq(n).addClass("lg-next-slide"),this.$slide.eq(f).addClass("lg-prev-slide")),setTimeout(function(){u.$slide.removeClass("lg-current");u.$slide.eq(n).addClass("lg-current");u.$outer.removeClass("lg-no-trans")},50)),u.lGalleryOn?(setTimeout(function(){u.loadContent(n,!0,0)},this.s.speed+50),setTimeout(function(){u.lgBusy=!1;u.$el.trigger("onAfterSlide.lg",[f,n,t,i])},this.s.speed)):(u.loadContent(n,!0,u.s.backdropDuration),u.lgBusy=!1,u.$el.trigger("onAfterSlide.lg",[f,n,t,i])),u.lGalleryOn=!0,this.s.counter&&$("#lg-counter-current").text(n+1)),u.index=n)};n.prototype.goToNextSlide=function(n){var t=this,i=t.s.loop;n&&t.$slide.length<3&&(i=!1);t.lgBusy||(t.index+1<t.$slide.length?(t.index++,t.$el.trigger("onBeforeNextSlide.lg",[t.index]),t.slide(t.index,n,!1,"next")):i?(t.index=0,t.$el.trigger("onBeforeNextSlide.lg",[t.index]),t.slide(t.index,n,!1,"next")):t.s.slideEndAnimatoin&&!n&&(t.$outer.addClass("lg-right-end"),setTimeout(function(){t.$outer.removeClass("lg-right-end")},400)))};n.prototype.goToPrevSlide=function(n){var t=this,i=t.s.loop;n&&t.$slide.length<3&&(i=!1);t.lgBusy||(t.index>0?(t.index--,t.$el.trigger("onBeforePrevSlide.lg",[t.index,n]),t.slide(t.index,n,!1,"prev")):i?(t.index=t.$items.length-1,t.$el.trigger("onBeforePrevSlide.lg",[t.index,n]),t.slide(t.index,n,!1,"prev")):t.s.slideEndAnimatoin&&!n&&(t.$outer.addClass("lg-left-end"),setTimeout(function(){t.$outer.removeClass("lg-left-end")},400)))};n.prototype.keyPress=function(){var n=this;if(this.$items.length>1)$(window).on("keyup.lg",function(t){n.$items.length>1&&(t.keyCode===37&&(t.preventDefault(),n.goToPrevSlide()),t.keyCode===39&&(t.preventDefault(),n.goToNextSlide()))});$(window).on("keydown.lg",function(t){n.s.escKey===!0&&t.keyCode===27&&(t.preventDefault(),n.$outer.hasClass("lg-thumb-open")?n.$outer.removeClass("lg-thumb-open"):n.destroy())})};n.prototype.arrow=function(){var n=this;this.$outer.find(".lg-prev").on("click.lg",function(){n.goToPrevSlide()});this.$outer.find(".lg-next").on("click.lg",function(){n.goToNextSlide()})};n.prototype.arrowDisable=function(n){!this.s.loop&&this.s.hideControlOnEnd&&(n+1<this.$slide.length?this.$outer.find(".lg-next").removeAttr("disabled").removeClass("disabled"):this.$outer.find(".lg-next").attr("disabled","disabled").addClass("disabled"),n>0?this.$outer.find(".lg-prev").removeAttr("disabled").removeClass("disabled"):this.$outer.find(".lg-prev").attr("disabled","disabled").addClass("disabled"))};n.prototype.setTranslate=function(n,t,i){this.s.useLeft?n.css("left",t):n.css({transform:"translate3d("+t+"px, "+i+"px, 0px)"})};n.prototype.touchMove=function(n,t){var i=t-n;Math.abs(i)>15&&(this.$outer.addClass("lg-dragging"),this.setTranslate(this.$slide.eq(this.index),i,0),this.setTranslate($(".lg-prev-slide"),-this.$slide.eq(this.index).width()+i,0),this.setTranslate($(".lg-next-slide"),this.$slide.eq(this.index).width()+i,0))};n.prototype.touchEnd=function(n){var t=this;t.s.mode!=="lg-slide"&&t.$outer.addClass("lg-slide");this.$slide.not(".lg-current, .lg-prev-slide, .lg-next-slide").css("opacity","0");setTimeout(function(){t.$outer.removeClass("lg-dragging");n<0&&Math.abs(n)>t.s.swipeThreshold?t.goToNextSlide(!0):n>0&&Math.abs(n)>t.s.swipeThreshold?t.goToPrevSlide(!0):Math.abs(n)<5&&t.$el.trigger("onSlideClick.lg");t.$slide.removeAttr("style")});setTimeout(function(){t.$outer.hasClass("lg-dragging")||t.s.mode==="lg-slide"||t.$outer.removeClass("lg-slide")},t.s.speed+100)};n.prototype.enableSwipe=function(){var n=this,t=0,i=0,r=!1;if(n.s.enableSwipe&&n.doCss()){n.$slide.on("touchstart.lg",function(i){n.$outer.hasClass("lg-zoomed")||n.lgBusy||(i.preventDefault(),n.manageSwipeClass(),t=i.originalEvent.targetTouches[0].pageX)});n.$slide.on("touchmove.lg",function(u){n.$outer.hasClass("lg-zoomed")||(u.preventDefault(),i=u.originalEvent.targetTouches[0].pageX,n.touchMove(t,i),r=!0)});n.$slide.on("touchend.lg",function(){n.$outer.hasClass("lg-zoomed")||(r?(r=!1,n.touchEnd(i-t)):n.$el.trigger("onSlideClick.lg"))})}};n.prototype.enableDrag=function(){var n=this,i=0,r=0,t=!1,u=!1;if(n.s.enableDrag&&n.doCss()){n.$slide.on("mousedown.lg",function(r){n.$outer.hasClass("lg-zoomed")||n.lgBusy||$(r.target).text().trim()||(r.preventDefault(),n.manageSwipeClass(),i=r.pageX,t=!0,n.$outer.scrollLeft+=1,n.$outer.scrollLeft-=1,n.$outer.removeClass("lg-grab").addClass("lg-grabbing"),n.$el.trigger("onDragstart.lg"))});$(window).on("mousemove.lg",function(f){t&&(u=!0,r=f.pageX,n.touchMove(i,r),n.$el.trigger("onDragmove.lg"))});$(window).on("mouseup.lg",function(f){u?(u=!1,n.touchEnd(r-i),n.$el.trigger("onDragend.lg")):($(f.target).hasClass("lg-object")||$(f.target).hasClass("lg-video-play"))&&n.$el.trigger("onSlideClick.lg");t&&(t=!1,n.$outer.removeClass("lg-grabbing").addClass("lg-grab"))})}};n.prototype.manageSwipeClass=function(){var t=this.index+1,n=this.index-1;this.s.loop&&this.$slide.length>2&&(this.index===0?n=this.$slide.length-1:this.index===this.$slide.length-1&&(t=0));this.$slide.removeClass("lg-next-slide lg-prev-slide");n>-1&&this.$slide.eq(n).addClass("lg-prev-slide");this.$slide.eq(t).addClass("lg-next-slide")};n.prototype.mousewheel=function(){var n=this;n.$outer.on("mousewheel.lg",function(t){t.deltaY&&(t.deltaY>0?n.goToPrevSlide():n.goToNextSlide(),t.preventDefault())})};n.prototype.closeGallery=function(){var n=this,t=!1;this.$outer.find(".lg-close").on("click.lg",function(){n.destroy()});if(n.s.closable){n.$outer.on("mousedown.lg",function(n){t=$(n.target).is(".lg-outer")||$(n.target).is(".lg-item ")||$(n.target).is(".lg-img-wrap")?!0:!1});n.$outer.on("mousemove.lg",function(){t=!1});n.$outer.on("mouseup.lg",function(i){($(i.target).is(".lg-outer")||$(i.target).is(".lg-item ")||$(i.target).is(".lg-img-wrap")&&t)&&(n.$outer.hasClass("lg-dragging")||n.destroy())})}};n.prototype.destroy=function(n){var t=this;n||(t.$el.trigger("onBeforeClose.lg"),$(window).scrollTop(t.prevScrollTop));n&&(t.s.dynamic||this.$items.off("click.lg click.lgcustom"),$.removeData(t.el,"lightGallery"));this.$el.off(".lg.tm");$.each($.fn.lightGallery.modules,function(n){t.modules[n]&&t.modules[n].destroy()});this.lGalleryOn=!1;clearTimeout(t.hideBartimeout);this.hideBartimeout=!1;$(window).off(".lg");$("body").removeClass("lg-on lg-from-hash");t.$outer&&t.$outer.removeClass("lg-visible");$(".lg-backdrop").removeClass("in");setTimeout(function(){t.$outer&&t.$outer.remove();$(".lg-backdrop").remove();n||t.$el.trigger("onCloseAfter.lg")},t.s.backdropDuration+50)};$.fn.lightGallery=function(t){return this.each(function(){if($.data(this,"lightGallery"))try{$(this).data("lightGallery").init()}catch(i){console.error("lightGallery has not initiated properly")}else $.data(this,"lightGallery",new n(this,t))})};$.fn.lightGallery.modules={}})();;
(function(){"use strict";function st(n){return n.valueOf()/a-.5+b}function e(n){return new Date((n+.5-b)*a)}function o(n){return st(n)-k}function d(i,r){return u(n(i)*t(s)-l(r)*n(s),t(i))}function v(i,r){return p(n(r)*t(s)+t(r)*n(s)*n(i))}function g(i,r,f){return u(n(i),t(i)*n(r)-l(f)*t(r))}function nt(i,r,u){return p(n(r)*n(u)+t(r)*t(u)*t(i))}function tt(n,t){return i*(280.16+360.9856235*n)-t}function ht(n){return n<0&&(n=0),.0002967/Math.tan(n+.00312536/(n+.08901179))}function it(n){return i*(357.5291+.98560028*n)}function rt(t){var r=i*(1.9148*n(t)+.02*n(2*t)+.0003*n(3*t)),u=i*102.9372;return t+r+u+f}function ut(n){var i=it(n),t=rt(i);return{dec:v(t,0),ra:d(t,0)}}function ct(n,t){return Math.round(n-y-t/(2*f))}function ft(n,t,i){return y+(n+t)/(2*f)+i}function et(t,i,r){return k+t+.0053*n(i)-.0069*n(2*r)}function lt(i,r,u){return w((n(i)-n(r)*n(u))/(t(r)*t(u)))}function at(n,t,i,r,u,f,e){var o=lt(n,i,r),s=ft(o,t,u);return et(s,f,e)}function ot(r){var o=i*(218.316+13.176396*r),u=i*(134.963+13.064993*r),s=i*(93.272+13.22935*r),f=o+i*6.289*n(u),e=i*5.128*n(s),h=385001-20905*t(u);return{ra:d(f,e),dec:v(f,e),dist:h}}function c(n,t){return new Date(n.valueOf()+t*a/24)}var f=Math.PI,n=Math.sin,t=Math.cos,l=Math.tan,p=Math.asin,u=Math.atan2,w=Math.acos,i=f/180,a=864e5,b=2440588,k=2451545,s=i*23.4397,r={},h,y;r.getPosition=function(n,t,r){var h=i*-r,f=i*t,e=o(n),u=ut(e),s=tt(e,h)-u.ra;return{azimuth:g(s,f,u.dec),altitude:nt(s,f,u.dec)}};h=r.times=[[-.833,"sunrise","sunset"],[-.3,"sunriseEnd","sunsetStart"],[-6,"dawn","dusk"],[-12,"nauticalDawn","nauticalDusk"],[-18,"nightEnd","night"],[6,"goldenHourEnd","goldenHour"]];r.addTime=function(n,t,i){h.push([n,t,i])};y=.0009;r.getTimes=function(n,t,r){for(var c=i*-r,g=i*t,nt=o(n),w=ct(nt,c),b=ft(0,c,w),l=it(b),a=rt(l),tt=v(a,0),u=et(b,l,a),s,y,d,p={solarNoon:e(u),nadir:e(u-.5)},f=0,k=h.length;f<k;f+=1)s=h[f],y=at(s[0]*i,c,g,tt,w,l,a),d=u-(y-u),p[s[1]]=e(d),p[s[2]]=e(y);return p};r.getMoonPosition=function(r,f,e){var y=i*-e,a=i*f,v=o(r),s=ot(v),h=tt(v,y)-s.ra,c=nt(h,a,s.dec),p=u(n(h),l(a)*t(s.dec)-n(s.dec)*t(h));return c=c+ht(c),{azimuth:g(h,a,s.dec),altitude:c,distance:s.dist,parallacticAngle:p}};r.getMoonIllumination=function(i){var e=o(i||new Date),r=ut(e),f=ot(e),s=149598e3,h=w(n(r.dec)*n(f.dec)+t(r.dec)*t(f.dec)*t(r.ra-f.ra)),c=u(s*n(h),f.dist-s*t(h)),l=u(t(r.dec)*n(r.ra-f.ra),n(r.dec)*t(f.dec)-t(r.dec)*n(f.dec)*t(r.ra-f.ra));return{fraction:(1+t(c))/2,phase:.5+.5*c*(l<0?-1:1)/Math.PI,angle:l}};r.getMoonTimes=function(n,t,u,f){var s=new Date(n),d,a,g,nt,h,l,v,y,p,tt,it,w,o,b,rt,e,k;for(f?s.setUTCHours(0,0,0,0):s.setHours(0,0,0,0),d=.133*i,a=r.getMoonPosition(s,t,u).altitude-d,e=1;e<=24;e+=2){if(g=r.getMoonPosition(c(s,e),t,u).altitude-d,nt=r.getMoonPosition(c(s,e+1),t,u).altitude-d,v=(a+nt)/2-g,y=(nt-a)/2,p=-y/(2*v),tt=(v*p+y)*p+g,it=y*y-4*v*g,w=0,it>=0&&(rt=Math.sqrt(it)/(Math.abs(v)*2),o=p-rt,b=p+rt,Math.abs(o)<=1&&w++,Math.abs(b)<=1&&w++,o<-1&&(o=b)),w===1?a<0?h=e+o:l=e+o:w===2&&(h=e+(tt<0?b:o),l=e+(tt<0?o:b)),h&&l)break;a=nt}return k={},h&&(k.rise=c(s,h)),l&&(k.set=c(s,l)),h||l||(k[tt>0?"alwaysUp":"alwaysDown"]=!0),k};typeof exports=="object"&&typeof module!="undefined"?module.exports=r:typeof define=="function"&&define.amd?define(r):window.SunCalc=r})();;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

///****** Self-Initializing object ******///
GolfNow.Web.Date = (function ($, datejs) {
	var that = this;
	var DEFAULT_DAYS_AHEAD = 7;

	var dateObj = {
		IsToday: function (date) {
			var myDate;
			if (!_.isDate(date)) {
				myDate = datejs.parse(date).clearTime();
			}
			else {
				myDate = new datejs(date).clearTime();
			}

			return datejs.today().equals(myDate);
		},
		DaysBetween: function (date1, date2) {
			if (!_.isDate(date1)) {
				try {
					date1 = datejs.parse(date1).clearTime();
				} catch (e) {
					date1 = new datejs(date1).clearTime();
				}
			}

			if (!_.isDate(date2)){
				try {
					date2 = datejs.parse(date2).clearTime();
				} catch (e) {
					date2 = new datejs(date2).clearTime();
				}
			}

			//Get 1 day in milliseconds
			var one_day = 1000 * 60 * 60 * 24;

			//Convert both dates to milliseconds
			var date1_ms = date1.getTime();
			var date2_ms = date2.getTime();

			// Calculate the difference in milliseconds
			var difference_ms = date2_ms - date1_ms;

			// Convert back to days and return
			return Math.round(difference_ms / one_day);
		},
		DaysFromToday: function (date) {
			if (date === null) {
				return DEFAULT_DAYS_AHEAD;
			}
			var today = datejs.today();
			date = _.isDate(date) ? date.clearTime() : datejs.parse(date).clearTime();
			var days = this.DaysBetween ? this.DaysBetween(today, date.clearTime()) : GolfNow.Web.Date.DaysBetween(today, date.clearTime());
			return days < 0 ? DEFAULT_DAYS_AHEAD : days;
		},
		GetSunsetDate: function (hoursToSunset) {
			var def = $.Deferred();

			var activeDate = datejs.parse(GolfNow.Web.Cache.GetActiveDate());
			var currentClientTime = new datejs();
			var sunsetDate = null;
			var millisecondsToSunset = hoursToSunset * 3600000;
			var locSvc = GolfNow.Web.LocationServices;

			var locateMeCallback = _.once(function (locationData) {
				//get the current active date to verify it's not in the future.
				if (!$.isEmptyObject(locationData) && activeDate.equals(new datejs(currentClientTime).clearTime())) {
					var latitude = locationData.Lat || locationData.Latitude;
					var longitude = locationData.Long || locationData.Longitude;
					var times = SunCalc.getTimes(currentClientTime, latitude, longitude);

					//7200000 is 2 hrs in milliseconds
					var timeUntilSunset = times.sunset - currentClientTime;
					if (timeUntilSunset < millisecondsToSunset) {
						sunsetDate = currentClientTime.addDays(1).clearTime();
					}

					if (sunsetDate !== null) {
						def.resolve(sunsetDate);
					}
					else {
						def.reject(activeDate);
					}
				}
				else {
					def.reject(activeDate);
				}
			});

			var coords = GolfNow.Web.LocationServices.GeoCoordinates();
			coords.done(function (data) {
				if (!$.isEmptyObject(data)) {
					locateMeCallback(data);
				} else {
					locSvc.LocateMe(false, locateMeCallback, locateMeCallback);
				}
			});

			return def.promise();
		}
	};

	return dateObj;
})(jQuery, Date);;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Request = GolfNow.Web.Request || {};

GolfNow.Web.Request = (function ($, amp, _, gnUtils) {
	///****** Public methods ******///
	var _scriptRequestUrls = [], _waitingScriptRequestUrls = [],
		_tmplCacheKey = "",
		requestObj = {
			// Issue an ajax GET request
			Get: function (topic, url, cache, timeout, options) {
				var deferred = $.Deferred();
				timeout = (timeout === undefined || timeout === null) ? 30000 : timeout;
				options = $.extend({
					method: 'GET',
					contentType: 'application/json; charset=UTF-8',
					url: url,
					cache: cache,
					timeout: timeout
				}, options || {});
				ajaxRequest(options)
				.done(function (successData, status, xhr) {
					deferred.resolve(successData, status, xhr);
				})
				.fail(function (xhr, status, error) {
					handleRequestError(xhr);
					deferred.reject(xhr, status, error);
				})
				.always(function (result, status) {
					amp.publish('xhr_get_always_' + topic, { requestStatus: status, result: result });
				});

				return deferred.promise();
			},
			// Issue an ajax POST request
			Post: function (topic, url, data, options) {
				var deferred = $.Deferred();

				options = $.extend(options || {}, {
					method: 'POST',
					contentType: 'application/json; charset=UTF-8',
					data: data,
					url: url
				});
				ajaxRequest(options)
					.done(function (successData, status, xhr) {
						deferred.resolve(successData, status, xhr);
					})
					.fail(function (xhr, status, error) {
						handleRequestError(xhr);
						deferred.reject(xhr, status, error);
					})
					.always(function (result, status) {
						amp.publish('xhr_post_always_' + topic, { requestStatus: status, result: result });
					});

				return deferred.promise();
			},
			// Issue an ajax PUT request
			Put: function (topic, url, cache, timeout) {
				var deferred = $.Deferred();
				timeout = (timeout === undefined) ? 30000 : timeout;

				ajaxRequest({
					method: 'PUT',
					url: url,
					cache: cache,
					timeout: timeout
				})
					.done(function (successData, status, xhr) {
						deferred.resolve(successData, status, xhr);
					})
					.fail(function (xhr, status, error) {
						handleRequestError(xhr);
						deferred.reject(xhr, status, error);
					})
					.always(function (result, status) {
						amp.publish('xhr_put_always_' + topic, { requestStatus: status, result: result });
					});

				return deferred.promise();
			},
			// Issue an ajax GET script request
			LoadScript: function (topic, url, options) {
				var deferred = $.Deferred(),
					status = '', foundUrl = _.findWhere(_scriptRequestUrls, { url: url }) || null;

				if (foundUrl === null) {
					var script = document.createElement('script');

					_scriptRequestUrls.push({ url: url, topic: topic });
					var myCdnUrl = url || cdnUrl.substring(0, cdnUrl.length -1) || location.protocol + '//' + location.host;

					script.type = 'text/javascript';
					script.src = url;
					script.onload = script.onreadystatechange = function (evt) {
						status = 'success';
						var myUrl = evt.currentTarget.src;
						var myReq = _.find(_scriptRequestUrls, function (obj) { return myUrl.indexOf(obj.url) > -1; });

						GolfNow.Web.Utils.ConsoleLog('xhr-parent-script-' + myReq.topic + '-done');
						amp.publish('xhr_loadscript_always_' + myReq.topic, { requestStatus: status });

						_.each(_.uniq(_waitingScriptRequestUrls), function (scriptReq) {
							if (myUrl.indexOf(scriptReq.url) > -1) {
								GolfNow.Web.Utils.ConsoleLog('xhr-waiting-script-' + scriptReq.topic + '-done');
								amp.publish('xhr_loadscript_always_' + scriptReq.topic, { requestStatus: status });
							}
						});

						deferred.resolve();
					};
					script.onerror = function () {
						status = 'failed';
						deferred.reject();
						_waitingScriptRequestUrls = [];
						_scriptRequestUrls = [];
					};

					$('body')[0].appendChild(script);
				} else {
					_waitingScriptRequestUrls.unshift({ url: url, topic: topic });
				}

				return deferred.promise();
			},
			LoadTemplateContent: function (topic, url, options, tmplVersionKey) {
				var cacheKey = topic + '_' + tmplVersionKey;
				var content = GetLocalStorageValue(cacheKey) || null;
				if (content === null) {
					return this.GetTemplateContent(topic, url, options, cacheKey);
				} else {
					return $.Deferred()
						.resolve(content)
						.always(function (result, status) {
							status = 'success';
							var fulltopic = 'xhr_getcontent_always_' + topic;
							GolfNow.Web.Utils.ConsoleLog(fulltopic + ' - ' + status);
							amp.publish(fulltopic, { requestStatus: status, result: result });
						});
				}
			},
			GetTemplateContent: function (topic, url, options, cacheKey) {
				cacheKey = cacheKey === undefined || cacheKey === null ? '' : cacheKey;
				var deferred = $.Deferred();

				options = $.extend({
					headers: {},
					method: 'GET',
					dataType: 'html',
					cache: false,
					url: url
				}, options || {});

				ajaxRequest(options)
					.done(function (successData, status, xhr) {
						if(cacheKey !== '') SetLocalStorageValue(cacheKey, successData);
						deferred.resolve(successData, status, xhr);
					})
					.fail(function (xhr, status, error) {
						if (xhr.status === 200) {
							deferred.resolve(xhr.responseText);
						} else {
							handleRequestError(xhr);
							deferred.reject(xhr, status, error);
						}
					})
					.always(function (result, status) {
						var fulltopic = 'xhr_getcontent_always_' + topic;
						GolfNow.Web.Utils.ConsoleLog(fulltopic + ' - ' + status);
						amp.publish(fulltopic, { requestStatus: status, result: result });
					});

				return deferred.promise();
			},
			GetContent: function (topic, url, options) {
				var deferred = $.Deferred();

				options = $.extend({
					headers: {},
					method: 'GET',
					dataType: 'html',
					cache: false,
					url: url
				}, options || {});

				ajaxRequest(options)
					.done(function (successData, status, xhr) {
						deferred.resolve(successData, status, xhr);
					})
					.fail(function (xhr, status, error) {
						if (xhr.status === 200) {
							deferred.resolve(xhr.responseText);
						} else {
							handleRequestError(xhr);
							deferred.reject(xhr, status, error);
						}
					})
					.always(function (result, status) {
						var fulltopic = 'xhr_getcontent_always_' + topic;
						GolfNow.Web.Utils.ConsoleLog(fulltopic + ' - ' + status);
						amp.publish(fulltopic, { requestStatus: status, result: result });
					});

				return deferred.promise();
			},

			PostWidget: function (topic, url, data) {
				var deferred = $.Deferred();

				ajaxRequest({
					method: 'POST',
					dataType: 'html',
					contentType: 'application/json; charset=UTF-8',
					data: JSON.stringify(data),
					url: url
				})
				.done(function (successData, status, xhr) {
					deferred.resolve(successData, status, xhr);
				})
				.fail(function (xhr, status, error) {
					handleRequestError(xhr);
					deferred.reject(xhr, status, error);
				})
				.always(function (result, status) {
					amp.publish('xhr_post_widget_always_' + topic, { requestStatus: status, result: result });
				});

				return deferred.promise();
			}
		};

	///****** Private methods ******///
	function ajaxRequest(options, url) {
		var _csrfToken = null;
		var $csrfElem = $('#gn_widget_csrf > input');
		var csrfHeader = null;
		if ($csrfElem.length) {
			_csrfToken = $csrfElem.val();
			if (_csrfToken === '') {
				$csrfElem = $('#teetime-search > input');
				_csrfToken = $csrfElem.val();
			}
			csrfHeader = { __RequestVerificationToken: _csrfToken };
		}
		
		options = $.extend(options || {}, {
			dataType: options.dataType || 'json',
			url: url,
			headers: options.headers || csrfHeader || getHeaderAntiForgeryToken(),
			timeout: options.timeout || 30000
		});
		return $.ajax(options);
	}
	/*
	 * GNSCM-7313: Account Update - 2.1.1-CSRF
	 * GNSCM-7314: Add/Remove Wallet option - 2.1.2,2.1.3-CSRF
	 * GNSCM-7316: Friend Request accept/remove - 2.1.5,2.1.6,2.1.7-CSRF
	 */
	function getHeaderAntiForgeryToken(options, url) {
		var $csrfElem = $('.ajaxAntiForgery input[name="__RequestVerificationToken"]').first();
		var csrfHeader = null;
		
		if ($csrfElem.length) {
			csrfHeader = { __RequestVerificationToken: $csrfElem.val() };
		}		
		return csrfHeader;
	}
	function handleRequestError(errorData) {
		switch (errorData.status) {
			case 400:   //Bad Request
			case 401:   //Unathorized
			case 403:   //Forbidden
			case 404:   //Not Found
			case 500:   //Internal Server Error
			case 501:   //Not Implemented
			case 502:   //Bad Gateway
			case 503:   //Service Unavailble
			case 504:   //Gateway Timeout
			case 505:   //Http Version Not Support
			case 506:   //Variant Also Negotiates
			case 507:   //Insufficient Storage
			case 509:   //Bandwidth Limit Exceeded
			case 510:   //Not Extended
				GolfNow.Web.Utils.ConsoleWarn('Known Request Error - Status: ' + errorData.status + '-' + errorData.statusText);
				break;
			default:
				GolfNow.Web.Utils.ConsoleError('Unknown Request Error - Status: ' + errorData.status + '-' + errorData.statusText);
				break;
		}
	}

	function GetLocalStorageValue(key) {
		var retVal = null;
		var types = _.keys(amplify.store.types);
		if (types.length > 0) {
			retVal = amplify.store(key) || amplify.store.sessionStorage(key) || amplify.store.memory(key) || null;
		}

		if (retVal === null && types.length === 0) {
			if (typeof (GolfNow.Web.Cache) !== 'undefined') {
				retVal = GolfNow.Web.Cache.Fallback.getItem(key) || null;
			}
		}
		return retVal;
	}

	function SetLocalStorageValue(key, value) {
		var expiration = expiration || 1000 * 60 * 60 * 24; //24 hours default cache expiration

		if (amplify.store.types.sessionStorage) {
			amplify.store.sessionStorage(key, value, { expires: expiration });
		}
		else {
			if (amplify.store.types.localStorage) {
				amplify.store.localStorage(key, value);
			} else {
				if (typeof (GolfNow.Web.Cache) !== 'undefined') {
					GolfNow.Web.Cache.SetAltStorageValue(key, value, { expires: expiration });
				}
			}
		}
	}

	/// Return the public object
	return requestObj;
})(jQuery, amplify, _, GolfNow.Web.Utils);;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Client = GolfNow.Web.Client || {};
GolfNow.Web.Cache = GolfNow.Web.Cache || {};

/* Active date cache key name */
var _activeDateCacheName = 'GolfNow.Web.Client.ActiveDate';
var _facilityViewCacheName = 'GolfNow.FacilityView';

GolfNow.Web.Cache.SetSessionStorageValue = function (key, value, expiration) {
	expiration = expiration || 1000 * 60 * 60 * 24; //24 hours default cache expiration
	GolfNow.Web.Cache.SetValue(key, value, false, expiration);
};

GolfNow.Web.Cache.SetLocalStorageValue = function (key, value, expiration) {
	GolfNow.Web.Cache.SetValue(key, value, true, expiration);
};

/* Save object to client session storage. interface to amplify */
GolfNow.Web.Cache.SetValue = function (key, value, useLocalStorage, expiration) {
	if (typeof expiration === "undefined") { expiration = null; }

	if (useLocalStorage) {
		if (amplify.store.types.localStorage) {
			if (expiration === null) {
				amplify.store.localStorage(key, value);
			}
			else {
				amplify.store.localStorage(key, value, { expires: expiration });
			}
		} else {
			GolfNow.Web.Cache.SetAltStorageValue(key, value, expiration);
		}
	}
	else {
		if (amplify.store.types.sessionStorage) {
			if (expiration === null) {
				amplify.store.sessionStorage(key, value);
			}
			else {
				amplify.store.sessionStorage(key, value, { expires: expiration });
			}
		}
		else {
			GolfNow.Web.Cache.SetAltStorageValue(key, value, expiration);
		}
	}
};

GolfNow.Web.Cache.SetAltStorageValue = function (key, value, expiration) {
	var types = _.keys(amplify.store.types);
	if (types.length > 0) {
		if (expiration === null) {
			amplify.store(key, value);
		}
		else {
			amplify.store(key, value, { expires: expiration });
		}
	} else {
		this.Fallback.setItem(key, value);
	}
}

/* Retrieve data from cache */
GolfNow.Web.Cache.GetValue = function (key) {
	var retVal = null;
	var types = _.keys(amplify.store.types);
	if (types.length > 0) {
		retVal = amplify.store(key) || amplify.store.sessionStorage(key) || amplify.store.memory(key) || null;

	} else {
		retVal = this.Fallback.getItem(key) || null;
	}

	return retVal;
};

/* set active date */
GolfNow.Web.Cache.SetActiveDate = function (value) {
	var _expiration = 1000 * 60 * 60 * 24; //24 hours default cache expiration
	GolfNow.Web.Cache.SetLocalStorageValue(_activeDateCacheName, value, _expiration);
};

/* get active date */
GolfNow.Web.Cache.GetActiveDate = function () {
	var _currentDate = Date.today();
	var strDate = GolfNow.Web.Cache.GetValue(_activeDateCacheName);
	var dateValue = strDate === null ? null : new Date(strDate);
	if (dateValue === null || (dateValue !== null && dateValue < _currentDate)) {
		dateValue = _currentDate;
	}

	return GolfNow.Web.Utils.GetDateString(dateValue);
};

GolfNow.Web.Cache.SetFacilityViewOption = function (value) {
	GolfNow.Web.Cache.SetLocalStorageValue(_facilityViewCacheName, value);
};

/* localStorage fallback uses amplify memory and sends to server to store in distributed cache */
GolfNow.Web.Cache.Fallback = function () {
	var userId = getUserId();
	function getSiteCode() {
		return siteCode || 'gn';
	}
	function getUserId() {
		var userId = getUserIdCookie();
		if (userId === '') {
			userId = generateUUID();
		}
		return userId;
	}
	function getUserIdCookie() {
		var name = getSiteCode() + '_userId';
		var value = `; ${document.cookie}`;
		var parts = value.split(`; ${name}=`);
		if (parts.length === 2) return parts.pop().split(';').shift();
		return '';
	}
	function setUserIdCookie(cvalue) {
		var d = new Date();
		d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
		var expires = "expires=" + d.toUTCString();
		document.cookie = getSiteCode() + "_userId=" + cvalue + "; " + expires + "; path=/; samesite=none";
	}
	function generateUUID() {
		var d = new Date().getTime();
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		setUserIdCookie(uuid);
		return uuid;
	}
	function getRequestUrl(url) {
		if (topDomainAssetPrefix === '/') return url;

		return topDomainAssetPrefix + url.replace(/^\//, '');
	}
	function SetItem(key, value, expiration) {
		var url = getRequestUrl('/api/utilities/setcacheitem');
		var serverKey = userId + '__' + key.replace(/\./g, '-');
		amplify.store(key, value);
		$.ajax({
			method: 'POST',
			async: false,
			url: url,
			data: JSON.stringify({ key: serverKey, value: value }),
			contentType: 'application/json; charset=UTF-8',
			dataType: 'json'
		});
	}
	function GetItem(key) {
		var data = amplify.store(key);
		if (data === undefined || data === null) {
			var serverKey = userId + '__' + key.replace(/\./g, '-');
			var url = getRequestUrl('/api/getcacheitem/' + serverKey);
			response = $.ajax({
				method: 'GET',
				dataType: 'json',
				contentType: 'application/json; charset=UTF-8',
				async: false,
				url: url
			}).responseJSON;

			if (response && response.result === 'success' && !$.isEmptyObject(response.data)) {
				data = JSON.parse(response.data);
			} else {
				data = null;
			}
		}
		return data;
	}

	return {
		setItem: SetItem,
		getItem: GetItem
	};
}();;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Domains = GolfNow.Web.Domains || {};

GolfNow.Web.Domains = function ($, gnCache, gnReq) {

	// Default Configuration for .com domain
	var _requiresCookiePolicy, _latitude, _longitude, _golfnowCarePhone, _golfnowCareHours, _vipPhone, _bookingCenterPhone, _bookingCenterHours,
		_cacheTimeoutMinutes = 1000 * 60 * 20, _cacheTimeoutMinutesFailure = 1000 * 60 * 2, _siteConfReq = null;
	this.siteConfigSettings = {};

	_defaultDomain = {
		"domain": "golfnow.com",
		"location": {
			"city": "Orlando",
			"state": "FL",
			"country": "US",
			"lat": 28.5383355,
			"long": -81.37923649999999
		},
		"cookiePolicy": true,
		"golferCares": { "phone": "1-800-767-3574", "hours": "8AM - 5PM ET" },
		"bookingCenter": { "phone": "1-800-767-3574", "hours": "8AM - 5PM ET" },
		"vipPhone": "1-833-GolfVIP",
		"locale": "en-US"
	};
	// End of Default Configuration for .com domain

	// if new domain is added configuration goes here.
	var _gnDomains = [
		{
			"domain": "demo.golfnow.com",
			"location": {
				"city": "Orlando",
				"state": "FL",
				"country": "US",
				"lat": 28.5383355,
				"long": -81.37923649999999
			},
			"cookiePolicy": true,
			"golferCares": { "phone": "1-800-767-3574", "hours": "8AM - 5PM ET" },
			"bookingCenter": { "phone": "1-800-767-3574", "hours": "8AM - 5PM ET" },
			"vipPhone": "1-833-GolfVIP",
			"locale": "en-US"
		},
		{
			"domain": "golfnow.co.uk",
			"location": {
				"city": "Covent Garden",
				"state": "London",
				"country": "UK",
				"lat": 51.50859,
				"long": -0.125649
			},
			"cookiePolicy": true,
			"golferCares": { "phone": "UK Phone: +44 28 9568 0287 or IE Phone: +353 1800 852 936", "hours": "9AM - 5PM" },
			"bookingCenter": { "phone": "UK Phone: +44 28 9568 0287 or IE Phone: +353 1800 852 936", "hours": "9AM - 5PM" },
			"vipPhone": "",
			"locale": "en-GB"
		},
		{
			"domain": "golfnow.eu",
			"location": {
				"city": "Paris",
				"state": "France",
				"country": "FR",
				"lat": 48.8589384,
				"long": 2.2646349
			},
			"cookiePolicy": true,
			"golferCares": { "phone": "UK Phone: +44 28 9568 0287 or IE Phone: +353 1800 852 936", "hours": "9AM - 5PM" },
			"bookingCenter": { "phone": "UK Phone: +44 28 9568 0287 or IE Phone: +353 1800 852 936", "hours": "9AM - 5PM" },
			"vipPhone": "",
			"locale": "en-FR"
		},
		{
			"domain": "golfnow.com.au",
			"location": {
				"city": "Brisbane City",
				"state": "Queensland",
				"country": "AU",
				"lat": -27.470125,
				"long": 153.021072
			},
			"cookiePolicy": true,
			"golferCares": { "phone": "+61 1800 942 929", "hours": "9AM - 5PM AET - Mon - Fri" },
			"bookingCenter": { "phone": "+61 1800 942 929", "hours": "9AM - 5PM AET - Mon - Fri" },
			"vipPhone": "",
			"locale": "en-AU"
		},
		{
			"domain": "teeoff.com",
			"location": {
				"city": "Orlando",
				"state": "FL",
				"country": "US",
				"lat": 28.5383355,
				"long": -81.37923649999999
			},
			"cookiePolicy": true,
			"golferCares": { "phone": "1-855-383-3633", "hours": "8AM - 5PM ET" },
			"bookingCenter": { "phone": "1-855-383-3633", "hours": "8AM - 5PM ET" },
			"vipPhone": "1-855-383-3633",
			"locale": "en-US"
		}
	];

	var _domain = GetDomain(), _localDomain = _defaultDomain;

	function loadSiteSettings() {
		var cacheKey = 'GolfNow.Web.SiteSettings';
		var def = $.Deferred();
		var that = this;

		if (!_.isEmpty(that.siteConfigSettings))
			return def.resolve(that.siteConfigSettings);

		var siteSettings = gnCache.GetValue(cacheKey) || null;
		if (!_.isNull(siteSettings)) {
			that.siteConfigSettings = siteSettings;
			return def.resolve(siteSettings);
		}

		// use the local objects to determine which domain host to use
		_localDomain = _defaultDomain;
		for (var i = 0; i < _gnDomains.length; i++) {
			if (location.hostname.toLocaleLowerCase().indexOf(_gnDomains[i].domain) > -1) {
				_localDomain = _gnDomains[i];
				break;
			}
		}

		var requestUrl = 'api/config/getsitesettings';
		var urlPrefix = 'https://www.' + _localDomain.domain;
		if (/promotions|blog|travel|tournaments|concierge|news|base|origin-base|memberships/.test(location.hostname)) {
			urlPrefix = urlPrefix.substr('https://'.length).lastIndexOf('/') > -1 ? urlPrefix : urlPrefix + '/';
			requestUrl = urlPrefix + requestUrl;
		} else if(requestUrl.indexOf('https://') === -1 && requestUrl.indexOf('/') !== 0){
			requestUrl = '/' + requestUrl;
		}

		if (_siteConfReq === null || _siteConfReq.state() !== 'pending') {
			_siteConfReq = gnReq.Get('settingsRequest', requestUrl, true);
			return _siteConfReq
				.done(function (response) {
					gnCache.SetSessionStorageValue(cacheKey, response, null);
					that.siteConfigSettings = response;
					def.resolve(that.siteConfigSettings);
				})
				.fail(function () {
					gnCache.SetSessionStorageValue(cacheKey, _localDomain, null);
					that.siteConfigSettings = _localDomain;
					def.resolve(that.siteConfigSettings);
				});

		} else {
			return _siteConfReq;
		}

		return def.promise();
	}

	function GetDomain() {
		var _domainObj = siteConfigSettings;
		if (_.isEmpty(_domainObj) || location.hostname.toLocaleLowerCase().indexOf(_domainObj.domain) === -1) {
			for (var i = 0; i < _gnDomains.length; i++) {
				if (location.hostname.toLocaleLowerCase().indexOf(_gnDomains[i].domain) > -1) {
					_domainObj = _gnDomains[i];
					break;
				}
			}
		}

		return _domainObj;
	}

	function GetDomainLocation() {
		// Default lat and long for Orlando area if not configuration available
		var _lat = _defaultDomain.location.lat, _long = _defaultDomain.location.long,
			city = _defaultDomain.location.city, state = _defaultDomain.location.state, country = _defaultDomain.location.country;

		if (_domain !== null && _domain.hasOwnProperty("location")) {
			var domainLocation = _domain.location;
			if (domainLocation.hasOwnProperty("lat") && domainLocation["lat"] && domainLocation.hasOwnProperty("long") && domainLocation["long"]) {
				_lat = domainLocation.lat;
				_long = domainLocation.long;
			}
		}

		var _domainGeo = {
			latitude: _lat,
			longitude: _long,
			city: city,
			state: state,
			country: country
		};
		return _domainGeo;
	}

	function RequiresDomainCookiePolicy() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("cookiePolicy") && settings["cookiePolicy"]) {
					return settings.cookiePolicy;
				} else {
					return _localDomain.cookiePolicy; //// Default for GolfNow.com which does not require cookie policy to show.
				}
			});
	}

	function BookingCenterPhone() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("bookingCenter") && settings["bookingCenter"]) {
					return settings.bookingCenter.phone;
				} else {
					return _localDomain.bookingCenter.phone;
				}

			});
	}

	function BookingCenterHours() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("bookingCenter") && settings["bookingCenter"]) {
					return settings.bookingCenter.hours;
				} else {
					return _localDomain.bookingCenter.hours;
				}
			});
	}

	function GolfNowCarePhone() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("golferCares") && settings["golferCares"]) {
					return settings.golferCares.phone;
				} else {
					return _localDomain.golferCares.phone;
				}
			});
	}

	function GolfNowCareHours() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("golferCares") && settings["golferCares"]) {
					return settings.golferCares.hours;
				} else {
					return _localDomain.golferCares.hours;
				}
			});
	}

	function VipPhone() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings !== null && settings.hasOwnProperty("vipPhone") && settings["vipPhone"]) {
					return settings.vipPhone;
				} else {
					return _localDomain.vipPhone;
				}
			});
	}

	function PMPReportSettings() {
		return loadSiteSettings().then(function (data) {
			return data.pmp_report_settings;
		});
	}

	function GetDomainHost() {
		return siteConfigSettings.domain;
	}

	function Radius_CourseView() {
		return loadSiteSettings().then(function (data) {
			return data.radius_CourseViewDefault;
		});
	}

	function Radius_ListView() {
		return loadSiteSettings().then(function (data) {
			return data.radius_ListViewDefault;
		});
	}

	function HoursToSunset() {
		return loadSiteSettings().then(function (data) {
			return data.hoursToSunset;
		});
	}

	function InterstitialVersion() {
		return loadSiteSettings().then(function (data) {
			return data.interstitial_version;
		});
	}

	function InterstitialEnabled() {
		return loadSiteSettings().then(function (data) {
			return data.interstitial_enabled;
		});
	}
	
	function InterstitialInactiveDaysLater() {
		return loadSiteSettings().then(function (data) {
			if (data !== null && data.hasOwnProperty("interstitial_inactive_days_later") && data["interstitial_inactive_days_later"]) {
				return data.interstitial_inactive_days_later;
			} else {
				return null;
			}
		});
	}

	function InterstitialInactiveDaysExit() {
		return loadSiteSettings().then(function (data) {
			if (data !== null && data.hasOwnProperty("interstitial_inactive_days_exit") && data["interstitial_inactive_days_exit"]) {
				return data.interstitial_inactive_days_exit;
			} else {
				return null;
			}
		});
	}

	function TmplVersionKey() {
		return loadSiteSettings().then(function (data) {
			return data.tmplVersionKey;
		});
	}

	function PrivateCoursesFormUrl() {
		return loadSiteSettings().then(function (data) {
			return data.privateCoursesFormUrl;
		});
	}

	function ClubChampionFormUrl() {
		return loadSiteSettings().then(function (data) {
			return data.clubChampionFormUrl;
		});
	}

	function ConvertGuestCheckoutSection() {
		return loadSiteSettings().then(function (data) {
			return data.convert_guest_checkout_section;
		});
	}

	function SiteDisplayName() {
		return loadSiteSettings().then(function (data) {
			return data.siteDisplayName;
		});
	}

	function OffPlatformCopy() {
		return loadSiteSettings().then(function (data) {
			return data.offplatform_copy;
		});
	}

	function TopTierFacilityEnabled() {
		return loadSiteSettings().then(function (data) {
			return data.top_tier_facility_enabled;
		});
	}

	function init() {
		return loadSiteSettings()
			.then(function (settings) {
				if (settings.radius_CourseViewDefault)
					defaultCourseViewSearchRadius = settings.radius_CourseViewDefault;

				if (settings.radius_ListViewDefault)
					defaultListViewSearchRadius = settings.radius_ListViewDefault;

				return settings;
			});
	}
	var domain = {
		GetDomainLocation: GetDomainLocation,
		GetDomainHost: GetDomainHost,
		RequiresDomainCookiePolicy: RequiresDomainCookiePolicy,
		GolfNowCarePhone: GolfNowCarePhone,
		GolfNowCareHours: GolfNowCareHours,
		BookingCenterPhone: BookingCenterPhone,
		BookingCenterHours: BookingCenterHours,
		VIPPhone: VipPhone,
		Radius_CourseView: Radius_CourseView,
		Radius_ListView: Radius_ListView,
		InterstitialEnabled: InterstitialEnabled,
		InterstitialVersion: InterstitialVersion,
		InterstitialInactiveDaysLater: InterstitialInactiveDaysLater,
		InterstitialInactiveDaysExit: InterstitialInactiveDaysExit,
		TmplVersionKey: TmplVersionKey,
		PrivateCoursesFormUrl: PrivateCoursesFormUrl,
		ClubChampionFormUrl: ClubChampionFormUrl,
		HoursToSunset: HoursToSunset,
		ConvertGuestCheckoutSection: ConvertGuestCheckoutSection,
		SiteDisplayName: SiteDisplayName,
		OffPlatformCopy: OffPlatformCopy,
		PMPReportSettings: PMPReportSettings,
		SiteConfigSettings: function () {
			return siteConfigSettings;
		}
	};

	init();
	return domain;
}(jQuery, GolfNow.Web.Cache, GolfNow.Web.Request);;
var defaultListSort = defaultListSort || '',
	defaultListView = defaultListView || '',
	defaultSearchRadius = defaultSearchRadius || 25,
	defaultCourseViewSearchRadius = defaultCourseViewSearchRadius || defaultSearchRadius,
	defaultListViewSearchRadius = defaultListViewSearchRadius || defaultSearchRadius,
	maximumSearchRadius = maximumSearchRadius || 255,
	siteCode = siteCode || 'gn',
	defaultUnits = defaultUnits || 'mi',
	cdnUrl = cdnUrl || '',
	utype = utype || '',
	uid = uid || '',
	authenticated = uid !== '' && utype !== 'guest',
	nonPostalCodeCountries = nonPostalCodeCountries || ["ie", "bm", "fj"],
	viewOverrideParams = viewOverrideParams || null, autoLoginProps = autoLoginProps || {};

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

Date.prototype.toDateDisplayString = function (forDisplay) {
	if (_.isUndefined(forDisplay) || _.isNull(forDisplay) || forDisplay === '') forDisplay = true;

	if (forDisplay) {
		if (Foundation.utils.is_small_only()) {
			return this.toString(GolfNow.Web.Utils.GetDefaultMobileDateFormatString());
		}

		return this.toString(GolfNow.Web.Utils.GetDefaultDateFormatString());
	} else {
		return this.toString('MMM dd yyyy');
	}
};

String.prototype.toDateDisplayString = function (forDisplay) {
	if (_.isUndefined(forDisplay) || _.isNull(forDisplay) || forDisplay === '') forDisplay = true;

	var date = Date.parse(this);

	if (date)
		return date.toDateDisplayString(forDisplay);
	else
		return new Date().toDateDisplayString(forDisplay);
};

if (!String.prototype.startsWith) {
	String.prototype.startsWith = function (searchString, position) {
		position = position || 0;
		return this.lastIndexOf(searchString, position) === position;
	};
}

///****** Self-Initializing object ******///
GolfNow.Web.Utils = (function ($) {
	var SERVER_DISPLAY_MODE = null;

	var DEFAULT_SEARCH_RADIUS = defaultSearchRadius;
	var DEFAULT_SEARCH_COURSEVIEW_RADIUS = DEFAULT_SEARCH_RADIUS;
	var DEFAULT_SEARCH_LISTVIEW_RADIUS = DEFAULT_SEARCH_RADIUS;
	var MAXIMUM_SEARCH_RADIUS = maximumSearchRadius;
	var DEFAULT_SEARCH_SORT = defaultListSort;
	var DEFAULT_SEARCH_VIEW = defaultListView;
	var DEFAULT_SEARCH_VIEW_Geo = defaultListView;
	var DEFAULT_SEARCH_VIEW_Course = 'Grouping';
	var MAXIMUM_CALENDAR_DAYSOUT = 366;
	var DEFAULT_RATE_TYPE = 'all';
	var DEFAULT_UNITS = defaultUnits;

	var PRICE_CEILING = 10000;
	var PRICE_FLOOR = 0;

	var IS_HOMEPAGE_SEARCH = false;
	var IS_DESTINATION_CITY_PAGE = false;

	var CREDITS_CACHE_KEY = "GolfNow.CreditsAvailable";
	var REWARDS_CACHE_KEY = "GolfNow.RewardsAvailable";
	var PENDING_SOCIAL_REQUESTS_KEY = "GolfNow.PendingRequests";
	var TEETIME_OFFER_CACHE_KEY = "GolfNow.TeeTimeOffer";

	var GNUK_WEBSITE_URL = "https://golfnow.co.uk/";
	var GNAU_WEBSITE_URL = "https://golfnow.com.au/";

	var DEFAULT_DATE_FORMAT_STRING = "ddd, MMM dd";
	var DEFAULT_DATE_MOBILE_FORMAT_STRING = "ddd, MMM dd";

	var TIME_PERIOD_OPTIONS = [
		"12 AM", "12:30 AM", "1 AM", "1:30 AM", "2 AM",  "2:30 AM",  "3 AM",  "3:30 AM",
		"4 AM",  "4:30 AM",  "5 AM", "5:30 AM", "6 AM",  "6:30 AM",  "7 AM",  "7:30 AM",
		"8 AM",  "8:30 AM",  "9 AM", "9:30 AM", "10 AM", "10:30 AM", "11 AM", "11:30 AM",
		"12 PM", "12:30 PM", "1 PM", "1:30 PM", "2 PM",  "2:30 PM",  "3 PM",  "3:30 PM",
		"4 PM",  "4:30 PM",  "5 PM", "5:30 PM", "6 PM",  "6:30 PM",  "7 PM",  "7:30 PM",
		"8 PM",  "8:30 PM",  "9 PM+", "9:30 PM+", "10 PM+", "10:30 PM+", "11 PM+", "11:30 PM+",
		"11:59 PM"
	];
	var SORT_DISPLAY_NAME_MAPPINGS = [{
			key: 'Facilities.Weight',
			display: 'Best Deals'
		}, {
			key: 'Facilities.Name',
			display: 'A-Z'
		}, {
			key: 'Facilities.Rating',
			display: 'Rating'
		}, {
			key: 'Facilities.Distance',
			display: 'Closest'
		}, {
			key: 'Date',
			display: 'Time'
		}, {
			key: 'GreensFees',
			display: 'Price'
		}];

	var TIME_PERIOD_OPT = _.range(0, 49, 6);

	//State destinations order
	var FL_DESTINATIONS_ID = ['41', '43', '39', '38', '44', '192', '37', '201', '190', '40', '36', '204', '42', '181', '202', '203'];
	var AZ_DESTINATIONS_ID = ['9', '11', '12', '10'];
	var CA_DESTINATIONS_ID = ['20', '22', '16', '23', '21', '17', '19', '177', '18', '26', '178', '15', '14', '24'];
	var TX_DESTINATIONS_ID = ['143', '145', '141', '146', '191', '199', '195', '144', '142'];
	var MI_DESTINATIONS_ID = ['75', '76', '168', '79', '78', '77'];
	var OH_DESTINATIONS_ID = ['116', '115', '114', '117', '186', '182', '185'];
	var SC_DESTINATIONS_ID = ['134', '133', '130', '132', '131'];
	var IL_DESTINATIONS_ID = ['56', '172', '176', '197', '173'];
	var GA_DESTINATIONS_ID = ['45', '46', '48', '47', '183'];
	var NY_DESTINATIONS_ID = ['110', '111', '109', '112', '108', '113'];
	var WA_DESTINATIONS_ID = ['157', '159', '158', '180', '184', '200'];
	var NV_DESTINATIONS_ID = ['104', '105', '169', '106'];
	var MO_DESTINATIONS_ID = ['84', '82', '81', '83'];
	var TN_DESTINATIONS_ID = ['140', '139', '138', '137'];
	var MA_DESTINATIONS_ID = ['67', '68', '69'];
	var MN_DESTINATIONS_ID = ['80', '170'];
	var CT_DESTINATIONS_ID = ['33'];
	var WI_DESTINATIONS_ID = ['163', '162', '160', '161'];
	var IN_DESTINATIONS_ID = ['57', '205'];
	var OR_DESTINATIONS_ID = ['122', '120', '121', '171', '179'];
	var MD_DESTINATIONS_ID = ['72', '71', '70'];
	var KY_DESTINATIONS_ID = ['61', '60'];
	var LA_DESTINATIONS_ID = ['65', '62', '64', '63', '66'];
	var AL_DESTINATIONS_ID = ['4', '6', '5', '7'];
	var KS_DESTINATIONS_ID = ['59', '58'];
	var CO_DESTINATIONS_ID = ['30', '29', '32', '27', '31'];
	var VA_DESTINATIONS_ID = ['153', '155', '156', '154', '152', '151'];
	var NJ_DESTINATIONS_ID = ['98', '110', '126', '100', '198', '99'];
	var PA_DESTINATIONS_ID = ['126', '127', '174', '124', '125'];
	var NC_DESTINATIONS_ID = ['89', '92', '91', '88', '90', '93'];
	var NE_DESTINATIONS_ID = ['96', '95'];
	var OK_DESTINATIONS_ID = ['118', '119'];
	var HI_DESTINATIONS_ID = ['51', '52', '50', '49'];
	var UT_DESTINATIONS_ID = ['149', '150', '148', '147'];
	var IA_DESTINATIONS_ID = ['53', '175'];
	var NH_DESTINATIONS_ID = ['97'];
	var RI_DESTINATIONS_ID = ['129', '128'];
	var AR_DESTINATIONS_ID = ['8'];
	var DE_DESTINATIONS_ID = ['35'];
	var MS_DESTINATIONS_ID = ['85', '86'];
	var ME_DESTINATIONS_ID = ['74', '228', '73'];
	var ID_DESTINATIONS_ID = ['55', '54'];
	var NM_DESTINATIONS_ID = ['101', '102', '103'];
	var WV_DESTINATIONS_ID = ['164'];
	var MT_DESTINATIONS_ID = ['87'];
	var VT_DESTINATIONS_ID = ['283', '460'];
	var SD_DESTINATIONS_ID = ['136', '135'];
	var ND_DESTINATIONS_ID = ['94'];
	var WY_DESTINATIONS_ID = ['165', '196'];
	var AK_DESTINATIONS_ID = ['1', '2', '3'];

	var golfpassBadgeClassName = function (productName) {
		if (productName === '') return '';

		if (/GolfPass\+$/ig.test(productName) || /GolfPass\+ Seasonal$/ig.test(productName)) {
			return 'golfpass-plus-badge';
		} else if (/GolfPass\+\sVIP$/ig.test(productName)) {
			return 'golfpass-plus-vip-badge';
		} else {
			return 'vip-badge';
		}
	};

	//Register custom media queries
	Foundation.utils.register_media('medium-only-landscape', 'gn-mq-medium-only-landscape');
	Foundation.utils.register_media('retina', 'gn-mq-retina');

	// global regex form validator method
	$.validator.addMethod(
		"gnRegexValidate",
		// 1st param should always be the regex
		// 2nd param should be the message to display (used in the validator.format call below)
		function (value, elem, params) {
			var regexp = params[0];
			var re = new RegExp(regexp);
			return this.optional(elem) || re.test(value);
		},
		$.validator.format("{1}")
	);

	$.validator.addMethod(
		"gnDateOfBirthValidate",
		// 1st param should always be the regex
		// 2nd param should be the message to display (used in the validator.format call below)
		function (value, elem, params) {

			dob = params;
			userValue = $(dob).val();

			var today = new Date();
			var nowyear = today.getFullYear();
			var nowmonth = today.getMonth();
			var nowday = today.getDate();

			var birth = new Date(userValue);

			var birthyear = birth.getFullYear();
			var birthmonth = birth.getMonth();
			var birthday = birth.getDate();

			var age = nowyear - birthyear;
			var age_month = nowmonth - birthmonth;
			var age_day = nowday - birthday;


			if (age > 100) {
				return false;
			}
			if (age_month < 0 || (age_month === 0 && age_day < 0)) {
				age = parseInt(age) - 1;

			}
			if ((age === 18 && age_month <= 0 && age_day <= 0) || age < 18) {
				return false;
			}

			return true;
		},
		"You must be older than 18."
	);

	$.validator.addMethod(
		"gnHtmlTags",
		// 1st param should always be the regex
		// 2nd param should be the message to display (used in the validator.format call below)
		function (value, elem, params) {

			var field = params;
			userValue = $(field).val();

			var regex = /<[^>]*>/g;
			if (userValue.match(regex)) {
				return false;
			}
			return true;
		},
		"Invalid input."
	);

	// validator for postal code validation relying on country provided
	$.validator.addMethod(
		"gnPostalCodeFormat",
		function (value, elem, params) {
			var country = params, re;
			country = $(country).val();

			if (!GolfNow.Web.Utils.CountryRequiresPostalCode(country.toLowerCase())) {
				return true;
			} else {
				if ("us" === country.toLowerCase()) {
					re = /^(\d{5}|\d{9})$/;
					return re.test(value);
				}
				else {
					if ("ca" === country.toLowerCase()) {
						re = /^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$/i;
						return re.test(value);
					} else {
						return true;
					}
				}
			}
		},
		"Invalid Postal Code"
	);

	// validator for postal code required or not relying on country provided
	$.validator.addMethod(
		"gnPostalCodeRequired",
		function (value, elem, params) {
			var country = params;
			country = $(country).val();

			if (!GolfNow.Web.Utils.CountryRequiresPostalCode(country.toLowerCase())) {
				return true;
			} else {
				return !this.optional(elem);
			}
		},
		"The Postal Code Field Is Required."
	);
	$.validator.addMethod(
		"gnCreditCardExpiration",
		function (value, element, params) {
			var minMonth = new Date().getMonth() + 1;
			var minYear = new Date().getFullYear();
			var month = parseInt($(params.month).val(), 10);
			var year = parseInt($(params.year).val(), 10);
			year = year < 2000 ? year + 2000 : year;

			return (!month || !year || year > minYear || (year === minYear && month >= minMonth));
		},
		'Invalid Expiration Date'
	);


	// generic validator to allow for validation of a subject field based on the value in this field
	$.validator.addMethod(
		"gnValidateField",
		function (value, elem, params) {
			var $subject = $(params);
			$subject.valid();

			return true;
		}
	);

	// generic validator for password
	$.validator.addMethod(
		"gnPasswordValidate",
		function (value, elem, params) {
			var re = /^(?=.*[A-Za-z])(?=.*\d)(?!.*[\^/\\#$%@^&*+<(>)""'])[\S]{10,}$/;
			return re.test(value);
		},
		$.validator.format("{0}")
	);

	// generic validator for password
	$.validator.addMethod(
		"gnPasswordLoginValidate",
		function (value, elem, params) {
			var re = /^(?=.*[A-Za-z])(?=.*\d)(?!.*[\^/\\#$%@^&*+<(>)""'])[\S]{8,}$/;
			return re.test(value);
		},
		$.validator.format("{0}")
	);

	// generic validator for username
	$.validator.addMethod(
		"gnUserNameValidate",
		function (value, elem, params) {
			var re = /^[a-zA-Z0-9]+$/g;
			return re.test(value);
		},
		$.validator.format("{0}")
	);

	// generic validator for email
	$.validator.addMethod(
		"gnEmailValidate",
		function (value, elem, params) {
			var re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,8}$/;
			return re.test(value);
		},
		$.validator.format("{0}")
	);

	$.validator.addMethod(
		"gnDateValidate",
		function (value, elem, params) {
			var month = params[0];
			var day = params[1];
			var year = params[2];
			var daysInMonth = new Date(value, month, 0).getDate();
			if (day > daysInMonth)
				return Date.validateDay(day, value, month);
		},
		$.validator.format("{3}")
	);

	$.validator.addMethod(
		'le',
		function (value, element, param) {
			var val = $(param).val();
			return this.optional(element) || !val || parseInt(value) <= parseInt(val);
		},
		'Invalid Value'
	);

	$.validator.addMethod(
		'slt',
		function (value, element, param) {
			var val = $(param).val();
			return this.optional(element) || !val || parseInt(value) < parseInt(val);
		},
		'Invalid Value'
	);

	$.validator.addMethod(
		'ge',
		function (value, element, param) {
			var val = $(param).val();
			return this.optional(element) || !val || parseInt(value) >= parseInt(val);
		},
		'Invalid Value'
	);

	$.validator.addMethod(
		'sgt',
		function (value, element, param) {
			var val = $(param).val();
			return this.optional(element) || !val || parseInt(value) > parseInt(val);
		},
		'Invalid Value'
	);

	$.validator.addMethod("equalToIgnoreCase",
		function (value, element, param) {
			return this.optional(element) || value.toLowerCase() === $(param).val().toLowerCase();
		});

	$.fn.phoneAndHours = function () {
		var $loginElem = $('.inner-wrap .login-link');
		var gnwDomains = GolfNow.Web.Domains;
		var $that = this;

		function placeGolfNowCarePhone($elem, formatted_number, mobile_number) {
			if (arguments.length === 2) {
				mobile_number = formatted_number;
				formatted_number = $elem;
				$elem = $('.golfnow-care-phone');
			}
			$elem.each(function (idx, elem) {
				if (!Foundation.utils.is_large_up() && elem.tagName === 'A') {
					elem.href = "tel:" + mobile_number.replace(/\s|-/g, '');
				}
				elem.innerHTML = '';
				elem.appendChild(document.createTextNode(formatted_number));
			});
		}

		function placeBookingCenterPhone($elem, formatted_number, mobile_number) {
			if (arguments.length === 2) {
				mobile_number = formatted_number;
				formatted_number = $elem;
				$elem = $('.booking-center-phone');
			}
			$elem.each(function (idx, elem) {
				if (!Foundation.utils.is_large_up() && elem.tagName === 'A') {
					elem.href = "tel:" + mobile_number.replace(/\s|-/g, '');
				}
				elem.innerHTML = '';
				elem.appendChild(document.createTextNode(formatted_number));
			});
		}

		function placeVIPPhone($elem, formatted_number, mobile_number) {
			if (arguments.length === 2) {
				mobile_number = formatted_number;
				formatted_number = $elem;
				$elem = $('.golfnow-vip-phone');
			}
			$elem.each(function (idx, elem) {
				if (!Foundation.utils.is_large_up() && elem.tagName === 'A') {
					elem.href = "tel:" + mobile_number.replace(/\s|-/g, '');
				}
				elem.innerHTML = '';
				elem.appendChild(document.createTextNode(formatted_number));
			});
		}

		var domainHost = gnwDomains && gnwDomains.GetDomainHost() || 'golfnow.com';
		if ($loginElem.length && /%2Fcms%2Fheader-footer/.test($loginElem.attr('href'))) {
			var href = $loginElem.attr('href');
			var pos = href.indexOf('/customer/login');
			var originalHost = href.substr(0, pos);
			var ohPos = originalHost.indexOf('%3F');
			originalHost = originalHost === '' ? '/' : ohPos > -1 ? originalHost.substr(0, ohPos) : originalHost;
			var newHost = domainHost;
			var pos2 = href.indexOf('returnUrl');
			if (pos > -1) {
				$loginElem.attr('href', 'https://www.' + newHost + '/customer/login?returnUrl=' + encodeURIComponent(originalHost));
			}
		}

		/////***** Renders the GolfNow care phone dynamically based on domain (HTML in _PencilAd.cshtml)*****///
		return $that.each(function (idx, elem) {
			var $elem = $(elem), $thatElem;
			if ($elem.hasClass('golfnow-care-phone')) {
				$thatElem = $elem;
				$.when(gnwDomains.GolfNowCarePhone()).done(function (phone) {
					// default the element with the returned number
					placeGolfNowCarePhone($thatElem, phone, phone);

					// make call to see if there an associated ad number
					try {
						_googWcmGet(placeGolfNowCarePhone, phone, { timeout: 300, cache: false });
					} catch (e) { /* ignore */ }
				});
			}

			if ($elem.hasClass('golfnow-care-hours')) {
				$thatElem = $elem;
				$.when(gnwDomains.GolfNowCareHours()).done(function (hours) {
					$thatElem.html('');
					$thatElem.append(document.createTextNode(hours));
				});
			}

			if ($elem.hasClass('booking-center-phone')) {
				$thatElem = $elem;
				$.when(gnwDomains.BookingCenterPhone()).done(function (phone) {
					// default the element with the returned number
					placeBookingCenterPhone($thatElem, phone, phone);

					// make call to see if there an associated ad number
					try {
						_googWcmGet(placeBookingCenterPhone, phone, { timeout: 300, cache: false });
					} catch (e) {/* ignore */ }
				});
			}

			if ($elem.hasClass('booking-center-hours')) {
				$thatElem = $elem;
				$.when(gnwDomains.BookingCenterHours()).done(function (hours) {
					$thatElem.html('');
					$thatElem.append(document.createTextNode(hours));
				});
			}

			if ($elem.hasClass('golfnow-vip-phone')) {
				$thatElem = $elem;
				gnwDomains.VIPPhone().done(function (phone) {
					// default the element with the returned number
					placeVIPPhone($thatElem, phone, phone);
				});

			}
		});
		/////*****End of Renders the GolfNow care phone dynamically based on domain (HTML in _PencilAd.cshtml)*****///
	};

	$.fn.scrollToAnchor = function () {
		this.on('click', 'a[href^="#"]', function (e) {
			e.preventDefault();

			var offset = 75;
			var mainHeaderOffsetHeight = 0;
			var id = $(this).attr('href');
			id = id.substr(1);
			if (id === '') return;

			var $mainHeader = $('header#main-header');
			var $targetElement = $('a[name=' + id + '],#' + id);
			if ($targetElement.length === 0) return;

			if ($mainHeader.length !== 0) {
				mainHeaderOffsetHeight = $mainHeader[0].offsetHeight;
			};

			var $delegateTarget = $(e.delegateTarget);
			var stickyContainer = $('.contain-to-grid.sticky:not(.fixed):first').height() || 0;
			var targetPosition = $targetElement.offset().top - $delegateTarget.offset().top + 0;
			if ($delegateTarget.hasClass('sticky') || $delegateTarget.find('.sticky').length) {
				targetPosition = $targetElement.offset().top - $delegateTarget[0].offsetHeight - mainHeaderOffsetHeight;
			}
			if (stickyContainer > 0)
				targetPosition -= stickyContainer;
			else
				targetPosition += mainHeaderOffsetHeight;

			$('html, body').animate({
				scrollTop: targetPosition
			}, 350);

			return false;
		});
		return this;
	};

	///****** Public methods ******///
	var utilObj = {
		GetDateString: function(date) {
			if (date instanceof Date)
				date = Date.parse(date.toDateDisplayString(false));
			else
				date = Date.parse(date);

			if (date) { return date.toDateDisplayString(false); }
			else { return new Date().toDateDisplayString(false); }
		},

		CountryRequiresPostalCode: function (country) {
			country = typeof country === "undefined" ? "" : country;
			return $.inArray(country.toLowerCase(), nonPostalCodeCountries) === -1 ? true : false;
		},

		LogOutOfAmazonSession: function (callback) {
			if (typeof amazon === "undefined") {
				$.when($.getScript('https://api-cdn.amazon.com/sdk/login1.js'))
					.then(function () {
						amazon.Login.logout();
						callback();
					});
			}

			return false;
		},

		LogOutOfQantasSession: function(){
			if (typeof window.qff_auth !== "undefined") {
				window.qff_auth.logout();
			}
		},

		Logout: function () {
			GolfNow.Web.Utils.ClearAvatarUrlCacheValues();
		},

		GetDefaultUnitOfMeasure: function () {
			return DEFAULT_UNITS;
		},

		GetDefaultDateFormatString: function () {
			return DEFAULT_DATE_FORMAT_STRING;
		},

		GetDefaultMobileDateFormatString: function () {
			return DEFAULT_DATE_MOBILE_FORMAT_STRING;
		},

		GetDefaultSearchRadius: function (units, view) {
			view = view || GolfNow.Web.UrlParams.GetHashParams()['view'] || this.GetDefaultSearchView();

			if (!_.isString(view)) return DEFAULT_SEARCH_RADIUS;

			var overrideRadius = _.isNull(viewOverrideParams) ? 0 : Number(viewOverrideParams.Radius) || 0;

			switch (view.toLowerCase()) {
				case "course":
					return Math.max(overrideRadius, DEFAULT_SEARCH_COURSEVIEW_RADIUS);
				case "list":
				case "map":
					return Math.max(overrideRadius, DEFAULT_SEARCH_LISTVIEW_RADIUS);
				default:
					return Math.max(overrideRadius, DEFAULT_SEARCH_RADIUS);
			}
		},

		GetDefaultCourseViewSearchRadius: function (units) {
			return DEFAULT_SEARCH_COURSEVIEW_RADIUS;
		},

		GetDefaultListViewSearchRadius: function (units) {
			return DEFAULT_SEARCH_LISTVIEW_RADIUS;
		},

		GetMaximumSearchRadius: function (units) {
			return MAXIMUM_SEARCH_RADIUS;
		},

		SetDefaultSearchRadius: function (radius) {
			DEFAULT_SEARCH_RADIUS = radius;
		},

		SetMaximumSearchRadius: function(radius){
			MAXIMUM_SEARCH_RADIUS = radius;
		},

		SetDefaultCourseViewSearchRadius: function (radius) {
			DEFAULT_SEARCH_COURSEVIEW_RADIUS = radius;
		},

		SetDefaultListViewSearchRadius: function (radius) {
			DEFAULT_SEARCH_LISTVIEW_RADIUS = radius;
		},

		GetServerDisplayMode: function () {
			if (SERVER_DISPLAY_MODE === null)
				SERVER_DISPLAY_MODE = Foundation.utils.is_small_only() ? "small" : Foundation.utils.is_medium_only() ? "medium" : "large";

			return SERVER_DISPLAY_MODE.toLowerCase();
		},

		SetServerDisplayMode: function (displayMode) {
			SERVER_DISPLAY_MODE = displayMode.toLowerCase();
		},

		GetTimePeriodString: function (timePeriod) {
			timePeriod = (typeof timePeriod === "undefined" || timePeriod === null) ? 0 : Number(timePeriod);
			return TIME_PERIOD_OPTIONS[timePeriod];
		},

		GetMinTimePeriodValue: function () {
			return 10;
		},

		GetMaxTimePeriodValue: function () {
			return TIME_PERIOD_OPTIONS.length - 7;
		},

		GetSortDisplayNameMappings: function () {
			return SORT_DISPLAY_NAME_MAPPINGS;
		},

		GetStartTimePeriodValue: function (searchDate) {
			return this.CalcStartTimePeriod(searchDate);

		},

		GetEndTimePeriodValue: function (searchDate) {
			var val = this.CalcStartTimePeriod(searchDate) + 4;
			if (val > this.GetMaxTimePeriodValue())
				val = this.GetMaxTimePeriodValue();

			return val;
		},

		GetTimePeriodOptions: function(){
			return TIME_PERIOD_OPT;
		},

		CalcStartTimePeriod: function(searchDate){
			var minPeriod = 10;
			searchDate = !_.isDate(searchDate) ? Date.parse(searchDate) || Date.today() : searchDate;

			if (Date.today().toShortDateString() === searchDate.toShortDateString()) {
				var hour = Date.now().getHours();
				var minutes = Date.now().getMinutes();
				minPeriod = hour * 2;
				if (minutes >= 30)
					minPeriod += 1;
			}

			return minPeriod;
		},

		GetPriceFloor: function () {
			return PRICE_FLOOR;
		},

		GetPriceCeiling: function () {
			return PRICE_CEILING;
		},

		GetDefaultSearchView: function (type) {
			type = type !== undefined && type !== null ? type : _.isNull(viewOverrideParams) ? 0 : viewOverrideParams.SearchType;
			switch (this.GetSearchTypeName(type)) {
				case 'GeoLocation':
				case '0':
				case 0:
					return DEFAULT_SEARCH_VIEW_Geo;
				case 'Facility':
				case '1':
				case 1:
					// check SearchParamsAction to see if we need to use the server settings or not
					// if so, then ignore the stored value otherwise proceed as normal
					var storedView = viewOverrideParams.SearchParamsAction === 1 ? viewOverrideParams.View : GolfNow.Web.Cache.GetValue('GolfNow.FacilityView') || null;
					return storedView || DEFAULT_SEARCH_VIEW_Course;
				default:
					return DEFAULT_SEARCH_VIEW;
			}
		},

		GetDefaultSearchSort: function () {
			return _.isNull(viewOverrideParams) ? DEFAULT_SEARCH_SORT : viewOverrideParams.DefaultSort || DEFAULT_SEARCH_SORT;
		},
		GetDefaultSearchSortRollup: function () {
			var ds = this.GetDefaultSearchSort();
			var dsd = _.isNull(viewOverrideParams) ? 0 : viewOverrideParams.SortDirection || 0;
			return this.GetSearchSortRollupFromSort(ds, dsd);
		},
		GetSearchSortRollupFromSort: function (sort, sortDirection) {
			sort = (sort === null || typeof sort === 'undefined') ? this.GetDefaultSearchSort() : sort;
			sortDirection = sortDirection || _.isNull(viewOverrideParams) ? 0 : viewOverrideParams.SortDirection || 0;

			switch (sort) {
				case 'Date':
					return sort += Number(sortDirection) === 0 ? '.MinDate' : '.MaxDate';
				case 'GreensFees':
					return sort += Number(sortDirection) === 0 ? '.MinPrice' : '.MaxPrice';
				default:
					return sort;
			}
		},
		SetDefaultSearchView: function(view){
			DEFAULT_SEARCH_VIEW = view;
		},
		SetDefaultSearchViewByType: function (view, type) {
			switch (this.GetSearchTypeName(type)) {
				case 'GeoLocation':
				case '0':
				case 0:
					DEFAULT_SEARCH_VIEW_Geo = view;
					break;
				case 'Facility':
				case '1':
				case 1:
					DEFAULT_SEARCH_VIEW_Course = view;
					break;
				default:
					DEFAULT_SEARCH_VIEW = view;
					break;
			}
		},
		SetDefaultSearchSort: function(sort){
			DEFAULT_SEARCH_SORT = sort;
		},

		GetMaximumCalendarDays: function(){
			return MAXIMUM_CALENDAR_DAYSOUT;
		},

		GetDefaultRateType: function(){
			return DEFAULT_RATE_TYPE;
		},

		GetDefaultExcludeFeaturedFacilities: function(){
			return excludeFeaturedFacilitiesDefault || false;
		},

		GetAllowedRateTypes: function() {
				var rateTypes = [
					{
						text: 'All Rate Types',
						value: 'all'
					},
					{
						text: 'Ladies',
						value: 'ladies'
					},
					{
						text: 'Resident',
						value: 'resident'
					},
					{
						text: 'Senior',
						value: 'senior'
					},
					{
						text: 'Twilight',
						value: 'twilight'
					},
					{
						text: 'Walking',
						value: 'walking'
					}
				];

				return rateTypes;
			},

		// This is needed more for the Properties than the values
		// When new or different refine values are needed
		GetRefineDefaults: function (units,view) {
			return {
				Latitude: null,
				Longitude: null,
				FacilityId: null,
				FacilityIds: null,
				MarketId: null,
				HotDealsOnly: false,
				PromotedCampaignsOnly: false,
				PriceMin: 0,
				PriceMax: 10000,
				Players: 0,
				TimeMin: this.GetMinTimePeriodValue(),
				TimeMax: this.GetMaxTimePeriodValue(),
				TimePeriod: null,
				Radius: this.GetDefaultSearchRadius(units,view),
				Holes: 3,
				SearchType: null,
				Date: GolfNow.Web.Cache.GetActiveDate(),
				View: view || this.GetDefaultSearchView(),
				SortBy: this.GetDefaultSearchSort(),
				SortByRollup: this.GetDefaultSearchSortRollup(),
				FacilityType: 0,
				RateType: this.GetDefaultRateType(),
				//GA Site Search parameters
				Q: null,
				QC: null
			};
		},

		GetRefineDefaultsLower: function (units,view) {
			return {
				latitude: null,
				longitude: null,
				facilityId: null,
				facilityIds: null,
				marketId: null,
				hotdealsonly: false,
				promotedcampaignsonly: false,
				pricemin: 0,
				pricemax: 10000,
				players: 0,
				timemin: this.GetMinTimePeriodValue(),
				timemax: this.GetMaxTimePeriodValue(),
				timeperiod: null,
				radius: this.GetDefaultSearchRadius(units,view),
				holes: 3,
				searchtype: null,
				date: GolfNow.Web.Cache.GetActiveDate(),
				view: view || this.GetDefaultSearchView(),
				sortby: this.GetDefaultSearchSort(),
				sortbyrollup: this.GetDefaultSearchSortRollup(),
				facilitytype: 0,
				ratetype: this.GetDefaultRateType(),
				//GA Site Search parameters
				q: null,
				qc: null
			};
		},

		UrlDecodeString: function (str) {
			// some items have the label property encoded and spaces replaced with plus sign(+)
			// we want to decode and replace the plus signs(+) with a space
			var re = /\+/g;
			return $('<div/>').html(decodeURIComponent(str).replace(re, ' ')).text();
		},

		GetSearchTypeName: function (typeVal) {
			var searchType = typeVal;
			switch (typeVal) {
				case 'GeoLocation':
				case '0':
				case 0:
					searchType = 'GeoLocation';
					break;
				case 'Facility':
				case '1':
				case 1:
					searchType = 'Facility';
					break;
				case 'Market':
				case '2':
				case 2:
					searchType = 'Market';
					break;
				case 'Destination':
				case '3':
				case 3:
					searchType = 'Destination';
					break;
				case 'GoPlay':
				case '4':
				case 4:
					searchType = 'GoPlay';
					break;
				case 'Favorites':
				case '5':
				case 5:
					searchType = 'Favorites';
					break;
				default:
					searchType = 'GeoLocation';
					break;
			}
			return searchType;
		},

		ConsoleLog: function (msg, e) {
			try {
				if (console) console.log(msg, e || '');
			} catch (e) {/*empty code*/}
		},
		ConsoleWarn: function (msg) {
			try {
				if (console) console.warn(msg);
			} catch (e) {/*empty code*/ }
		},
		ConsoleError: function (msg) {
			try {
				if (console) console.error(msg);
			} catch (e) {/*empty code*/ }
		},
		GetGooglePlacesAutoCompleteResults_Geo: function (searchkey) {
			var d = $.Deferred();
			var results = [];

			autoCompleteService.getPlacePredictions({ input: searchkey, types: [] }, function (predictions, status) {
				if (status !== google.maps.places.PlacesServiceStatus.OK) {
					d.resolve( { } );
				} else {
					results = $.map(predictions, function (prediction, i) {
						if ($.inArray("street_address", prediction.types) < 0) {
							return {
								label: prediction.description,
								value: prediction.description,
								type: 'places',
								id: prediction.place_id
							};
						}
					});

					d.resolve(results);
				}
			});

			return d.promise();
		},

		GetGooglePlacesAutoCompleteResults_Regions: function (searchkey) {
			var d = $.Deferred();
			var results = [];

			autoCompleteService.getPlacePredictions({ input: searchkey, types: ['(regions)'] }, function (predictions, status) {
				if (status !== google.maps.places.PlacesServiceStatus.OK) {
					d.resolve({});
				} else {
					results = $.map(predictions, function (prediction, i) {
						return {
							label: prediction.description,
							value: prediction.description,
							type: 'places',
							id: prediction.place_id
						};
					});

					d.resolve(results);
				}
			});

			return d.promise();
		},

		ShowAvailableCustomerRewards: function (apiRewardsUrl, apiCreditsUrl) {
			var isMobile = !Foundation.utils.is_large_up();
			var rewardsAvailable = parseInt(GolfNow.Web.Cache.GetValue(REWARDS_CACHE_KEY));
			var creditsAvailable = parseInt(GolfNow.Web.Cache.GetValue(CREDITS_CACHE_KEY));

			if (authenticated && isNaN(rewardsAvailable) || isNaN(creditsAvailable)) {
				var creditsReq = GolfNow.Web.Request.Post('rewards-credits-request', apiCreditsUrl);
				var rewardsReq = GolfNow.Web.Request.Get('get-rewards-profile', apiRewardsUrl, true);

				$.when
					.apply(this, [creditsReq, rewardsReq])
					.done(function ([creditsData], [rewardsData]) {
						var credits = "0", rewards = "0";

						if (creditsData && creditsData.length > 0)
							credits = creditsData.length;

						if (rewardsData && rewardsData.rewardsAvailable)
							rewards = rewardsData.rewardsAvailable;
						
						GolfNow.Web.Cache.SetSessionStorageValue(CREDITS_CACHE_KEY, credits, 1000 * 60 * 30);
						GolfNow.Web.Cache.SetSessionStorageValue(REWARDS_CACHE_KEY, rewards, 1000 * 60 * 30);

						badgeCount = parseInt(rewards) + parseInt(credits);
						if (!isNaN(badgeCount) && badgeCount > 0) {
							$('a[data-rewards]').parent('li').addClass('badge1').attr('data-badge', badgeCount);
							if (isMobile) {
								$('.activity-indicator').remove();
								var $activityIndicator = $('<span>', { 'class': 'activity-indicator', 'html': '' });
								$activityIndicator.addClass('right');
								$('.toggle-topbar.menu-icon.touch-menu').prepend($activityIndicator);
							}
						}
					});
			} else {
				if (rewardsAvailable > 0 || creditsAvailable > 0) {
					$('a[data-rewards]').parent('li').addClass('badge1').attr('data-badge', rewardsAvailable + creditsAvailable);

					if (isMobile) {
						$('.activity-indicator').remove();

						var $activityIndicator = $('<span>', { 'class': 'activity-indicator', 'html': '' });
						$activityIndicator.addClass('right');
						$('.toggle-topbar.menu-icon.touch-menu').prepend($activityIndicator);
					}
				}
			}
		},

		ClearAvailableCustomerRewards: function () {
			GolfNow.Web.Cache.SetSessionStorageValue(CREDITS_CACHE_KEY, null);
			GolfNow.Web.Cache.SetSessionStorageValue(REWARDS_CACHE_KEY, null);
		},

		LogoutOfInstructorsSession: function (url) {
			var params = {};
			$.ajax({
				url: url + '/secure/logoutFromApp',
				type: 'GET',
				dataType: 'jsonp',
				data: params,
				jsonp: 'callback'
			})
			.done(function (data) {
				if (!_.isEmpty(data) && data.success) {
					GolfNow.Web.Utils.ConsoleLog("Logout successful from applet");
				}
			})
			.fail(function (xhr, status, error) {
				GolfNow.Web.Utils.ConsoleError('Failed to logout from applet.');
			});
		},

		SetAvatarUrlCacheValues: function (avatarUrlCacheValue, avatarUrlCacheHasChangedValue) {
			GolfNow.Web.Cache.SetLocalStorageValue('avatarUrlCache', avatarUrlCacheValue);
			GolfNow.Web.Cache.SetLocalStorageValue('avatarUrlCacheHasChanged', avatarUrlCacheHasChangedValue);
		},

		GetAvatarUrlCacheValues: function () {
			var avatarCacheValues = {
				AvatarUrlCache: GolfNow.Web.Cache.GetValue('avatarUrlCache'),
				AvatarUrlCacheHasChanged: GolfNow.Web.Cache.GetValue('avatarUrlCacheHasChanged')
			};
			return avatarCacheValues;
		},

		ClearAvatarUrlCacheValues: function () {
			GolfNow.Web.Cache.SetLocalStorageValue('avatarUrlCache', '');
			GolfNow.Web.Cache.SetLocalStorageValue('avatarUrlCacheHasChanged', '');
		},

		ShowCustomerVIPBadge: function (productName) {
			var $desktopWelcome = $('a#large-customer-welcome[data-vip]');
			var desktopWelcomeCount = $desktopWelcome.length;
			var $smallWelcome = $('a#subNavLink[data-vip]');
			var smallWelcomeCount = $smallWelcome.length;
			var $myAccountWelcome = $('h2#my-account-welcome[data-vip]');
			var deskTopText = $desktopWelcome.html();
			var smallText = $smallWelcome.html();
			var myAccountText = $myAccountWelcome.html() || '' + ' ';

			// based on the supplied productName, change the badge className accordingly
			var gpBadgeClassName = golfpassBadgeClassName(productName);

			if ($desktopWelcome.children('p').length < desktopWelcomeCount) {
				$desktopWelcome.html('<p class="large-customer-welcome-label">' + deskTopText + '</p>' + '<span class="' + gpBadgeClassName + ' vip-blue show-for-large-up" style="display: inline; float: left;"></span>');
			}
			if ($smallWelcome.siblings('span').length < smallWelcomeCount) {
				$smallWelcome.html(smallText + ' <span class="' + gpBadgeClassName + '"></span>');
			}
			if ($myAccountWelcome.length && $myAccountWelcome.html() !== myAccountText) {
				$myAccountWelcome.html(myAccountText);
			}
		},

		GetGolfPassBadgeClassName: golfpassBadgeClassName,

		ShowPendingSocialRequests: function (apiUrl) {
			var that = this;
			var isMobile = !Foundation.utils.is_large_up();
			var buildRequestElems = function (count) {
				if (count > 0) {
					count = count >= 99 ? '99+' : count.toString();
					$('.activity-pending-requests').remove();
					var $pendingCount = $('<span>', { 'class': 'alert label right activity-pending-requests', 'html': count });
					$('a[data-activity]').prepend($pendingCount);

					$('.activity-indicator').remove();
					var $activityIndicator = $('<span>', { 'class': 'activity-indicator', 'html': '' });
					if (isMobile) {
						$activityIndicator.addClass('right');
						$('.toggle-topbar.menu-icon.touch-menu').prepend($activityIndicator);
					} else {
						$('#large-customer-welcome').prepend($activityIndicator);
					}
				}
			};
			var getPendingRequests = function () {
				GolfNow.Web.Request.Get('get-social-requests', apiUrl, true)
					.done(function (data) {
						if (data && data.status === 'success') {
							buildRequestElems(data.value);
						} else {
							buildRequestElems(0);
						}
						GolfNow.Web.Cache.SetSessionStorageValue(PENDING_SOCIAL_REQUESTS_KEY, data.value);
					});
			};
			GolfNow.Web.Page.Sub('social-activity-changed', function () {
				that.ClearPendingSocialRequests();
				if (authenticated) getPendingRequests();
			});
			var pendingRequests = parseInt(GolfNow.Web.Cache.GetValue(PENDING_SOCIAL_REQUESTS_KEY));
			if (authenticated && isNaN(pendingRequests)) {
				getPendingRequests();
			} else {
				buildRequestElems(pendingRequests);
			}
		},

		ClearPendingSocialRequests: function(){
			GolfNow.Web.Cache.SetSessionStorageValue(PENDING_SOCIAL_REQUESTS_KEY, null);
			$('.activity-indicator').remove();
			$('.activity-pending-requests').remove();
		},

		SetHomePageSearch: function (_isHomePageSearch) {
			_isHomePageSearch = typeof _isHomePageSearch !== "boolean" ? false : _isHomePageSearch;

			IS_HOMEPAGE_SEARCH = _isHomePageSearch;
		},

		IsHomePageSearch: function () {
			return IS_HOMEPAGE_SEARCH;
		},

		SetDestinationCityLoaded: function (_isDestinationCityPage) {
			_isDestinationCityPage = typeof _isDestinationCityPage !== "boolean" ? false : _isDestinationCityPage;

			IS_DESTINATION_CITY_PAGE = _isDestinationCityPage;
		},

		IsDestinationCityPage: function () {
			return IS_DESTINATION_CITY_PAGE;
		},

		SetTeeTimeOfferAccepted: function (offerTeeTimeId) {
			GolfNow.Web.Cache.SetSessionStorageValue(TEETIME_OFFER_CACHE_KEY, offerTeeTimeId);
		},

		GetAcceptedTeeTimeOffer: function () {
			return GolfNow.Web.Cache.GetValue(TEETIME_OFFER_CACHE_KEY) || null;
		},

		GetSiteCode: function () {
			return siteCode;
		},

		HandleUnitsConversion: handleUnitsConversion,
		AppendRadiusUnits: function (distance) {
			if (typeof distance === 'undefined' || distance === null) return 0 + DEFAULT_UNITS;
			return distance + DEFAULT_UNITS;
		},

		SetCookie: function (name, value, exdays) {
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + exdays);
			value = encodeURI(value) + (exdays === null ? '' : '; expires=' + exdate.toUTCString());
			document.cookie = name + '=' + value + '; path=/; samesite=none; domain=' + location.host.substr(location.host.indexOf('.')) + '; secure;';
		},

		GetCookie: function (name) {
			var i, x, y, ARRcookies = document.cookie.split(';');
			for (i = 0; i < ARRcookies.length; i++) {
				x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
				y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
				x = x.replace(/^\s+|\s+$/g, '');
				if (x === name) {
					return decodeURI(y);
				}
			}
			return null;
		},

		GetABTrackGoogleEventValue: function (name) {
			if (name.indexOf(' B ') > -1) {
				name = name.replace(' B ', ' B4 ');
			}
			if (name.indexOf(' B2 ') > -1) {
				name = name.replace(' B2 ', ' B4 ');
			}
			return name;
		},

		BuildMenuAvatarLogin: function (loginMenuObj) {
			if (typeof (loginMenuObj) !== 'undefined') {
				GolfNow.Web.Utils.SetAvatarLoginTemplate(loginMenuObj.firstName, loginMenuObj.lastName, loginMenuObj.awsBaseProfilePicUrl, loginMenuObj.avatarUrl, loginMenuObj.homePageUrl, loginMenuObj.socialUrl);
			} else {
				if (typeof (GolfNow.Web.Cache) !== 'undefined') {
					var cachedMenuObj = GolfNow.Web.Cache.GetValue('login_menu_builder_obj') || null;

					if (typeof (cachedMenuObj) !== 'undefined' && cachedMenuObj !== null)
						GolfNow.Web.Utils.SetAvatarLoginTemplate(cachedMenuObj.firstName, cachedMenuObj.lastName, cachedMenuObj.awsBaseProfilePicUrl, cachedMenuObj.avatarUrl, cachedMenuObj.homePageUrl, cachedMenuObj.socialUrl);
				}
			}
		},

		SetAvatarLoginTemplate: function (firstName, lastName, profilePicUrl, avatarUrl, homePageUrl, myProfilePageUrl) {
			var model = {
				FirstName: firstName,
				LastName: lastName,
				ProfilePicUrl: profilePicUrl,
				AvatarUrl: avatarUrl
			};

			avatarLoginPicTmpl = $.templates('#avatarLoginPicTmpl');
			avatarLoginPicTmpl.link('.login-menu-pic-container', model);
			$(".login-menu-pic-link-container").attr("href", myProfilePageUrl);
		},

		ReplaceDefaultSpecialCharacterMsg: function (defaultMsg, characterToFind, replacement) {
			return defaultMsg.replace(characterToFind, replacement);
		},

		GetVisitorModalWebsiteUrl: function (country) {
			switch (country.toLowerCase()) {
				case 'uk':
				case 'gb':
				case 'ie':
					return GNUK_WEBSITE_URL;
				case 'au':
					return GNAU_WEBSITE_URL;
				default:
					break;
			}
		},

		GetVisitorModalCountry: function (country) {
			if (typeof country === 'undefined' || country === null) return {};

			var countryCode = '';
			var countryName = '';
			var countriesName = '';

			switch (country.toLowerCase()) {
				case 'uk':
				case 'gb':
				case 'ie':
					countryCode = 'UK'; //country code stays the same for UK/GB/IE for analytics
					countryName = 'United Kingdom';
					countriesName = 'UK & Ireland';
					break;
				case 'au':
					countryCode = 'AU';
					countryName = 'Australia';
					break;
				default:
					break;
			}
			return { countryCode: countryCode, countryName: countryName, countriesName: countriesName };
		},

		SetVisitorModalText: function (country, websiteUrl) {
			var replaceVal = country.countryCode.toLowerCase() !== 'au' ? country.countriesName : country.countryName;
			var title = $('h2#visitorModalTitle').html().replace('countryCode', replaceVal);
			var note = $('.visitor-location-note span').html().replace('countryCode', replaceVal).replace('websiteUrl', websiteUrl);

			$('h2#visitorModalTitle').html(title);
			$('.visitor-location-note span').html(note);
		},

		BindVisitorModalClickEvents: function (countryCode, websiteUrl) {
			$('#stay-location, #visitor-location-modal .close-reveal-modal').on('click', function (e) {
				TrackGoogleEvent('visitor' + countryCode, countryCode + ' Visitor', 'Click', 'Stay US Site');
			});

			$('#go-location, #visitorLocationLink').on('click', function (e) {
				var urlParams = '?utm_source=GolfNow.com&utm_medium=referral&utm_campaign=redirect_modal';
				TrackGoogleClickEvent('visitor' + countryCode, countryCode + ' Visitor', 'Click', 'Visit ' + countryCode + ' Site', null, websiteUrl + urlParams);
			});
		},

		IsFacilityPageLeftSide: function () {
			// The class 'fdi-left-side' is used to know if we are using the facility tee times page left side layout (_FacilityDetailInformationSideBySide.cshtml)
			// This class is only used in _FacilityDetailInformationSideBySide.cshtml and it is necessary when using this layout in order to adjust the elements correctly.
			return $('#facility-listing').hasClass('fdi-left-side');
		},

		RedirectToFacilityUrl: function () {
			var redirectToFacilityUrl = bestDealsFacilityPage ? redirectToBestDealsFacilityLink : redirectToFacilityLink;
			return redirectToFacilityUrl;
		},

		GetFormattedLocaleTime: function (timeStr) {
			Date.CultureInfo.name = gnSiteLocale || 'en-US';
			var d = new Date();
			d.set({ hour: 20 });
			var minutePart = '';
			var pos = timeStr.indexOf(' ');
			var includePlus = timeStr.indexOf('+') > -1;
			var ampm = d.toLocaleString().indexOf('PM') > -1;
			if (pos > -1) {
				var i = timeStr.split(' ');
				var timePart = hourPart = i[0];
				var ampmPart = i[1];
				if (timePart.indexOf(':') > 0) {
					var timeParts = timePart.split(':');
					hourPart = timeParts[0];
					minutePart = timeParts[1];
				}
				var t = (hourPart != 12 && ampmPart.indexOf('PM') > -1) ? Number(hourPart) + 12 : Number(hourPart);
				t = t >= 24 ? 23 : t;
				d.set({ hour: t });
				if (minutePart !== '') d.set({ minute: Number(minutePart) });
			} else {
				d.set({ hour: Number(timeStr) });
			}
			// to add html formatting: <\\sub>tt</\\sub>
			var formatString = (ampm && gnSiteLocale === 'en-US') ? minutePart === '' ? 'h tt' : 'h:mm tt' : 'HH';
			formatString += includePlus ? '+' : '';
			return d.toString(formatString);
		},

		LoadGlobalNav: function (code) {
			var navElemSelector = 'header nav.brand-nav > ul';
			var $navElemSelector = $(navElemSelector);
			if ($navElemSelector.length) {
				var siteSettings = GolfNow.Web.Domains.SiteConfigSettings();
				var locale = siteSettings.locale || 'en_US';
				locale = locale.replace('-', '_');
				code = code || 'GN';
				$.templates({
					navTmpl: '#global-nav-tmpl',
					imgTmpl: '<img src="{{>imgsrc}}" alt="{{>alt}}" title="{{>title}}" />'
				});

				$.getJSON('https://static.golfchannel.com/global-nav/global-nav.v2.json', function (navData) {
					var filtered = _.reject(navData.mainnav, function (obj) {
						return obj.code === code || (!_.isUndefined(obj.locale) && !_.contains(obj.locale, locale));
					});
					var modified = _.map(filtered, function (obj, idx) {
						var source = 'GolfNow';
						switch (siteCode) {
							case 'gnuk':
								source = 'GolfNowUK';
								break;
							case 'gnau':
								source = 'GolfNowAU';
								break;
						}
						obj['utm_source'] = source;
						return obj;
					});
					var html = $.render.navTmpl(modified);
					$navElemSelector.html(html);
				});
			}
		},
		BrightEdgePluginDisabled: function () {
			$('#brightedge-plugin-container').hide();
		},
		CategorizeURLPath() {
			const url = document.location.pathname;

			// Define regular expressions for the different URL patterns
			const routes = {
				home: /^\/$/,
				facilityPage: /^\/tee-times\/facility\/[\w-]+\/search$/,
				teeTimeDetails: /^\/tee-times\/facility\/\d+\/tee-time\/\d+$/,
				hotDeals: /^\/tee-times\/hot-deals$/,
				coursesNearMe: /^\/tee-times\/courses-near-me$/,
				bestCourses: /^\/tee-times\/best-golf-courses-near-me\/search$/,
				golfPass: /^\/memberships\/golfpass$/
			};

			// Check the URL against each pattern
			for (const [category, pattern] of Object.entries(routes)) {
				if (pattern.test(url)) {
					switch (category) {
						case 'facilityPage':
							return 'Facility Page';
						case 'teeTimeDetails':
							return 'Tee Time Details';
						case 'hotDeals':
							return 'Hot Deals Near Me';
						case 'bestCourses':
							return 'Best Courses Near Me';
						case 'golfPass':
							return 'GolfPass Landing Page';
						default:
							return category.charAt(0).toUpperCase() + category.slice(1).replace(/([A-Z])/g, ' $1').trim();
					}
				}
			}

			// If none of the predefined categories match, return the URL path directly
			return url;
		}
	};

	///****** Private methods & routings ******///
	function handleUnitsConversion(units, distance) {
		units = (typeof units === "undefined" || units === null) ? defaultUnits : units;

		var multiplier = 1;
		switch (units) {
			case 'km':
				multiplier = 1.609;
				break;
			default:
				break;
		}
		return Number(Math.round(distance * multiplier).toFixed(0));
	}

	/// Return the public object
	return utilObj;

})(jQuery); // Define dependencies

jQuery(function ($) {
	$(".exit-off-canvas").click(function () {
		$(".off-canvas-wrap").css("height", "auto");
		$(".subMenu").removeClass("showMenu");
	});

	$(".right-off-canvas-toggle").click(function () {
		// GNSCM - 7818 - Without this can't scroll when menu open on tablet
		if (Foundation.utils.is_medium_only()) {
			setTimeout(function () {
				$('html').css('overflow', 'unset');
			}, 1000);
		}
		
		
		var menuHeight = $(".off-canvas-list").height() + $('.creditMenuWrapper').outerHeight();
		if (menuHeight > $(window).height()) {
			$(".off-canvas-wrap").height(menuHeight);
		} else {
			$(".off-canvas-wrap").height($(window).height());
		}
	});

	$('#reservation-button-top, #purchase-button-top').on('click', function (e) {
		GolfNow.Web.Utils.ClearAvailableCustomerRewards();
	});

	$('#logoutAccountMenu, #logoutAccountPage, #logoutHamburgerMenu').click(function (e) {
		e.preventDefault();
		GolfNow.Web.Utils.ClearAvailableCustomerRewards();
		GolfNow.Web.Utils.ClearPendingSocialRequests();
		var href = $(this).attr('href');
		GolfNow.Web.Utils.LogOutOfAmazonSession(function () {
			window.location.href = href;
		});
		GolfNow.Web.Utils.LogOutOfQantasSession();
		GolfNow.Web.Utils.Logout();
	});
	$('.golfnow-care-hours,.golfnow-care-phone,.booking-center-hours,.booking-center-phone,.golfnow-vip-phone').phoneAndHours();

	var lgNav = _.once(GolfNow.Web.Utils.LoadGlobalNav);
	lgNav('GN');

	if (!_.isEmpty(autoLoginProps)) {
		$.getScript(autoLoginProps.scriptUrl, function () {
			var gid = new GolfId(autoLoginProps.clientId, autoLoginProps.redirectUrl, autoLoginProps.baseUrl);

			//during the GolfNow logout (when GolfID is enabled) we need to call the logout function from the golfid.js in order to make sure the user is logged out.
			//this is needed because at the time we force the logout using the iframe URL on the Logout.cshtml, there is no GolfID reference since the user is already logged in
			if (autoLoginProps.isForcedGolfIdLogout) {
				gid.logout(function () {
					window.location.href = autoLoginProps.returnUrl;
				});
			}
			else {
				gid.autoLogin(autoLoginProps.securityKey, null, function (data) {
					if (data.code && data.state && data.uri) {
						var ajaxUri = data.uri.replace('oauth-callback', 'oauth-ajax-callback');
						var menuSelector = Foundation.utils.is_large_up() ? 'nav.top-bar .top-bar-section .login-box-helper' : '.off-canvas-wrap.subpage .inner-wrap #hamburger-menu';
						var dataContainerSelector = Foundation.utils.is_large_up() ? 'li.loggedin-data-container' : 'a.loggedin-data-container:first';
						var $menuSelector = $(menuSelector);

						if ($menuSelector.length) {
							$menuSelector.load(ajaxUri + '&isLargeDevice=' + Foundation.utils.is_large_up(), function () {
								var $dataElem = $(dataContainerSelector);
								if (Foundation.utils.is_large_up()) {
									$dataElem.addClass('not-click');
								} else {
									$(document).foundation('offcanvas', 'reflow');
								}

								var isGPMember = $dataElem.data('isgpmember') || false;
								var isGPPMember = $dataElem.data('isgppmember') || false;
								var subscriptionProductId = $dataElem.data('subscription-product-id');
								var memberProductInfo = isGPMember || isGPPMember ? 'ProductId ' + subscriptionProductId : 'Non-Member';

								var firstName = $dataElem.data('firstname') || '';
								var lastName = $dataElem.data('lastname') || '';
								var customerId = $dataElem.data('customerid') || '';

								if (!_.isEmpty(firstName) && !_.isEmpty(lastName)) {
									GolfNow.Web.Utils.SetAvatarLoginTemplate(firstName, lastName, autoLoginProps.profilePicUrl, autoLoginProps.avatarUrl, autoLoginProps.homepageUrl, autoLoginProps.profileUrl);
								}

								if (autoLoginProps.gp && isGPMember) {
									if (_.isUndefined(productSubscriptionName) || productSubscriptionName === '') { productSubscriptionName = 'GolfPass+'; }
									GolfNow.Web.Utils.ShowCustomerVIPBadge(productSubscriptionName);
								}

								if (autoLoginProps.rewards) GolfNow.Web.Utils.ShowAvailableCustomerRewards(autoLoginProps.rewardsProfileUrl, autoLoginProps.creditsProfileUrl);
								if (autoLoginProps.social) GolfNow.Web.Utils.ShowPendingSocialRequests(autoLoginProps.pendingRequestsUrl);

								if (dataLayer) dataLayer.push({ 'authStatus': 'Logged In', 'membershipStatus': memberProductInfo });
								uid = customerId;

								GolfNow.Web.Page.Pub('customer-authenticated', {
									firstName: firstName,
									lastName: lastName,
									gpMember: isGPMember,
									gppMember: isGPPMember,
									customerId: customerId
								});
							});
						} else {
							$('#ajax-golfid-return').load(ajaxUri + '&returnMenu=false');
						}
					}
				});
			}
		});
	}
});
;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

GolfNow.Web.Page = (function ($, amp, _, gnRequest) {
	///****** Public methods ******///
	var pageObj = {
		// Subscribe to a topic
		Sub: function (topic, callback) {
			amp.subscribe(topic, callback);
		},
		// Publish a topic
		Pub: function (topic, data) {
			amp.publish(topic, data);
			_sendMessage(JSON.stringify({
				'message': topic,
				'data': data
			}));
		},
		// An array of topics published via this object
		PublishedTopics: function () {
			return _publishedTopics;
		},
		// Get the page name
		PageName: function () {
			return _pageName;
		},
		SetPreventResize: function (preventResize) {
			_preventResize = typeof _preventResize !== "boolean" ? false : _preventResize;
			_preventResize = preventResize;
		},

		// Method that brings everything alive
		PageLoad: pageLoad,
		RedirectToUnsupported: redirectToDeviceRestrictionPage,
		RedirectToHome: redirectToHomePage,
		GetPageConfig: getPageConfig,
		GetCurrentClientProfile: getCurrentClientProfile,
		SendMessage: sendMessage,
		LazyLoadHamburgerMenu: lazyLoadHamburgerMenu
	};

	///****** Private methods ******///
	var _pageName = '',
		_configData = {},
		_publishedTopics = [
			'window_resize',
			'page_init',
			'mq_small_screen',
			'mq_medium_screen',
			'mq_large_screen',
			'mq_xlarge_screen'
		],
		_allowedDeviceModes = ['small', 'medium', 'large'],
		_baseUrl, _pageLoadClientProfile,
		$ttSearchElem = $('#teetime-search'),
		$searchElem = $ttSearchElem.length ? $ttSearchElem : $('#pre-fedsearch, #fed-search-big'),
		_preventResize = false,

		// Send a message to the parent
		_sendMessage = function (msg, src) {
			if (window.parent === null) return;

			src = src || window.parent;

			// Make sure you are sending a string, and to stringify JSON
			// messages: loggedin, loggedout, reload
			src.postMessage(msg, '*');
		}, setPageConfigOnce = _.once(setPageConfig);

	function sendMessage(msg, src) {
		_sendMessage(msg, src);
	}

	// Widget event handlers
	function widget_loading(data) {
		GolfNow.Web.Utils.ConsoleLog('Loading ' + data.widgetName + '...');
	}
	function widget_loadComplete(data) {
		GolfNow.Web.Utils.ConsoleLog('Done loading ' + data.widgetName);
	}
	function widget_loadError(data) {
		GolfNow.Web.Utils.ConsoleLog('Error loading ' + data);
	}

	// Subscribe to topics
	function subscribe2Topics() {
		amp.subscribe('widget_loading', widget_loading);
		amp.subscribe('widget_loadComplete', widget_loadComplete);
		amp.subscribe('widget_loadError', widget_loadError);
	}

	// Publish topics
	function publishTopics() {
		// publish a page_init event that all page elements can subscribe to
		amp.publish('page_init', $searchElem.data('configData'));

		// push event onto the dataLayer for optimize trigger event
		dataLayer.push({ 'event': 'optimize.active' });
	}

	function getCurrentClientProfile() {
		if (Foundation.utils.is_small_only()) {
			return 'small';
		} else if (Foundation.utils.is_medium_only()) {
			return 'medium';
		} else if (Foundation.utils.is_large_up()) {
			return 'large';
		}
	}

	// Event bindings
	function bindEvents() {

		lazyLoadHamburgerMenu();

		// Listen to messages from parent window
		bindIFrameEvent(window, 'message', function (e) {
			if (e.isTrusted && e.origin.indexOf('golfpass.com')) {
				switch (e.data) {
					case 'reportBodyHeight':
						var $main = $('main');
						_sendMessage(JSON.stringify({
							'message': 'resize',
							'data': {
								'scrollHeight': $main.length ? $main.height() : $(document).height()
							}
						}), e.source);
						break;
					case 'hideHeaderFooter':
						$('head, footer').hide();
						break;
					case 'reportBackNavigation':
						_sendMessage(JSON.stringify({
							'message': 'navigationStack',
							'data': {
								'currentPage': document.location.href,
								'navStack': GolfNow.Web.Cache.GetValue('navigation_BackStack') || null
							}
						}), e.source);
						break;
					case 'goBack':
						history.back();
						break;
					case 'goForward':
						history.forward();
						break;
				}
				return;
			} else {
				return;
			}
		});

		bindMediaQueryChanges();

		var premain = document.querySelector('main, .main-content, .inner-wrap');
		if (typeof (ResizeSensor) !== 'undefined' && ResizeSensor && premain !== null) {
			var resizeElemEvtHandler = _.debounce(function () {
				_sendMessage(JSON.stringify({
					'message': 'resize',
					'data': {
						'scrollHeight': premain.clientHeight
					}
				}));
			}, 150, true);
			new ResizeSensor(premain, resizeElemEvtHandler);
		} else {
			var docHeight = $(document).height();
			var resizeEvtHandler = _.debounce(function () {
				amp.publish('window_resize');

				var resizeHeight = $(document).height();
				if (resizeHeight !== docHeight) {
					_sendMessage(JSON.stringify({
						'message': 'resize',
						'data': {
							'scrollHeight': resizeHeight
						}
					}));
				}
			}, 150, true);

			// bind to window resize event??
			$(window).resize(resizeEvtHandler);
		}

	}
	function bindIFrameEvent(element, eventName, eventHandler) {
		if (window.parent === null) return;

		if (element.addEventListener) {
			element.addEventListener(eventName, eventHandler, false);
		} else if (element.attachEvent) {
			element.attachEvent('on' + eventName, eventHandler);
		}
	}
	function bindMediaQueryChanges() {
		// Define media queries for the sizes supported
		var mqSmall = window.matchMedia(Foundation.media_queries['small-only']); //40 or 47.9375 = 640px
		var mqMed = window.matchMedia(Foundation.media_queries['medium-only']); //40.063 or 48 = 641px - 1024px
		var mqLargeUp = window.matchMedia(Foundation.media_queries['large']); // 1025px - 1440px
		//var mqXLarge = window.matchMedia(Foundation.media_queries['xlarge']); // 1441px

		// Add listeners for media query changes
		var dbLargeScrHandler = _.debounce(handleLargeScreen, 200, true);
		var dbMediumScrHandler = _.debounce(handleMediumScreen, 200, true);
		var dbSmallScrHandler = _.debounce(handleSmallScreen, 200, true);
		try {
			//mqXLarge.addListener(function mqXLarge(changed) {
			//	if (changed.matches) dbLargeScrHandler();
			//});
			mqLargeUp.addListener(_.debounce(function mqLargeUp(changed) {
				if (changed.matches === true) handleLargeScreen();
			}, 150));
			mqMed.addListener(_.debounce(function mqMed(changed) {
				if (changed.matches === true) handleMediumScreen();
			}, 150));
			mqSmall.addListener(_.debounce(function mqSmall(changed) {
				if (changed.matches === true) handleSmallScreen();
			}), 150);

			// Handle current media query matches
			if (mqLargeUp.matches) dbLargeScrHandler();
			if (mqMed.matches) dbMediumScrHandler();
			if (mqSmall.matches) dbSmallScrHandler();
		} catch (e) {
			redirectToBrowserRestrictionPage();
		}
	}

	// Media Query change handlers
	function handleSmallScreen() {
		GolfNow.Web.Utils.ConsoleLog('Handling Small Screen');
		var newClientProfile = getCurrentClientProfile();
		if (newClientProfile !== _pageLoadClientProfile && !_preventResize) {
			document.location.reload();
		} else {
			_pageLoadClientProfile = newClientProfile;
			amp.publish('mq_small_screen');
		}
	}
	function handleMediumScreen() {
		GolfNow.Web.Utils.ConsoleLog('Handling Medium Screen');
		var newClientProfile = getCurrentClientProfile();
		if (newClientProfile !== _pageLoadClientProfile && !_preventResize) {
			document.location.reload();
		} else {
			_pageLoadClientProfile = newClientProfile;
			amp.publish('mq_medium_screen');
		}
	}
	function handleLargeScreen() {
		GolfNow.Web.Utils.ConsoleLog('Handling Large Screen');
		var newClientProfile = getCurrentClientProfile();
		if (newClientProfile !== _pageLoadClientProfile && !_preventResize) {
			document.location.reload();
		} else {
			_pageLoadClientProfile = newClientProfile;
			amp.publish('mq_large_screen');
		}
	}

	function lazyLoadHamburgerMenu(isWordpress) {
		// lazy load hamburger menu if needed
		var $navBar = $('nav.top-bar').length > 0 ? $('nav.top-bar') : $('div.inner-wrap');
		$navBar.on('click', 'li.toggle-topbar > .right-off-canvas-toggle > i', function (evt) {
			checkIfNeedsHamburgerMenu(getCurrentClientProfile(), isWordpress);
			setTimeout(function () {
				hamburgerSubMenuClickEvent();
			}, 500);
		});
	}

	function checkIfNeedsHamburgerMenu(clientProfile, isWordpress) {
		isWordpress = isWordpress || false;
		var useRelativeUrlsParam = isWordpress ? '&useRelativeUrls=false' : '';
		var adaptiveProfile = $('body > div').data('dm');

		if ((isWordpress && typeof adaptiveProfile == 'undefined') || adaptiveProfile === 'large' && clientProfile !== 'large') {
			var $hamburgerAside = $('#hamburger-menu > aside');
			var reflowElems = function () {
				$(document).foundation('offcanvas', 'reflow');
				$(document).foundation('dropdown', 'reflow');
				$('.off-canvas-wrap.subpage').css({
					'height': 'auto',
					'top': '0px'
				});
				GolfNow.Web.Utils.ShowCustomerVIPBadge(productSubscriptionName);
				GolfNow.Web.Utils.BuildMenuAvatarLogin();

				//need to bind the open modal login button click event after hamburger menu is fully loaded
				GolfNow.Web.Login.OpenModalLoginButtonEvent();
			};

			if (!$hamburgerAside.length) {
				var ver = new Date().getTime();
				var url = getRequestUrl('/api/menu/hamburger?v=' + ver + useRelativeUrlsParam);

				$('#hamburger-menu').load(url, reflowElems);
			}
		}
		//need to call the function in here as well to cover the scenario in which there is no need to "reflowElems"
		GolfNow.Web.Login.OpenModalLoginButtonEvent();
	}

	function hamburgerSubMenuClickEvent() {
		$(".right-off-canvas-menu").off('click', '.has-submenu > a');
		$(".right-off-canvas-menu").on('click', '.has-submenu > a', function (e) {
			e.preventDefault();

			var $context = $(this).parent();

			$context.find("i").first().toggleClass("fa-chevron-up").toggleClass("fa-chevron-down");
			$context.children('ul.subMenu').toggleClass("showMenu");
			$(".off-canvas-wrap").height($(".off-canvas-list").height() + $('.creditMenuWrapper').outerHeight());
		});
	}

	function redirectToDeviceRestrictionPage() {
		if (document.location.href.lastIndexOf('unsupported') < 0)
			document.location.href = '/device/unsupported';
	}

	function redirectToBrowserRestrictionPage() {
		if (document.location.href.lastIndexOf('unsupported') < 0)
			document.location.href = '/browser/unsupported';
	}

	function redirectToHomePage() {
		//TODO: enable this when css no longer has the size restrictions
		//if (document.location.href.lastIndexOf('unsupported') > -1)
		//    document.location.href = '/';
	}

	function getRequestUrl(url) {
		if (topDomainAssetPrefix === '/') return url;

		return topDomainAssetPrefix + url.replace(/^\//, '');
	}

	function loadAsyncSections(sections, sectionSize, configPageName, pageModel, tmplVersion) {
		// loop through all sections
		_.each(sections, function (section, idx, sectionItems) {
			var sectionName = section.Name.toLowerCase();
			var $section = $('#' + sectionName);
			var sectionType = section.Type.toLowerCase();
			var rndNumber = 0;
			if (sectionType === 'randomize_widgets') {
				var widgetCount = section.Widgets.length;
				rndNumber = Math.floor(Math.random() * widgetCount) + 1;
			}

			// loop through the widgets in the section
			_.each(section.Widgets, function (widget, idx, widgetItems) {
				// check if this widget is apart of a set of randomized widgets
				// then skip over the index that doesn't match the random number
				if (sectionType === 'randomize_widgets' && rndNumber > 0 && idx + 1 !== rndNumber) return;

				var widgetName = widget.Name.toLowerCase();
				if (_baseUrl.indexOf('/', _baseUrl.length -1) === -1) _baseUrl += '/';
				var url = _baseUrl + 'api/widgets/' + sectionSize.toLowerCase() + '-' + widgetName + '/template/' + sectionName + '/' + configPageName + '?v=' + tmplVersion;
				//var url = _baseUrl + '/widgets/' + widgetName;
				var doneTopic = 'async_' + widgetName + '_init',
					failTopic = 'async_' + widgetName + '_fail',
					alwaysTopic = 'async_' + widgetName + '_always';

				// update publishedTopic array
				_publishedTopics.push(doneTopic);
				_publishedTopics.push(failTopic);
				_publishedTopics.push(alwaysTopic);

				var widgetReq;
				if (!_.isNull(widget.Model) && _.isNull(widget.PageModel) && pageModel) {
					widget["PageModel"] = JSON.stringify(pageModel);
					widget.PageModel["DisplayMode"] = sectionSize;
					widgetReq = gnRequest.PostWidget(widgetName, url, widget);
				} else {
					widgetReq = gnRequest.GetContent(widgetName, url, { cache: true, contentType: 'text/html; charset=UTF-8' });
				}
				// make async request to load content
				widgetReq
					.done(function getContentDone(response) {
						$section.append(response);
						amp.publish(doneTopic);
					})
					.fail(function getContentFail(data) {
						amp.publish(failTopic);
					})
					.always(function getContentAlways(data) {
						$section.removeClass('gn_widget_spacer').find('.lazy-load-wrapper').remove();
						amp.publish(alwaysTopic);
					});
			});
		});
	}

	function pageLoad(pageName, allowedDeviceModes, pageConfig, searchViews, searchRefinements, baseUrl, pageModel) {
		try {
			if (!Modernizr.templatestrings) {
				redirectToBrowserRestrictionPage();
				return;
			}
		} catch (e) {
			redirectToBrowserRestrictionPage();
			return;
		}

		// show page content
		$('.off-canvas-wrap').show();

		_pageLoadClientProfile = getCurrentClientProfile();

		// use CDN if enabled for widgets
		//_baseUrl = baseUrl || cdnUrl.substring(0, cdnUrl.length -1) || location.protocol + '//' + location.host;
		_baseUrl = baseUrl || location.protocol + '//' + location.host;

		searchRefinements = searchRefinements || {};
		searchViews = searchViews || [];
		pageConfig = pageConfig || {};

		var hasPageConfig = !_.isEmpty(pageConfig);

		// build a page object with size and view data
		// attach object to hidden section element for later use
		setPageConfigOnce({ PageName: pageName, Size: pageConfig, Views: searchViews, Refinements: searchRefinements });

		if (pageName === null || typeof pageName === 'undefined') GolfNow.Web.Utils.ConsoleWarn('pageName variable is not set');

		// Page load method...should run first then publish a topic that'll trigger others to run their init method
		_pageName = pageName;
		GolfNow.Web.Utils.ConsoleLog('Page Load: ' + _pageName);

		var configTopic = _pageName + '_config';
		var configUrl = '/api/config/getpageconfig/' + _pageName;

		var getConfigTopic = 'xhr_get_always_' + configTopic;
		_publishedTopics.push(getConfigTopic);

		// subscribe to the always topic for the GetRequest
		amp.subscribe(getConfigTopic, function getTopicSub(data) {
			// another way to react to topics
			GolfNow.Web.Utils.ConsoleLog('Topic Get Request - Always: Status = ' + data.requestStatus);
		});

		// get page configuration first via XHR Deferrers
		// handle configuration dependent methods in Done & Fail
		// handle configuration independent methods in Always or outside of this call
		var pageLoadedEventHandled = false;
		if (hasPageConfig) {
			// determine if there are any sections that need to be loaded async
			var asyncLoadSections = _.where(pageConfig.Sections, { PreLoad: false });
			if (asyncLoadSections.length > 0) {
				pageLoadedEventHandled = true;
				GolfNow.Web.Domains.TmplVersionKey()
					.done(function (tmplVersion) {
						loadAsyncSections(asyncLoadSections, pageConfig.Name, _pageName, pageModel, tmplVersion);
					})
					.always(publishTopics);
			}
		}

		// methods that do not depend on configuration data
		subscribe2Topics();
		bindEvents();
		if (!pageLoadedEventHandled) publishTopics();
	}

	function setPageConfig(pageConfig) {
		_configData = pageConfig;

		GolfNow.Web.Cache.SetSessionStorageValue('searchConfigData', _configData);
		if ($searchElem.length) {
			$searchElem.data('configData', _configData);
		} else {
			GolfNow.Web.Utils.ConsoleWarn('::Found Search Elem Not Found::');
		}
	}

	function getPageConfig() {
		if (!_.isEmpty(_configData)) {
			return _configData;
		} else {
			var pc = GolfNow.Web.Cache.GetValue('searchConfigData') || null;
			if (pc !== null && pc['PageName']) {
				return (pc.PageName === _pageName) ? pc : null;
			}
			return pc;
		}
	}
	/// Return the public object
	return pageObj;
	// Define dependencies
})(jQuery, amplify, _, GolfNow.Web.Request);;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

// Class to track recent searches.
GolfNow.Web.RecentSearches = function () {
	this._recentSearchesCacheName = "GolfNow.Web.RecentSearches";
	this._maxRecentSearches = 3;
	this._maxStoredSearches = 30;

	this._searches = this.GetFromCache(false);
};

GolfNow.Web.RecentSearches.prototype.GetFromCache = function (honorSearchLimit) {
	honorSearchLimit = typeof honorSearchLimit === 'undefined' ? true : honorSearchLimit;
	var recentSearches = GolfNow.Web.Cache.GetValue(this._recentSearchesCacheName);
	if (recentSearches === null) { return []; }

	recentSearches = _.reject(recentSearches, function (s) { return s.id === -1 || s.label === ''; });

	if (honorSearchLimit) recentSearches = recentSearches.slice(0, this._maxRecentSearches);

	return recentSearches;
};

GolfNow.Web.RecentSearches.prototype.Get = function () {
	// make sure we copy from the original to keep from modifying both arrays by reference
	var searches = _.reject(this._searches, function (s) { return s.id === -1 || s.label === ''; });
	searches = searches.slice(0, this._maxRecentSearches);

	return searches;
};

GolfNow.Web.RecentSearches.prototype.Add = function (id, label, searchType, lat, long, geometryViewPort) {
	lat = lat || null;
	long = long || null;
	geometryViewPort = geometryViewPort || null;

	for (var i = 0; i < this._searches.length; i++) {

		//check for undefined to prevent removing entries when both ids are undefined but labels are different
		var idsAreEqual = typeof this._searches[i].id !== 'undefined' && typeof id !== 'undefined' && this._searches[i].id === id;
		// sometimes the id is different but the label is the same
		if (idsAreEqual || this._searches[i].label === label) {
			this._searches.splice(i, 1);
			GolfNow.Web.Cache.SetLocalStorageValue(this._recentSearchesCacheName, this._searches, 1000 * 60 * 60 * 24 * 30); /* 30 days */
			break;
		}
	}

	// Make sure we're within the set storage limit
	while (this._searches.length >= this._maxStoredSearches) { this._searches.pop(); }

	var newSearchObj = {
		'id': id,
		'label': label,
		'searchType': searchType
	};

	if (searchType && searchType === 'GEOLOCATION' && lat !== null && long !== null) {
		newSearchObj['lat'] = lat;
		newSearchObj['long'] = long;
		newSearchObj['geometryViewPort'] = geometryViewPort;
	}

	this._searches.unshift(newSearchObj);

	GolfNow.Web.Cache.SetLocalStorageValue(this._recentSearchesCacheName, this._searches, 1000 * 60 * 60 * 24 * 30); /* 30 days */
};

GolfNow.Web.RecentSearches.prototype.AddObj = function (searchType, searchObj) {
	searchObj.Latitude = searchObj.Latitude || null;
	searchObj.Longitude = searchObj.Longitude || null;
	searchObj.geometryViewPort = null;

	for (var i = 0; i < this._searches.length; i++) {
		// sometimes the id is different but the label is the same
		if (this._searches[i].id === searchObj.Id || this._searches[i].label === searchObj.Formatted_Address) {
			this._searches.splice(i, 1);
			GolfNow.Web.Cache.SetLocalStorageValue(this._recentSearchesCacheName, this._searches, 1000 * 60 * 60 * 24 * 30); /* 30 days */
			break;
		}
	}

	// Make sure we're within the set storage limit
	while (this._searches.length >= this._maxStoredSearches) { this._searches.pop(); }
	var newSearchObj = {
		id: searchObj.Id,
		label: searchObj.Formatted_Address,
		searchType: searchType,
		lat: searchObj.Latitude,
		long: searchObj.Longitude,
		city: searchObj.City,
		state: searchObj.State,
		postal: searchObj.PostalCode,
		country: searchObj.Country
	};

	this._searches.unshift(newSearchObj);

	GolfNow.Web.Cache.SetLocalStorageValue(this._recentSearchesCacheName, this._searches, 1000 * 60 * 60 * 24 * 30); /* 30 days */
};

GolfNow.Web.RecentSearches.prototype.Find = function (lat, long, includeViewPort) {
	includeViewPort = includeViewPort || false;

	var def = $.Deferred();

	var searches = this._searches;
	var currentPos = GolfNow.Web.Cache.GetValue("GolfNow.Web.Client.CurrentPosition") || null;
	if (!$.isEmptyObject(searches)) {
		var loc = _.findWhere(searches, { searchType: 'GEOLOCATION', lat: Number(lat), long: Number(long) }) || null;
		if (!$.isEmptyObject(loc)) {
			return includeViewPort ? def.resolve(loc) : def.resolve(loc.label);
		}
	}
	if (!_.isEmpty(currentPos) && currentPos.Latitude === lat && currentPos.Longitude === long) {
		GolfNow.Web.Utils.ConsoleLog("USING CURRENT POSITION");
		var loc = {
			geometryViewPort: null,
			id: null,
			label: currentPos.Address2,
			lat: currentPos.Latitude,
			long: currentPos.Longitude,
			searchType: "GEOLOCATION",
		};
		return includeViewPort ? def.resolve(loc) : def.resolve(loc.label);
	} else {
		return def.resolve(null);
	}

	return def.promise();
};

GolfNow.Web.RecentSearches.prototype.FindById = function (id, url) {
	var def = $.Deferred();
	var locationFound = false;

	var searches = this._searches;
	if (!$.isEmptyObject(searches)) {
		var loc = _.findWhere(searches, { searchType: 'GEOLOCATION', id: id });
		if (!$.isEmptyObject(loc)) {
			locationFound = true;
			def.resolve(loc);
		}
	}

	//perform geoapi lookup
	if (!locationFound)
		return GolfNow.Web.Request.Get('find-location-byid', url, true);

	return def.promise();
};;
var GolfNow = GolfNow || {},
	upostal = upostal || null;
GolfNow.Web = GolfNow.Web || {};

GolfNow.Web.LocationServices = function () {
	var _locationCacheName = "GolfNow.Web.Client.CurrentPosition",
		_lastLocationCheck = "GolfNow.Web.Client.LastLocationCheck";
	var _defaultLocationMessage = "Find tee times near you";
	var _defaultLocationErrorMessage = "Help us find tee times near you";
	var _hasGPSLocation = false;
	var _gpsLocationOff = true;
	var _geo_Options = {
		timeout: 900,   // maximum length of time (milliseconds) the device is allowed to take to return a position.
		enableHighAccuracy: false,  // provide more accurate position if possible at a cost of slower response times and increased power consumption
		maximumAge: 1000 * 60 * 60 * 0.5 //maximum age (1/2 hour) of a possible cached position that is acceptable to return
	};
	var _cachedLocation = {};
	// create a definition of the expected types
	//_cachedLocation.State.__proto__ = {
	//    NOT_ASKED: 0,
	//    SVC_ON_DENIED: 1,
	//    SVC_OFF_UNAVAILABLE: 2,
	//    SVC_ON_TIMEOUT: 3,
	//    SVC_ON_ALLOWED: 4,
	//    NO_GPS: 5,
	//    MANUAL_LOCATION_SETTING: 6
	//};

	var _localStorageTimeout = {
		expires: 1000 * 60 * 60 * 24 * 30   // 30 days
	};
	var _statecode = 0;
	var _defaultGeo = GetDefaultLocationPerDomain();
	var xhrCitySearch = null;
	var lazyGetGeographicDetails = _.debounce(GetGeographicDetails3, 150);
	var _reverseLookup = null;

	document.addEventListener('DOMContentLoaded', function (evt) {
		if (cmsHeaderFooter) return;

		// If nothing is stored in location cache, asynchronously load Google Maps API if it hasn't already been loaded.
		// Either way, try to determine location and hide Hot Deals and Top Rated links unless user's location can be determined.
		_cachedLocation = GolfNow.Web.Cache.GetValue(_locationCacheName);
		if ((typeof google === 'undefined' || typeof google.maps === 'undefined'))
		{
			var $googleScriptTag = $('script[id*="jsGoogle"]');
			if ($googleScriptTag.length === 0) {
				var script = document.createElement('script');
				script.type = 'text/javascript';
				script.src = '//maps.googleapis.com/maps/api/js?libraries=geometry&callback=GolfNow.Web.LocationServices.UpdateUsersLocation';
				document.body.appendChild(script);
			} else {
				GolfNow.Web.LocationServices.UpdateUsersLocation(false, _cachedLocation === null);
			}
		}
		else
		{
			GolfNow.Web.LocationServices.UpdateUsersLocation(false, _cachedLocation === null);
		}
	});

	function getRequestUrl(url) {
		if (topDomainAssetPrefix === '/') return url;

		return topDomainAssetPrefix + url.replace(/^\//, '');
	}

	function UpdateUsersLocation(clearCache, forceCheck) {
		clearCache = (typeof clearCache === 'undefined') ? false : clearCache;
		forceCheck = (typeof forceCheck === 'undefined') ? true : forceCheck;

		if (clearCache) {
			GolfNow.Web.Cache.SetValue(_lastLocationCheck, null, true);
			GolfNow.Web.Cache.SetValue(_locationCacheName, null, true);
		}

		if (!requiresGooglePlaces) return;

		LocateMe(forceCheck,
			function () { },
			function () { }
		);
	}

	function LocateMe(forceCheck, success, error, ignoreManualLocationSetting) {
		ignoreManualLocationSetting = ignoreManualLocationSetting || false;
		var locationTimeout = setTimeout(function () {
			// force default
			LocateMe_Error({ code: 3, message: _defaultLocationErrorMessage }, error);
			GolfNow.Web.Utils.ConsoleLog('LocateMe time out');
		}, 4500);

		_cachedLocation = GolfNow.Web.Cache.GetValue(_locationCacheName);
		var lastLocationCheck = GolfNow.Web.Cache.GetValue(_lastLocationCheck) || null;
		if (lastLocationCheck !== null) {
			lastLocationCheck = new Date(lastLocationCheck);
			if (_.isDate(lastLocationCheck)) {
				var expires = (120).minutes().fromNow();
				if (lastLocationCheck.compareTo(expires) === -1 && _cachedLocation !== null) forceCheck = false;
			}
		}

		
		if (_cachedLocation && _cachedLocation.State && _.isObject(_cachedLocation.State) && !_cachedLocation.Status) {
			_cachedLocation.Status = _cachedLocation.State;
		}
		if ((!forceCheck || _cachedLocation && _cachedLocation.Status && _cachedLocation.Status.code && _cachedLocation.Status.code === 6) && !ignoreManualLocationSetting) {
			clearTimeout(locationTimeout);

			// if we don't currently
			if (_cachedLocation && _cachedLocation.Latitude && _cachedLocation.Longitude) {
				_cachedLocation.Status = _cachedLocation.Status || { code: 0 };
				_cachedLocation.Status.message = _cachedLocation.Status.message && _cachedLocation.Status.message !== _defaultLocationErrorMessage ? _cachedLocation.Status.message : _defaultLocationMessage;
				_statecode = _cachedLocation.Status.code;

				GolfNow.Web.Cache.SetLocalStorageValue(_locationCacheName, _cachedLocation, _localStorageTimeout.expires);

				if (_.isFunction(success)) success(_cachedLocation);

				GolfNow.Web.Utils.ConsoleLog(_cachedLocation.Latitude + "::" + _cachedLocation.Longitude + "::Location Cache");
			} else {
				// force default
				LocateMe_Error({ 'code': 0 }, error);
			}
		} else {
			if (navigator.geolocation) {
				GolfNow.Web.Cache.SetValue(_lastLocationCheck, Date.now(), true);
				navigator.geolocation.getCurrentPosition(
					function (position) {
						clearTimeout(locationTimeout);
						
						LocateMe_Success(position, success);

						GolfNow.Web.Utils.ConsoleLog(position.coords.latitude + "::" + position.coords.longitude + "::W3C Navigator");
					},
					function (err) {
						clearTimeout(locationTimeout);

						GolfNow.Web.Utils.ConsoleLog((err.message || 'Unavailable') + ':: W3C Navigator');
						GolfNow.Web.Utils.ConsoleLog('forcing default: ' + _defaultGeo.latitude + '::' + _defaultGeo.longitude + '::W3C Navigator');

						// force default
						LocateMe_Error(err, error);
					},
					_geo_Options
				);
			}
			else {
				clearTimeout(locationTimeout);
				
				GolfNow.Web.Utils.ConsoleLog('No Geo available :: W3C Navigator');

				// force default
				LocateMe_Error({ 'code': 5 }, error);
			}
		}
	}

	function LocateMe_Success(position, callback) {
		_statecode = 4;
		_cachedLocation = _cachedLocation || {};
		_cachedLocation.Status = _cachedLocation.Status || {};

		_cachedLocation.Latitude = position.coords.latitude;
		_cachedLocation.Longitude = position.coords.longitude;
		_cachedLocation.Status.message = _defaultLocationMessage;
		_cachedLocation.Status.code = _statecode;

		var mycachedLocation = _cachedLocation;
		lazyGetGeographicDetails(position.coords.latitude, position.coords.longitude, function (data) {
			data.Status = mycachedLocation.Status;

			mycachedLocation = saveLocation(data);

			if (_.isFunction(callback)) callback(mycachedLocation);
		});
	}

	function LocateMe_Error(error, callback) {
		_cachedLocation = _cachedLocation || {};
		_cachedLocation.Status = _cachedLocation.Status || {};

		_cachedLocation.Status.message = _cachedLocation.City ? 'Search Near ' + _cachedLocation.City : _defaultLocationErrorMessage;
		GolfNow.Web.Utils.ConsoleLog(error.code);

		switch (error.code) {
			case 1: //error.PERMISSION_DENIED
			case 2: //error.POSITION_UNAVAILABLE
				_statecode = error.code;
				break;
			case 3: //error.TIMEOUT
				_statecode = error.code;
				break;
			default:
				_statecode = error.code;
		}
		_cachedLocation.Status.code = _statecode;

		// force default location or use what was saved
		if (!_cachedLocation.Latitude && !_cachedLocation.Longitude) {
			_cachedLocation.Latitude = _defaultGeo.latitude;
			_cachedLocation.Longitude = _defaultGeo.longitude;

			var mycachedLocation = _cachedLocation;
			lazyGetGeographicDetails(_cachedLocation.Latitude, _cachedLocation.Longitude, function (data) {
				data.Status = mycachedLocation.Status;

				mycachedLocation = saveLocation(data);

				if (_.isFunction(callback)) callback(mycachedLocation);
				return;
			});
		}

		if (_.isFunction(callback)) callback(_cachedLocation);
	}

	function saveLocation(locationData) {
		_cachedLocation = _cachedLocation ? _cachedLocation : GolfNow.Web.Cache.GetValue(_locationCacheName) || {};
		_cachedLocation.Status = locationData.Status ? locationData.Status : _cachedLocation.Status || {};

		// attempt to set the status message
		if (_cachedLocation.City && _cachedLocation.Status && (_cachedLocation.Status.message && _.isString(_cachedLocation.Status.message)) && (_cachedLocation.Status.code && _.isNumber(_cachedLocation.Status.code))) {
			var successCodes = [0, 4, 6];
			if (_.contains(successCodes,_cachedLocation.Status.code)) {
				// gps success
				if (_cachedLocation.Status.message !== _defaultLocationMessage) {
					_cachedLocation.Status.message = _defaultLocationMessage;
				}
			} else {
				// gps failure
				if (_cachedLocation.Status.message !== 'Search Near ' + locationData.City) {
					_cachedLocation.Status.message = 'Search Near ' + locationData.City;
				}
			}
		} else {
			_cachedLocation.Status.code = 0;
			_cachedLocation.Status.message = _defaultLocationMessage;
		}

		_cachedLocation.Country = locationData.Country || null;
		_cachedLocation.City = locationData.City || null;
		_cachedLocation.State = locationData.State || null;
		_cachedLocation.PostalCode = locationData.PostalCode || null;

		// use formatted addres if it exists
		if (locationData.Formatted_Address !== '') {
			_cachedLocation.Address = _cachedLocation.Address2 = locationData.Formatted_Address;

			if (locationData.Latitude)
				_cachedLocation.Latitude = locationData.Latitude;

			if (locationData.Longitude)
				_cachedLocation.Longitude = locationData.Longitude;
		} else {
			// no formatted address so build it using address properties
			if (locationData.Latitude)
				_cachedLocation.Latitude = locationData.Latitude;

			if (locationData.Longitude)
				_cachedLocation.Longitude = locationData.Longitude;

			// handling for US & Canada
			if (locationData.Country === 'US' || locationData.Country === 'CA') {
				_cachedLocation.Address = _cachedLocation.Address2 = locationData.City;
				if (locationData.State)
					_cachedLocation.Address = _cachedLocation.Address2 += ', ' + locationData.State;

				if (locationData.PostalCode)
					_cachedLocation.Address = _cachedLocation.Address2 += ', ' + locationData.PostalCode;

				if(locationData.Country)
					_cachedLocation.Address += ', ' + locationData.Country;
			} else {
				// handling for International
				var addr, addr2 = '';
				if(locationData && locationData.City){
					addr = addr2 += locationData.City;
				}
				if (locationData && locationData.PostalCode)
					addr = addr2 += ', ' + locationData.PostalCode;

				if(locationData && locationData.Country){
					if(addr.length > 0)
						addr += ', ' + locationData.Country;
					else
						addr += locationData.Country;
				}
				_cachedLocation.Address = addr;
				_cachedLocation.Address2 = addr2;
			}
		}

		GolfNow.Web.Cache.SetLocalStorageValue(_locationCacheName, _cachedLocation, _localStorageTimeout.expires);
		return _cachedLocation;
	}

	function SetUsersLocation(location_data, callback) {
		var myCachedLocation = _cachedLocation;
		if (location_data) {
			location_data.Status = { code: 6, message: _defaultLocationMessage };
			myCachedLocation = saveLocation(location_data);
		}

		if (_.isFunction(callback)) callback(myCachedLocation);
	}

	function storeErrorMsg() {
		_cachedLocation.Longitude = null;
		_cachedLocation.Latitude = null;

		GolfNow.Web.Cache.SetLocalStorageValue(_locationCacheName, _cachedLocation, _localStorageTimeout.expires);
	}

	function Status(forceCheck) {
		var def = $.Deferred();
		forceCheck = forceCheck === undefined ? false : forceCheck;

		if (!forceCheck && _cachedLocation && _cachedLocation.Status) {
			def.resolve(_cachedLocation.Status);
		} else {
			def.reject({});
		}
		return def.promise();
	}

	function State() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.State) {
			def.resolve(_cachedLocation.State);
		} else {
			def.resolve('');
		}
		return def.promise();
	}

	function Address() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.Address) {
			def.resolve(_cachedLocation.Address);
		} else {
			def.resolve('');
		}
		return def.promise();
	}

	function Country() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.Country) {
			def.resolve(_cachedLocation.Country);
		} else {
			def.resolve('');
		}
		return def.promise();
	}

	function GeoCoordinates() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.Latitude && _cachedLocation.Longitude) {
			def.resolve({ Lat: _cachedLocation.Latitude, Long: _cachedLocation.Longitude });
		} else {
			def.resolve(null);
		}
		return def.promise();
	}

	function City() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.City) {
			def.resolve(_cachedLocation.City);
		} else if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.Address) {
			if (_cachedLocation.Country === 'US' || _cachedLocation.Country === 'CA') {
				var city = _cachedLocation.Address;
				var cityPos = _cachedLocation.Address.indexOf(',');
				if (cityPos > -1) {
					city = _cachedLocation.Address.substr(0, cityPos);
				}
				def.resolve(city);
			} else {
				def.resolve(_cachedLocation.Address);
			}
		} else {
			def.resolve('');
		}
		return def.promise();
	}

	function PostalCode() {
		var def = $.Deferred();
		if (_cachedLocation && !$.isEmptyObject(_cachedLocation) && _cachedLocation.PostalCode) {
			def.resolve(_cachedLocation.PostalCode);
		}  else {
			def.resolve('');
		}
		return def.promise();
	}

	function GeoPlacesLookup(lat, lon) {
		GolfNow.Web.Utils.ConsoleLog('GeoPlacesLookup');

		var d = $.Deferred();
		var locName = '';
		var myLat = Number(lat);
		var myLong = Number(lon);
		var callbackSuccess = function (locationData) {
			if (locationData && locationData.Formatted_Address && locationData.Formatted_Address !== '') {
				locName = locationData.Formatted_Address;
			} else if (locationData && locationData.Country && locationData.Country.toLowerCase() === 'us' || locationData && locationData.Country && locationData.Country.toLowerCase() === 'ca') {
				if (locationData.City)
					locName += locationData.City;

				if (locationData.State)
					if (locName.length > 0)
						locName += ", " + locationData.State;
					else
						locName += locationData.State;

				if (locationData.PostalCode)
					locName += " " + locationData.PostalCode;

			} else if (locationData) {
				if (locationData.City) {
					locName += locationData.City;
				}
				if (locationData.Country) {
					if (locName.length > 0)
						locName += ', ' + locationData.Country;
					else
						locName += locationData.Country;
				}
			}

			var recentSearches = new GolfNow.Web.RecentSearches();
			recentSearches.Add(locationData.Id, locName, 'GEOLOCATION', myLat, myLong);
			return d.resolve(locName);
		};

		var callbackFail = function () {
			var url = getRequestUrl('/api/autocomplete/georeverse');
			_reverseLookup = GolfNow.Web.Request.Post('latlong_lookup', url, JSON.stringify({ lat: myLat, lng: myLong }));
			_reverseLookup
				.done(function (data) {
					if (data !== null && data.addressInformation !== null) {
						var locationData = data.addressInformation || null;
						var id = data.id;
						//mongoId has a value of 0 for all types except "course" type
						if (data.mongoId && data.mongoId !== '0') {
							id = data.mongoId;
						}
						var location_data = {
							Id: id,
							City: locationData.city,
							State: locationData.stateProv,
							PostalCode: locationData.zip,
							Country: locationData.countryCode,
							Geometry: null,
							Formatted_Address: locationData.formatted,
							Latitude: data.geo.lat,
							Longitude: data.geo.lon
						}

						var recentSearches = new GolfNow.Web.RecentSearches();
						recentSearches.AddObj('GEOLOCATION', location_data);
						return d.resolve(location_data.Formatted_Address);
					}
					GolfNow.Web.Utils.ConsoleError('Unable to reverse lookup location');
					return d.reject();
				});
		}

		lazyGetGeographicDetails(myLat, myLong, callbackSuccess, callbackFail);

		return d.promise();
	}


	function GetDefaultLocationPerDomain(useDomainOnly)
	{
		if (typeof useDomainOnly === 'undefined' || useDomainOnly === '') useDomainOnly = false;
		var _locationGeo;
		if (useDomainOnly) {
			_locationGeo = GolfNow.Web.Domains.GetDomainLocation();
		} else {
			_locationGeo = upostal || GolfNow.Web.Domains.GetDomainLocation();
		}
		return _locationGeo;
	}

	function GetGeographicDetails3(lat, lon, successCallback, failCallback) {
		var location_data = { Formatted_Address: null };
		if (!lat || !lon) {
			if (_.isFunction(successCallback)) {
				return successCallback(location_data);
			}
		} else {
			var myLat = Number(lat).toLocaleString("en-US", { maximumFractionDigits: 5 });
			var myLong = Number(lon).toLocaleString("en-US", { maximumFractionDigits: 5 });

			if (!/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/.test(lat) || !/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/.test(lon)) {
				if (_.isFunction(failCallback)) {
					return failCallback(location_data);
				}
			}

			if (_reverseLookup !== null && _reverseLookup.state() === 'pending') {
				if (_.isFunction(failCallback)) {
					return failCallback(location_data);
				}
			}

			var recentSearches = new GolfNow.Web.RecentSearches();
			var foundSearch = recentSearches.Find(myLat, myLong, true);
			foundSearch
				.done(function (data) {
					if (data !== null) {
						var locationData = {
							Id: data.id,
							City: data.city,
							State: data.state,
							PostalCode: data.postal,
							Country: data.country,
							Geometry: null,
							Formatted_Address: data.label,
							Latitude: data.lat,
							Longitude: data.long
						};
						if (locationData !== null) {
							if(_.isFunction(successCallback)) return successCallback(locationData);
						}
					}
					if (_.isFunction(failCallback)) return failCallback();

					// only run this if no failCallback is provided
					var url = getRequestUrl('/api/autocomplete/georeverse');
					_reverseLookup = GolfNow.Web.Request.Post('latlong_lookup', url, JSON.stringify({ lat: myLat, lng: myLong }));
					_reverseLookup
						.done(function (data) {
							if (data !== null && data.addressInformation !== null) {
								var locationData = data.addressInformation || null;
								var id = data.id;
								//mongoId has a value of 0 for all types except "course" type
								if (data.mongoId && data.mongoId !== '0') {
									id = data.mongoId;
								}
								location_data = {
									Id: id,
									City: locationData.city,
									State: locationData.stateProv,
									PostalCode: locationData.zip,
									Country: locationData.countryCode,
									Geometry: null,
									Formatted_Address: locationData.formatted,
									Latitude: data.geo.lat,
									Longitude: data.geo.lon
								}

								recentSearches.AddObj('GEOLOCATION', location_data);
								if (_.isFunction(successCallback)) successCallback(location_data);
							} else {
								if (_.isFunction(failCallback)) failCallback();
							}
						});
				})
				.fail(function () {
					if (_.isFunction(failCallback)) return failCallback();
				});
		}
	}

	function parseAllGeoResults(results, location_data, finished, isDefault) {
		var returnedObj = {};
		$.each(results, function (i, result) {
			if (!finished) {
				returnedObj = parseGeoAddressComponents(result, location_data, finished, isDefault);
				finished = returnedObj.finished;
			}
		});

		return returnedObj;
	}

	function parseGeoAddressComponents(result, location_data, finished, isDefault) {
		// loop over all address_components to build address parts we want
		$.each(result.address_components, function (i, b) {
			if (!finished) {
				location_data.Formatted_Address = result.formatted_address;
				location_data.Geometry = result.geometry;

				$.each(b.types, function (i, c) {

					if (!location_data.PostalCode && c === "postal_code") {
						location_data.PostalCode = b.short_name;
						location_data.Id = result.place_id;
					}
					else if (!location_data.Neighborhood && (c === "neighborhood" || c === "administrative_area_level_2")) {
						location_data.Neighborhood = b.short_name;
						location_data.Id = result.place_id;
					}
					else if (!location_data.State && c === "administrative_area_level_1") {
						location_data.State = b.short_name;
						location_data.Id = result.place_id;
					}
					else if (!location_data.Country && c === "country") {
						location_data.Country = b.short_name;
						location_data.Id = result.place_id;
					}
					else if (!location_data.City && (c === "locality" || c === "sublocality" || c === "administrative_area_level_3")) {
						location_data.City = b.long_name;
						location_data.Id = result.place_id;
					}
					else if (!isDefault) {
						if (location_data.PostalCode && location_data.State && location_data.Neighborhood && location_data.Country && location_data.City)
						{
							finished = true;
							location_data.Id = result.place_id;
							buildFormattedAddress(location_data);
							return;
						}
					} else {
						finished = true;
						location_data.Id = result.place_id;
						return;
					}
				});
			}
		});

		buildFormattedAddress(location_data);
		return { location_data: location_data, finished: finished };
	}

	function buildFormattedAddress(location_data) {
		if(!location_data)
			return;

		if (location_data.City)
			location_data.Formatted_Address = location_data.City;

		if (location_data.State)
			location_data.Formatted_Address += ', ' + location_data.State;

		if (location_data.PostalCode)
			location_data.Formatted_Address += ', ' + location_data.PostalCode;

		if (location_data.Country)
			location_data.Formatted_Address += ', ' + location_data.Country;
	}

	function GetGeoCitySearch(address) {
		var d = $.Deferred();
		var results = [];

		if (xhrCitySearch && xhrCitySearch.readystate !== 4) {
			xhrCitySearch.abort();
		}

		var url = getRequestUrl('/api/autocomplete/geocity/' + address);
		xhrCitySearch = $.ajax({
			url: url,
			method: 'GET',
			dataType: 'json',
			contentType: 'application/json; charset=utf-8',
			success: function (geodata) {
				results = _.map(geodata.hits, function (hit) {
					return {
						label: hit.displayName,
						value: hit.displayName,
						type: 'places',
						id: hit.id,
						lat: hit.geo.lat,
						long: hit.geo.lon,
						city: hit.type === 'city' ? hit.name : hit.addressInformation.city || '',
						state: hit.addressInformation.stateProv || hit.addressInformation.stateProvFull || '',
						zip: hit.addressInformation.zip || '',
						country: hit.addressInformation.countryCode || ''
					};
				});
				d.resolve(_.take(results, 5));
			},
			error: function (xhr, status, error) {
				// If the request is aborted (user continued to type), then fail, otherwise return empty.
				if (status === "abort") { d.reject(); }
				else { d.resolve({}); }
			},
			always: function () {
				xhrCitySearch = null;
			}
		});

		return d.promise();
	}

	// calculate the radius using the bounds returned from the places lookup
	// the bounds are made up of the farthest SouthWest point(lat/long) and the farthest NorthEast point(lat/long)
	// using the google geometry library, we will compute the "distance"
	function CalculateRadius_v2(googleViewPortLatLngBounds) {
		// http://stackoverflow.com/questions/9121883/google-maps-v3-viewable-map-radius-in-miles
		// using google geometry
		var swPoint = googleViewPortLatLngBounds.getSouthWest();
		var nePoint = googleViewPortLatLngBounds.getNorthEast();

		// debugging
		GolfNow.Web.Utils.ConsoleLog('SouthWestLat:' + swPoint.lat() + '::SouthWestLng:' + swPoint.lng());
		GolfNow.Web.Utils.ConsoleLog('NorthEastLat:' + nePoint.lat() + '::NortEastLng:' + nePoint.lng());

		// pass values to geometry library to compute distance in meters then convert to miles
		var proximityMeters = google.maps.geometry.spherical.computeDistanceBetween(swPoint, nePoint);
		var milesRadius = proximityMeters * 0.000621371192;
		var kilometersRadius = proximityMeters * 0.001;

		// get the smallest value between the calculated and defined maximum radius
		var units = GolfNow.Web.Utils.GetDefaultUnitOfMeasure();
		var radius = Math.min(milesRadius, GolfNow.Web.Utils.GetMaximumSearchRadius('mi'));

		// get the largest value between calulated and defined default radius
		radius = Math.max(radius, GolfNow.Web.Utils.GetDefaultSearchRadius('mi', GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")));

		return Number(Math.round(radius).toFixed(0));
	}

	// calculates the radius using the bounds returned from the places lookup
	// the bounds are made up of the farthest SouthWest point(lat/long) and the farthest NorthEast point(lat/long)
	// using general math, we will compute the "distance"
	function CalculateRadius_v1(googleViewPortLatLngBounds) {
		// radius of the earch in miles
		var earthRadius = 3958.756;
		var earthRadiusKilometers = 6371;

		// debugging
		GolfNow.Web.Utils.ConsoleLog('SouthWestLat:' + googleViewPortLatLngBounds.getSouthWest().lat() + '::SouthWestLng:' + googleViewPortLatLngBounds.getSouthWest().lng());
		GolfNow.Web.Utils.ConsoleLog('NorthEastLat:' + googleViewPortLatLngBounds.getNorthEast().lat() + '::NortEastLng:' + googleViewPortLatLngBounds.getNorthEast().lng());

		// nasty math stuff
		var dLat = deg2rad(googleViewPortLatLngBounds.getSouthWest().lat() - googleViewPortLatLngBounds.getNorthEast().lat());
		var dLng = deg2rad(googleViewPortLatLngBounds.getSouthWest().lng() - googleViewPortLatLngBounds.getNorthEast().lng());
		var area = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(deg2rad(googleViewPortLatLngBounds.getNorthEast().lat())) *
					Math.cos(deg2rad(googleViewPortLatLngBounds.getSouthWest().lat())) *
					Math.sin(dLng / 2) * Math.sin(dLng / 2);
		var cir = 2 * Math.atan2(Math.sqrt(area), Math.sqrt(1 - area));

		// calculated distance in miles
		var milesRadius = earthRadius * cir;
		var kilometersRadius = earthRadiusKilometers * cir;

		// get the smallest value between the calculated and defined maximum radius
		var units = GolfNow.Web.Utils.GetDefaultUnitOfMeasure();
		var radius = Math.min(milesRadius, GolfNow.Web.Utils.GetMaximumSearchRadius('mi'));

		// get the largest value between calulated and defined default radius
		radius = Math.max(radius, GolfNow.Web.Utils.GetDefaultSearchRadius('mi', GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")));

		return Math.round(radius);
	}

	// support method used by CalculateRadius_v1
	function deg2rad(deg) {
		return deg * (Math.PI / 180);
	}

	return {
		Address: Address,
		Country: Country,
		HasGPS: navigator.geolocation !== null,
		OffMessage: _defaultLocationErrorMessage,
		OnMessage: _defaultLocationMessage,
		LocateMe: LocateMe,
		State: State,
		Status: Status,
		UpdateUsersLocation: UpdateUsersLocation,
		SetUsersLocation: SetUsersLocation,
		GeoCoordinates: GeoCoordinates,
		Address_City: City,
		GoogleLookUp: _.debounce(GeoPlacesLookup, 150),
		CalculateRadius: CalculateRadius_v2,
		GetGeographicDetails: lazyGetGeographicDetails,
		GetGeographicDetails2: lazyGetGeographicDetails,
		GetGeoCitySearch: GetGeoCitySearch,
		PostalCode: PostalCode,
		GeoPlacesLookup: _.debounce(GeoPlacesLookup, 150)
	};
}();;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Analytics = GolfNow.Web.Analytics || {};

// Making an object to handle GTM interactions for ExactTarget.
// Wanted to keep this separate from GTM analytics tracking in
// case the two have to co-exist.
GolfNow.Web.Analytics.ExactTarget = function (orgId, userId) {

	/* ExactTarget Search Data Object*/
	this.searchData = {
		"source": {
			"searchType": ""
		},
		"searchFilters": "",
		"SortSelection": "",
		"ResultsView": ""
	};

	this.cartData = {
		"item": "",
		"price": "",
		"quantity": "",
		"unique_id": ""
	};

	this._customPageViewSent = false;
	this._orgId = orgId;
	this._userId = userId;
};


GolfNow.Web.Analytics.ExactTarget.prototype.TrackSearch = function (searchParameters) {
	if (typeof _etmc === 'undefined') return;

	this.SetUserInfo();
	this.SetCustomPageView();

	var holes = !searchParameters.Holes ? 'Any' : this._getHolesParse(searchParameters.Holes);
	var refinements = {
		'display': searchParameters.HotDealsOnly ? 'HotDeals' : 'All',
		'price': !searchParameters.MinPrice && !searchParameters.MaxPrice ? 'Any' : searchParameters.MinPrice + '-' + searchParameters.MaxPrice,
		'distance': !searchParameters.Radius ? GolfNow.Web.Utils.GetDefaultSearchRadius() : searchParameters.Radius,
		'golfers': !searchParameters.Players ? 'Any' : searchParameters.Players,
		'time': !searchParameters.TimePeriod ? 'Any' : searchParameters.TimePeriod,
		'holes': holes
	};

	var view = !searchParameters.View ? '' : searchParameters.View;
	var sort = this._getSortDesignation(searchParameters.View === "Course" ? searchParameters.SortByRollup : searchParameters.SortBy, searchParameters.SortDirection.toString());

	this.searchData.searchFilters = refinements;
	this.searchData.SortSelection = sort;
	this.searchData.ResultsView = view;

	switch (GolfNow.Web.Utils.GetSearchTypeName(searchParameters.SearchType)) {
		case searchType_GeoLocation:
		case searchType_GoPlay:
			this.searchData.source.searchType = 'GeoLocation';
			this.searchData.source.latitude = searchParameters.Latitude;
			this.searchData.source.longitude = searchParameters.Longitude;
			break;
		case searchType_Destination:
			this.searchData.source.searchType = 'Destination';
			this.searchData.source.destination = searchParameters.MarketName;
			break;
		case searchType_Market:
			this.searchData.source.searchType = 'Area';
			this.searchData.source.areaId = searchParameters.MarketId;
			break;
		case searchType_Facility:
			this.searchData.source.searchType = 'Facility';
			this.searchData.source.facilityId = searchParameters.FacilityId;
			break;
	}

	_etmc.push(["trackPageView", { "search": this.searchData }]);
};

GolfNow.Web.Analytics.ExactTarget.prototype.TrackCategory = function (golfFacilityId, city, state) {
	if (typeof _etmc === 'undefined') return;

	this.SetCustomPageView();
	this.SetUserInfo();
	var category = city !== "" ? city : '';
	var extend = state !== "" ? ', ' + state : '';
	category = category + extend;
	_etmc.push(["trackPageView", { "category": category, "item": golfFacilityId }]);
};

GolfNow.Web.Analytics.ExactTarget.prototype.TrackCheckout = function (facilityId, pricePerPlayer, players) {
	if (typeof _etmc === 'undefined') return;

	this.SetUserInfo();
	this.TrackPageView();
	this.SetCustomPageView();

	this.cartData.item = facilityId;
	this.cartData.price = pricePerPlayer;
	this.cartData.quantity = players;
	this.cartData.unique_id = facilityId;

	_etmc.push(["trackCart", { "cart": [this.cartData] }]);
};

GolfNow.Web.Analytics.ExactTarget.prototype.TrackConfirmation = function (facilityId, reservationId, pricePerPlayer, players) {
	if (typeof _etmc === 'undefined') return;

	this.SetUserInfo();
	this.TrackPageView();
	this.SetCustomPageView();

	this.cartData.item = facilityId;
	this.cartData.order_number = reservationId;
	this.cartData.price = pricePerPlayer;
	this.cartData.quantity = players;
	this.cartData.unique_id = facilityId;

	_etmc.push(["trackConversion", { "cart": [this.cartData] }]);
};

GolfNow.Web.Analytics.ExactTarget.prototype.SetUserInfo = function () {
	if (typeof _etmc === 'undefined') return;

	_etmc.push(["setOrgId", this._orgId]);

	if (uid) {
		_etmc.push(["setUserInfo", { "email": this._userId }]);
	}
	else {
		_etmc.push(["setUserInfo", { "email": "" }]);
	}
};

GolfNow.Web.Analytics.ExactTarget.prototype.TrackPageView = function () {
	if (typeof _etmc === 'undefined') return;

	_etmc.push(["trackPageView"]);
};

GolfNow.Web.Analytics.ExactTarget.prototype._getSortDesignation = function (sortBy, sortDirection) {
	if (!sortBy || !sortDirection) { return ''; }

	var sortDesignation = '';
	sortDirection = sortDirection === 0 ? "Ascending" : "Descending";

	var sortParts = sortBy.split('.');
	if (sortParts.length > 1) {
		if (sortParts[0] === "Date") {
			sortDesignation = "Date";
		} else if (sortParts[0] === "Facilities") {
			if (sortParts[1] === "Distance") { sortDesignation = "Distance"; }
			else if (sortParts[1] === "Rating") { sortDesignation = "Rating"; }
			else if (sortParts[1] === "Name") { sortDesignation = "Name"; }
		}
	} else {
		sortDesignation = sortParts[0];
	}

	sortDesignation = sortDesignation + ' ' + sortDirection;

	return sortDesignation;
};

GolfNow.Web.Analytics.ExactTarget.prototype.SetCustomPageView = function () {
	this._customPageViewSent = true;
};

GolfNow.Web.Analytics.ExactTarget.prototype.IsTrackPageViewSent = function () {
	return this._customPageViewSent;
};

GolfNow.Web.Analytics.ExactTarget.prototype._getHolesParse = function (holes) {
	if (holes === '1') {
		return '9';
	}
	else {
		return '18';
	}
};;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Analytics = GolfNow.Web.Analytics || {};

GolfNow.Web.Analytics.Google = function () {
	var _className = 'GolfNow.Web.Analytics.Google';
	var _refineURL = '/search-refine';
	
	var _trackRefinePageView = function () {
		_trackPageView(_refineURL);
	};

	var _trackPageView = function (pageUrl) {
		try {
			ga('set', 'page', pageUrl);
			ga('send', 'pageview');
			GolfNow.Web.Utils.ConsoleLog(_className + ': Tracking Virtual PageView (' + pageUrl + ')');
		} catch(e) { /**/ }
	};

	/// DataLayer
	var _trackPageView2 = function (event, pageUrl, pageTitle) {
		if (typeof dataLayer === "undefined") return;
		try {
			dataLayer.push({
				'event': event,
				'virtualPageURL': pageUrl,
				'virtualPageTitle': pageTitle
			});
		} catch (e) { /**/ }
	};

	var _trackCharityAutoOptInImpression = function (charityName, charityId) {
		//charityImpression
		if (typeof dataLayer === "undefined") return;
		try {
			dataLayer.push({
				'event': 'charityImpression',
				'eventCategory': 'Charity Impression',
				'eventAction': charityName + ' Impression',
				'eventLabel': charityId
			});
		} catch (e) { /**/ }
	};

	/// valid actions:
	/// Auto Opt In, Select Amount, No Thanks
	var _trackCharityDonation = function (donationObj) {
		if (typeof dataLayer === "undefined") return;
		var donationAmount = /no thanks/ig.test(donationObj.charityAction) ? '' : donationObj.donationAmount;
		var charityName = donationObj.charityName || donationObj.charityId;

		try {
			dataLayer.push({
				'event': 'charityDonation',
				'eventCategory': 'Charity Donation',
				'eventAction': charityName + ' ' + donationObj.charityAction,
				'eventLabel': donationAmount
			});
		} catch (e) { /**/ }
	}

	return {
		TrackPageView: _trackPageView,
		TrackPageView2: _trackPageView2,
		TrackRefinePageView: _trackRefinePageView,
		TrackCharityAutoOptInImpression: _trackCharityAutoOptInImpression,
		TrackCharityDonation: _trackCharityDonation
	};
}();;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Analytics = GolfNow.Web.Analytics || {};
GolfNow.Web.Analytics.Google = GolfNow.Web.Analytics.Google || {};

// Making an object to handle Enhanced ECommerce actions for Google.
GolfNow.Web.Analytics.Google.Ecommerce = function () {
	var getSearchPageSection = function getSearchPageSection() {
		var section = 'Homepage';
		try {
			var currentUrl = window.location.href;

			// Cases
			if (currentUrl.indexOf("destinations") > -1) {
				section = 'Destination Page';
			}
			else if (currentUrl.indexOf("hot-deals") > -1) {
				section = 'Hotdeals Page';
			}
			else if (currentUrl.indexOf("play-fast") > -1) {
				section = 'Play Fast';
			}
			else if (currentUrl.indexOf("play-nine") > -1) {
				section = 'Play Nine';
			}
			else if (currentUrl.indexOf("play-single") > -1) {
				section = 'Play Single';
			}
			else if (currentUrl.indexOf("play-walk") > -1) {
				section = 'Play Walk';
			}
			else if (currentUrl.indexOf("facility") > -1) {
				section = 'Facility Search';
			}
			else if (currentUrl.indexOf("search") > -1) {
				section = 'Location Search';
			}
			else if (currentUrl.indexOf("select-rate") > -1) {
				section = 'Select Rate';
			}
		}
		catch (e) {
			GolfNow.Web.Utils.ConsoleLog(e);
		}

		return section;
	};

	var getCurrencyCode = function () {
		var currencyCode = ''

		try {
			var mainElem = document.querySelector('main');
			if (mainElem !== null) {
				currencyCode = mainElem.dataset.currency || '';

			}

			if (currencyCode === '') {
				var currencyMetaElem = document.querySelector("meta[name='currency-code']");
				if (currencyMetaElem !== null) {
					currencyCode = currencyMetaElem.content;
				}
			}
		} catch (e) { }

		if (currencyCode === '' || currencyCode === 'CLP')
			currencyCode = defaultCurrencyCode;

		return currencyCode;
	};

	var _productImpression = function (name, id, pricePerGolfer, ishotdeal, searchType, city, state, country, category) {
		if (typeof dataLayer === "undefined") return;
		if (typeof category === "undefined") category = '';

		var search = GolfNow.Web.Utils.GetSearchTypeName(searchType);
		if ((category === '') && (ishotdeal !== ''))
		{
			category = ishotdeal.toLowerCase() === "true" ? "Hot Deal" : "Course";
		}

		if (search === '')
		{
			search = getSearchPageSection();
		}

		dataLayer.push({
			'event': 'productImpression',
			'eventLabel': id,
			'ecommerce': {
				'impressions': [{
					'name': name,               // Name or ID is required.
					'id': id,                   // Facility ID
					'price': pricePerGolfer,    // Price per golfer
					'category': category,       // "Hot Deal" or "Course"
					'list': search,             // Facility or Location (tee time view)
					'Dimension36': city,        // Custom Dimension City (string)
					'Dimension37': state,       // Custom Dimension State (string)
					'Dimension38': country,     // Custom Dimension Country (string)
					'currencyCode': getCurrencyCode()
				}]
			}
		});
	};

	var _productClick = function (name, id, pricePerGolfer, ishotdeal, searchType, city, state, country, redirectUrl, category) {
		if (typeof dataLayer === "undefined") return;
		if (typeof category === "undefined") category = '';
		if (redirectUrl === '' || redirectUrl === null || redirectUrl === undefined) redirectUrl = null;

		var search = GolfNow.Web.Utils.GetSearchTypeName(searchType);

		if (category === '' && ishotdeal !== '') {
			if (_.isString(ishotdeal))
				category = ishotdeal.toLowerCase() === "true" ? "Hot Deal" : "Course";
			else if (_.isBoolean(ishotdeal))
				category = ishotdeal ? "Hot Deal" : "Course";
		}
		if (search === '') {
			search = getSearchPageSection();
		}
		try
		{
			var callbackReached = (redirectUrl === null) ? true : false;
			dataLayer.push({
				'event': 'productClick',
				'eventLabel': id,
				'ecommerce': {
					'click': {
						'actionField': { 'list': search },      // Optional property.
						'products': [{
							'name': name,                           // Name or ID is required.
							'id': id,                               // Facility ID
							'price': pricePerGolfer,                // Price per golfer
							'category': category,                   // "Hot Deal" or "Course"
							'Dimension36': city,                    // Custom Dimension City (string)
							'Dimension37': state,                   // Custom Dimension State (string)
							'Dimension38': country,                 // Custom Dimension Country (string)
							'currencyCode': getCurrencyCode()
						}]
					}
				},
				'eventCallback': function () {
					callbackReached = true;
					if (redirectUrl !== null) document.location.href = redirectUrl;
				}
			});

			GolfNow.Web.Utils.ConsoleLog('referrer:', document.referrer);
			window.setTimeout(function () {
				if (!callbackReached) document.location.href = redirectUrl;
			}, 250);
		}
		catch (e) {
			GolfNow.Web.Utils.ConsoleLog(e);

			if (redirectUrl !== null) document.location.href = redirectUrl;
		}
	};

	var _productDetailsView = function (name, id, pricePerGolfer, originalPricePerGolfer, category, city, state, country) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productDetailView',
			'eventLabel': id,
			'ecommerce': {
				'detail': {
					'products': [{
						'name': name,								// Name or ID is required.
						'id': id,									// Facility ID
						'price': pricePerGolfer,					// Price per golfer
						'originalPrice': originalPricePerGolfer,	// Original Price per golfer
						'category': category,						// "Hot Deal" or "Course"
						'Dimension36': city,						// Custom Dimension City (string)
						'Dimension37': state,						// Custom Dimension State (string)
						'Dimension38': country,					// Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _addToCart = function (name, id, pricePerGolfer, category, city, state, country) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'addToCart',
			'eventLabel': id,
			'ecommerce': {
				'add': {
					'products': [{
						'name': name,               // Name or ID is required.
						'id': id,                   // Facility ID
						'price': pricePerGolfer,    // Price per golfer
						'category': category,       // "Hot Deal" or "Course"
						'Dimension36': city,        // Custom Dimension City (string)
						'Dimension37': state,       // Custom Dimension State (string)
						'Dimension38': country,     // Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _checkoutStep1 = function (name, id, pricePerGolfer, category, city, state, country, redirectUrl) {
		if (typeof dataLayer === "undefined") {
			document.location = redirectUrl;
			return;
		}

		try {
			var callbackReached = false;
			dataLayer.push({
				'event': 'productCheckout',
				'eventLabel': id,
				'ecommerce': {
					'checkout': {
						'actionField': { 'step': 1 },
						'products': [{
							'name': name,               // Name or ID is required.
							'id': id,                   // Facility ID
							'price': pricePerGolfer,    // Price per golfer
							'category': category,       // "Hot Deal" or "Course"
							'Dimension36': city,        // Custom Dimension City (string)
							'Dimension37': state,       // Custom Dimension State (string)
							'Dimension38': country,     // Custom Dimension Country (string)
							'currencyCode': getCurrencyCode()
						}]
					}
				},
				'eventCallback': function () {
					callbackReached = true;
					document.location = redirectUrl;
				}
			});

			window.setTimeout(function () {
				if (!callbackReached)
					window.location.href = redirectUrl;
			}, 250);
		} catch (e) {
			GolfNow.Web.Utils.ConsoleLog(e);
			window.location.href = redirectUrl;
		}
	};

	var _checkoutStep2 = function (name, id, pricePerGolfer, category, variant, city, state, country, quantity) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 2 },
					'products': [{
						'name': name,               // Name or ID is required.
						'id': id,                   // Facility ID
						'price': pricePerGolfer,    // Price per golfer
						'category': category,       // "Hot Deal" or "Course"
						'variant': variant,         // N/A for Course Rollup & Facility/Choose Rate
						'Dimension36': city,        // Custom Dimension City (string)
						'Dimension37': state,       // Custom Dimension State (string)
						'Dimension38': country,     // Custom Dimension Country (string)
						'quantity': quantity,        // Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _checkoutStep3 = function (name, id, pricePerGolfer, category, variant, city, state, country, quantity) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 3 },
					'products': [{
						'name': name,               // Name or ID is required.
						'id': id,                   // Facility ID
						'price': pricePerGolfer,    // Price per golfer
						'category': category,       // "Hot Deal" or "Course"
						'variant': variant,         // N/A for Course Rollup & Facility/Choose Rate
						'Dimension36': city,        // Custom Dimension City (string)
						'Dimension37': state,       // Custom Dimension State (string)
						'Dimension38': country,     // Custom Dimension Country (string)
						'quantity': quantity,        // Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _checkoutStep3MultiProducts = function (parentId, products) {
		if (typeof dataLayer === "undefined") return;

		if (!_.isArray(products)) {
			GolfNow.Web.Utils.ConsoleError('Invalid argument: products \n expected an array.');
			return;
		}

		var cc = getCurrencyCode();
		_.each(products, function (product) {
			product['currencyCode'] = cc;
		});


		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': parentId,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 3 },
					'products': products
				}
			}
		});
	};

	var _checkoutStep4 = function (name, id, pricePerGolfer, category, variant, city, state, country, quantity) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 4 },
					'products': [{
						'name': name,               // Name or ID is required.
						'id': id,                   // Facility ID
						'price': pricePerGolfer,    // Price per golfer
						'category': category,       // "Hot Deal" or "Course"
						'variant': variant,         // N/A for Course Rollup & Facility/Choose Rate
						'Dimension36': city,        // Custom Dimension City (string)
						'Dimension37': state,       // Custom Dimension State (string)
						'Dimension38': country,     // Custom Dimension Country (string)
						'quantity': quantity,        // Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _checkoutStep4MultiProducts = function (id, products) {
		if (typeof dataLayer === "undefined") return;

		if (!_.isArray(products)) {
			GolfNow.Web.Utils.ConsoleError('Invalid argument: products \n expected an array.');
			return;
		}

		var cc = getCurrencyCode();
		_.each(products, function (product) {
			product['currencyCode'] = cc;
		});


		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 4 },
					'products': products
				}
			}
		});
	};

	var _purchase = function (transId, businessRevenue, taxesAndFees, promoCode, name, productId, pricePerGolfer, category, variant, city, state, country, quantity) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productPurchase',
			'eventLabel': productId,
			'ecommerce': {
				'purchase': {
					'actionField': {
						'id': transId,                  // Transaction ID. Required for purchases and refunds.
						'revenue': businessRevenue,     // Total value (incl. tax and shipping)
						'tax': taxesAndFees,            // Until taxes and fees are split out
						'coupon': promoCode
					},
					'products': [{                      // List of productFieldObjects.
						'name': name,                   // Name or ID is required.
						'id': productId,                // Facility ID
						'price': pricePerGolfer,        // Price per golfer
						'category': category,           // "Hot Deal" or "Course"
						'variant': variant,             // N/A for Course Rollup & Facility/Choose Rate
						'Dimension36': city,            // Custom Dimension City (string)
						'Dimension37': state,           // Custom Dimension State (string)
						'Dimension38': country,         // Custom Dimension Country (string)
						'quantity': quantity,            // Custom Dimension Country (string)
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _purchaseMultiProducts = function (actionField, products) {
		if (typeof dataLayer === "undefined") return;

		if (!_.isArray(products)) {
			GolfNow.Web.Utils.ConsoleError('Invalid argument: products \n expected an array.');
			return;
		}

		var cc = getCurrencyCode();
		_.each(products, function (product) {
			product['currencyCode'] = cc;
		});


		dataLayer.push({
			'event': 'productPurchase',
			'eventLabel': actionField.productId,
			'ecommerce': {
				'purchase': {
					'actionField': actionField,
					'products': products
				}
			}
		});
	};

	var _getLoginPageInformation = function (apiUrl, facilityId, teetimeId, players, callback) {
		$.ajax({
			url: apiUrl,
			type: 'POST',
			datatype: 'json',
			data: {
				FacilityId: facilityId,
				TeetimeId: teetimeId,
				Players: players
			},
			success: function (data) {
				callback(data);
			}
		});
	};

	var _removeFromCart = function (name, id, pricePerGolfer, originalPrice, category, quantity) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'removeFromCart',
			'ecommerce': {
				'remove': {
					'products': [{
						'name': name,
						'id': id,
						'price': pricePerGolfer,
						'originalPrice': originalPrice,
						'category': 'VIP',
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};


	var _vipProductImpression = function (name, id, price, category, list) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productImpression',
			'eventLabel': id,
			'ecommerce': {
				'impressions': [{
					'name': name,
					'id': id,
					'price': price,
					'category': category,
					'list': list,
					'currencyCode': getCurrencyCode()
				}]
			}
		});
	};

	var _vipCheckoutStep1 = function (name, id, price, category) {
		if (typeof dataLayer === "undefined") { return; }

		var callbackReached = false;
		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 1 },
					'products': [{
						'name': name,
						'id': id,
						'price': price,
						'category': category,
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _vipProductClick = function (name, id, price, category, list) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productClick',
			'eventLabel': id,
			'ecommerce': {
				'click': {
					'actionField': { 'list': list },
					'products': [{
						'name': name,
						'id': id,
						'price': price,
						'category': category,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _vipAddToCart = function (name, id, price, originalPrice, category, list, redirectUrl) {
		if (typeof dataLayer === "undefined") return;
		if (redirectUrl === '' || redirectUrl === null || redirectUrl === undefined) redirectUrl = null;

		try {
			var callbackReached = redirectUrl === null ? true : false;
			dataLayer.push({
				'event': 'addToCart',
				'eventLabel': id,
				'ecommerce': {
					'add': {
						'actionField': { 'list': list },
						'products': [{
							'name': name,
							'id': id,
							'price': price,
							'originalPrice': originalPrice,
							'category': category,
							'currencyCode': getCurrencyCode()
						}]
					}
				},
				'eventCallback': function () {
					callbackReached = true;
					if (redirectUrl !== null)
						document.location = redirectUrl;
				}
			});

			window.setTimeout(function () {
				if (!callbackReached)
					window.location.href = redirectUrl;
			}, 250);
		} catch (e) {
			GolfNow.Web.Utils.ConsoleLog(e);

			if (redirectUrl !== null)
				window.location.href = redirectUrl;
		}
	};

	var _vipCheckoutStep2 = function (name, id, price, category) {
		if (typeof dataLayer === "undefined") { return; }

		var callbackReached = false;
		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 2 },
					'products': [{
						'name': name,
						'id': id,
						'price': price,
						'category': category,
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _vipCheckoutStep3 = function (name, id, price, originalPrice, category) {
		if (typeof dataLayer === "undefined") { return; }

		var callbackReached = false;
		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 3 },
					'products': [{
						'name': name,
						'id': id,
						'price': price,
						'originalPrice': originalPrice,
						'category': category,
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _vipCheckoutStep4 = function (name, id, price, originalPrice, category) {
		if (typeof dataLayer === "undefined") { return; }

		var callbackReached = false;
		dataLayer.push({
			'event': 'productCheckout',
			'eventLabel': id,
			'ecommerce': {
				'checkout': {
					'actionField': { 'step': 4 },
					'products': [{
						'name': name,
						'id': id,
						'price': price,
						'originalPrice': originalPrice,
						'category': category,
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	var _vipPurchase = function (transId, businessRevenue, taxesAndFees, name, productId, price, originalPrice, category) {
		if (typeof dataLayer === "undefined") return;

		dataLayer.push({
			'event': 'productPurchase',
			'eventLabel': productId,
			'ecommerce': {
				'purchase': {
					'actionField': {
						'id': transId,
						'revenue': businessRevenue,
						'tax': taxesAndFees,
					},
					'products': [{
						'name': name,
						'id': productId,
						'price': price,
						'originalPrice': originalPrice,
						'category': category,
						'quantity': 1,
						'currencyCode': getCurrencyCode()
					}]
				}
			}
		});
	};

	return {
		AddToCart: _addToCart,
		CheckoutStep1: _checkoutStep1,
		CheckoutStep2: _checkoutStep2,
		CheckoutStep3: _checkoutStep3,
		CheckoutStep3MultProducts: _checkoutStep3MultiProducts,
		CheckoutStep4: _checkoutStep4,
		CheckoutStep4MultiProducts: _checkoutStep4MultiProducts,
		GetLoginPageInformation: _getLoginPageInformation,
		ProductImpression: _productImpression,
		ProductClick: _productClick,
		ProductDetailsView: _productDetailsView,
		Purchase: _purchase,
		PurchaseMultiProducts: _purchaseMultiProducts,
		RemoveFromCart: _removeFromCart,

		VipProductImpression: _vipProductImpression,
		VipCheckoutStep1: _vipCheckoutStep1,
		VipProductClick: _vipProductClick,
		VipAddToCart: _vipAddToCart,
		VipCheckoutStep2: _vipCheckoutStep2,
		VipCheckoutStep3: _vipCheckoutStep3,
		VipCheckoutStep4: _vipCheckoutStep4,
		VipPurchase: _vipPurchase
	};
}();;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

GolfNow.Web.PmpReporting = function () {
	var _pmpReportSettings = GolfNow.Web.Domains.PMPReportSettings();
	var _batchReportUrl = '/api/pmp-batch/batch-report';
	var _pmpBatchCacheKey = 'pmpBatch';
	var _pmpBatchLogCacheKey = 'pmpBatchLog';
	var _pmpClick = 'pmp_click';
	var _pmpImpression = 'pmp_impression';
	var _pmpPurchase = 'pmp_purchase';
	var _collectionName = 'pmp_logs_web';
	var _channelId = '';

	var _reportPmpClickEvent = function reportPmpClickEvent(courseName, facilityId, facilityTag, eventZone) {
		reportPmpEvent(courseName, facilityId, {
			event: _pmpClick,
			tags: facilityTag,
			event_zone: eventZone
		});
	}

	var _reportPmpImpressionEvent = function reportPmpImpressionEvent(courseName, facilityId, facilityTag, eventZone) {
		reportPmpEvent(courseName, facilityId, {
			event: _pmpImpression,
			tags: facilityTag,
			event_zone: eventZone
		});
	}

	var _reportPmpPurchaseEvent = function reportPmpPurchaseEvent(courseName, facilityId, playerCount, reservationId, facilityTags) {
		reportPmpEvent(courseName, facilityId, {
			event: _pmpPurchase,
			player_count: playerCount,
			reservationId: reservationId,
			tags: facilityTags,
			event_zone: 'purchase'
		});
	}

	function reportPmpEvent(courseName, facilityId, record, onRecordedAction = null) {
		var deferred = $.Deferred();

		_pmpReportSettings.done(function (settings) {
			let valid = record && Object.keys(record).length > 0;
			let eventName = record['event'];

			if (!valid)
				return;

			var sessionDurationInMinutes = settings.session_duration;
			var batchIntervalInMinutes = settings.batch_interval;

			let logs = GolfNow.Web.Cache.GetValue(_pmpBatchCacheKey);
			if (!logs) {
				logs = {
					StartFormattedDate: 0
				};
			}

			let utcNow = new Date();

			logs.SessionId = logs.SessionId > 0 ? logs.SessionId : utcNow.getTime();
			logs.BatchId = logs.BatchId > 0 ? logs.BatchId : utcNow.getTime();
			logs.Records = logs.Records || [];
			logs.FacilitiesClicks = logs.FacilitiesClicks || new Array();

			// we have a record of facility clicks, when a purchase is made if a click has a match
			// then we report the purchase
			if (eventName) {
				if (eventName === _pmpClick) {
					if (!logs.FacilitiesClicks.includes(facilityId))
						logs.FacilitiesClicks.push(facilityId);
				} else if (eventName === _pmpPurchase) {
					// if a click isn't found above the purchase won't be added
					if (!logs.FacilitiesClicks.includes(facilityId))
						return;
				}
			}

			function getMinuteOftheYear(date) {
				let start = new Date(date.getFullYear(), 0, 0);
				let diff = date - start;
				let oneMinute = 1000 * 60;
				let minutes = Math.floor(diff / oneMinute);
				return minutes;
			}

			let minuteYearNow = getMinuteOftheYear(utcNow);
			let sessionMinuteOfYear = getMinuteOftheYear(new Date(logs.SessionId));
			let isSessionExpired = sessionMinuteOfYear + sessionDurationInMinutes < minuteYearNow;

			// if user session has expired then reset the log of FacilitiesClicked for that session
			if (isSessionExpired) {
				logs.SessionId = utcNow.getTime();
				logs.FacilitiesClicks = new Array();
			}

			// create a record here and push it to the log
			if (settings && settings.enabled) {
				record["date"] = utcNow.toISOString();
				record["facility_id"] = facilityId;
				record["facility_name"] = unescapeApostrophe(courseName);
				record["session_id"] = clientIP;

				if (eventName) {
					record['access_route'] = (eventName != _pmpPurchase) ? window.location.pathname : '/checkout';
				}

				logs.Records.push(record);
			}

			logs.EndFormattedDate = daysIntoYear(utcNow);

			if (logs.StartFormattedDate === 0)
				logs.StartFormattedDate = logs.EndFormattedDate;

			let batchDate = new Date(logs.BatchId);
			let batchMinuteOld = getMinuteOftheYear(batchDate);
			let isBatchExpired = batchMinuteOld + batchIntervalInMinutes < minuteYearNow;

			// if batch collection has expired then attempt to post batch
			if (settings && settings.enabled && (eventName === _pmpPurchase || isBatchExpired)) {
				// cache a copy of the logs in case the server-side post fails
				GolfNow.Web.Cache.SetValue(_pmpBatchLogCacheKey, logs, true);

				GolfNow.Web.Request.Post('post-pmp-log-batch', _batchReportUrl, JSON.stringify(logs))
					.done(function (data) {
						if (data && !data.success) {
							GolfNow.Web.Utils.ConsoleError('Failed to post PMP log batch: ' + data.statusDescription);

							// attempt to report via client-side if server-side fails
							//'secondaryReportAttempt();
						}
					})
					.fail(function (err) {
						GolfNow.Web.Utils.ConsoleError('Failed to post PMP log batch to server: ' + err);

						// attempt to report via client-side if server-side fails
						//secondaryReportAttempt();
					});

				logs.Records = [];
				logs.BatchId = utcNow.getTime();
				logs.StartFormattedDate = 0;
				logs.EndFormattedDate = 0;
			}

			GolfNow.Web.Cache.SetValue(_pmpBatchCacheKey, logs, true);

			if (onRecordedAction) onRecordedAction();
		})
		.fail(function (err) {
			GolfNow.Web.Utils.ConsoleError('Exception during batch of PMP logs: ' + err);

			return deferred.reject();
		});

		return deferred.promise();
	}

	// This is a temporary function to resolve the issue of posting the batch to the server
	async function secondaryReportAttempt() {
		var pmpBatchLogs = GolfNow.Web.Cache.GetValue(_pmpBatchLogCacheKey);
		const records = pmpBatchLogs.Records;
		const list = [];
		//const db = firebase.firestore();
		const now = new Date();
		const formattedDate = now.toISOString().slice(0, 7).replace(/-/g, '');
		var collectionName = _collectionName + '_' + formattedDate;

		for (const record of records) {
			const recordObj = {};
			for (const [key, value] of Object.entries(record)) {
				recordObj[key] = value;
			}
			list.push(recordObj);
		}
		const dicc = {
			start_date_id: pmpBatchLogs.StartFormattedDate,
			end_date_id: pmpBatchLogs.EndFormattedDate,
			channel_id: _channelId || '',
			pmp_events: list
		};
		const document = { ...dicc };

		//const result = await db.collection(collectionName).add(document);

		dataLayer.push({
			'pmpBatch': _channelId || '',
			'documentId': result.id || '',
			'successful': result != null && result.id != ''
		});

		GolfNow.Web.Cache.SetValue(_pmpBatchLogCacheKey, null, true);

		return result !== null && result.id !== '';	
	}

	// get difference between current date of the year and the first day of the year and factor it out to days
	function daysIntoYear(date) {
		let fullYear = date.getFullYear();
		return [fullYear, (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000].join('');
	}

	function init(collectionName, channelId) {
		_collectionName = collectionName;
		_channelId = channelId;
	}

	function unescapeApostrophe(val) {
		var re1 = /\\'/g;
		var re2 = /&#39;/g;
		var re3 = /&amp;#39;/g;
		return val.replace(re1, "'").replace(re2, "'").replace(re3, "'");
	}

	return {
		ReportPmpImpressionEvent: _reportPmpImpressionEvent,
		ReportPmpClickEvent: _reportPmpClickEvent,
		ReportPmpPurchaseEvent: _reportPmpPurchaseEvent,
		Init: init
	};
}();;
function validateForm(){$("form").validate()}function replaceAll(n,t,i){var r=t.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1");return n.replace(new RegExp(r,"g"),i)}function toggleReviewText(n){var t=document.getElementById("Less"+n),i=document.getElementById("More"+n);t.style.display!=="none"?(t.style.display="none",i.style.display="block"):(t.style.display="block",i.style.display="none")}function TrackGoogleEvent(n,t,i,r,u){try{t==="Featured Course"&&_.isString(r)&&(r.includes(siteConfigSettings.pmpTier1)||r.includes(siteConfigSettings.pmpTier2))&&batchPmpEvent(i,r,t);dataLayer&&dataLayer.push({event:n,eventCategory:t,eventAction:i,eventLabel:r,eventValue:u})}catch(f){GolfNow.Web.Utils.ConsoleLog(f)}}function TrackGoogleClickEvent(n,t,i,r,u,f){try{if(t==="Featured Course"&&_.isString(r)&&(r.includes(siteConfigSettings.pmpTier1)||r.includes(siteConfigSettings.pmpTier2))&&batchPmpEvent(i,r,t),dataLayer){var e=!1;dataLayer.push({event:n,eventCategory:t,eventAction:i,eventLabel:r,eventValue:u,eventCallback:function(){e=!0;window.location.href=f}});window.setTimeout(function(){e||(window.location.href=f)},250)}else window.location.href=f}catch(o){GolfNow.Web.Utils.ConsoleLog(o);window.location.href=f}}function batchPmpEvent(n,t){if(_.isString(t)&&_.isString(n)){var i=null;t.includes("|")?i=t.split("|"):t.includes(":")&&(i=t.split(":"));!_.isNull(i)&&i.length>1&&(i[3].includes("/")&&(i[3]=i[3].split("/")[0]),n.includes("impression")?GolfNow.Web.PmpReporting.ReportPmpImpressionEvent(i[0].trim(),i[1].trim(),i[2].trim(),i[3].trim()):n.includes("click")&&GolfNow.Web.PmpReporting.ReportPmpClickEvent(i[0].trim(),i[1].trim(),i[2].trim(),i[3].trim()))}}var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Client=GolfNow.Web.Client||{};var xhrFacility,federatedSearchValidation=/^[\d\D]+$/,_trkcodeCacheName="GolfNow.Web.Client.TRK",_locationCacheName="GolfNow.Web.Client.CurrentPosition",_searchParameterCacheName="GolfNow.Web.SearchParameters",_searchAjaxTimeOut=3e4,_federatedSearcFacilityResults=[],_currentPageName="",_prevChangeLocationSearchKey="",$googleAttribution=$("<li />").append($("<span />").addClass("pull-right").append($("<img />").addClass("google-logo"))),_requestedTemplates=[];GolfNow.Web.Client.ForceFullPageHeight=function(){$("div.off-canvas-wrap").css("height","100%").children("div.inner-wrap").css("min-height","100%");GolfNow.Web.Page.Pub("forcefullscreen")};GolfNow.Web.Client.ForceDefaultPageHeight=function(){$("div.off-canvas-wrap").css("height","").children("div.inner-wrap").css("height","");GolfNow.Web.Page.Pub("revertfullscreen")};GolfNow.Web.Client.getCurrentPosition=function(n,t){GolfNow.Web.LocationServices.LocateMe(!1,n,t)};GolfNow.Web.Client.LoadTemplate=function(n,t,i,r){var u=function(n){_requestedTemplates.push(n)},f;return _.contains(_requestedTemplates,t)?$.Deferred().resolve():(f=cdnUrl!=="",$.templates[t])?(u(t),$.Deferred().resolve()):GolfNow.Web.Domains.TmplVersionKey().then(function(i){n.indexOf("http")===-1&&f&&(n=cdnUrl.substring(0,cdnUrl.length-1)+n);var r=i===""?n:n+"?v="+i,u=t+"_request";return GolfNow.Web.Request.LoadTemplateContent(u,r,{method:"GET",cache:!0,dataType:"html"},replaceAll(r,"/","_"))}).then(function(n){var t={};return i&&(t.helpers=i),r&&(t.tags=r),n&&n!==""&&(t.markup=n),{tmplResources:t,tmpl:n}}).done(function(n){return $.templates[t]?(u(t),n):($.templates(t,n.tmplResources),u(t),n)})};GolfNow.Web.Client.SearchController=function(n){var i="GolfNow.Web.Client.PreloadCache",l="GolfNow.Web.Client.RestoreParameters",r=$("#gn_widget_csrf > input"),u,t=this,f=null,a=null,v=!1,o=0,y=[],b=["FacilityName","FacilitySlug","MarketName","Address","undefined"],e=function(n,i,e){(e||(e=t.SearchParameters.Get()),t.IsRequestPending())||(e.SortByRollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(e.SortBy,e.SortDirection),e.CurrentClientDate=Date.today(),r.length&&(u=r.val(),u===""&&(r=$("#teetime-search > input"),u=r.val())),f=$.ajax({headers:{__RequestVerificationToken:u},url:"/api/tee-times/tee-time-results",dataType:"json",data:JSON.stringify(e),contentType:"application/json; charset=utf-8",type:"POST",timeout:_searchAjaxTimeOut,beforeSend:function(n,i){t.teeTimesLoading=!0;i.data=JSON.stringify(_.omit(_.omit(JSON.parse(i.data),b),function(n){return typeof n=="undefined"||n===null}))},success:function(t){var u=$("#promocampaigntoggle"),i=$("#promo-campaign-container"),f=GolfNow.Web.Page.GetPageConfig().Refinements,s=_.findWhere(f,{Name:"Save-Extra"})||{Mode:0},h=s.Mode===1,r=function(){return e.PageNumber===0?t.ttResults.promotedCampaigns&&t.ttResults.promotedCampaigns.total?(y=t.ttResults.promotedCampaigns.campaignIds,t.ttResults.promotedCampaigns.total):0:t.ttResults.promotedCampaigns&&t.ttResults.promotedCampaigns.total?_.union(y,t.ttResults.promotedCampaigns.campaignIds).length:void 0};_currentPageName=document.location.pathname.substring(0,11)==="/tee-times/"?document.location.pathname.substring(11):document.location.pathname.substring(1);e.Address&&e.Address!==""&&(t.ttResults.predicate.address=e.Address);e.PageNumber===0&&(o=r());e.PageNumber>0&&r()>0&&(o=r());o>0&&h?(i.is(":visible")||TrackGoogleEvent("promotedCampaignFilter","Promoted Campaign Filters","Impression",_currentPageName),i.find("span#toggle-header").html("Promoted Offers"),t.ttResults.promotedCampaigns.total>0&&i.attr({"data-timemin":t.ttResults.promotedCampaigns.timeMin,"data-timemax":t.ttResults.promotedCampaigns.timeMax}),i.parent().addClass("dual-toggle"),i.show()):(i.find("span#toggle-header").html("Promoted Offers"),u.is(":checked")||i.hide(),i.parent().removeClass("dual-toggle"));n(t)},complete:function(){t.teeTimesLoading=!1;f=null},error:i}))},p=[{view:"Course",sort:GolfNow.Web.Utils.GetDefaultSearchSort(),dir:"0"},{view:"List",sort:GolfNow.Web.Utils.GetDefaultSearchSort(),dir:"0"},{view:"Grouping",sort:GolfNow.Web.Utils.GetDefaultSearchSort(),dir:"0"},{view:"Tile",sort:GolfNow.Web.Utils.GetDefaultSearchSort(),dir:"0"},{view:"Course-Tile",sort:GolfNow.Web.Utils.GetDefaultSearchSort(),dir:"0"},{view:"Map",sort:"",dir:"0"},{view:"Map-Tile",sort:"",dir:"0"}],k=function(){var h=["Address","HotDealsOnly","PromotedCampaignsOnly","PriceMin","PriceMax","Players","TimePeriod","TimeMax","TimeMin","Holes","Radius","FacilityType","RateType","Q","QC"],f={},t=s(),r,e,n,o,i,u;if(t&&!$.isEmptyObject(t)){r=Object.getOwnPropertyNames(t);for(e in r)n=r[e],o=_.map(h,function(n){return n.toLowerCase()}),_.isString(n)&&_.indexOf(o,n.toLowerCase(),!1)>-1&&(i=t[n],i&&i!=="false"&&(u={},u[n]=i,$.extend(f,u)))}return f},s=function(n){var t,r,u,i;return n=n||!1,t=GolfNow.Web.Cache.GetValue(_searchParameterCacheName),n&&(r=_.map(_.keys(t),function(n){return n.toLowerCase()}),u=_.values(t),t=_.object(r,u)),i="Radius",n&&(i=i.toLowerCase()),t&&t[i]&&(t[i]=Math.max(Number(t[i])||0,GolfNow.Web.Utils.GetDefaultSearchRadius("mi",GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")))),t},d=function(n){var t=_.once(function(t){n({Latitude:t.Latitude,Longitude:t.Longitude,Address:t.Address})});GolfNow.Web.Client.getCurrentPosition(t,t)},g=function(n,t){n.PageNumber=t;GolfNow.Web.Cache.SetSessionStorageValue(i,n)},w=function(){return GolfNow.Web.Cache.GetValue(i)},nt=function(n){var t=w();return t&&t.PageNumber===n?!0:!1},tt=function(){var n=_.once(function(){GolfNow.Web.Page.Pub("searchController_Initialized",t)});$(window).on("unload",function(){void 0});searchController=t;GolfNow.Web.Client.SearchController.InitializeFederatedSearch();n()},h=function(n,r){t.ResultsData=n;var u=t.SearchParameters.Get();t.RenderResults(n,u,r);t.RenderPredicates(u).then(function(){t.AfterSearch(n,u,r)}).done(function(){var n=JSON.parse(JSON.stringify(u)),r,f;n.PageNumber++;r=n.PageNumber;f=t.TotalPages();r<f?e(function(t){g(t,n.PageNumber)},null,n):GolfNow.Web.Cache.SetSessionStorageValue(i,null)})},c=function(n){n.statusText!=="abort"&&(t.RenderError(),t.AfterSearch())};this.ResultsData={};this.ViewSortMappings=p;this.LoadTemplates=function(){for(var n,u,r=[],i=0;i<t.JsTemplates.length;i++)n=t.JsTemplates[i],u=n.isPath?n.tmplPath:"/Tmpls/_"+n.tmplPath+".tmpl.html",r.push(GolfNow.Web.Client.LoadTemplate(u,n.accessorName,n.helpers,n.tags));return r};this.TotalRecords=function(){return this.ResultsData.total};this.TotalPages=function(){if(t.ResultsData.ttResults.predicate){var n=t.ResultsData.ttResults.predicate.pageSize;return n>t.TotalRecords()?1:Math.ceil(t.TotalRecords()/n)}return 1};this.ResetAdvancedSearchParams=function(){t.SearchParameters.ResetAdvancedSearchParams()};this.DoSearch=function(){var n=t.SearchParameters.Get();$.when.apply(this,this.LoadTemplates()).then(function(){t.BeforeSearch(n)}).then(function(){t.RenderPredicates(n)}).done(function(){t.SearchParameters.QueryNeedsLocation()?d(function(n){n?t.SearchParameters.Set({Latitude:n.Latitude,Longitude:n.Longitude,Address:n.Address},!0):t.SearchParameters.Set({Latitude:null,Longitude:null},!0);e(h,c)}):e(h,c)})};this.DoOffPlatformSearch=_.once(function(){var n=$("#ttresults");GolfNow.Web.Search.toggleLoadingAnimation(4);GolfNow.Web.Page.Sub("widget_loadComplete",function(t){if(/(RelatedCourses)$/.test(t.widgetName)){var i=GolfNow.Web.Domains.OffPlatformCopy();$relatedCourses=$("gn-related-courses");i.done(function(n){$("#tee-times-unavailable-description").text(n)});$relatedCourses.before(n);$relatedCourses.find(".favorite-tile span.course-rating span").attr("style","line-height:1.9em !important").end().find("#related-courses").addClass("content-slider").lightSlider({item:3,loop:!1,pager:!1,autoWidth:!1,slideMove:2,easing:"cubic-bezier(0.25, 0, 0.25, 1)",speed:600,controls:!Modernizr.touch,responsive:[{breakpoint:1367,settings:{item:3.41,slideMove:1,slideMargin:6}},{breakpoint:1025,settings:{item:3.41,slideMove:1,slideMargin:6}},{breakpoint:800,settings:{item:2.45,slideMove:1,slideMargin:6}},{breakpoint:480,settings:{item:1.26,slideMove:1}}],onSliderLoad:function(n){GolfNow.Web.Search.toggleLoadingAnimation(3);_.delay(function(){$(n).height(385);$relatedCourses.height(400)},350)}})}})});this.NextResult=function(n){var r=t.SearchParameters.NextPage(),f=t.TotalPages(),o=GolfNow.Web.Cache.GetValue(i),s=o&&!$.isEmptyObject(o),u;(r<f||s)&&(u=function(i){var r=!1;t.IsRequestPending()?(r||(r=!0,n()),setTimeout(function(){u(i)},550)):(r||(r=!0,n()),setTimeout(i,550))},u(function(){var n=function(n){h(n,!0)};nt(r)?n(w()):e(n,c)}));r>=f&&s&&GolfNow.Web.Cache.SetSessionStorageValue(i,null)};this.SelectActiveDate=function(n,i){var f=t.SearchParameters.Get(),u,r;if(typeof i=="undefined"&&(i=!1),u=GolfNow.Web.Utils.GetSearchTypeName(f.SearchType),r={Date:n,PageNumber:0},i===!1){if(u==="Facility"){t.SearchParameters.Set(r,!0);t.SaveSearchParameters(r,!0);GolfNow.Web.UrlParams.HandleFacilityUrlHash(t);return}if(u==="GoPlay"){t.SearchParameters.Set(r,!0);t.SaveSearchParameters(r,!0);GolfNow.Web.UrlParams.HandleGoPlayUrlHash(t,{date:n.toDateDisplayString(!1)});return}}t.SearchParameters.Set(r,i);t.SaveSearchParameters(r,i)};this.NextDate=function(n){(n===undefined||n===null)&&(n=1);var r=t.SearchParameters.Get(),i=Date.parse(r.Date).addDays(n),o=GolfNow.Web.Date.DaysFromToday(i);if(o<=GolfNow.Web.Utils.GetMaximumCalendarDays()-1){var u=GolfNow.Web.Utils.GetSearchTypeName(r.SearchType),f=u==="Facility",e=u==="GoPlay";t.SavePickerSelectedDate(i);this.SelectActiveDate(i,!f&&!e);GolfNow.Web.Page.Pub("search_date_changed",i);r=t.SearchParameters.Get();f||e||(r.Date=i.toDateDisplayString(!1),t.RedirectToCustomSearchPage(r))}$(".button-prev-date").show();this.SetNavDatePickerDate(i)};this.PreviousDate=function(n){n=_.isNull(n)||_.isUndefined(n)?-1:Math.abs(n)*-1;var r=t.SearchParameters.Get(),u=Date.today(),i=Date.parse(r.Date).addDays(n);if(i.compareTo(u)===1||i.equals(u)){var f=GolfNow.Web.Utils.GetSearchTypeName(r.SearchType),e=f==="Facility",o=f==="GoPlay";t.SavePickerSelectedDate(i);this.SelectActiveDate(i,!e&&!o);GolfNow.Web.Page.Pub("search_date_changed",i);r=t.SearchParameters.Get();e||o||(r.Date=i.toDateDisplayString(!1),t.RedirectToCustomSearchPage(r))}u.equals(i)&&$(".button-prev-date").hide();this.SetNavDatePickerDate(i)};this.SetDate=function(n,i){typeof i=="undefined"&&(i=!1);n instanceof Date?(t.SavePickerSelectedDate(n),this.SelectActiveDate(n,i),Date.today().compareTo(Date.parse(this.SearchParameters.Get().Date))===0?$(".button-prev-date").hide():$(".button-prev-date").show()):GolfNow.Web.Utils.ConsoleWarn("Set date requires a date object")};this.SavePickerSelectedDate=function(n){a=n;setTimeout(function(){$(".date-picker").attr("data-content",$("#select-date-translate").text())},2e3);GolfNow.Web.Page.Pub("search_date_picker_set",n)};this.GetPickerSelectedDate=function(){return a};this.SetDisplayDates=function(n){if(n){var t=n.toDateDisplayString();$("#currentDateText").html(t);$("#currentDateRefineText").html(t);$("#search-header-date").html(t)}};this.SetNavDatePickerDate=function(n){var i=$("#dayPicker").pickadate("picker");i&&!t.teeTimesLoading&&i.set("select",n)};this.teeTimesLoading=!1;this.redirectOnSearch=!1;this.Initialize=function(n,i){var h,r,o,f,w;if(i=typeof i=="undefined"?!0:i,n=n||defaultViewOverrideParams,$.isEmptyObject(n))h=s(),t.SearchParameters.Set(h,!0);else{n.ResetLocation&&t.ResetFederatedSearchParameters();n.RedirectOnSearch&&(t.redirectOnSearch=!0);n.DisableLocationChange&&(v=n.DisableLocationChange);switch(n.SearchParamsAction){case 0:var c=GolfNow.Web.Utils.GetSearchTypeName(n.SearchType),e=GolfNow.Web.UrlParams.GetHashParams(),l=!_.isEmpty(e),a=e.view||n.View||null,u=e.sortby||n.SortBy||null,y=e.latitude||n.Latitude||null,p=e.longitude||n.Longitude||null;if($.extend(_.omit(n,["View","SortBy","SortByRollup","SortDirection"]),s()),n.ExcludeFeaturedFacilities!==GolfNow.Web.Utils.GetDefaultExcludeFeaturedFacilities()&&(n.ExcludeFeaturedFacilities=GolfNow.Web.Utils.GetDefaultExcludeFeaturedFacilities()),GolfNow.Web.Utils.GetSearchTypeName(n.SearchType)!==c&&(n.SearchType=c),l&&u){r=u.split(".");o="0";switch(r.length){case 3:u=r[0]+"."+r[1];o=r[2];break;case 2:f=r[1];isNaN(Number(f))&&(f.indexOf("Min")!==-1||f.indexOf("Max")!==-1)||!isNaN(Number(f))?(u=r[0],o=f):u=r[0]+"."+f;break;default:u=r[0]}n.View=a;n.SortBy=u;n.SortByRollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(u,o);n.SortDirection=o;n.Latitude=y;n.longitude=p}break;case 2:$.extend(n,k())}t.SearchParameters.Set(n,!0)}w=_.once(function(){GolfNow.Web.Page.Pub("searchController_Initialized",t)});GolfNow.Web.Page.Sub("page_init",function(){GolfNow.Web.Search.handlePreviousDateLink();GolfNow.Web.Search.handleSortState();Foundation.utils.is_medium_up()&&(GolfNow.Web.Search.removeUnSupportedViewOptions($("#view-options > li > a")),GolfNow.Web.Search.removeUnSupportedSortOptions($("#sort-options > li > a"),GolfNow.Web.Page.GetCurrentClientProfile()));GolfNow.Web.FederatedSearch.handlePageRefinements()});!i||n.OffPlatformCourse||window.location.hash?n.OffPlatformCourse&&t.DoOffPlatformSearch():t.DoSearch();tt()};this.ShouldRedirectOnSearch=function(){return t.redirectOnSearch?t.redirectOnSearch:!1};this.RedirectToCustomSearchPage=function(n,i){var u,e,r,f;$.isEmptyObject(n)||(t.SearchParameters.Set(n,!0),t.SaveSearchParameters(n));$.isEmptyObject(i)||(t.SearchParameters.Set(i,!0),t.SaveFederatedSearchParameters(i));u="/tee-times/search";e=GolfNow.Web.Utils.GetSearchTypeName(n.SearchType);switch(e){case searchType_Facility:case searchType_Destination:u=window.location.pathname;break;case searchType_Favorites:return GolfNow.Web.UrlParams.HandleGoPlayUrlHash(t,!1)}r=t.SearchParameters.GetLc();f=[];typeof r.sortby!="undefined"&&r.sortby!==null?r.sortby=r.sortby&&r.sortby.indexOf("|")>0?r.sortby.replace("|","."):r.sortby+"."+(r.sortdirection||"0"):f.push("sortby","sortbyrollup","sortdirection");var o=GolfNow.Web.Utils.GetRefineDefaultsLower(null,r.view),s=GolfNow.Web.UrlParams.GetHashOmits(f),h=_.extendOwn(_.omit(o,s),r),c=GolfNow.Web.UrlParams.BuildHashParamsFromSearchParams(h,o,s),l=u+"#"+c;window.location.href=l;GolfNow.Web.Client.SearchController.CloseFederatedSearch()};this.SaveSearchParameters=function(n){var i=$.extend(GolfNow.Web.Cache.GetValue(_searchParameterCacheName),n),r,u,f;i.Date&&(i.Date=GolfNow.Web.Utils.GetDateString(i.Date));var e={},o=_.difference(t.SearchParameters.GetKeys(),["Radius"]);for(r in i)u=o.find(function(n){if(n.toLowerCase()===r.toLowerCase())return n}),u!==undefined&&u!==""&&(f=i[r],r===undefined&&(f=null),e[u]=f);GolfNow.Web.Cache.SetSessionStorageValue(_searchParameterCacheName,e,18e5)};this.SaveFederatedSearchParameters=function(n){var i={Address:null,Latitude:null,Longitude:null,FacilityId:null,FacilityName:null,MarketId:null,MarketName:null,SearchType:"GeoLocation"};$.extend(i,n);t.SearchParameters.Set(i,!0);t.SaveSearchParameters(i)};this.SaveCurrentFederatedSearchParameters=function(){var i=["Latitude","Longitude","Address","FacilityId","FacilityName","MarketId","MarketName","SearchType","Q","QC"],n={},r=this.SearchParameters.Get();$.each(r,function(t,r){if($.inArray(t,i)!==-1&&r&&r!=="false"){var u={};u[t]=r;$.extend(n,u)}});t.SaveFederatedSearchParameters(n)};this.ResetFederatedSearchParameters=function(){t.SaveFederatedSearchParameters({})};this.RenderResults=function(){GolfNow.Web.Utils.ConsoleWarn("RenderResults not implemented")};this.RenderError=function(){GolfNow.Web.Utils.ConsoleWarn("Error fetching results")};this.RenderPredicates=function(){GolfNow.Web.Utils.ConsoleWarn("RenderResults not implemented")};this.BeforeSearch=function(){};this.AfterSearch=function(){};this.JsTemplates=[];this.RenderResults=n.RenderResults;this.RenderPredicates=function(t){var i=new $.Deferred;return GolfNow.Web.Page.Sub("renderPredicates",function(n){i.resolve(n)}),n.RenderPredicates(t),i.promise()};this.BeforeSearch=function(t){var i=new $.Deferred;return GolfNow.Web.Page.Sub("beforeSearch",function(n){i.resolve(n)}),n.BeforeSearch(t),i.promise()};this.AfterSearch=function(t,i,r){var u=new $.Deferred;return GolfNow.Web.Page.Sub("afterSearch",function(n){u.resolve(n.params,n.append)}),n.AfterSearch(t,i,r),u.promise()};this.RenderError=n.RenderError;this.JsTemplates=n.JsTemplates;this.UseGooglePlaces=n.UseGooglePlaces;this.GetRestoreFedSearchKey=function(n){function f(){var t=_.defaults(i,GolfNow.Web.Utils.GetRefineDefaults(null,i.View)),u=Object.getOwnPropertyNames(t),f,n,e;for(f in u)n=u[f],r.hasOwnProperty(n)&&r[n]&&(e=r[n],t[n]=e);return t}var r=t.SearchParameters.Get(),i,u;return(n=n===undefined?!1:n,i={},!r)?i:(u=GolfNow.Web.Utils.GetSearchTypeName(r.SearchType),(u==="GeoLocation"||u==="GoPlay")&&r.Latitude&&r.Longitude&&(r.Address?(i.Location=r.Address,i=f()):(n=!0,$.when.apply(this,[this.RecentSearches.Find(r.Latitude,r.Longitude),GolfNow.Web.LocationServices.Address()]).done(function(n,r){var u="";u=n?n:r;i.Location=u;i=f();t.SetRefinedResultsDisplay(i,$("#fedresults"),$(".list-refined-items"))}))),u!=="GoPlay"||v||GolfNow.Web.LocationServices.Address().done(function(n){i.Location=n;i=f()}),u!=="GeoLocation"&&u!=="GoPlay"||r.Latitude&&r.Longitude||(i=f()),u==="Facility"&&r.FacilityName&&(i=r,i.Location=r.FacilityName,i=f()),u==="Market"&&r.MarketName&&(i.Location=r.MarketName,i=f()),u==="Destination"&&r.MarketName&&(i.Location=r.MarketName,i=f(),(i.Radius===null||_.isNaN(Number(i.Radius)))&&viewOverrideParams.Radius!==undefined&&(i.Radius=viewOverrideParams.Radius)),u==="Favorites"&&(i.Location="",i=f()),n?void 0:(t.SetRefinedResultsDisplay(i,$("#fedresults"),$(".list-refined-items")),i))};this.SetRefinedResultsDisplay=function(n,t,i){if(!_.isNull(n)&&!_.isEmpty(n)){var u=GolfNow.Web.Utils.GetSearchTypeName(n.SearchType),r=n.Location===undefined?"":GolfNow.Web.Utils.UrlDecodeString(n.Location);t.text(r);$("#fedresults-refine").text(r);GolfNow.Web.Page.Pub("set-filter-display-values",{refinedObj:n,refinedItems:Object.getOwnPropertyNames(n),searchType:u,location:r});i.empty()}};this.IsRequestPending=function(){var n=f&&f.readyState!==4;return n||!1};this.SetRestoreParameters=function(n){GolfNow.Web.Cache.SetSessionStorageValue(l,n)};this.GetRestoreParameters=function(){return GolfNow.Web.Cache.GetValue(l)};this.ChangeView=function(n,i,r){var s,u,f,e,o;return(i=i||t.SearchParameters.Get(),r=_.isUndefined(r)||_.isNull(r)?!0:r,s=i.View,s===n)?i:(u="",f="",$.grep(p,function(t){t.view===n&&(u=t.sort,f=t.dir)}),i.SortBy||(rollUpSortBy=i.SortBy=u),(i.SortDirection===undefined||i.SortDirection===null)&&(i.SortDirection=f),i.SortBy&&(rollUpSortBy=GolfNow.Web.Utils.GetSearchSortRollupFromSort(i.SortBy,i.SortDirection)),(n==="Course"||n==="Tile"||n==="Course-Tile")&&rollUpSortBy==="GreensFees.MaxPrice"&&(i.SortDirection="0"),i.SortByRollup=rollUpSortBy,rollUpSortBy===""&&(i.SortByDirection=""),i.View=n,/^Course$|^Course-Tile$|^Map$|^Map-Tile$|List/.test(n)&&($(".search-results #loading .list-animation").show(),$(".search-results #loading .chip-animation").hide(),$(".search-results #loading .tile-animation").hide()),/Grouping/.test(n)&&($(".search-results #loading .chip-animation").show(),$(".search-results #loading .list-animation").hide(),$(".search-results #loading .tile-animation").hide()),/^Tile$|^Tile-HD$/.test(n)&&($(".search-results #loading .tile-animation").show(),$(".search-results #loading .chip-animation").hide(),$(".search-results #loading .list-animation").hide()),!r)?i:(i=t.SearchParameters.Set(i,!0),e=GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType),o=window.location.pathname,GolfNow.Web.FederatedSearch.StoreUserFacilityViewOption(e,n),TrackGoogleEvent("viewChange","View","Change",e+"|"+o.substr(o.lastIndexOf("/")+1)+"|"+n),i)};this.ChangeSort=function(n,i){var s,c,h;i=_.isUndefined(i)||_.isNull(i)?!0:i;var r=t.SearchParameters.Get(),o=r.View,e=n.split("|"),u="",f="0";return(e.length===2?(u=e[0],f=e[1]):u=e[0],rollUpSortBy=r.SortBy=u,r.SortDirection=f,(o==="Course"||o==="Tile"||o==="Course-Tile")&&rollUpSortBy==="GreensFees.MaxPrice"&&(r.SortDirection=f="0"),r.SortByRollup=rollUpSortBy=GolfNow.Web.Utils.GetSearchSortRollupFromSort(u,f),s={sortBy:u,sortByRollup:rollUpSortBy,sortDirection:f},!i)?s:(c=GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType),h=window.location.pathname,TrackGoogleEvent("sortChange","Sort","Change",c+"|"+h.substr(h.lastIndexOf("/")+1)+"|"+rollUpSortBy),s)};this.GetRecentSearches=function(){return this.RecentSearches.Get()};this.AddRecentSearch=function(n,t,i,r,u,f){this.RecentSearches.Add(n,t,i,r,u,f)};this.FindRecentSearchesById=function(n,t){return this.RecentSearches.FindById(n,t)};this.RecentSearches=new GolfNow.Web.RecentSearches;this.SearchParameters=new GolfNow.Web.SearchParameters;$(this.SearchParameters).on("ParametersUpdated",function(){t.DoSearch()});$(this.SearchParameters).on("OffPlatformSearch",function(){t.DoOffPlatformSearch()})};GolfNow.Web.Client.SearchController.OpenFederatedSearch=function(){try{$("#searchModal").foundation("reveal","open")}catch(n){GolfNow.Web.Utils.ConsoleWarn("OpenFederatedSearch:"+n)}};GolfNow.Web.Client.SearchController.NextDateWrapped=function(n){searchController.NextDate(n)};GolfNow.Web.Client.SearchController.InitializeFederatedSearch=_.once(function(){var n,t;GolfNow.Web.Utils.ConsoleLog("fedresults?:"+$("#fedresults").length);n=searchController?searchController.GetRestoreFedSearchKey():null;n&&n.Location&&n.Location!==""&&(t=$("#fedresults"),t.length>0&&searchController.SetRefinedResultsDisplay(n,t,$(".list-refined-items")));$("#fedsearch").length>0&&$("#fedsearch").val().length>0?(GolfNow.Web.Client.SearchController.StepTwo(),$("#fedsearch").trigger("keyup")):GolfNow.Web.Client.SearchController.StepOne()});GolfNow.Web.Client.SearchController.ShowRefineSearch=function(){GolfNow.Web.Page.Pub("show-refine-search-clicked",null);$("#searchModal").hasClass("open")||GolfNow.Web.Client.SearchController.OpenFederatedSearch();GolfNow.Web.Client.SearchController.StepThree();$(".federatedStepOne").parents(".autocomplete-results").hide()};GolfNow.Web.Client.SearchController.ShowSearchFilters=function(n){GolfNow.Web.Page.Pub("show-search-filters-clicked",{mediumOverride:n});Foundation.utils.is_medium_only()&&!n?($(".off-canvas-wrap").foundation("offcanvas","show","offcanvas-overlap-right"),$("gn-search-filters aside.left-off-canvas-menu > .filters.search-options-wrap").height($(".inner-wrap").height()+500)):(Foundation.utils.is_small_only()||n)&&($("#searchModal").hasClass("open")||GolfNow.Web.Client.SearchController.OpenFederatedSearch(),n||($("#searchModal").find(".search-bar").hide(),GolfNow.Web.Client.SearchController.StepThree()),$(".federatedStepOne").parents(".autocomplete-results").hide())};GolfNow.Web.Client.SearchController.StepOne=function(){$(".filter-options-head-wrapper .reset-filters, .federatedStepTwo, .federatedStepThree").hide();$(".filter-options-head-wrapper .search-modal-header").html("Search");$(".federatedStepOne").show()};GolfNow.Web.Client.SearchController.StepTwo=function(){$(".federatedStepOne, .federatedStepThree").hide();$(".federatedStepTwo").show()};GolfNow.Web.Client.SearchController.StepThree=function(){$(".federatedStepOne, .federatedStepTwo").hide();$(".filter-options-head-wrapper .search-modal-header").html("Filters");$(".federatedStepThree, .reset-filters").show();_.defer(function(){$(document).foundation("reflow")})};GolfNow.Web.Client.SearchController.CloseFederatedSearch=function(){try{$("#searchModal").foundation("reveal","close");$(".off-canvas-wrap").foundation("offcanvas","hide","offcanvas-overlap-right")}catch(n){GolfNow.Web.Utils.ConsoleWarn("CloseFederatedSearch:"+n)}};GolfNow.Web.Client.SearchController.validateFedSearch=function(n){var t=/\-/g,i=n;return n.length>0&&!federatedSearchValidation.test(n)?!1:n.length>0&&n.match(t)!==null&&n.match(t).length>1?!1:!0};GolfNow.Web.Client.SearchController.GetSearchParameterValue=function(n){if(typeof n!="undefined"){var t=GolfNow.Web.Cache.GetValue(_searchParameterCacheName);if(t!==null)return t[n]}};GolfNow.Web.Client.ChangeLocationSetup=function(n){var i=$("#location-search"),r=searchController.GetRestoreFedSearchKey(),t;return r&&i.val(r.Location||""),t=$("<ul />").addClass("f-dropdown").addClass("medium").addClass("autocomplete-results").css("left",i.css("left")).css("display","none"),t.append($("<li />").addClass("throbber").html('<i class="fas fa-spinner fa-spin font-30"><\/i>')),t.append($("<li />").addClass("message").html(n)),i.after(t),{$textbox:i,$resultsList:t}};GolfNow.Web.Client.ChangeLocation_Click=function(){var t,u;$("#save-location-change").removeClass("disabled").prop("disabled",!1);t=$(this);t.parents(".autocomplete-results").hide();var n=t.parents().siblings("input#location-search"),i=$(this).attr("data-id"),r=$(this).attr("data-name");n.val(r);u={placeId:i};placeDetailService.getDetails(u,function(t,u){u===google.maps.places.PlacesServiceStatus.OK?(n.data("selectedPlaceId",i),n.data("selectedPlaceName",r),n.data("selectedPlaceGeo_lat",t.geometry.location.lat()),n.data("selectedPlaceGeo_long",t.geometry.location.lng())):alert("Unable to determine your geo location. Please try other search.")})};GolfNow.Web.Client.ChangeLocation_Click2=function(){var n,t;$("#save-location-change").removeClass("disabled").prop("disabled",!1);n=$(this);n.parents(".autocomplete-results").hide();t=n.parents().siblings("input#location-search");t.val(n.attr("data-name"));t.data("selectedPlaceId",n.attr("data-id"));t.data("selectedPlaceName",n.attr("data-name"));t.data("selectedPlaceGeo_lat",n.data("lat"));t.data("selectedPlaceGeo_long",n.data("long"));t.data("selectedPlaceGeoEid",n.data("eid"));t.data("selectedPlaceCity",n.data("city"));t.data("selectedPlaceState",n.data("state"));t.data("selectedPlaceZip",n.data("zip"));t.data("selectedPlaceCountry",n.data("country"))};GolfNow.Web.Client.ChangeLocation_SaveClick=function(){var i=$(this),n=i.parent().find("input#location-search"),e=n.data("selectedPlaceId"),r=n.data("selectedPlaceName"),u={Latitude:n.data("selectedPlaceGeo_lat")||"",Longitude:n.data("selectedPlaceGeo_long")||"",City:n.data("selectedPlaceCity")||"",State:n.data("selectedPlaceState")||"",PostalCode:n.data("selectedPlaceZip")||"",Country:n.data("selectedPlaceCountry")||"",Formatted_Address:r},f=n.data("selectedPlaceGeoEid")||"",t;n.val()===""||e===""||r===""||$.isEmptyObject(u)?($("#save-location-change-error").text("Location error. Please select a different item from the search results."),$("#save-location-change-label").show()):(t=function(){GolfNow.Web.LocationServices.SetUsersLocation(u,function(n){GolfNow.Web.Page.Pub("user-location-changed",n);$("#change-location-modal").foundation("reveal","close");$(".federatedNearMe a.nearMeLink span").text(n.Status.message)})},f!==""?GolfNow.Web.Request.Post("log-search-selection","/api/autocomplete/geoselection/"+f,null).always(t):t());i.addClass("disabled").prop("disabled",!0)};GolfNow.Web.Client.ChangeLocation_CancelClick=function(){$("#change-location-modal").foundation("reveal","close")};GolfNow.Web.Client.ChangeLocationSearch=function(n,t){function r(n){var r,i,u,f;$.each(n,function(n,e){r=$("<li />").addClass("location");i=$("<a />");u=$("<i />").addClass("gn-location");f=$("<span />").html(e.label);i.append(u).append(f);i.attr("data-id",e.id);i.attr("data-name",e.label);i.attr("data-lat",e.lat);i.attr("data-long",e.long);i.attr("data-city",e.city);i.attr("data-state",e.state);i.attr("data-zip",e.zip);i.attr("data-country",e.country);i.on("click",GolfNow.Web.Client.ChangeLocation_Click2);r.append(i);t.append(r)});t.find(".throbber").hide();t.find(".facility, .location").show();t.find(".facility, .location").length===0&&t.find(".message").show()}function u(n){var t=/\-/g,i=n;return n.length>0&&!federatedSearchValidation.test(n)?!1:n.length>0&&n.match(t)!==null&&n.match(t).length>1?!1:!0}var i;if($("#save-location-change-error").text("").parents(".row").hide(),i=n.val(),i!==_prevChangeLocationSearchKey)if(_prevChangeLocationSearchKey=i,i&&i.length>=3){if(u(i))n.tooltipster("hide");else{n.tooltipster("show");return}t.find(".facility, .location").remove();t.show();t.find(".message").hide();t.find(".throbber").show();GolfNow.Web.LocationServices.GetGeoCitySearch(i).done(r)}else t.hide()};GolfNow.Web.Client.ToggleCallCenterMasking=function(n,t){return GolfNow.Web.Request.Post("toggle-masking-on-request","/api/account/callcenter-mask",JSON.stringify({agentEmail:n,isMasked:t}))};GolfNow.Web.Client.GetGooglePlacesWrapper=function(n,t,i){var r=$("#federatedResultsLocations .federatedSearchResults ul"),u=$("#federatedResultsLocations .federatedSearchResults p"),f;r.hide();u.show();f=[];$.when.apply(this,[GolfNow.Web.Utils.GetGooglePlacesAutoCompleteResults_Geo(n),GolfNow.Web.Utils.GetGooglePlacesAutoCompleteResults_Regions(n)]).then(function(f,e){var o=_.uniq(_.union(f,e),function(n){return n.value});t(o,n,i);u.hide();r.show()})};GolfNow.Web.Client.FormUtilities=GolfNow.Web.Client.FormUtilities||{};GolfNow.Web.Client.FormUtilities.CleanValue=GolfNow.Web.Client.FormUtilities.CleanValue||function(n){return n&&n!=="on"&&n!==""?n:null};GolfNow.Web.Client.FormUtilities.GetSelectedItem=GolfNow.Web.Client.FormUtilities.GetSelectedItem||function(n){return n.filter("input:checked:first")};GolfNow.Web.Client.FormUtilities.GetSelectedValue=GolfNow.Web.Client.FormUtilities.GetSelectedValue||function(n){var t=n.filter("input:checked:first").prop("value");return GolfNow.Web.Client.FormUtilities.CleanValue(t)};GolfNow.Web.Client.FormUtilities.SetSelectedValue=GolfNow.Web.Client.FormUtilities.SetSelectedValue||function(n,t,i){i=typeof i=="undefined"?null:i;n.filter("input").prop("checked",null).closest("li,div,label").removeClass("active");n.filter("input[value='"+t+"']").prop("checked",!0).closest("li,div,label").addClass("active");!GolfNow.Web.Client.FormUtilities.GetSelectedValue(n)&&n.length>1&&(i!==null&&n.filter("input[value='"+i+"']").prop("checked",!0).closest("li,div,label").addClass("active"),!GolfNow.Web.Client.FormUtilities.GetSelectedValue(n)&&n.length>1&&n.filter("input:first").prop("checked",!0).closest("li,div.label").addClass("active"))};GolfNow.Web.Client.FormUtilities.SetZipCodeValidations=GolfNow.Web.Client.FormUtilities.SetZipCodeValidations||function(n,t){t.toLowerCase()==="us"?n.prop("type","tel"):n.prop("type","text")};;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

// Making a somewhat "generic" map controller so 
// that we might repurpose it later if more mapping becomes desired.
GolfNow.Web.MapController = function () {
	var map = null,
		mapMarkers = [],
		$mapInfoWindow = [],
		$mapFacilityAddress = [],
		infoWindow = null,
		facilityTileSelector = '#map-info-window .facility-tile',
		mapBounds = {},
		mapOptions = {},
		listResultHash = '',
		jsTemplates = [
			{
				tmplPath: 'MapResults',
				accessorName: 'mapResultsTemplate',
				isPath: false,
				helpers: {
					colhotdeal: Foundation.utils.debounce(isHotDeal, 150, true),
					contents_rendered: Foundation.utils.debounce(contentsRendered, 150, true),
					units: GolfNow.Web.Utils.AppendRadiusUnits,
					displayVIPBadge: Foundation.utils.debounce(displayVIPBadge, 150, true),
					playersFilterOption: Foundation.utils.debounce(getPlayersFilterOption, 150, true)
				}
			},
			{ tmplPath: 'CubeRollupNewCourse', accessorName: 'cubeRollupNewCourseTemplate', isPath: false },
			{
				tmplPath: 'TilesRollupCourse',
				accessorName: 'tilesRollupCourseTemplate',
				isPath: false,
				helpers: {
					resultHash: _.debounce(function () {
						if (listResultHash === '') listResultHash = GolfNow.Web.UrlParams.GetUrlHash() || '';
						return listResultHash;
					}, 150, true),
					units: GolfNow.Web.Utils.AppendRadiusUnits
				}
			},
			{
				tmplPath: 'TilesRollupCourseWide',
				accessorName: 'tilesRollupCourseWideTemplate',
				isPath: false,
				helpers: {
					resultHash: _.debounce(function () {
						if (listResultHash === '') listResultHash = GolfNow.Web.UrlParams.GetUrlHash() || '';
						return listResultHash;
					}, 150, true),
					units: GolfNow.Web.Utils.AppendRadiusUnits,
					hotDealZone: courseWideTileHotDealZone,
					isMobile: function () {
						return Foundation.utils.is_small_only();
					}
				},
				daysout: GolfNow.Web.Date.DaysFromToday
			},
			{ tmplPath: 'TilesRollupCourseWideTile', accessorName: 'CourseWideTileTemplate', isPath: false },
			{ tmplPath: 'TilesRollupCourseWideTile-PC', accessorName: 'CourseWideTilePCTemplate', isPath: false },
			{
				tmplPath: 'TilesRollupHotDeal',
				accessorName: 'tilesRollupHotDealTemplate',
				isPath: false,
				helpers: {
					resultHash: _.debounce(function (append) {
						if (listResultHash === '') {
							listResultHash = GolfNow.Web.UrlParams.GetUrlHash() || '';
							return listResultHash;
						}

						var hash = '#hotdealsonly=true';
						if (append && _.isNumber(append)) hash += '&daysout=' + append;
						return hash;
					}, 150, true),
					isBestDealsPage: function () {
						return $('.special-rates').hasClass('best-tee-times-deals');
					},
					units: GolfNow.Web.Utils.AppendRadiusUnits
				}
			},
			{ tmplPath: 'StarRatings', accessorName: 'starRatingsTemplate', isPath: false },
			{ tmplPath: 'star', accessorName: 'star', isPath: false }
		],
		resizeTimer = null,
		hotDealsOnly = false,

		DrawMap = function (id, options, facilities, featuredFacilities, params) {
			var customMapType = new google.maps.StyledMapType(
				[
					{ "featureType": "water", "elementType": "all", "stylers": [{ "hue": "#7fc8ed" }, { "saturation": 55 }, { "lightness": -6 }, { "visibility": "on" }] },
					{ "featureType": "water", "elementType": "labels", "stylers": [{ "hue": "#7fc8ed" }, { "saturation": 55 }, { "lightness": -6 }, { "visibility": "off" }] },
					{ "featureType": "poi.park", "elementType": "geometry", "stylers": [{ "hue": "#83cead" }, { "saturation": 1 }, { "lightness": -15 }, { "visibility": "on" }] },
					{ "featureType": "landscape", "elementType": "geometry", "stylers": [{ "hue": "#f3f4f4" }, { "saturation": -84 }, { "lightness": 59 }, { "visibility": "on" }] },
					{ "featureType": "landscape", "elementType": "labels", "stylers": [{ "hue": "#ffffff" }, { "saturation": -100 }, { "lightness": 100 }, { "visibility": "off" }] },
					{ "featureType": "road", "elementType": "geometry", "stylers": [{ "hue": "#ffffff" }, { "saturation": -100 }, { "lightness": 100 }, { "visibility": "on" }] },
					{ "featureType": "road", "elementType": "labels", "stylers": [{ "hue": "#bbbbbb" }, { "saturation": -100 }, { "lightness": 26 }, { "visibility": "on" }] },
					{ "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "hue": "#ffcc00" }, { "saturation": 100 }, { "lightness": -35 }, { "visibility": "simplified" }] },
					{ "featureType": "road.highway", "elementType": "geometry", "stylers": [{ "hue": "#ffcc00" }, { "saturation": 100 }, { "lightness": -22 }, { "visibility": "on" }] },
					{ "featureType": "poi.school", "elementType": "all", "stylers": [{ "hue": "#d7e4e4" }, { "saturation": -60 }, { "lightness": 23 }, { "visibility": "on" }] }
				]
				,
				{ name: 'GolfNow' }
			);

			var customMapTypeId = 'custom_style';
			mapOptions = {
				mapTypeControlOptions: {
					mapTypeIds: [google.maps.MapTypeId.ROADMAP, customMapTypeId]
				}
			};
			$.extend(mapOptions, options);

			hotDealsOnly = params.hotDealsOnly;

			if (!map) {
				$.when.apply(this, loadTemplates())
					.done(function () {
						var mapParams = $.extend({}, { 'insLocation': 0 }, params);
						$.link.mapResultsTemplate('#map-info-col-headers', mapParams);

						map = new google.maps.Map(document.getElementById(id), mapOptions);

						$mapInfoWindow = $('#map-info-window');
						$mapFacilityAddress = $('#map-info-window .facility-address');
						$mapFacilityAddress.find('.column > p').text('Select a pin to see the Tee Time information.');
						google.maps.event.addListener(map, 'click', function () {
							$mapInfoWindow.hide();
						});
						//map.mapTypes.set(customMapTypeId, customMapType);
						//map.setMapTypeId(customMapTypeId);
						drawMapComplete(facilities, featuredFacilities, mapOptions);
					})
					.fail(function () {
						// some type of networking error..show mulligan page
						GolfNow.Web.Utils.ConsoleWarn('Unable to load templates');

						GolfNow.Web.Page.Pub('no_results_rendered', null);
					});
			}
			else {
				map.setCenter({ lat: mapOptions.center.lat, lng: mapOptions.center.lng });
				cleanUp();
				$mapFacilityAddress.show();

				drawMapComplete(facilities, featuredFacilities, mapOptions);
			}
		},

		addMapMarker = function (facility) {
			if ($.isEmptyObject(facility)) { return false; }

			var image = ((hotDealsOnly && facility.hasHotDeal) || facility.isHotDeal) ? '/Content/images/pin_orange.png' : '/Content/images/pin_blue.png';
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(facility.latitude, facility.longitude),
				map: map,
				title: facility.name,
				icon: image
			});
			marker.gnFacility = facility;

			google.maps.event.addListener(marker, 'click', function () {
				$mapInfoWindow.show();
				var infoString = '<span id="map-pin-title">' +
					' ' + marker.gnFacility.name +
					'<br/>' + marker.gnFacility.address.line1 +
					'<br/> ' + marker.gnFacility.address.city +
					', ' + marker.gnFacility.address.stateProvinceCode +
					' ' + marker.gnFacility.address.postalCode + ' ' +
					'</span>';

				if (infoWindow) { infoWindow.close(); }
				infoWindow = new google.maps.InfoWindow({
					content: infoString
				});
				google.maps.event.addListener(infoWindow, 'domready', function () {
					$('#map-pin-title')
						.on('click', function () {
							window.location.href = $('.facility-tile a:first').attr('href');
						});
				});
				infoWindow.open(map, marker);

				if (!$.isEmptyObject(marker.gnFacility.address)) {
					$mapFacilityAddress.hide();
				}

				$mapInfoWindow.find('.facility-tile').show();
				map.setCenter(marker.position);
				var mapTmplData = [{ 'facilities': [marker.gnFacility], 'hotDealsOnly': hotDealsOnly, 'insLocation': 1 }];
				$.link.mapResultsTemplate(facilityTileSelector, mapTmplData);
			});
			mapMarkers.push(marker);

			mapBounds.extend(marker.position);
			return true;
		},

		cleanUp = function () {
			if ($mapInfoWindow.length > 0) { $mapInfoWindow.find('.facility-tile').hide(); }
			if (infoWindow) { infoWindow.close(); }
			for (var i = 0; i < mapMarkers.length; i++) {
				mapMarkers[i].setMap(null);
			}
			mapMarkers = [];
		},

		fitMapToBounds = function (options) {
			if (mapBounds.isEmpty()) { return false; }

			map.fitBounds(mapBounds);

			return true;
		},

		handleWindowResize = function () {
			if (resizeTimer) { clearTimeout(resizeTimer); }

			resizeTimer = setTimeout(handleWindowResizeHelper, 250);
		},

		handleWindowResizeHelper = function () {
			//fitMapToBounds(mapOptions);
		},

		loadTemplates = function () {
			var loadCalls = [];
			for (var i = 0; i < jsTemplates.length; i++) {
				var currItem = jsTemplates[i];
				var path = currItem.isPath ? currItem.tmplPath : '/Tmpls/_' + currItem.tmplPath + '.tmpl.html';
				loadCalls.push(GolfNow.Web.Client.LoadTemplate(path, currItem.accessorName, currItem.helpers));
			}
			// add a call to make sure we are using the correct api link
			//loadCalls.push(addClientIdToMapsUrl());
			return loadCalls;
		},

		addClientIdToMapsUrl = function () {
			var d = new $.Deferred();

			var $jsElem = $('#jsGooglePlaces');
			if ($jsElem.length && ($jsElem.attr('src').indexOf('&client=') < 0)) {
				var $jsElem = $('#jsGooglePlaces');
				var jsElem = $jsElem[0];
				var url = $jsElem.attr('src');
				if (jsGoogleMapsUrl !== url) {
					url = jsGoogleMapsUrl;

					$.getScript(url).done(function () {
						d.resolve();
					});
				} else {
					d.resolve();
				}
			} else {
				d.resolve();
			}

			return d.promise();
		},
		drawMapComplete = function (facilities, featuredFacilities, mapOptions) {
			mapBounds = new google.maps.LatLngBounds();

			$.each(facilities, function (index, facility) {
				addMapMarker(facility);
			});

			$.each(featuredFacilities, function (index, featuredFacility) {
				addMapMarker(featuredFacility);
			});

			// add marker at search center point
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng),
				map: map,
				title: 'Search Center'
			});
			mapMarkers.push(marker);

			if (facilities.length > 1 || featuredFacilities.length > 1) {
				fitMapToBounds(mapOptions);
			} else {
				// make sure the marker is in view 
				map.setCenter(mapBounds.getCenter());
			}

			GolfNow.Web.Page.Sub('window_resize', handleWindowResize);

			GolfNow.Web.Page.Pub('content_rendered', null);
		};

	// helper method for teeTimeResultsTemplate to control the HotDeals column toggle
	function isHotDeal() {
		var rootData = this.ctx.root;
		if (rootData && rootData.hotDealsOnly) {
			return (Boolean(rootData.hotDealsOnly) === true);
		} else {
			return false;
		}
	}

	function contentsRendered(isRendered) {
		var rendered = !_.isNull(isRendered) ? isRendered : null;
		GolfNow.Web.Page.Pub('content_rendered', rendered);
		return true;
	}

	function getPlayersFilterOption() {
		var players = Number(searchController.SearchParameters.Get().Players) || '';
		return _.isNumber(players) && players > 0 ? players : '';
	}

	function displayVIPBadge(rate) {
		var rootData = null;
		var root = this.ctx.root;

		if (root && root.length > 1)
			rootData = this.ctx.root[this.getIndex()];
		else if (root && root.length === 1)
			rootData = this.ctx.root[0];

		if (rootData && rate)
			return rootData.isVipMember && rate.vipEligible;
	}

	function courseWideTileHotDealZone(item, index, items) {
		return item.displayRate.isHotDeal;
	}

	return {
		DrawMap: DrawMap
	}
}();
;
/// <reference path="GolfNow.Web.Client.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Navigation = GolfNow.Web.Navigation || {};
GolfNow.Web.Navigation.StateViewName = "GolfNow_NavigationState";

// each page that wants to tracked, should call the Add method
// and as the user navigates through the site, a collection of pages
// will be built so we can intelligently handle our back buttons
GolfNow.Web.Navigation = function () {
    // store navigation movement before we leave the page
    $(window).on('pagehide', function () {
        storeMovement();
    });

    var movingBack = false,
        movingForward = false,
        navigationBackStack = [],
        navigationForwardStack = [],
        navigationBackStackName = 'navigation_BackStack',
        navigationForwardStackName = 'navigation_ForwardStack',
        verifyNavUrl = function (url) {
            if (url === document.location.pathname) {
                return false;
            }
            return true;
        },
        storeMovement = function () {
            if (navigationBackStack.length && !movingBack)
                GolfNow.Web.Cache.SetSessionStorageValue(navigationBackStackName, navigationBackStack);

            if (navigationForwardStack.length && movingBack)
                GolfNow.Web.Cache.SetSessionStorageValue(navigationForwardStackName, navigationForwardStack);

            movingBack = false;
            movingForward = false;
        },
        pullBackUrl = function () {
            var urlStack = GolfNow.Web.Cache.GetValue(navigationBackStackName) || null;
            if (urlStack !== null) {
                var urlObj = urlStack.shift();
                if (urlObj) {
                    GolfNow.Web.Cache.SetSessionStorageValue(navigationBackStackName, urlStack, null);
                    return urlObj.url;
                }
            }
            return '';
        },
        pullForwardUrl = function () {
            var urlStack = GolfNow.Web.Cache.GetValue(navigationForwardStackName) || null;
            if (urlStack !== null) {
                var urlObj = urlStack.shift();
                if (urlObj) {
                    GolfNow.Web.Cache.SetSessionStorageValue(navigationForwardStackName, urlStack, null);
                    return urlObj.url;
                }
            }
            return '';
        },
        insertForward = function (navObj) {
            if (navObj && navObj.url !== '/') {
                navigationForwardStack = GolfNow.Web.Cache.GetValue(navigationForwardStackName) || [];
                if (navigationForwardStack.length === 0) {
                    navigationForwardStack.unshift(navObj);
                } else if (navigationForwardStack[0].name !== navObj.name && navigationForwardStack[0].url !== navObj.url) {
                    navigationForwardStack.unshift(navObj);
                }
            }
        },
        Back = function (returnUrl, distance) {
            window.history.go(-1);
            //if (BackEnabled()) {
            //    returnUrl = returnUrl || false;
            //    distance = distance || 0;

            //    var i = 0;
            //    var backUrl = '';

            //    do {
            //        backUrl = pullBackUrl();
            //        i++;
            //    } while (i < distance && verifyNavUrl(backUrl) === false);

            //    if (backUrl === '') backUrl = '/';

            //    movingBack = true;
            //    if (!returnUrl) {
            //        document.location.href = htmlDecode(backUrl);
            //    } else {
            //        storeMovement();
            //        return htmlDecode(backUrl);
            //    }
            //}
        },
        PeekBack = function () {
            var urlStack = GolfNow.Web.Cache.GetValue(navigationBackStackName) || null;
            if (urlStack !== null) {
                var urlObj = urlStack[0];
                if (urlObj) {
                    return urlObj;
                }
            }
            return null;
        },
        Forward = function (returnUrl, distance) {
            if (BackEnabled()) {
                returnUrl = returnUrl || false;
                distance = distance || 0;

                var i = 0;
                var forwardUrl = '';

                do {
                    forwardUrl = pullForwardUrl();
                    i++;
                } while ((i < distance) && (verifyNavUrl(forwardUrl) === false));

                if (forwardUrl === '')
                    return null;

                movingForward = true;
                if (!returnUrl) {
                    document.location.href = htmlDecode(forwardUrl);
                } else {
                    storeMovement();
                    return htmlDecode(forwardUrl);
                }
            }
        },
        BackEnabled = function () {
            if (document.referrer) {
                var ref = document.referrer.match(/:\/\/(.[^/]+)/)[1];
                var cur = document.location.href.match(/:\/\/(.[^/]+)/)[1];
                return ref.toLowerCase() === cur.toLowerCase();
            }
            return false;
        },
        DisableBack = function () {
            window.history.forward();
        },
        SkipPage = function () {
            //window.history.back(1);
            Back(false, 1);
        },
        CancelBackNavigation = function () {
            // Three different events doing similar to cover Safari,Firefox,chrome,IE,others
            window.onload = DisableBack();
            window.onpageshow = function (evts) {
                if (evts.persisted) { DisableBack(); }
            };

            window.onunload = function () { void 0; };
        },
        SkipBackNavigation = function () {
            // Three different events doing similar to cover Safari,Firefox,chrome,IE,others
            window.onload = SkipPage();
            window.onpageshow = function (event) {
                if (event.persisted) { SkipPage(); }
            };
            window.onunload = function () { void 0; };
        },
        Add = function (pageName, pageUrl) {
            navigationBackStack = GolfNow.Web.Cache.GetValue(navigationBackStackName) || [];
            var newLoc = { name: pageName, url: pageUrl };
            if (navigationBackStack.length === 0) {
                navigationBackStack.unshift(newLoc);
            } else if (navigationBackStack[0].url !== pageUrl) {
                navigationBackStack.unshift(newLoc);
            }
            insertForward(newLoc);
        },
        htmlDecode = function (htmlEncodedStr) {
            return $('<div/>').html(htmlEncodedStr).text();
        };

    return {
        Add: Add,
        Back: Back,
        PeekBack: PeekBack,
        Forward: Forward,
        BackEnabled: BackEnabled,
        DisableBack: DisableBack,
        SkipPage: SkipPage,
        CancelBackNavigation: CancelBackNavigation,
        SkipBackNavigation: SkipBackNavigation
    };
}();

//$('.deepNav nav a, a.back-link').click(function (event) { event.preventDefault(); GolfNow.Web.Navigation.Back(); });;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.SearchParameters=function(){Array.prototype.find||(Array.prototype.find=function(n){var t;if(this===null)throw new TypeError("Array.prototype.find called on null or undefined");if(typeof n!="function")throw new TypeError("predicate must be a function");var i=Object(this),u=i.length>>>0,f=arguments[1],r;for(t=0;t<u;t++)if(r=i[t],n.call(f,r,t,i))return r;return""});var n={},i=function(){var t=n.HotDealsOnly;return t?3:Foundation.utils.is_small_only()?10:Foundation.utils.is_medium_only()?15:Foundation.utils.is_large_up()?20:void 0},t=function(n){return n==="Tile-PC"||n==="Course-Tile-PC"?!0:null};n.Radius=GolfNow.Web.Utils.GetDefaultSearchRadius();n.Latitude=null;n.Longitude=null;n.Address=null;n.PageSize=30;n.PageNumber=0;n.SearchType=0;n.SortBy=GolfNow.Web.Utils.GetDefaultSearchSort();n.SortDirection=0;n.Date=null;n.HotDealsOnly=null;n.GolfPassPerksOnly=null;n.BestDealsOnly=null;n.PriceMin=null;n.PriceMax=null;n.Players=null;n.TimePeriod=null;n.Holes=null;n.FacilityType=null;n.RateType=GolfNow.Web.Utils.GetDefaultRateType();n.TimeMin=null;n.TimeMax=null;n.FacilityId=null;n.FacilityName=null;n.FacilitySlug=null;n.FacilityIds=null;n.MarketId=null;n.MarketName=null;n.SortByRollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(n.SortBy,n.SortDirection);n.View=GolfNow.Web.Utils.GetDefaultSearchView(0);n.ExcludeFeaturedFacilities=GolfNow.Web.Utils.GetDefaultExcludeFeaturedFacilities();n.ExcludePrivateFacilities=null;n.RateTagCodes=null;n.Tags=null;n.NextAvailableTeeTime=null;n.TeeTimeCount=i();n.PromotedCampaignsOnly=null;n.Q=null;n.QC=null;this.ResetAdvancedSearchParams=function(){var i=GolfNow.Web.Utils.GetRefineDefaults(null,n.View);i.SearchType=GolfNow.Web.Utils.GetSearchTypeName(n.SearchType);i.HotDealsOnly=t(n.View);i.PromotedCampaignsOnly=t(n.View);i.View=n.View;i.SortBy=n.SortBy;i.SortByDirection=n.SortDirection;i.SortByRollup=n.SortByRollup;i.Latitude=n.Latitude;i.Longitude=n.Longitude;i.FacilityId=n.FacilityId;i.FacilityIds=n.FacilityIds;i.FacilityName=n.FacilityName;i.FacilityType=n.FacilityType;i.MarketId=n.MarketId;i.MarketName=n.MarketName;this.Set(i,!0)};this.NextPage=function(){return++n.PageNumber};this.Set=function(t,i){var s=Object.getOwnPropertyNames(n),u,f,r,o,e;for(u in t)f=s.find(function(n){if(n.toLowerCase()===u.toLowerCase())return n}),f!==undefined&&f!==""&&(r=t[u],u===undefined&&(r=null),u.toLowerCase()==="date"?(o=_.isDate(r)?r:Date.parse(r),e=GolfNow.Web.Utils.GetDateString(o),GolfNow.Web.Cache.SetActiveDate(e),n[f]=e):n[f]=r);return i||viewOverrideParams.OffPlatformCourse?viewOverrideParams.OffPlatformCourse&&$(this).trigger("OffPlatformSearch"):$(this).trigger("ParametersUpdated"),n};this.Get=function(){return _.clone(n)};this.GetLc=function(){var t=_.map(_.keys(n),function(n){return n.toLowerCase()}),i=_.values(n);return _.object(t,i)};this.GetKeys=function(){return _.allKeys(n)};this.ResetAdvancedSearchParams();this.QueryNeedsLocation=function(){var t=GolfNow.Web.Utils.GetSearchTypeName(n.SearchType);return(t===searchType_GeoLocation||t===searchType_GoPlay)&&!n.Latitude||!n.Longitude}};;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Tracking = GolfNow.Web.Tracking || {};
GolfNow.Web.Tracking.Customer = GolfNow.Web.Tracking.Customer || {};

GolfNow.Web.Tracking.Customer = function () { }

GolfNow.Web.Tracking.Customer.ReservationCacheName = 'GolfNow.Web.Tracking.Customer.Reservations';
GolfNow.Web.Tracking.Customer.FacilityCacheName = 'GolfNow.Web.Tracking.Customer.Facilities';
GolfNow.Web.Tracking.Customer.RecentlyViewedCacheName = 'GolfNow.Web.Tracking.Customer.RecentlyViewed';

GolfNow.Web.Tracking.Customer.GetReservations = function () {
	var customerReservationsList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.ReservationCacheName);
	return customerReservationsList.Get();
}

GolfNow.Web.Tracking.Customer.AddReservation = function (facilityId, facilityName, address, imgPath, rating, slug) {
	var customerReservationsList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.ReservationCacheName);
	customerReservationsList.Add(facilityId, facilityName, address, imgPath, rating, slug);
}

GolfNow.Web.Tracking.Customer.GetFacilities = function () {
	var customerFacilityList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.FacilityCacheName);
	return customerFacilityList.Get();
}

GolfNow.Web.Tracking.Customer.AddFacility = function (facilityId, facilityName, address, imgPath, rating, slug) {
	var customerFacilityList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.FacilityCacheName);
	customerFacilityList.Add(facilityId, facilityName, address, imgPath, rating, slug);
}

GolfNow.Web.Tracking.Customer.GetRecentlyViewed = function () {
	var recentlyViewedList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.RecentlyViewedCacheName);
	return recentlyViewedList.Get();
}

GolfNow.Web.Tracking.Customer.AddRecentlyViewed = function (facilityId, facilityName, address, imgPath, rating, slug) {
	var recentlyViewedList = new GolfNow.Web.Tracking.Locations(GolfNow.Web.Tracking.Customer.RecentlyViewedCacheName);
	recentlyViewedList.Add(facilityId, facilityName, address, imgPath, rating, slug);
}

GolfNow.Web.Tracking.Customer.LogPurchaseWorflow = function (reportingPage, facilityId, teetimeId, reservationId) {
	var reportingType = 'Purchase';
	var url = '/api/utilities/log-workflow';
	var workflowReq = GolfNow.Web.Request.Post('report-type-log', url, JSON.stringify({
		ReportingType: reportingType,
		ReportingPage: reportingPage,
		FacilityId: facilityId,
		TeeTimeId: teetimeId,
		ConfirmationId: reservationId || null
	}));

	workflowReq
		.done(function (data) { })
		.fail(function () {
			GolfNow.Web.Utils.ConsoleError('Log Workflow failed');
		});
}

// Class to track recent searches.
GolfNow.Web.Tracking.Locations = function (cacheName) {
	this._cacheName = cacheName;
	this._locations = this.GetFromCache();
	this._maxLocations = 10;
}

GolfNow.Web.Tracking.Locations.prototype.GetFromCache = function () {
	var recentLocations = GolfNow.Web.Cache.GetValue(this._cacheName);
	if (recentLocations === null) { return []; }

	return recentLocations;
}

GolfNow.Web.Tracking.Locations.prototype.Get = function () {
	return this._locations;
}

// We are assuming the ids of the items being stored are valid integers. If we end up storing items
// with non-numeric ids, we will have to re-work this code a bit.
GolfNow.Web.Tracking.Locations.prototype.Add = function (id, label, address, img, rating, slug) {
	//handling for optional parameters (address, img, rating)
	address = (address === undefined) ? null : address;
	img = (img === undefined) ? null : img;
	rating = (rating === undefined) ? { avgerageRating: null, reviewCount: null } : rating;
	slug = (slug === undefined) ? null : slug;

	for (var i = 0; i < this._locations.length; i++) {
		if (Number(this._locations[i].id) === Number(id)) {
			this._locations.splice(i, 1);
		}
	}

	while (this._locations.length >= this._maxLocations) { this._locations.pop(); }

	var newLocationObj = {
		'id': id,
		'label': label,
		'address': address,
		'imgPath': img,
		'rating': rating,
		'seoFriendlyName': slug
	};

	this._locations.unshift(newLocationObj);

	GolfNow.Web.Utils.ConsoleLog("Number of Locations: " + this._locations.length);

	GolfNow.Web.Cache.SetLocalStorageValue(this._cacheName, this._locations, 1000 * 60 * 60 * 12); /* 12 hours */
};
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Ads=GolfNow.Web.Ads||{};GolfNow.Web.Ads.Dfp=function(n){var u,h=[],t=[],r=[],f=!1,c=function(n,t,i){h.push({name:n,dimensions:t,id:i})},e=function(n){t=t||[];u=n;v();f=!0},l=function(){return f},a=function(t,i){if(_.isEmpty(googletag))return t&&t.adUnits&&t.adUnits.length&&n("#ad").parent("gn-dfpad").hide(),GolfNow.Web.Utils.ConsoleWarn("googletag object is empty. Ads will not display"),t;var u=n.Deferred();return googletag.cmd.push(function(){var f,e;t&&t.adUnits&&t.adUnits.length&&t.adUnits[0].hasSingleDiscreetDimension?(f=t.adUnits[0],s(f.AdUnitName,f.Dimensions,f.Id,f.gamId)):t&&t.adUnits&&t.adUnits.length&&(f=t.adUnits[0],e=f.FullNames,n.each(e,function(n,t){s(f.AdUnitName,t.Dimensions,t.Id,f.gamId)}));GolfNow.Web.Utils.ConsoleLog("Targets:",r);n.each(r,function(n,t){googletag.pubads().setTargeting(t.name,t.value)});googletag.pubads().collapseEmptyDivs();googletag.pubads().disableInitialLoad();googletag.enableServices();u.resolve(t,i)}),u.promise()},i=function(n,t){r.push({name:n,value:t})},v=function(){GolfNow.Web.Page.Sub("publish_dfp_ad",o)},o=function(n){_.isEmpty(googletag)||(n===""&&GolfNow.Web.Utils.ConsoleWarn("Ad Unit name is empty"),googletag.cmd.push(function(){GolfNow.Web.Utils.ConsoleLog("Ad Display called for:"+n);googletag.display(n)}))},y=function(n,t,r,u,f,o){n&&!_.isEmpty(r)&&(e(t),i("ct_url",u),i("is18Up",f),i("is21Up",o))},s=function(n,i,r,f){try{t.push(googletag.defineSlot("/"+(f||u)+"/"+n,i,r).setCollapseEmptyDiv(!0,!0).addService(googletag.pubads()))}catch(e){}},p=function(){_.isEmpty(googletag)||_.isUndefined(googletag.pubads)||googletag.pubads().refresh(t)};return{DefineSlot:c,DisplayAd:o,Init:e,IsInitialized:l,Publish:a,SetTargeting:i,PageSetup:y,RefreshAds:p}}(jQuery);;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Ads = GolfNow.Web.Ads || {};

GolfNow.Web.Ads.Partners = (function ($, _) {
    var _self = this, _customer = null, _facility = null,
        _reservation = null, _slots = [], _targets = [];

    // networkCode, customer, facility, reservation
    function init(config) {

        _self.customer = {};
        _self.facility = {};
        _self.reservation = {};
        _self.publish = function () { GolfNow.Web.Utils.ConsoleWarn('Publish method not implemented.') };
        _self.resizeHandler = function () { GolfNow.Web.Utils.ConsoleWarn('ResizeHandler event not implemented.') }

        _self.customer = config.customer;
        _self.facility = config.facility;
        _self.reservation = config.reservation;

        _bindEvents();
    }

    function _publish() {
        _self.publish(_self.customer, _self.facility, _self.reservation);
    }

    function setPublishHandler(publishMethod, adUnitName) {
        _self.publish = publishMethod;
        _self.publish(_self.customer, _self.facility, _self.reservation);
        _displayAd(adUnitName);
    }

    function setResizeHandler(resizeHandlerMethod) {
        _self.resizeHandler = resizeHandlerMethod;
    }

    function _displayAd(adUnitName) {
        GolfNow.Web.Page.Pub('publish_adPartner_ad', adUnitName);
    }

    function _refreshAd(adUnitName) {
        GolfNow.Web.Page.Pub('refresh_adPartner_ad', adUnitName);
    }

    // PRIVATE METHODS //
    var _bindEvents = function () {
        // subscribe to window resize events
        GolfNow.Web.Page.Sub('window_resize', function () {
            var display = Foundation.utils.is_small_only() ? "small" : "large";
            _self.resizeHandler(display);
        });
        GolfNow.Web.Page.Sub('publish_adPartner_ad', _displayAdListener);
        GolfNow.Web.Page.Sub('refresh_adPartner_ad', _refreshAdListener);
    };

    var _displayAdListener = function (adUnitName) {
        googletag.cmd.push(function () {
            googletag.display(adUnitName);
        });
    };

    var _refreshAdListener = function (adUnitName) {
        googletag.cmd.push(function () {
            googletag.pubads().clear();
            googletag.display(adUnitName);
        });
    };

    return {
        Init: init,
        SetPublishHandler: setPublishHandler,
        SetResizeHandler: setResizeHandler,
        DisplayAd: _displayAd,
        RefreshAd: _refreshAd
    }

})(jQuery, _);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Ads=GolfNow.Web.Ads||{};GolfNow.Web.Ads.GolfBalls=function(n){var t={gb_confirmationpage_bottom_all_5_small:{width:290,height:50},gb_confirmationpage_bottom_all_5_medium:{width:468,height:60},gb_confirmationpage_bottom_all_5_large:{width:728,height:90},gb_confirmationpage_right_large_3:{width:300,height:300}},i="",r="",u="",f="",e="",o=function(n,t){u=typeof n=="undefined"?"GolfNow":n;f=typeof t=="undefined"?"Customer":t},s=function(n){e=typeof n=="undefined"?"GolfNow":n},h=function(n,t){i=n;r=t},c=function(n){var i,r,u;for(i in t)if(t.hasOwnProperty(i)&&(r=t[i],u=r.width+"x"+r.height,u==n))return i;return""},l=function(o){if(o instanceof Array){var s=o.map(function(n){var i=t[n],r,u;return i?(r=i.width,u=i.height,r+"x"+u):""}).join(","),h='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"       xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">           <soap:Body>                <GetMultipleCheckoutBanner xmlns="'+r+'">                    <CustomerParameters>                        <NameValuePair>                            <Name>FirstName<\/Name>                            <Value>'+u+"<\/Value>                        <\/NameValuePair>                        <NameValuePair>                            <Name>LastName<\/Name>                            <Value>"+f+"<\/Value>                        <\/NameValuePair>                        <NameValuePair>                            <Name>TransactionSize<\/Name>                            <Value>"+e+"<\/Value>                        <\/NameValuePair>                        <NameValuePair>                            <Name>AdSize<\/Name>                            <Value>"+s+"<\/Value>                        <\/NameValuePair>                    <\/CustomerParameters>                <\/GetMultipleCheckoutBanner>            <\/soap:Body>        <\/soap:Envelope>";n.ajax({type:"POST",url:i,data:h,contentType:"text/xml; charset=ansi",dataType:"xml",success:function(t){n(t).find("BannerHTML").each(function(t,i){var u=n(i).find("Size").text(),f=c(u),r=n.parseHTML(n(i).find("HTML").text());n(r).find("a").attr("target","_blank");n("#"+f).html(r)})},error:function(){}})}};return{ShowAds:l,SetName:o,SetTransactionBucket:s,SetServiceDetails:h}}(jQuery);;
/// <reference path="_references.js" />

var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
GolfNow.Web.Ads = GolfNow.Web.Ads || {};

GolfNow.Web.Ads.ClubHub = (function ($, _) {
    function init(adUnitName) {
        GolfNow.Web.Ads.Partners.SetPublishHandler(_publish, adUnitName);
        GolfNow.Web.Ads.Partners.SetResizeHandler(_resize);
    }

    function initTest(adUnitName) {
        GolfNow.Web.Ads.Partners.SetPublishHandler(_publishTest, adUnitName);
    }

	function _publish(customer, facility, reservation) {
		if (_.isEmpty(googletag)) return;

        googletag.cmd.push(function () {
            googletag.defineSlot('/145042136/desktop', [[375, 160], [300, 300], [360, 210], [728, 90]], 'div-gpt-ad-1497656061163-0').addService(googletag.pubads());
            googletag.defineSlot('/145042136/mobile-new', [[300, 600], [150, 80], [400, 110], [290, 50]], 'div-gpt-ad-1497656061163-1').addService(googletag.pubads());
            //googletag.defineSlot('/145042136/tablet', [468, 60], 'div-gpt-ad-1497656061163-2').addService(googletag.pubads());

            googletag.pubads().enableSingleRequest();
            googletag.pubads().collapseEmptyDivs();

            var leadTime = GolfNow.Web.Date.DaysBetween(new Date(), reservation.playDateTime);
            var roundFeeBuckets = reservation.greensFee <= 50 ? '0-50' : reservation.greensFee <= 100 ? '51-100' : '100+';
            googletag.pubads()
            .setTargeting('round_fee', roundFeeBuckets)
            //.setTargeting('local_golfer', ((customer.Address.StateProvinceCode || '') === facility.Address.StateProvinceCode).toString())
            .setTargeting('course_name', _.escape(facility.Name))
            .setTargeting('course_state', facility.Address.StateProvinceCode)
            .setTargeting('lead_time', leadTime < 3 ? leadTime.toString() : '3plus')
            .setTargeting('course_city', _.escape(facility.Address.City))
            .setTargeting('course_country', facility.Address.Country)
            .setTargeting('customer_city', _.escape(customer.Address.City || ''))
            .setTargeting('customer_state', customer.Address.StateProvinceCode || '')
            .setTargeting('customer_country', customer.Address.Country || '')
            .setTargeting('customer_gender', customer.Gender || '')
            .setTargeting('click_id', reservation.reservationId);

            //googletag.pubads().enableSyncRendering();
            googletag.enableServices();
        });
    }

	function _publishTest(customer, facility, reservation) {
		if (_.isEmpty(googletag)) return;

        googletag.cmd.push(function () {
            googletag.defineSlot('/145042136/clubhub', ['fluid'], 'div-gpt-ad-1-0').addService(googletag.pubads());

            googletag.pubads().enableSingleRequest();

            var leadTime = GolfNow.Web.Date.DaysBetween(new Date(), reservation.playDateTime);
            var roundFeeBuckets = reservation.greensFee <= 50 ? '0-50' : reservation.greensFee <= 100 ? '51-100' : '100+';
            googletag.pubads()
            .setTargeting('round_fee', roundFeeBuckets)
            .setTargeting('local_golfer', ((customer.Address.StateProvinceCode || '') === facility.Address.StateProvinceCode).toString())
            .setTargeting('course_name', _.escape(facility.Name))
            .setTargeting('course_state', facility.Address.StateProvinceCode)
            .setTargeting('lead_time', leadTime < 3 ? leadTime.toString() : '3plus')
            .setTargeting('course_city', _.escape(facility.Address.City))
            .setTargeting('course_country', facility.Address.Country)
            .setTargeting('customer_city', _.escape(customer.Address.City || ''))
            .setTargeting('customer_state', customer.Address.StateProvinceCode || '')
            .setTargeting('customer_country', customer.Address.Country || '')
            .setTargeting('customer_gender', customer.Gender || '')
            .setTargeting('click_id', reservation.reservationId);

            googletag.enableServices();
        });
    }

    function _resize(size) {
        var adUnitName = 'div-gpt-ad-1497656061163-';
        switch (size) {
            case 'small':
                adUnitName += '1';
                break;
            case 'medium':
                adUnitName += '1';
                break;
            default:
                adUnitName += '0';
                break;
        }
        GolfNow.Web.Ads.Partners.RefreshAd(adUnitName);
    }

	return {
		Init: init,
		InitTest: initTest
	};

})(jQuery, _);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.UrlParams=GolfNow.Web.UrlParams||{};GolfNow.Web.Page.Sub("searchController_Initialized",function(n){searchController=n;GolfNow.Web.UrlParams.HandleUpdatedHashParameters(n)});GolfNow.Web.UrlParams.BackButton=function(){var n=!1,t=function(t){t===undefined&&(t=!0);n=t},i=function(){return n};return{SetClicked:t,Clicked:i}}();GolfNow.Web.UrlParams.HandleHashChange=function(){GolfNow.Web.UrlParams.HandleUpdatedHashParameters()};$(window).on("hashchange",GolfNow.Web.UrlParams.HandleHashChange).on("popstate",function(){GolfNow.Web.UrlParams.BackButton.SetClicked()});GolfNow.Web.UrlParams.HandleUpdatedHashParameters=function(n){var r,e,i,t,u,o,f;n=searchController||n;r=n?n.SearchParameters.GetLc():null;e=this;location.hash.length>0&&(location.pathname.startsWith("/search",location.pathname.length-7)||location.pathname.startsWith("/go-play")||location.pathname.startsWith("/tee-times/hot-deals")||location.pathname.startsWith("/favorites"))?(i=GolfNow.Web.Utils.GetSearchTypeName(r.searchtype),t=GolfNow.Web.UrlParams.GetHashParams(),t.sortby===undefined&&(t.sortby=r.sortby,t.sortbyrollup=r.sortbyrollup),t.view===undefined&&(t.view=r.view),t=GolfNow.Web.UrlParams.NormalizeViewAndSort(t,i),t=GolfNow.Web.UrlParams.HandleSpecialHashParams(n,t),n&&(i===searchType_Facility?e.HandleFacilityUrlHash(n,!1,null,t):i===searchType_GoPlay||i===searchType_Favorites?this.HandleGoPlayUrlHash(n,t,this.GetHashOmits(),!1):this.HandleGeoLocationUrlHash(n,t,this.GetHashOmits(),!1)),u=$("#main-header a.login"),u.length&&(o=u.prop("href"),u.prop("href",o+location.hash))):(i=GolfNow.Web.Utils.GetSearchTypeName(r.searchtype),i===searchType_Facility?this.HandleFacilityUrlHash(n):i===searchType_GoPlay||i===searchType_Favorites?this.HandleGoPlayUrlHash(n):i!==searchType_GeoLocation&&i!==searchType_Destination&&(f=_.extendOwn(r,_.omit(GolfNow.Web.Utils.GetRefineDefaultsLower(null,r.view),"searchtype")),n.SearchParameters.Set(f,!0),n.SaveSearchParameters(f)))};GolfNow.Web.UrlParams.PopulateSearchHeadline=function(n,t,i){var r=n?n.GetRestoreFedSearchKey():null;$.isEmptyObject(r)||(t=GolfNow.Web.Utils.GetSearchTypeName(t),t===searchType_Destination&&i&&(i.radius!==undefined||i.Radius!==undefined)&&(r.Radius=i.radius||i.Radius),n.SetRefinedResultsDisplay(r,$("#fedresults"),$(".list-refined-items")))};GolfNow.Web.UrlParams.GetHashParams=function(){for(var t={},n,r=/\+/g,u=/([^&;=]+)=?([^&;]*)/g,i=function(n){return decodeURIComponent(n.replace(r," "))},f=window.location.hash.substring(1);n=u.exec(f);)t[i(n[1]).toLowerCase()]=i(n[2]);return t};GolfNow.Web.UrlParams.NormalizeViewAndSort=function(n,t){var c=GolfNow.Web.Page.GetPageConfig(),s=[],r=[],u=function(n){return _.isUndefined(n)||_.isEmpty(n)?!1:GolfNow.Web.Utils.GetDefaultSearchView(t)===n},y=function(){GolfNow.Web.Utils.ConsoleWarn("Unable to get page config views in Url Params.");s=[{name:"Course","default":u("Course")},{name:"List","default":u("List")},{name:"Tile","default":u("Tile")},{name:"Map","default":u("Map")},{name:"Grouping","default":u("Grouping")},{name:"Map-Tile","default":u("Map-Tile")},{name:"Course-Tile","default":u("Course-Tile")}];r=[{view:"Course",sorts:[{Name:"Facilities.Weight"},{Name:"Facilities.Distance"},{Name:"Date"},{Name:"Facilities.Rating"},{Name:"GreensFees"},{Name:"Facilities.Name"}]},{view:"List",sorts:[{Name:"Facilities.Weight"},{Name:"Facilities.Distance"},{Name:"Date"},{Name:"Facilities.Rating"},{Name:"GreensFees"},{Name:"Facilities.Name"}]},{view:"Tile",sorts:[{Name:"Facilities.Weight"},{Name:"Facilities.Distance"},{Name:"Date"},{Name:"Facilities.Rating"},{Name:"GreensFees"},{Name:"Facilities.Name"}]},{view:"Map",sorts:[]},{view:"Grouping",sorts:[{Name:"GreensFees"}]},{view:"Map-Tile",sorts:[]},{view:"Course-Tile",sorts:[{Name:"Facilities.Distance"},{Name:"Facilities.Rating"},{Name:"Facilities.Name"}]}]},b=function(t){var i=_.findWhere(t,{name:n.view})||null;return i===null},p,f,i,e,l,h,a,o,w,v;if(_.isObject(c)&&_.isArray(c.Views)?(s=_.map(c.Views,function(n){return{name:n.Name,"default":n.Default}}),r=_.map(c.Views,function(n){return{view:n.Name,sorts:n.Sorts}})):y(),(_.isEmpty(s)||_.isEmpty(r))&&y(),(n.view===undefined||n.view===""||b(s))&&(p=_.findWhere(s,{"default":!0})||s[0],n.view=p.name||"Course"),typeof n.sortby=="undefined"||n.sortby===null||n.sortby===""){for(l=0;l<r.length;l++)if(h=_.findWhere(r,{view:n.view})||null,h!==null&&!_.isEmpty(h.sorts)){a=_.findWhere(h.sorts,{Default:!0})||h.sorts[0];i=a.Name;e=a.Direction;break}(typeof i=="undefined"||i===null)&&(i=r[0].sorts[0].Name,e=r[0].sorts[0].Direction)}else f=n.sortby.lastIndexOf("."),f!==-1&&(f===n.sortby.length-2||f===n.sortby.length-4||f===n.sortby.length-5)?(i=n.sortby.substr(0,f),e=n.sortby.substr(f+1)):(i=n.sortby,e=n.sortdirection||0);return n.sortdirection=e&&(e==1||e.toLowerCase()==="desc")?1:0,i==="Facilities.Rating"&&(n.sortdirection=1),o=GolfNow.Web.Search.getAllowedPageSorts(n.view),o&&o.Sorts&&o.Sorts.length?(w=_.findWhere(o.Sorts,{Name:i}),w?n.sortby=i:(v=_.findWhere(o.Sorts,{Default:!0}),n.sortby=v?v.Name:o.Sorts[0].Name)):n.sortby=i,(n.view==="Course"||n.view==="Map"||n.view==="Tile"||n.view==="Course-Tile"||n.view==="Map-Tile")&&(n.sortbyrollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(i,n.sortdirection)),GolfNow.Web.Search.handleSortState(n.view),n};GolfNow.Web.UrlParams.HandleSpecialHashParams=function(n,t){var i=this;return t=t||this.GetHashParams(),_.each(t,function(n,r,u){var e,o,s,h,f,c=window.location.search,v=function(t){t===""&&window.location.href.indexOf("?")!==-1&&(e=window.location.href,t=e.substr(e.indexOf("?"),e.indexOf("#")));n.indexOf("?")!==-1&&(n=n.substr(0,n.indexOf("?")))},y=function(n,r){GolfNow.Web.Cache.SetActiveDate(n);GolfNow.Web.Page.Pub("search_date_changed",Date.parse(GolfNow.Web.Cache.GetActiveDate()));u.date=n;GolfNow.Web.Utils.ConsoleLog("Overriding Date to:"+n);f=history.state||t;_.isEmpty(f)||delete f[r];s=i.BuildHashParamsFromSearchParams(f,f,i.GetHashOmits());h=c!==""?c:"";h+=s!==""&&s!=="#"?"#"+s:"";history.replaceState(f,null,_.isEmpty(h)?window.location.pathname:h);t=f},p,a,l,w;switch(r.toLowerCase()){case"daysout":GolfNow.Web.Cache.SetActiveDate("");v(c);p=(Number(n)||0)>=0?Number(n):0;o=GolfNow.Web.Utils.GetDateString(Date.parse("t + "+p+" d"));y(o,r.toLowerCase());break;case"weekday":GolfNow.Web.Cache.SetActiveDate("");a=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];v(c);l=isNaN(Number(n))?-1:Number(n);w=l>=0&&l<a.length?a[l]:0;o=GolfNow.Web.Utils.GetDateString(Date.parse("next "+w));y(o,r.toLowerCase())}}),t};GolfNow.Web.UrlParams.HandleFacilityUrlHash=function(n,t,i,r){var o,f,u,e,c,l;t=t||!1;r=r||null;var a=history.state,h=n.SearchParameters.GetLc(),v=GolfNow.Web.Utils.GetDefaultSearchView(1),y=viewOverrideParams.SearchParamsAction===1,s=t?i:GolfNow.Web.Utils.RedirectToFacilityUrl().toLowerCase().replace("[facilityid]",h.facilityslug||h.facilityid);if(s+=location.search,t&&s!==""){document.location.href=s;return}o=GolfNow.Web.Utils.GetRefineDefaultsLower(null,v);o.view=v;o.sortby="Date";f=this.GetHashOmits(["date","ratetype","radius","q","qc"]);o.facilityId=h.facilityid||viewOverrideParams.FacilityId;a===null?(viewOverrideParams.HotDealsOnly!==undefined&&viewOverrideParams.HotDealsOnly!==null?o.hotdealsonly=viewOverrideParams.HotDealsOnly:f.push("hotdealsonly"),f=_.uniq(f),c=r||_.omit(h,f),u=_.extendOwn(_.omit(o,f),c),y&&(u.view=viewOverrideParams.View,u.sortby=viewOverrideParams.SortBy),e=this.BuildHashParamsFromSearchParams(u,o,this.GetHashOmits(["latitude","longitude","facilityId"])),(e.indexOf("q=")>-1||e.indexOf("qc=")>-1)&&GolfNow.Web.Analytics.Google.TrackPageView(s+"?"+e),u.sortbyrollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(u.sortby,u.sortdirection),n.SearchParameters.Set(u),history.replaceState({id:h.facilityid},"Init",s+"#"+e)):(f.push("hotdealsonly"),f=_.uniq(f),c=r||_.omit(h,f),u=_.extendOwn(_.omit(o,f),c),y&&(u.view=viewOverrideParams.View,u.sortby=viewOverrideParams.SortBy),e=this.BuildHashParamsFromSearchParams(u,o,this.GetHashOmits(["latitude","longitude","facilityId"])),(e.indexOf("q=")>-1||e.indexOf("qc=")>-1)&&GolfNow.Web.Analytics.Google.TrackPageView(s+"?"+e),u.sortbyrollup=GolfNow.Web.Utils.GetSearchSortRollupFromSort(u.sortby,u.sortdirection),n.SearchParameters.Set(u),this.BackButton.Clicked()||_.isEqual(_.omit(_.pick(u,function(n){return!_.isNull(n)}),"facilityId"),_.omit(_.pick(a,function(n){return!_.isNull(n)}),"facilityId"))||history.pushState(u,null,s+"#"+e),this.BackButton.SetClicked(!1));l=n.GetRestoreFedSearchKey();$.isEmptyObject(l)||n.SetRefinedResultsDisplay(l,$("#fedresults"),$(".list-refined-items"))};GolfNow.Web.UrlParams.HandleGoPlayUrlHash=function(n,t,i,r){var g=this,l=!1,f,y,u,c,p,e,s;if(!_.contains(["private-clubs"],window.location.pathname.substr(1))){f=window.location.href;f.indexOf("#")!==-1&&(f=f.substr(0,f.indexOf("#")));n=n||searchController;i=i||["searchtype"];r=r||!1;var o=n.SearchParameters.GetLc(),h=GolfNow.Web.Utils.GetSearchTypeName(o.searchtype),a=h===searchType_Favorites,v=_.contains(["private-clubs"],window.location.pathname.substr(1)),w=_.contains(["tee-times/courses-near-me"],window.location.pathname.substr(1)),b=_.contains(["tee-times/hot-deals"],window.location.pathname.substr(1)),k=_.contains(["tee-times/best-golf-courses-near-me/search"],window.location.pathname.substr(1)),d=_.contains(["tee-times/promo-codes-and-offers"],window.location.pathname.substr(1));if((typeof t=="undefined"||t===null)&&(t=GolfNow.Web.UrlParams.GetHashParams(),t.sortbyrollup=o.sortbyrollup,t.sortby=o.sortby,t.view=o.view,t=GolfNow.Web.UrlParams.NormalizeViewAndSort(t),t=GolfNow.Web.UrlParams.HandleSpecialHashParams(n,t)),y=GolfNow.Web.Utils.GetRefineDefaultsLower(null,o.view),a||r?i.push("view","ratetype","facilityids","longitude","latitude"):i.push("promotedcampaignsonly","hotdealsonly","timemin","timemax","timeperiod","holes","list","view","sortby","ratetype","players","pricemin","pricemax","facilityids","longitude","latitude","facilitytype"),r&&(i=_.without(i,"hotdealsonly")),v&&(i=_.without(i,"longitude","latitude")),w&&(i=_.without(i,"timemin","timemax","hotdealsonly","promotedcampaignsonly")),b&&(i=_.without(i,"timemin","timemax","hotdealsonly","promotedcampaignsonly")),k&&(i=_.without(i,"timemin","timemax","hotdealsonly","promotedcampaignsonly")),d&&(i=_.without(i,"promotedcampaignsonly")),u=_.extendOwn(o,_.omit(t,i)),u.latitude=u.latitude||null,u.longitude=u.longitude||null,typeof t.latitude!="undefined"&&t.latitude!==null&&typeof t.longitude!="undefined"&&t.longitude!==null&&u.latitude!==null&&u.longitude!==null||h===searchType_Destination||viewOverrideParams.DisableLocationChange?h===searchType_Destination&&(u.latitude===null||u.longitude===null)&&(u.latitude=n.SearchParameters.Get().Latitude,u.longitude=n.SearchParameters.Get().Longitude,l=!0):(c=function(n){u.latitude=n.Latitude;u.longitude=n.Longitude;l=!0},GolfNow.Web.Client.getCurrentPosition(c,c)),p=["sortbyrollup","radius"],e=this.BuildHashParamsFromSearchParams(u,y,i.concat(p)),r)return e;(e.indexOf("q=")>-1||e.indexOf("qc=")>-1)&&GolfNow.Web.Analytics.Google.TrackPageView(f+"?"+e);n.SearchParameters.Set(u);this.BackButton.Clicked()?this.BackButton.SetClicked(!1):v?window.location.href=f+"#"+e:history.pushState(u,null,f+"#"+e);s=n.GetRestoreFedSearchKey();$.isEmptyObject(s)||(a&&(s.Location=""),n.SetRefinedResultsDisplay(s,$("#fedresults"),$(".list-refined-items")))}};GolfNow.Web.UrlParams.GetGoPlayUrlHash=function(n){return this.HandleGoPlayUrlHash(null,null,n,!0)};GolfNow.Web.UrlParams.HandleGeoLocationUrlHash=function(n,t,i,r){var e=this,o=!1,f,s,u,h;n=n||searchController;i=i||e.GetHashOmits();r=r||!1;f=n.SearchParameters.GetLc();s=GolfNow.Web.Utils.GetSearchTypeName(f.searchtype);typeof t=="undefined"||t===null?(t=GolfNow.Web.UrlParams.GetHashParams(),t.sortbyrollup=f.sortbyrollup,t.sortby=f.sortby,t.view=f.view,t=GolfNow.Web.UrlParams.NormalizeViewAndSort(t),t=GolfNow.Web.UrlParams.HandleSpecialHashParams(n,t)):t.view!==f.view&&(t=GolfNow.Web.UrlParams.NormalizeViewAndSort(t),o=!0);u=_.extendOwn(f,_.omit(t,i));u.latitude=u.latitude||null;u.longitude=u.longitude||null;u.hotdealsonly=u.hotdealsonly||!1;(typeof u.latitude=="undefined"||u.latitude===null||typeof u.longitude=="undefined"||u.longitude===null)&&s!==searchType_Destination?(h=function(n){u.latitude=n.Latitude;u.longitude=n.Longitude;o=!0},GolfNow.Web.Client.getCurrentPosition(h,h)):s===searchType_Destination&&(u.latitude===null||u.longitude===null)&&(u.latitude=n.SearchParameters.Get().Latitude,u.longitude=n.SearchParameters.Get().Longitude,o=!0);Number(t.radius)>GolfNow.Web.Utils.GetMaximumSearchRadius()&&(u.radius=GolfNow.Web.Utils.GetMaximumSearchRadius().toString(),o=!0);var c=function(t){var f,i,u;r||(GolfNow.Web.Page.Sub("beforeSearch",function(t){e.PopulateSearchHeadline(n,s,t)}),n.SearchParameters.Set(t,o),f=n.SearchParameters.Get(),n.SaveSearchParameters(f),o&&(i=window.location.href,i.indexOf("#")!==-1&&(i=i.substr(0,i.indexOf("#"))),u=e.BuildHashParamsFromSearchParams(t,n.SearchParameters.GetLc(),e.GetHashOmits()),(u.indexOf("q=")>-1||u.indexOf("qc=")>-1)&&GolfNow.Web.Analytics.Google.TrackPageView(i+"?"+u),n.IsRequestPending()?this.BackButton.Clicked()||history.pushState(t,"HandleGeoLocationUrlHash",i+"#"+u):window.location.href=i+"#"+u))},l=function(n,t){var i=$.Deferred();return t!==searchType_GeoLocation||n.address&&n.address!==""?i.resolve(n):$.when.apply(this,[GolfNow.Web.LocationServices.GeoPlacesLookup(n.latitude,n.longitude),GolfNow.Web.LocationServices.Address()]).done(function(t,r){t?(n.address=t,i.resolve(n)):(n.address=r,i.resolve(n))}),i.promise()},a=l(u,s);return a.done(c).then(function(n){if(r){var u=_.union(e.GetHashOmits(),i);return e.BuildHashParamsFromSearchParams(n,t,u)}})};GolfNow.Web.UrlParams.GetGeoLocationUrlHash=function(n){return this.HandleGeoLocationUrlHash(null,null,n,!0)};GolfNow.Web.UrlParams.GetUrlHash=function(){var i=searchController,r=i.SearchParameters.GetLc(),u=GolfNow.Web.Utils.GetSearchTypeName(r.searchtype),t=["radius","view","q","qc","longitude","latitude","sortby","searchtype"],n="";switch(u){case searchType_GoPlay:case searchType_Favorites:n=this.GetGoPlayUrlHash(t);break;default:this.GetGeoLocationUrlHash(t).done(function(t){n=t})}return n!==""?"#"+n:n};GolfNow.Web.UrlParams.BuildHashParamsFromSearchParams=function(n,t,i){for(var f=_.omit(n,function(n,r){var u=_.keys(t);return!_.contains(u,r)||_.contains(i,r)||_.isNull(n)}),u,e=Object.keys(f),o=e.length,r={};o--;)u=e[o],r[u.toLowerCase()]=f[u];return r.date&&(r.date=r.date.replace(/,/g,"")),$.param(r)};GolfNow.Web.UrlParams.isFacilitySearchType=function(n){var t=!1;switch(n){case"Facility":case"1":case 1:t=!0}return t};GolfNow.Web.UrlParams.GetHashOmits=function(n){n=n||[];var t=GolfNow.Web.FederatedSearch.getDefinedPageRefinements();return $.each(t,function(t,i){if(i.Mode===0)switch(i.Name.toLowerCase()){case"hot-deals":n.push("hotdealsonly");break;case"time":n.push("timemin","timemax");break;case"price-range":n.push("pricemin","pricemax");break;case"distance":n.push("radius");break;case"golfers":n.push("players");break;case"holes":n.push("holes");break;case"facility-type":n.push("facilitytype");break;case"rate-types":n.push("ratetype")}}),_.union(n,["searchtype","facilityid","facilityids","marketname","marketid","sortbyrollup","sortdirection","daysout","weekday","address","ratetagcodes","tags","nextavailableteetime"])};;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};
var gnRequest = GolfNow.Web.Request || {};

GolfNow.Web.Cancellation = (function ($) {
	// MEMBER VARIABLES //
	var _facilityId = '';
	var _facilityName = '';
	var _reservationId = '';
	var _facilityUrl = '';
	var _cancellationDetails = '';
	var _reservation = '';
	var _customerBenefitsSummary = '';
	var _accountBalanceTeeTime = '';
	var _newAccountBalanceTeeTime = 0;
	var _accountBalanceSiteCulture = '';
	var _newAccountBalanceSiteCulture = 0;
	var _cancellationCredits = 0;
	var _numPlayers = '';
	var _isEligible = true,
		_isCancellationProtectionEnabled = false,
		_isGPMember = false;

	var _eligibleModalId = '#EligibleModal';
	var _ineligibleModalId = '#IneligibleModal';
	var _successModalId = '#SuccessModal';
	var _reviewModalId = '#ReviewModal';
	var _failureModalId = '#FailureModal';

	var _worryFreePlayersId = '#WorryFreePlayers';
	var _eligiblePlayersId = '#EligiblePlayers';

	var _apiUrl = '';
	var _cancelCreditsUrl = '';
	var _cancellationDetailsUrl = '';
	var _requestPending = false;

	var _startingTopPos = 0;
	var _eventsBound = false;

	var _eligibleReason = 0;
	var _eligibleReasonText = '';
	var _eligiblePlayers = 0;

	// PUBLIC METHODS //
	var _init = function (apiUrl, ccUrl, cdUrl) {
		apiUrl = typeof (apiUrl) === 'undefined' ? '/api/account/reservation/cancel' : apiUrl;
		ccUrl = typeof (ccUrl) === 'undefined' ? '/api/account/cancellation-credits-summary' : ccUrl;
		cdUrl = typeof (cdUrl) === 'undefined' ? '/api/account/cancellation-details' : cdUrl;

		_apiUrl = apiUrl;
		_cancelCreditsUrl = ccUrl;
		_cancellationDetailsUrl = cdUrl;
		if(!_eventsBound) _bindEvents();
	};

	var _cancelModal = function (worryFreeEnabled,
		isEligible, reservationId, facilityId, facilityName,
		numPlayers, isGPMember, isCancellationProtectionEnabled, areaName) {

		_areaName = areaName;
		_isGPMember = isGPMember === undefined || isGPMember === null ? false : isGPMember;

		_reset();
		_worryFreeEnabled = worryFreeEnabled;
		_isEligible = isEligible;
		_reservationId = reservationId;
		_facilityId = facilityId;
		_facilityName = facilityName;
		_numPlayers = numPlayers;
		_isCancellationProtectionEnabled = isCancellationProtectionEnabled === 'true';

		getCancellationCredits();
	};

	// PRIVATE METHODS //
	var _reset = function () {
		_facilityId = '';
		_facilityName = '';
		_reservationId = '';
		_facilityUrl = '';
		_numPlayers = '';

		_requestPending = false;

		var selector = _worryFreePlayersId + ',' + _eligiblePlayersId;
		$(selector).empty();
		var option = $('<option />').val('').html('Please choose number of players.');
		$(selector).append(option);
		[1, 2, 3, 4].forEach(function (num) {
			option = $('<option />').val(num).html(num);
			$(selector).append(option);
		});
		$('.golfpass-save').hide();
		$('.golfpass-cancellation').hide();

		$('.points-refund').hide();
		$('.credit-card-refund').hide();
		$('.gift-card-refund').hide();
		$('.paypal-refund').hide();
		$('.paypal-direct-refund').hide();
		$('.account-balance-refund').hide();
	};

	var _showCancelModal = function () {
		if (_isEligible) {
			_eligibleModal(_reservationId, _facilityId, _facilityName, _numPlayers);
		} else {
			_ineligibleModal();
		}
	};

	var _affixModal = function (e) {
		if (e.namespace !== 'fndtn.reveal') return;
		var $modal = $(e.target);

		_startingTopPos = $(document).scrollTop();
		window.scrollTo(0, 0);
		GolfNow.Web.Client.ForceFullPageHeight();
		$modal.css({ top: 0 });
	};

	var _detachModal = function (e) {
		if (e.namespace !== 'fndtn.reveal') return;

		GolfNow.Web.Client.ForceDefaultPageHeight();
		$(document).scrollTop(_startingTopPos);
	};

	var _bindEvents = function () {
		_eventsBound = true;

		// BUTTON CLICK EVENTS //
		$(_successModalId).on('click', 'a.button', function () {
			window.location.href = _facilityUrl;
		});

		$(_ineligibleModalId).on('click', 'a.button', function () {
			_ineligibleModal(true);
		});

		$(_failureModalId).on('click', 'a.button', function () {
			_failureModal(true);
		});

		// MODAL DIALOG EVENTS //
		$('body')
			.on('opened.fndtn.reveal', _affixModal)
			.on('close.fndtn.reveal', _detachModal)
			.on('closed.fndtn.reveal', _successModalId, function (e) {
				if (e.namespace !== 'fndtn.reveal') return;

				location.reload(true);
			});

		$("#frmEligible").validate({
			errorElement: 'small',
			rules: {
				'EligiblePlayers': {
					required: true
				},
				'EligibleReason': {
					required: true
				}
			},
			messages: {
				'EligiblePlayers': {
					required: 'Required to continue'
				},
				'EligibleReason': {
					required: 'Required to continue'
				}
			},
			onfocusout: function (elem, evt) {
				var $elem = $(elem);
				if ($elem.valid()) {
					$elem.parent('label').removeClass('error').addClass('valid');
				} else {
					$elem.parent('label').removeClass('valid').addClass('error');
				}
			},
			submitHandler: submitEligibleModal
		});

		$("#frmReview").validate({
			submitHandler: submitReviewModal
		});
	};

	var _eligibleModal = function (reservationId, facilityId, facilityName, numPlayers) {
		_reservationId = reservationId;
		_facilityId = facilityId;
		_facilityName = facilityName;
		_numPlayers = numPlayers;

		$(_eligiblePlayersId + ' option').each(function () {
			if ($(this).val() > numPlayers) {
				$(this).remove();
			}
		});

		$(_eligibleModalId).foundation('reveal', 'open');

		TrackGoogleEvent('cancellationWorkflow', 'Cancellation Workflow', 'Impression', 'Detailed Cancellation Flow');
	};

	var _ineligibleModal = function (close) {
		close = typeof close === "undefined" ? false : Boolean(close);

		if (close)
			$(_ineligibleModalId).foundation('reveal', 'close');
		else
			$(_ineligibleModalId).foundation('reveal', 'open');
	};

	var _successModal = function () {
		var $successModal = $(_successModalId);

		setValues($successModal);

		if (!_isGPMember) {
			if (_cancellationDetails.refundable && _newAccountBalanceSiteCulture > 0)
				$('.golfpass-save').show();
			else if (!_cancellationDetails.refundable && _cancellationCredits > 0)
				$('.golfpass-cancellation').show();
		}

		$(_successModalId).foundation('reveal', 'open');
	};

	var _reviewModal = function () {
		var $reviewModal = $(_reviewModalId);

		setValues($reviewModal);

		$reviewModal.foundation('reveal', 'open');
	};

	var setValues = function($modal) {
		$modal.find('.confirmation-id').html(_cancellationDetails.reservationID);
		$modal.find('.course-name').html(_reservation.facility.name);
		$modal.find('.course-address-line1').html(_reservation.facility.address.line1);
		$modal.find('.course-address-line2').html(_reservation.facility.address.line2);
		$modal.find('.course-address-city').html(_reservation.facility.address.city);
		$modal.find('.course-address-state').html(_reservation.facility.address.stateProvinceCode);
		$modal.find('.course-address-postal').html(_reservation.facility.address.postalCode);

		$modal.find('.reservation-date').html(new Date(_reservation.teeTimeInvoice.playTime).toString('ddd., MMM dd, yyyy'));
		$modal.find('.reservation-time').html(new Date(_reservation.teeTimeInvoice.playTime).toString('h:mm tt'));
		$modal.find('.reservation-players').html(_eligiblePlayers);

		$modal.find('.cancellation-reason').html(_eligibleReasonText);

		//hide/show non-refundable subtotal box from the cancellation dialog after getting values from the API, 
		//this covers the scenario in which the user has multiple reservations, some with non-refundable subtotal and some without
		if (_reservation.teeTimeInvoice.nonRefundableSubtotal && _reservation.teeTimeInvoice.nonRefundableSubtotal.value > 0) {
			$modal.find('#non-refundable-subtotal-box').show();
			$modal.find('#non-refundable-subtotal').html(_reservation.teeTimeInvoice.nonRefundableSubtotal.formattedValue2);
		}
		else {
			$modal.find('#non-refundable-subtotal-box').hide();
		}

		var refundable = _cancellationDetails.refundable;
		if (refundable) {
			if (_cancellationDetails.loyaltyRefundableDetail) {
				var loyaltyPointsRefundable = _cancellationDetails.loyaltyRefundableDetail.pointsRefundable;
				if (loyaltyPointsRefundable && loyaltyPointsRefundable > 0.0) {
					$modal.find('.points-refund').show().find('.points-amount').html(loyaltyPointsRefundable.toFixed(2));
					$modal.find('.new-points-amount').html((_customerBenefitsSummary.golfNowRewardsSummary.availablePoints + loyaltyPointsRefundable).toFixed(2));
				}
			}

			if (_cancellationDetails.refundableDetails && _cancellationDetails.refundableDetails.distributions) {
				var teeTimeCurrencySymbol = GolfNow.Web.Currency.getSymbol(_reservation.teeTimeInvoice.currencyCode);

				_cancellationDetails.refundableDetails.distributions.forEach(function (distribution) {
					if (distribution && distribution.creditCardRefund) {
						_reservation.paymentDetails.forEach(function (paymentDetail) {
							var creditCardPayment = paymentDetail.creditCardPayment;
							if (creditCardPayment) {
								$modal.find('.new-credit-card-amount').html(creditCardPayment.creditCardType + ' ' + creditCardPayment.lastFour)
							}
						});
						$modal.find('.credit-card-refund').show().find('.credit-card-amount').html(teeTimeCurrencySymbol + distribution.creditCardRefund.amount.toFixed(2));
					}
					if (distribution.giftCardRefund)
						$modal.find('.gift-card-refund').show().find('.gift-card-amount').html(teeTimeCurrencySymbol + distribution.giftCardRefund.amount.toFixed(2));
					if (distribution.payPalRefund)
						$modal.find('.paypal-refund').show().find('.paypal-amount').html(teeTimeCurrencySymbol + distribution.payPalRefund.amount.toFixed(2));
					if (distribution.payPalDirectRefund)
						$modal.find('.paypal-direct-refund').show().find('.paypal-direct-amount').html(teeTimeCurrencySymbol + distribution.payPalDirectRefund.amount.toFixed(2));
					if (distribution.accountBalanceRefund) {
						$modal.find('.account-balance-refund').show().find('.account-balance-amount').html(teeTimeCurrencySymbol + distribution.accountBalanceRefund.amount.toFixed(2));
						_newAccountBalanceTeeTime = _accountBalanceTeeTime.value + distribution.accountBalanceRefund.amount;
						$modal.find('.new-account-balance-amount').html(teeTimeCurrencySymbol + _newAccountBalanceTeeTime.toFixed(2));

						if (_accountBalanceSiteCulture.currencyCode == _accountBalanceTeeTime.currencyCode)
							_newAccountBalanceSiteCulture = _newAccountBalanceTeeTime;
						else
							_newAccountBalanceSiteCulture = _accountBalanceSiteCulture.value;
							
						$(_successModalId).find('.golfpass-account-balance-amount').html(_accountBalanceSiteCulture.currencySymbol + _newAccountBalanceSiteCulture.toFixed(2));
					}
				});
			}

			$('.non-refundable-alert').hide();
			$('.refund-section').show();
		} else {
			$('.non-refundable-alert').show();
			$('.refund-section').hide();
		}
	}

	var _failureModal = function (close) {
		close = typeof close === "undefined" ? false : Boolean(close);

		if (close)
			$(_failureModalId).foundation('reveal', 'close');
		else {
			$(_failureModalId).foundation('reveal', 'open');
		}

		_reset();
	};

	function submitEligibleModal(form) {
		var $button = $(form['continue-button']);
		$button.attr('disabled', true).addClass('disabled').prepend('<i class="fas fa-spinner fa-spin"></i> &nbsp;');
		var eligibleReasonElem = form['EligibleReason'];
		var eligiblePlayersElem = form['EligiblePlayers'];

		_eligibleReason = eligibleReasonElem.options[eligibleReasonElem.selectedIndex].value;
		_eligibleReasonText = eligibleReasonElem.options[eligibleReasonElem.selectedIndex].text;
		_eligiblePlayers = eligiblePlayersElem.options[eligiblePlayersElem.selectedIndex].value;

		if (!_requestPending) {
			_requestPending = true;
			$.ajax({
				url: _cancellationDetailsUrl,
				method: 'post',
				datatype: 'json',
				contentType: 'application/json; charset=UTF-8',
				data: JSON.stringify({
					ReservationID: _reservationId,
					PlayersToCancel: _eligiblePlayers,
					CancellationReasonId: _eligibleReason
				})
			})
			.done(function (data) {
				if (data.success) {
					var cancelEligibleText = refundEligibleText = 'No';

					if (data.cancellationDetails.cancellable) {
						cancelEligibleText = 'Yes';

						_cancellationDetails = data.cancellationDetails;
						_reservation = data.reservation;
						_customerBenefitsSummary = data.customerBenefitsSummary;
						_accountBalanceTeeTime = data.accountBalanceTeeTime;
						_accountBalanceSiteCulture = data.accountBalanceSiteCulture;
						_reviewModal();
					} else {
						_failureModal();
					}

					if (data.cancellationDetails.refundable)
						refundEligibleText = 'Yes';

					TrackGoogleEvent('cancellationWorkflow', 'Cancellation Workflow', 'Review', 'CancelEligible: ' + (data.cancellationDetails.cancellable ? 'Yes' : 'No') + ' | RefundEligible: ' + (data.cancellationDetails.refundable ? 'Yes' : 'No'));
				}
				else {
					_failureModal();
				}
			})
			.error(function() {
				_failureModal();
			})
			.always(function () {
				_requestPending = false;
				eligibleReasonElem.value = '';
				eligiblePlayersElem.value = '';
				$button.removeAttr('disabled').removeClass('disabled').find('.fa-spinner').remove();
			});
		}
		return false;
	}

	function getCancellationCredits() {
		if (!_requestPending) {
			_requestPending = true;
			$.ajax({
				url: _cancelCreditsUrl,
				method: 'get',
				contentType: 'application/json; charset=UTF-8'
			})
			.done(function (data) {
				if (data) {
					_cancellationCredits = data.availableCredits;
					$('.worry-free-credits').text(_cancellationCredits);
				}
				_showCancelModal();
			})
			.error(function () {
				_failureModal();
			})
			.always(function () {
				_requestPending = false;
			});
		}
	}

	function submitReviewModal(form) {
		var $button = $(form['confirm-cancel-button']);
		$button.attr('disabled', true).addClass('disabled').prepend('<i class="fas fa-spinner fa-spin"></i> &nbsp;');

		if (!_requestPending) {
			_requestPending = true;
			$.ajax({
				url: _apiUrl,
				method: 'post',
				datatype: 'json',
				contentType: 'application/json; charset=UTF-8',
				data: JSON.stringify({
					ReservationID: _reservationId,
					FacilityID: _facilityId,
					PlayersToCancel: _eligiblePlayers,
					CancellationReasonId: _eligibleReason
				})
			})
			.done(function (data) {
				if (data.success) {
					_facilityUrl = data.facilityUrl;
					_successModal();
				}
				else {
					_failureModal();
				}
			})
			.always(function () {
				_requestPending = false;
				$button.removeAttr('disabled').removeClass('disabled').find('.fa-spinner').remove();

				TrackGoogleEvent('cancellationWorkflow', 'Cancellation Workflow', 'Submit', _eligiblePlayers + ' | ' + _eligibleReasonText);
			});
		}
		return false;
	}

	return {
		Init: _init,
		CancelModal: _cancelModal
	};
})(jQuery);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.FederatedSearch=function(){function o(){var i,f=0,e;$("#searchModal").on("focus","#fedsearch:text",function(){$(this).val().length>0&&$(this)[0].setSelectionRange(0,$(this).val().length)});$(".universal-search .search-bar input").focus(function(){$(".universal-search .search-refine").hide()});$(".container *:not(.container.universal-search *)").click(function(){$(".universal-search .search-refine").show()});$("#coursecontainer").hide();$("#placecontainer").hide();$(".federatedClose").click(function(){GolfNow.Web.Client.SearchController.CloseFederatedSearch(!1)});$(document).on("click","#closeBtn",function(){searchController.SetDate(i,!0);searchController.SetDisplayDates(i);GolfNow.Web.Client.SearchController.CloseFederatedSearch()}).on("change.fndtn.slider",function(n){n.namespace==="fndtn.slider"&&$("input[name='sldrRadius']").val($(n.target).attr("data-slider"))});e=function(n){if(n.originalEvent.persisted&&(f++,f<5))var t=setInterval(function(){searchController.IsRequestPending()||(GolfNow.Web.Client.SearchController.InitializeFederatedSearch(),window.clearInterval(t))},100)};$(window).on("pageshow",e);GolfNow.Web.Page.Sub("show-refine-search-clicked",function(){n=!0});GolfNow.Web.Page.Sub("show-search-filters-clicked",function(t){u=t.mediumOverride||!1;(Foundation.utils.is_small_only()||u)&&(n=!0)});GolfNow.Web.Page.Sub("edit-search-clicked",function(){n=!1});GolfNow.Web.Page.Sub("homepage-edit-search-clicked",function(){t=!0;n=!1});GolfNow.Web.Page.Sub("filter-option-changed",function(n){var t=_.debounce(s,300,!0);t(n)});r=GolfNow.Web.Search}function i(n){var t=n.SearchParameters.Get();f(t);Foundation.utils.is_small_only()&&$("h2.federatedSearchHeading").text("Filter Search")}function f(n,t){if(_.isObject(n)){var h=Number(n.TimeMin||GolfNow.Web.Utils.GetMinTimePeriodValue()),c=Number(n.TimeMax||GolfNow.Web.Utils.GetMaxTimePeriodValue()),l=Number(n.PriceMin||GolfNow.Web.Utils.GetPriceFloor()),a=Number(n.PriceMax||GolfNow.Web.Utils.GetPriceCeiling()),u=Number(n.Radius||GolfNow.Web.Utils.GetDefaultSearchRadius(null,n.View)),v=Number(n.Holes)||3,y=Number(n.Players)||0,p=n.HotDealsOnly||!1,w=n.PromotedCampaignsOnly||!1,r=n.Date,b=Number(n.FacilityType)||0,k=n.RateType||GolfNow.Web.Utils.GetDefaultRateType(),f=n.View,e=n.SortBy,o=n.SortByRollup,s=n.SortBy!==""?n.SortDirection:"",i=document.querySelector("gn-search-filters");i&&(i.setAttribute("timemin",h),i.setAttribute("timemax",c),i.setAttribute("pricemin",l),i.setAttribute("pricemax",a),i.setAttribute("radius",u),i.setAttribute("hotdealsonly",p),i.setAttribute("promotedcampaignsonly",w),i.setAttribute("holes",v),i.setAttribute("players",y),i.setAttribute("date",r),i.setAttribute("facilitytype",b),i.setAttribute("ratetype",k),i.setAttribute("view",f),i.setAttribute("sortby",e),i.setAttribute("sortbyrollup",o),i.setAttribute("sortdirection",s));t&&(t.date!==r&&GolfNow.Web.Page.Pub("search_date_changed",Date.parse(r)),$.observable(t).setProperty({radius:u,date:Date.parse(r).toDateDisplayString(),view:f,sortBy:e,sortByRollup:o,sortDirection:s}))}}function s(n){var t=document.querySelector("gn-search-filters"),o=[Number(t.getAttribute("pricemin")),Number(t.getAttribute("pricemax"))],r=[Number(t.getAttribute("timemin")),Number(t.getAttribute("timemax"))],l=Number(t.getAttribute("radius"))||GolfNow.Web.Utils.GetDefaultSearchRadius(null,GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")),a=Number(t.getAttribute("players")),v=Number(t.getAttribute("holes")),y=t.getAttribute("hotdealsonly"),p=t.getAttribute("promotedcampaignsonly"),w=t.getAttribute("facilitytype"),b=t.getAttribute("ratetype"),k=t.getAttribute("sortby"),d=t.getAttribute("sortbyrollup"),g=t.getAttribute("sortdirection"),nt=t.getAttribute("view"),i,u,f,s,c,h;r[0]<=GolfNow.Web.Utils.GetMinTimePeriodValue()&&(r[0]=GolfNow.Web.Utils.GetMinTimePeriodValue());r[1]>=GolfNow.Web.Utils.GetMaxTimePeriodValue()&&(r[1]=GolfNow.Web.Utils.GetMaxTimePeriodValue());o[1]>=130&&(o[1]=GolfNow.Web.Utils.GetPriceCeiling());i={HotDealsOnly:y,PromotedCampaignsOnly:p,Radius:l,Players:a,Holes:v,PriceMin:o[0],PriceMax:o[1],TimeMin:r[0],TimeMax:r[1],FacilityType:w,RateType:b,SortBy:k,SortByRollup:d,SortDirection:g,View:nt};u=n.SearchParameters.Get();i.SearchType=u.SearchType;f=n.GetPickerSelectedDate();f&&(n.SetNavDatePickerDate(f),n.SetDate(f,!0));s=GolfNow.Web.Utils.GetSearchTypeName(u.SearchType);switch(s){case 1:case searchType_Facility:var tt=u.FacilityId||viewOverrideParams.FacilityId,it=u.FacilityName||viewOverrideParams.FacilityName,e=GolfNow.Web.Utils.RedirectToFacilityUrl().toLowerCase().replace("[facilityid]",tt);e=e.substring(0,e.lastIndexOf("/"));f||(i.Date=u.Date);n.SearchParameters.Set(i,!0);c=!window.location.pathname.startsWith(e);GolfNow.Web.UrlParams.HandleFacilityUrlHash(n,c,e+"/search");GolfNow.Web.Client.SearchController.CloseFederatedSearch();break;default:n.SaveCurrentFederatedSearchParameters();n.ShouldRedirectOnSearch()?s===searchType_Favorites||s===searchType_GoPlay?GolfNow.Web.UrlParams.HandleGoPlayUrlHash(n,i):n.RedirectToCustomSearchPage(i):(n.SearchParameters.Set(i),n.SaveSearchParameters(i),h=n.GetRestoreFedSearchKey(),h&&n.SetRefinedResultsDisplay(h,$("#fedresults"),$(".list-refined-items")));GolfNow.Web.Client.SearchController.CloseFederatedSearch()}}function h(r){var h;GolfNow.Web.Utils.ConsoleLog("GeoPlace Handler");var e=r.id,f=r.name,o=r.lat,s=r.lon,c=r.searchTerm,l=r.sortBy,u={Latitude:o,Longitude:s,SearchType:searchType_GeoLocation,View:GolfNow.Web.Utils.GetDefaultSearchView("GeoLocation"),Address:f,PageNumber:0,Q:c||f,QC:"GeoLocation",sortBy:l};searchController.SearchParameters.Set(u,!0);searchController.SaveFederatedSearchParameters(u);e!==null&&e!==""&&searchController.AddRecentSearch(e,f,"GEOLOCATION",o,s,null);$("#fedsearch").val(f);i(searchController);h=GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType);n||t||!Foundation.utils.is_small_only()||h!==searchType_GeoLocation?(u.View=null,u.SortBy=null,u.SortByRollup=null,searchController.RedirectToCustomSearchPage(u)):$("#applyBtn").click()}function c(r,u){searchController.SearchParameters.Set({FacilityId:r,SearchType:searchType_Facility,FacilityName:u,Q:u,QC:"Course"},!0);searchController.AddRecentSearch(r,u,"FACILITY");$("#fedsearch").val(u);i(searchController);var f=GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType);n||t||!Foundation.utils.is_small_only()||f!==searchType_Facility?a(r):$("#applyBtn").click()}function l(){GolfNow.Web.LocationServices.HasGPS&&GolfNow.Web.LocationServices.LocateMe(!0,function(r){$("input#fedsearch").val(r.Address);$(".universal-search.front-ver-b.front-ver-b-on #geo_msg").text(r.State.message);$(".federatedNearMe > a.nearMeLink > span").text(r.State.message);var u={SearchType:searchType_GeoLocation,Latitude:r.Latitude,Longitude:r.Longitude,Address:r.Address,Radius:GolfNow.Web.Utils.GetDefaultSearchRadius(null,GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")),Q:"lat:"+r.Latitude+",lng:"+r.Longitude,QC:"GeoLocation"};searchController.ResetAdvancedSearchParams();searchController.SearchParameters.Set(u,!0);searchController.SaveFederatedSearchParameters(u);i(searchController);n||t||!Foundation.utils.is_small_only()?GolfNow.Web.Client.SearchController.ShowRefineSearch():$("#applyBtn").click()},function(r){GolfNow.Web.LocationServices.Address_City().done(function(){$("input#fedsearch").val(r.Address);$(".universal-search.front-ver-b.front-ver-b-on #geo_msg").text(r.State.message);$(".federatedNearMe > a.nearMeLink > span").text(r.State.message);var u={SearchType:searchType_GeoLocation,Latitude:r.Latitude,Longitude:r.Longitude,Address:r.Address,Radius:GolfNow.Web.Utils.GetDefaultSearchRadius(null,GolfNow.Web.Client.SearchController.GetSearchParameterValue("View")),Q:"lat:"+r.Latitude+",lng:"+r.Longitude,QC:"GeoLocation"};searchController.ResetAdvancedSearchParams();searchController.SearchParameters.Set(u,!0);searchController.SaveFederatedSearchParameters(u);i(searchController);n||t||!Foundation.utils.is_small_only()?GolfNow.Web.Client.SearchController.ShowRefineSearch():$("#applyBtn").click()})},!0)}function a(n){redirectToFacilityLink=redirectToFacilityLink.toLowerCase().replace("[facilityid]",n);window.location=redirectToFacilityLink}function v(n){var r=e(),t=n||[],i=$(".search-options-wrap");$.each(r,function(n,r){if(_.isArray(t)&&t.length>0){var u=_.findWhere(t,{Name:r.Name})||null;u&&(r.Mode=u.Mode)}switch(r.Mode){case 0:i.find("."+r.Name.toLowerCase()).hide();break;case 1:i.find("."+r.Name.toLowerCase()).show()}})}function e(){var t=[],n=GolfNow.Web.Page.GetPageConfig();return _.isObject(n)&&_.isObject(n.Refinements)?t=n.Refinements:GolfNow.Web.Utils.ConsoleWarn("Unable to get defined page refinements in FederatedSearch"),t}function y(){var n=GolfNow.Web.Page.GetPageConfig();return _.isNull(n)?(GolfNow.Web.Utils.ConsoleWarn("::getViewDisplayNames::Unable to get page config"),{}):_.map(n.Views,function(n){return{name:n.Name,"default":n.Default,display:n.Display||n.Name}})}function p(){var n=GolfNow.Web.Page.GetPageConfig(),t=GolfNow.Web.Utils.GetSortDisplayNameMappings();return n&&n.Views&&!_.isEmpty(n.Views)?_.map(n.Views,function(n){var i=_.map(n.Sorts,function(n){var i=_.findWhere(t,{key:n.Name})||null;return i!==null?_.extendOwn({Display:i.display},n):n});return{view:n.Name,sorts:i}}):(GolfNow.Web.Utils.ConsoleWarn("::getSortDisplayNames::Unable to get page config"),[{view:"",sorts:[]}])}function w(n){var r="",u=_.findWhere(GolfNow.Web.FederatedSearch.GetSortDisplayNames(),{view:n.view})||null,t=u!==null?u.sorts:[],i;try{$.observable(n.sortDisplayNames).refresh(t)}finally{return t&&t.length>0?(i=_.findWhere(n.sortDisplayNames,{Name:n.sortBy})||null,i!==null&&(r=i.Display),$(document).foundation("dropdown","reflow")):$.observable(n).setProperty({sortBy:"",sortByRollup:""}),r}}function b(n,t){var u="",f=_.findWhere(GolfNow.Web.FederatedSearch.GetSortDisplayNames(),{view:n})||null,i=f!==null?f.sorts:[],r;return i&&i.length>0&&(r=_.findWhere(i,{Name:t})||null,r!==null&&(u=r.Display)),{display:u,sortDisplayNames:i}}function k(n,t,i,u){var o,f,h,s,c,e;if(searchController.teeTimesLoading)return!1;if(o=t+"|"+i,f=null,_.isString(o)&&o!==""){if(h=searchController.SearchParameters.Get(),!r.isSortAllowed(o,n.view)){GolfNow.Web.Page.Pub("close-result-action-menus");return}if(s=document.querySelector("gn-search-filters"),s.getAttribute("sortby")!==t){s.setAttribute("sortdirection",t!==""?i:"");s.setAttribute("sortby",t);f=GolfNow.Web.FederatedSearch.SetSortDisplay(n.view,t);f!==null&&f.display!==""&&$.observable(n).setProperty("sortDisplay",f.display);GolfNow.Web.Page.Pub("close-result-action-menus");return}c=h.SortBy+"|"+h.SortDirection;c!==o?(e=searchController.ChangeSort(o,u),f=GolfNow.Web.FederatedSearch.SetSortDisplay(n.view,e.sortBy),e.sortDirection=e.sortBy!==""?e.sortDirection:"",s.setAttribute("sortbyrollup",e.sortByRollup),s.setAttribute("sortdirection",e.sortDirection),$.observable(n).setProperty({sortBy:e.sortBy,sortByRollup:e.sortByRollup,sortDirection:e.sortDirection,sortDisplay:f.display})):(f=GolfNow.Web.FederatedSearch.SetSortDisplay(n.view,t),$.observable(n).setProperty({sortBy:t,sortByRollup:GolfNow.Web.Utils.GetSearchSortRollupFromSort(t,i),sortDirection:t!==""?i:"",sortDisplay:f.display}));f!==null&&$.observable(n.sortDisplayNames).refresh(f.sortDisplayNames);GolfNow.Web.Page.Pub("close-result-action-menus")}}function d(n,t,i){var e,f,u,o;searchController.teeTimesLoading||(e=document.querySelector("gn-search-filters"),e.getAttribute("view")!==t&&e.setAttribute("view",t),f=GolfNow.Web.FederatedSearch.SetSortDisplay(t,n.sortBy),f.display===""&&$.observable(n).setProperty({sortBy:"",sortDisplay:f.display,sortDisplayNames:f.sortDisplayNames}),u=searchController.SearchParameters.Set(n,!0),u=searchController.ChangeView(t,u,i),r.handleSortState(),$.observable(n).setProperty("view",t),o=GolfNow.Web.FederatedSearch.SetObservableSortDisplay(n),u.SortBy!==""&&n.sortBy!==u.SortBy?($.observable(n).setProperty({sortBy:u.SortBy,sortByRollup:u.SortByRollup,sortDirection:u.SortDirection}),f=GolfNow.Web.FederatedSearch.SetSortDisplay(n.view,n.sortBy),f.display!==""&&$.observable(n).setProperty("sortDisplay",f.display)):n.sortDisplay===""&&o!==""&&$.observable(n).setProperty("sortDisplay",o))}function g(n,t){GolfNow.Web.Utils.GetSearchTypeName(n)===searchType_Facility&&GolfNow.Web.Cache.SetFacilityViewOption(t)}function nt(n,t){var i;switch(n){case"hotdealsonly":i=t;break;case"promotedcampaignsonly":i=t;break;case"pricemin":i=t;break;case"pricemax":i=t;break;case"timemin":i=GolfNow.Web.Utils.GetTimePeriodString(t);break;case"timemax":i=GolfNow.Web.Utils.GetTimePeriodString(t);break;case"players":switch(t){case"1":case 1:i="1";break;case"2":case 2:i="2";break;case"3":case 3:i="3";break;case"4":case 4:i="4";break;default:i="Any"}break;case"holes":switch(t){case"1":case 1:i="9";break;case"2":case 2:i="18";break;default:i="Any"}break;case"facilitytype":i=t}TrackGoogleEvent("filterRefine","Filter Refine","Apply",n+": "+i,i)}var n=!1,t=!1,u=!1,r=null;return{initPage:o,ShowAdvancedSearch:i,facilityHandler:c,geoPlaceHandler:h,nearmeHandler:l,handlePageRefinements:v,getDefinedPageRefinements:e,SetSearchFilters:f,GetViewDisplayNames:y,GetSortDisplayNames:p,SetObservableSortDisplay:w,SetSortDisplay:b,SetObservableSortOption:k,SetObservableViewOption:d,StoreUserFacilityViewOption:g,TrackApplyFilterAnalyticValue:nt}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.GeoPlaces=function(n){function e(n,t){var i=null,r=_.filter(n,function(n){return n.displayName.toLowerCase().startsWith(t.toLowerCase())}),u;return r.length&&(i=_.max(r,function(n){return n.contextInformation.score}),r.length===1?i=r[0]:(u=_.sortBy(r,function(n){return-n.contextInformation.score}),u[1].type!==i.type&&(i=_.find(n,function(n){return n.contextInformation.score===i.contextInformation.score&&n.displayName.toLowerCase().startsWith(t.toLowerCase())})))),i||n[0]}function o(){var t=n("#fed-search-big-date").pickadate({onSet:function(n){typeof lzTranslateDatepicker!="undefined"&&lzTranslateDatepicker(n.select,"#fed-search-big-date")}}).pickadate("picker");t.open(!1);_.delay(function(){t.focus()},150)}function s(n){i.SearchBtn_Event(n)}var t=null,i={},r=[],u=[],f="/api/autocomplete/geoselection/";return i={TypeAheadWrapper:function(t,r,u,f,o,s){var h=n("#federatedResultsLocations .federatedSearchResults ul, #federatedResultsCourses .federatedSearchResults ul"),c=n("#federatedResultsLocations .federatedSearchResults p, #federatedResultsCourses .federatedSearchResults p");h.hide();c.show();GolfNow.Web.LocationServices.GeoCoordinates().done(function(l){var a=l.Lat,v=l.Long;i.GetTypeAheadResults(t,f,a,v,o).done(function(i){var c=null,w=i.count,s=i.hits,h=_.groupBy(s,function(n){return n.type}),l=h.course||[],v=h.city||[],y=h.postal||[],p=h.place||[],a=_.uniq(_.union(v,p,y),function(t){return n.trim(t.displayName)});s&&s.length&&(c=e(s,t));l=_.sortBy(l,function(n){return-n.contextInformation.score});a=_.sortBy(a,function(n){return-n.contextInformation.score});r(l,t,o===0?!1:!0,c);u(a,t,f,c)}).fail(function(){}).always(function(){c.hide();h.show();typeof s!="undefined"&&s&&s()})})},TypeAheadWrapper2:function(t,f,o,s,h,c,l){var a=_.debounce(function(){n.observable(f).setProperty({allCoursesCount:0,allLocationsCount:0});n.observable(f.courses).refresh([]);n.observable(f.locations).refresh([])},300,!0),v=_.debounce(l,600,!1);GolfNow.Web.LocationServices.GeoCoordinates().done(function(y){var p=y.Lat,w=y.Long;i.GetTypeAheadResults(t,h,p,w,c).done(function(i){var l=null,g=i.count,p=i.hits,w=_.groupBy(p,function(n){return n.type}),a=w.course||[],b=w.city||[],k=w.postal||[],d=w.place||[],v=_.uniq(_.union(b,d,k),function(t){return n.trim(t.displayName)}),y;p&&p.length&&(l=e(p,t));y=f.searchPreviewLimit;a!==undefined&&a.length&&(l&&l.type==="course"&&n.observable(f).setProperty("topScoredItem",l),r=[],a.length>y&&(r=a),n.observable(f).setProperty("allCoursesCount",a.length),n.observable(f.courses).refresh(a.slice(0,y)));l&&l.type!=="course"&&n.observable(f).setProperty("topScoredItem",l);u=[];v.length>y&&(u=v);n.observable(f).setProperty("allLocationsCount",v.length);n.observable(f.locations).refresh(v.slice(0,y));o&&o(a,f,t,c===0?!1:!0,l);s&&s(v,f,t,h,l)}).fail(a).always(function(){l&&v();n.observable(f).setProperty("searching",!1)})})},TypeAheadWrapperReviews:function(t,u,f,e,o,s){var h=_.debounce(function(){n.observable(u).setProperty({allCoursesCount:0,allLocationsCount:0});n.observable(u.courses).refresh([]);n.observable(u.locations).refresh([])},300,!0),c=_.debounce(s,600,!1);GolfNow.Web.LocationServices.GeoCoordinates().done(function(){i.GetTypeAheadReviewsResults(t,e,o).done(function(i){var e=i,s=u.searchPreviewLimit;e!==undefined&&e.length&&(r=[],e.length>s&&(r=e),n.observable(u).setProperty("allCoursesCount",e.length),n.observable(u.courses).refresh(e.slice(0,s)));f&&f(e,u,t,o===0?!1:!0,null)}).fail(h).always(function(){s&&c()})})},TypeAheadWrapperInstructor:function(t,r,f,o,s,h){var c=_.debounce(function(){n.observable(r).setProperty({allCoursesCount:0,allLocationsCount:0});n.observable(r.locations).refresh([])},300,!0),l=_.debounce(h,600,!1);GolfNow.Web.LocationServices.GeoCoordinates().done(function(){i.GetTypeAheadInstructorLocationResults(t,o,s).done(function(i){var s=null,c=i.hits,l=_.groupBy(c,function(n){return n.type}),v=l.city||[],y=l.postal||[],p=l.place||[],h=_.uniq(_.union(v,p,y),function(t){return n.trim(t.displayName)}),a;c&&c.length&&(s=e(c,t));a=r.searchPreviewLimit;s&&s.type!=="course"&&n.observable(r).setProperty("topScoredItem",s);u=[];h.length>a&&(u=h);n.observable(r).setProperty("allLocationsCount",h.length);n.observable(r.locations).refresh(h.slice(0,a));f&&f(h,r,t,o,s)}).fail(c).always(function(){h&&l();n.observable(r).setProperty("searching",!1)})})},PreviousSearchesClickHandler:function(t,r){var u=r.view.data,f=Foundation.utils.is_medium_up()||Foundation.utils.is_small_only()&&GolfNow.Web.Utils.GetServerDisplayMode()==="large",s=f?n("#fed-search-big"):n("#fedsearch"),e=null,o="";switch(u.searchType){case"GEOLOCATION":e=f?i.Location_Click:i.RefineLocation_Click;o="location";break;case"FACILITY":e=f?i.Course_Click:i.RefineCourse_Click;o="course"}e({data:{$textbox:s,$resultsList:n("#autocomplete-wrapper"),id:u.id,name:u.label,lat:u.lat,lon:u.long,viewport:u.geometryViewPort,nextElem:"searchBtn",searchType:o,searchTerm:s.val()||"",sortBy:defaultListSort}})},CourseResultsClickHandler:function(t,r){var u=r.view.data,f=Foundation.utils.is_medium_up()||Foundation.utils.is_small_only()&&GolfNow.Web.Utils.GetServerDisplayMode()==="large",o=f?i.Course_Click:i.RefineCourse_Click,e=f?n("#fed-search-big"):n("#fedsearch");o({data:{$textbox:e,$resultsList:n("#autocomplete-wrapper"),id:u.contextInformation.courseId||u.contextInformation.ids?.golfFacilityID||u.contextInformation.ids?.courseInfoId,eid:u.id,name:u.displayName,lat:u.geo.lat,lon:u.geo.lon,nextElem:"searchBtn",searchType:"course",searchTerm:e.val()||"",sortBy:defaultListSort}})},LocationResultsClickHandler:function(t,r){var u=r.view.data,f=Foundation.utils.is_medium_up()||Foundation.utils.is_small_only()&&GolfNow.Web.Utils.GetServerDisplayMode()==="large",o=f?i.Location_Click:i.RefineLocation_Click,e=f?n("#fed-search-big"):n("#fedsearch");o({data:{$textbox:e,$resultsList:n("#autocomplete-wrapper"),id:u.mongoId,eid:u.id,name:u.displayName,lat:u.geo.lat,lon:u.geo.lon,nextElem:"searchBtn",searchType:"location",searchTerm:e.val()||"",sortBy:defaultListSort}})},LoadMoreCoursesClickHandler:function(t,i){var u=i.view.data;return n.observable(u.courses).insert(u.courses.length,r.slice(u.searchPreviewLimit)),!1},LoadMoreLocationsClickHandler:function(t,i){var r=i.view.data;return n.observable(r.locations).insert(r.locations.length,u.slice(r.searchPreviewLimit)),!1},GetTypeAheadResults:function(i,r,u,f,e){var o=n.Deferred(),s;return t&&t.readystate!==4&&t.abort(),s={searchkey:i,take:r,skip:e},u!==undefined&&u!==0&&f!==undefined&&f!==0&&(s.lat=u,s.lng=f),t=n.ajax({url:"/api/autocomplete/geolookup",method:"POST",dataType:"json",contentType:"application/json; charset=utf-8",data:JSON.stringify(s),success:function(n){o.resolve(n)},error:function(n,t){t==="abort"?o.reject():o.resolve({})},always:function(){t=null}}),o.promise()},GetTypeAheadReviewsResults:function(i,r,u){var f=n.Deferred(),e;return t&&t.readystate!==4&&t.abort(),e={searchkey:i,take:r,skip:u},t=n.ajax({url:"/api/tee-times/reviews-course-results",method:"POST",dataType:"json",contentType:"application/json; charset=utf-8",data:JSON.stringify(e),success:function(n){f.resolve(n)},error:function(n,t){t==="abort"?f.reject():f.resolve({})},always:function(){t=null}}),f.promise()},GetTypeAheadInstructorLocationResults:function(i,r,u){var f=n.Deferred(),e;return t&&t.readystate!==4&&t.abort(),e={searchkey:i,take:r,skip:u},t=n.ajax({url:"/api/autocomplete/geolookup",method:"POST",dataType:"json",contentType:"application/json; charset=utf-8",data:JSON.stringify(e),success:function(n){f.resolve(n)},error:function(n,t){t==="abort"?f.reject():f.resolve({})},always:function(){t=null}}),f.promise()},RefineCourse_Click:function(t){var i=t.data.id,r=t.data.name,u=n("#fedsearch").val();t.data.eid&&t.data.eid!==""&&GolfNow.Web.Request.Post("log-search-selection",f+t.data.eid,JSON.stringify(u));GolfNow.Web.FederatedSearch.facilityHandler(i,r)},RefineLocation_Click:function(t){var r=t.data.id,u=t.data.name,i=n("#fedsearch").val();t.data.eid&&t.data.eid!==""&&GolfNow.Web.Request.Post("log-search-selection",f+t.data.eid,JSON.stringify(i));GolfNow.Web.FederatedSearch.geoPlaceHandler(t.data)},Course_Click:function(t){var r,f,i,u;if((!t||!t.type||t.type==="click"||t.type==="keypress"||t.keyCode===13)&&(t.type!==undefined||t.data!==undefined)){r=t.data.nextElem||"searchBtn";f=n(this);f.context!==undefined&&f.parents(".autocomplete-results").hide();i=t.data.$textbox;u=t.data.$resultsList;i.length?(i.data().searchData=t.data,i.val(t.data.name),document.activeElement.id===i.attr("id")||document.activeElement.nodeName.toLowerCase()==="body"?i.trigger("blur",!0):r=""):(searchData=searchData,r="");u&&u.length&&u.hide();switch(r==="date"){case"date":o();break;default:s(i.length?i.data().searchData:searchData)}}},Location_Click:function(t){var r,f,i,u;if((!t||!t.type||t.type==="click"||t.type==="keypress"||t.keyCode===13)&&(t.type!==undefined||t.data!==undefined)){r=t.data.nextElem||"searchBtn";f=n(this);f.context!==undefined&&f.parents(".autocomplete-results").hide();i=t.data.$textbox;u=t.data.$resultsList;i.length?(i.data().searchData=t.data,i.val(t.data.name),document.activeElement.id===i.attr("id")||document.activeElement.nodeName.toLowerCase()==="body"?i.trigger("blur",!0):r=""):(searchData=t.data,r="");u&&u.length&&u.hide();switch(r==="date"){case"date":o();break;default:s(i.length?i.data().searchData:searchData)}}},SearchBtn_Event:function(t){var l=n(this),r=t.id,i=t.name,u=t.eid||"",a=t.$resultsList,e=t.searchTerm,o;if(l.parents(".autocomplete-results").hide(),t.searchType==="course"&&r)o=function(){searchController.SearchParameters.Set({FacilityId:r,SearchType:searchType_Facility,FacilityName:i,Q:i,QC:"Course"},!0);searchController.AddRecentSearch(r,i,"FACILITY");redirectToFacilityLink=redirectToFacilityLink.toLowerCase().replace("[facilityid]",r);GolfNow.Web.UrlParams.HandleFacilityUrlHash(searchController,!0,redirectToFacilityLink)},searchController&&(u!==""?GolfNow.Web.Request.Post("log-search-selection",f+u,JSON.stringify(e)).always(o):o());else if(t.searchType==="location"&&t.lat&&(t.lng||t.lon)){var s=t.lat,h=t.lng||t.lon,c=function(){var n={Latitude:s,Longitude:h,SearchType:searchType_GeoLocation,View:GolfNow.Web.Utils.GetDefaultSearchView("GeoLocation"),Address:i,PageNumber:0,Q:e||i,QC:"GeoLocation"},t;searchController.AddRecentSearch(r,i||e,"GEOLOCATION",s,h,null);t=GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType);t!==searchType_GeoLocation&&(n.SortBy=null,n.SortByRollup=null,n.View=null);searchController.RedirectToCustomSearchPage(n)};searchController&&(u!==""?GolfNow.Web.Request.Post("log-search-selection",f+u,JSON.stringify(e)).always(c):c())}else alert("Please retry your search entry."),n("#fed-search-big").trigger("focus")}}}(jQuery);;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

///****** Self-Initializing object ******///
GolfNow.Web.Gifting = (function ($) {
    //****** Private methods & routings ******//

    /// analytics tracking of clicks
    function trackGiftClick(giftUrl, facilityId) {
        // parse out everyting up to widget/
        var startPos = giftUrl.indexOf('/widget/');
        if (startPos > -1) {
            var data = { event: 'itsonme' };
            var pageName = 'Reservation Details';
            var url = giftUrl.substring(startPos + '/widget/'.length);
            var urlParts = url.split('-');
            var itsOnMeId = urlParts[1];
            var facilityName = _.reduce(_.rest(urlParts, 1), function (memo, part) { return memo + '-' + part; });
            facilityName += '-' + facilityId;

            var pageUrlParts = _.without(document.location.pathname.split('/'), '');
            switch (pageUrlParts[0]) {
                case 'courses':
                    pageName = 'Course Details';
                    break;
                case 'tee-times':
                    pageName = 'Confirmation';
                    break;
                case 'account':
                    pageName = 'Reservation Details';
                    break;
                default:
                    pageName = 'Reservation Details';
                    break;
            }

            data.parameters = { SearchType: pageName };
            data.searchEventLabel = facilityName;
            dataLayer.push(data);
        }
    }

    ///******* Public Methods Object***********///
    var giftingObj = {

        AddClickHandler: function (containerSelectorId, giftUrl, modalTitle, facilityId) {
            $(containerSelectorId).on('click', '#lnk-gift-this-course', function (evt) {
                trackGiftClick(giftUrl, facilityId);

                if (Foundation.utils.is_small_only()) {
                    window.open(giftUrl, '_blank');
                } else {
                var $iframe = $('<iframe />', {
                    'id': 'itsonmeiframe',
                    'src': giftUrl,
                    'width': '100%',
                    'height': '500px',
                    'frameborder': '0',
                    'marginwidth': '0',
                    'marginheight': '0',
                    'scrolling': 'auto'
                });
                var html = $iframe[0].outerHTML;
                showHtmlMessage('<span>' + modalTitle + '</span>', html, null);
                }
            });
        }
    }

    /// Return the public object
    return giftingObj;
})(jQuery);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Search=function(n){function yi(){searchController.SearchParameters.Get().View==="Map"||nt.is(":visible")||g.show().scrollTo()}function pi(){var o,r;if($("#inputCurrentDate").detach().appendTo(".off-canvas-wrap"),o=0,r=$("#inputCurrentDate").pickadate({format:GolfNow.Web.Utils.GetDefaultDateFormatString().toLowerCase(),disable:GolfNow.Web.Search.GetExludedDayIds(),min:!0,max:GolfNow.Web.Utils.GetMaximumCalendarDays(),close:"Close",clear:"",onOpen:GolfNow.Web.Search.DatePickerOnOpenHandler,onClose:GolfNow.Web.Search.DatePickerOnCloseHandler}),r.length>0&&!ut){var e=searchController.SearchParameters.Get(),u=GolfNow.Web.Utils.GetSearchTypeName(searchController.SearchParameters.Get().SearchType),i=u==="Facility",f=e.FacilityName,s=e.FacilityId,t=r.pickadate("picker"),h=_.once(function(){$(document).on("click","#dayPicker",function(n){if(GolfNow.Web.Page.Pub("close-result-action-menus"),t.refine=!1,t.get("open"))t.close();else{var r=window.location.pathname;TrackGoogleEvent("filterRefine","Filter Refine","Click","Date|"+r.substr(r.lastIndexOf("/")+1));_.isUndefined(f)||_.isNull(f)||!i||TrackGoogleEvent("enhancedDatePicker","Enhanced Date Picker","Impression","Enhanced|"+f.replaceAll("+"," ")+"|"+s);t.open()}n.stopPropagation()});$(document).on("click","#refineDayPicker",function(n){if(t.refine=!0,t.get("open"))t.close();else{var i=window.location.pathname;TrackGoogleEvent("filterRefine","Filter Refine","Click","Date|"+i.substr(i.lastIndexOf("/")+1));t.open()}n.stopPropagation()});t.on("set",function(t){if(t.select){var r=new n(t.select),f=$(this)[0],e=u==="GoPlay",s=u==="Favorites",o=r.toDateDisplayString();$("#currentDateRefineText").html(o);$("#search-header-date").html(o);typeof lzTranslateDatepicker!="undefined"&&(lzTranslateDatepicker(t.select,f),lzTranslateDatepicker(t.select,'[data-link="date"]'),lzTranslateDatepicker(t.select,"#fed-search-big-date"),lzTranslateDatepicker(t.select,"#search-header-date"),lzTranslateDatepicker(t.select,"#currentDateRefineText"),lzTranslateDatepicker(t.select,"#currentDateText"));searchController.SavePickerSelectedDate(r);GolfNow.Web.Page.Pub("search_date_changed",r);(!f.refine||i||e)&&!hi.IsHomePageSearch()&&(searchController.SetDate(r,!i&&!e||f.refine),i||e||searchController.RedirectToCustomSearchPage(searchController.SearchParameters.Get()))}});var o=GolfNow.Web.Cache.GetActiveDate(),r=n.parse(o),e=o.toDateDisplayString();t&&t.set("select",[r.getFullYear(),r.getMonth(),r.getDate()],{muted:!0});$("#search-header-date").html(e);$("#currentDateText").html(e);$("#currentDateRefineText").html(e);ut=!0;_.delay(GolfNow.Web.Page.Pub,300,"search-date-picker-bound",null)});t.on("render",vi);h()}}function wi(){var t,e,h,c;if(searchController!==null){var r,u=searchController.SearchParameters.Get(),i=u.FacilityId,f=u.FacilityName,o=n.today();if(u.SearchType===1&&(t=$("#inputCurrentDate_root"),t.length>0)){t.find("[data-nav='1']").on("click",function(){s.addMonths(1);TrackGoogleEvent("enhancedDatePicker","Enhanced Date Picker","Click","Next Month|"+f.replaceAll("+"," ")+"|"+i)});t.find("[data-nav='-1']").on("click",function(){o<s&&s.addMonths(-1);TrackGoogleEvent("enhancedDatePicker","Enhanced Date Picker","Click","Previous Month|"+f.replaceAll("+"," ")+"|"+i)});if(s=bi(t,o,u.Date,s),e=s.toString("yyyy-MM-dd"),n.parse(e)!==null&&(h=n.parse(e).addDays(45).toString("yyyy-MM-dd")),r=s.getUTCMonth()+"-"+s.getFullYear(),viewoverridesObj.OffPlatformCourse)return;ft.has(r)?(gt(t,ft.get(r),f,i),dt=!0):(c=GolfNow.Web.Request.Get("get_teetimesummaries","/api/tee-times/facility/"+i+"/summaries/from/"+e+"/to/"+h,!0,null,{headers:{"Cache-Control":"max-age=6000"}}),c.done(function(n){n!==null&&n.length<=0||(ft.set(r,n),gt(t,n,f,i))}).fail(function(){GolfNow.Web.Utils.ConsoleError("Failed to retrieve tee-time summaries")}).always(function(){dt=!0}))}}}function gt(t,i,r,u){var f;_.forEach(i,function(i){var s=n.parse(i.playDateUtc),e=s.clearTime().getTime(),o=GolfNow.Web.Date.DaysFromToday(new n(e));f=t.find("[data-pick='"+e+"']:not(:button)");i.numberOfTeeTimesAvailable===0?f.addClass("picker__day--disabled"):i.areHotDealsAvailable?f.addClass("picker__day--deal").click(function(){TrackGoogleEvent("enhancedDatePicker","Enhanced Date Picker","Click","Hot Deal|"+r.replace("+"," ")+"|"+u+"|"+o)}):f.addClass("picker__day--hasTeeTimes").click(function(){TrackGoogleEvent("enhancedDatePicker","Enhanced Date Picker","Click","No Hot Deal|"+r.replace("+"," ")+"|"+u+"|"+o)})})}function bi(t,i,r,u){return _.isUndefined(u)||_.isNull(u)?n.parse(r):i.getUTCMonth()===u.getUTCMonth()&&i.getFullYear()===u.getFullYear()?i:new n(t.find(".picker__month").text()+" 1 "+t.find(".picker__year").text())}function ki(){k.on({scroll:ni})}function di(n,t){n.event="search";var i=function(){var n=window.location.href,i=n.indexOf("#"),t=n.lastIndexOf("/");return i!==-1&&t!==-1&&i>t&&(n=n.substr(t+1,i-1-t)),n};if(t&&t.SearchType!==null){if(!isNaN(t.SearchType))switch(GolfNow.Web.Utils.GetSearchTypeName(t.SearchType)){case searchType_GeoLocation:t.SearchType=searchType_GeoLocation;break;case searchType_Facility:t.SearchType=searchType_Facility;break;case searchType_Market:t.SearchType=searchType_Market;break;case searchType_Destination:t.SearchType=searchType_Destination;break;case searchType_GoPlay:t.SearchType=searchType_GoPlay;break;case searchType_Favorites:t.SearchType=searchType_Favorites}switch(t.SearchType){case searchType_GeoLocation:n.searchEventLabel=t.Address;break;case searchType_Facility:n.searchEventLabel=t.FacilityName;break;case searchType_Market:n.searchEventLabel=t.MarketName;break;case searchType_Destination:n.searchEventLabel=t.MarketName;break;case searchType_GoPlay:n.searchEventLabel=i();break;case searchType_Favorites:n.searchEventLabel=t.FacilityIds}}n.parameters=t;dataLayer.push(n);exactTarget.TrackSearch(t)}function ni(){if(window.isFacilitySearch){k.off({scroll:ni});return}var i=this,n=$("#main-header div.contain-to-grid").hasClass("sticky"),t=n?6:5;!window.isFacilitySearch&&window.readyForAutoScroll&&k.scrollTop()>=li.height()-k.height()*t&&(window.readyForAutoScroll=!1,window.setTimeout(function(){searchController.NextResult(yi)},150))}function gi(t,i){var r=$(i),f=$("#hdnFacilityId").val(),a=r.data("facilityname"),v=searchController.SearchParameters.Get(),o=v.FacilityId||f,y=r.data("hotdeal")==="True",p=r.data("tradeoffer")==="True",w=r.data("memberpricetier"),b=r.data("hasmemberpricing")==="True",k=b?"/pt/"+w:"",u="/tee-times/facility/"+f+"/tee-time/"+t+k,s,e;if(p){r.addClass("disabled").attr("disabled",!0).prepend('<i class="fa-solid fa-loader fa-spin">&nbsp;<\/i>');u="/api/tee-times/facility/"+o+"/roll-tee-time/"+t;s=r.data("ratename");e={facilityId:Number(o),playerRule:Number(r.data("playerrule")),playerCount:Number(r.data("playercount")),rate:r.data("rate"),playTime:n.parse(r.data("playtime"))||n.parse(r.data("playtimeformatted")),playTimeFormatted:r.data("playtimeformatted")};e.playTime=e.playTime.toUTCString();var h=r.data("failurefunc")||null,c=_.isFunction(h)?h:function(){var n=$("<div>",{"class":"columns small-12",html:$("<p>",{"class":"font-24 color-red",text:"Sorry, this "+s+" rate is no longer available."})});r.find(".fa-loader").remove().end().parents(".rate-tile").html(n)},l=r.data("successfunc")||null,d=_.isFunction(l)?l:function(n){n!==null?(GolfNow.Web.Utils.SetTeeTimeOfferAccepted(n.teeTimeRateId),u="/tee-times/facility/"+n.facilityId+"/tee-time/"+n.teeTimeRateId,TrackGoogleClickEvent("payNowSave","Pay Now and Save","Pay Now Click",a+"|"+f,"",u)):c()},g=GolfNow.Web.Request.Post("offer-request",u,JSON.stringify(e));g.done(d).fail(c)}else GolfNow.Web.Analytics.Google.Ecommerce.ProductClick("",f,Number(t),y,"","","","",u)}function nr(){f=GolfNow.Web.Search.handleWindowResizeOverride||f;Foundation.utils.is_large_up()?f(3):Foundation.utils.is_medium_only()?f(1):Foundation.utils.is_small_only()&&f(0);GolfNow.Web.Page.Sub("mq_small_screen",function(){f(0)});GolfNow.Web.Page.Sub("mq_medium_screen",function(){f(1)});GolfNow.Web.Page.Sub("mq_large_screen",function(){f(2)});GolfNow.Web.Page.Sub("mq_xlarge_screen",function(){f(3)});ot=_.once(GolfNow.Web.Localization.GetString);return new GolfNow.Web.Client.SearchController({UseGooglePlaces:usegoogleplaces,RenderPredicates:function(t){var r=new n,u,i,f;r=new n(r.getFullYear(),r.getMonth(),r.getDate());u=$("#inputCurrentDate").pickadate("picker");i=new n(t.Date);u&&u.set("select",[i.getFullYear(),i.getMonth(),i.getDate()],{muted:!0});f=i.toDateDisplayString();$("#currentDateText").html(f);$("#currentDateRefineText").html(f);GolfNow.Web.Page.Pub("renderPredicates",t);GolfNow.Web.FederatedSearch.SetSearchFilters(t)},RenderResults:function(n,t,i){var nt,l,b,k,p,w,y,s,d;if(rt=!1,nt=t,GolfNow.Web.Page.Sub("content_rendered",function(){h(1);window.readyForAutoScroll=n.total>=t.PageSize*(t.PageNumber+1)?!0:!1;g.hide()}),n.limitReached?GolfNow.Web.Utils.ConsoleLog("(400+ Results)"):GolfNow.Web.Utils.ConsoleLog("("+n.total+" Results)"),vr(n),n.total>0)if(ar(n,t.SearchType),yr(n,t.SearchType),n.ttResults.predicate.view.indexOf("Map")!==-1){$("#map-wrapper").show();$("#ttresults").hide();l=10;switch(n.ttResults.predicate.radius){case 25:l=9;break;case 50:l=8}i?$.observable(o).insert(n.ttResults.facilities):(r=n,o=r.ttResults.facilities,wt=r.ttResults.featuredFacilities);b={center:{lat:n.ttResults.predicate.latitude,lng:n.ttResults.predicate.longitude},zoom:l};GolfNow.Web.MapController.DrawMap("map-canvas",b,o,wt,n.ttResults.predicate);h(1)}else if($("#map-wrapper").hide(),$("#ttresults").show(),i&&r)c(1),r.ttResults.startIndex=n.ttResults.startIndex||0,n.ttResults.featuredFacilities=r.ttResults.featuredFacilities,GolfNow.Web.Domains.BookingCenterPhone().done(function(n){u.phoneNumber=n}),u.facilityName=t.FacilityName,n.ttResults.teeTimes?$.observable(e).insert(n.ttResults.teeTimes):$.observable(o).insert(n.ttResults.facilities),GolfNow.Web.Page.Pub("search_results_data_loaded",{totalRecords:n.total,pageSize:n.ttResults.predicate.pageSize,startIndex:n.ttResults.startIndex||0,serverData:r,coursesByFeatured:u,teetimes:e||o,isTeeTimes:!$.isEmptyObject(n.ttResults.teeTimes)});else{it=0;bt=0;r=n;u={featured:[]};GolfNow.Web.Domains.BookingCenterPhone().done(function(n){u.phoneNumber=n});u.facilityName=t.FacilityName;$.extend(!0,u,n.ttResults.predicate);e=_.clone(r.ttResults.teeTimes);o=_.clone(r.ttResults.facilities);n.ttResults.predicate.view.toLowerCase()==="grouping"&&(e=tr(e),n.ttResults.predicate.view="List");GolfNow.Web.Page.Pub("search_results_data_loaded",{totalRecords:n.total,pageSize:n.ttResults.predicate.pageSize,startIndex:n.ttResults.startIndex,minDailyTeeTimeRate:n.ttResults.minDailyTeeTimeRate,maxDailyTeeTimeRate:n.ttResults.maxDailyTeeTimeRate,serverData:r,coursesByFeatured:u,featuredFacilities:r.ttResults.featuredFacilities,teetimes:e||o,isTeeTimes:!$.isEmptyObject(e),featuredFacilityInsertLocation:it,featuredFacilityInsertLocation2:bt});u.chipLimitDisplayedOnWideTile=ir();try{k=$.templates.teeTimeResultsTemplate;k.link("#ttresults",[u]);GolfNow.Web.Page.Pub("tee_times_data_loaded",{teeTimes:_.clone(r.ttResults.teeTimes)})}catch(ut){h(3);GolfNow.Web.Utils.ConsoleLog(ut)}}else{si();var a="",f,d,ft=[{tmplPath:"SearchResultMulliganMessage",accessorName:"mulliganMessageTemplate",isPath:!1,tags:{filterslink:function(n){return Foundation.utils.is_large_up()||GolfNow.Web.Utils.GetSearchTypeName(n)===searchType_GoPlay?this.tagCtx.render():'<a class="search-action search-refine-btn pointerLink">'+this.tagCtx.render()+"<\/a>"},nextavailablelink:function(n){return'<a href="javascript:GolfNow.Web.Client.SearchController.NextDateWrapped('+n+');">'+this.tagCtx.render()+"<\/a>"}}}],v=!1;if(n.ttException&&(n.ttException.predicateSearchType=t.SearchType),n.ttException&&n.ttException.facility&&n.ttException.facility.isPrivate&&n.ttException.facility.isPrivateCourseLabelEnabled&&(v=!0),p=!1,n.ttException&&n.ttException.facility&&n.ttException.facility.isClubFitting&&(p=!0,v=!0),f=_.findWhere(ft,{tmplPath:"SearchResultMulliganMessage"})||null,f===null)h(2,a);else{for(_.isArray(f)||(f=[f]),w=[],y=0;y<f.length;y++)s=f[y],d=s.isPath?s.tmplPath:"/Tmpls/_"+s.tmplPath+".tmpl.html",w.push(GolfNow.Web.Client.LoadTemplate(d,s.accessorName,s.helpers,s.tags));$.when.apply(this,w).done(function(){n.ttException&&_.isFunction($.templates.mulliganMessageTemplate)&&!v?a=$.render.mulliganMessageTemplate(n.ttException):n.ttException&&v&&(n.ttException.errorType===1&&(a=$.render.mulliganMessageTemplate(n.ttException)),tt.empty(),$("#pResultsOptions").hide(),p&&(kt=""));GolfNow.Web.Utils.GetSearchTypeName(t.SearchType)===searchType_GoPlay&&fi(t.PromotedCampaignsOnly,t.View)?h(5):h(2,a)})}}},BeforeSearch:function(n){$(".search-action").addClass("searching").prop("disabled",!0);y.show();t="";n.PageNumber===0&&(e=[],o=[],b=[],r={ttResults:null},it=0,at.empty());GolfNow.Web.Page.Pub("beforeSearch",n);a.is(":visible")&&a.slideUp().empty();a.off("click",".copy-promo-code",lt);h(4)},AfterSearch:function(n,t,i){var f,e,r,h,o,c;if($(".search-action").removeClass("searching").prop("disabled",!1),t&&GolfNow.Web.Page.Pub("afterSearch",{data:n,params:t,append:i}),t&&!i&&di({},t),f=$("#fedresults"),f.length>0&&f.text()===""&&(e=searchController.GetRestoreFedSearchKey(!0),e&&e.Location&&searchController.SetRefinedResultsDisplay(e,f,$(".list-refined-items"))),n&&n.ttResults&&(r=[],n.ttResults.facilities&&n.ttResults.facilities.length&&(r=r.concat(n.ttResults.facilities)),n.ttResults.featuredFacilities&&n.ttResults.featuredFacilities.length&&(r=r.concat(n.ttResults.featuredFacilities)),r.length>0)){h=_.uniq(_.map(r,n=>n.id||n.facilityId));o=_.difference(h,b);b=_.union(b,o);var l=GolfNow.Web.Request.Post("get-course-metrics","/api/course/metrics",JSON.stringify({courseIds:o})),s=[],u=[];_.each(r,function(n){n.isSmartPlay&&s.push(n.id||n.facilityId)});Foundation.utils.is_medium_up()?l.done(function(n){_.each(n,function(n){_.find(s,function(t){return t===n.courseId})?u.push({courseId:n.courseId,roundsBooked:n.roundsBooked,hasSmartPlayTag:!0}):u.push({courseId:n.courseId,roundsBooked:n.roundsBooked,hasSmartPlayTag:!1})});st(u)}).fail(function(){}):(_.each(s,function(n){u.push({courseId:n,roudsBooked:null,hasSmartPlayTag:!0})}),st(u))}c=GolfNow.Web.Utils.GetSearchTypeName(searchController.SearchParameters.Get().SearchType);c.toLowerCase()==="facility"&&$(document).foundation("tooltip","reflow");GolfNow.Web.Page.SendMessage(JSON.stringify({message:"resize",data:{scrollHeight:$("#ttresults").height()}}));GolfNow.Web.Page.Pub("afterSearch",{params:t,append:i})},RenderError:function(){h(3);GolfNow.Web.Utils.ConsoleWarn("Error Encountered")},JsTemplates:[{tmplPath:"TeeTimeResults",accessorName:"teeTimeResultsTemplate",isPath:!1,helpers:{colsort:Foundation.utils.debounce(ti,150,!0),colview:Foundation.utils.debounce(ii,150,!0),colhotdeal:Foundation.utils.debounce(rr,150,!0),contents_rendered:Foundation.utils.debounce(fr,150,!0),featured_rendered:Foundation.utils.debounce(er,150,!0),displayVIPBadge:Foundation.utils.debounce(ur,150,!0),playersFilterOption:Foundation.utils.debounce(or,150,!0),units:GolfNow.Web.Utils.AppendRadiusUnits}},{tmplPath:"TilesRollupCourse",accessorName:"tilesRollupCourseTemplate",isPath:!1,helpers:{resultHash:_.debounce(function(){return t===""&&(t=GolfNow.Web.UrlParams.GetUrlHash()||""),t},150,!0),units:GolfNow.Web.Utils.AppendRadiusUnits}},{tmplPath:"TilesRollupCourseWide",accessorName:"tilesRollupCourseWideTemplate",isPath:!1,helpers:{resultHash:_.debounce(function(){if(t==="")return(t=GolfNow.Web.UrlParams.GetUrlHash()||"",$(".special-rates").hasClass("promo-campaign-landing"))?t.replace("hotdealsonly=false","hotdealsonly=true"):t},150,!0),tradeOnlyResultHash:_.debounce(function(){return t===""&&(t=GolfNow.Web.UrlParams.GetUrlHash()||""),t.replace("hotdealsonly=false","hotdealsonly=true")},150,!0),units:GolfNow.Web.Utils.AppendRadiusUnits,hotDealZone:kr,isMobile:function(){return Foundation.utils.is_small_only()},getHighestHolesCount:function(n,t){var i=0,r=0;return!_.isNull(n)&&!_.isUndefined(n)&&n.length>0&&(i=_.max(n,function(n){return n.displayRate.holeCount}).displayRate.holeCount||Number.NEGATIVE_INFINITY),!_.isNull(t)&&!_.isUndefined(t)&&t.length>0&&(r=_.max(t,function(n){return n.displayRate.holeCount}).displayRate.holeCount||Number.NEGATIVE_INFINITY),Math.max(i,r)},allTeeTimes:function(n,t){return _.uniq(_.union(t,n),!1,function(n){return n.teeTimeId})},isPromotedCampaignLanding:function(){return $(".special-rates").hasClass("promo-campaign-landing")},daysout:GolfNow.Web.Date.DaysFromToday}},{tmplPath:"TilesRollupCourseWideTile",accessorName:"CourseWideTileTemplate",isPath:!1},{tmplPath:"TilesRollupCourseWideTile-PC",accessorName:"CourseWideTilePCTemplate",isPath:!1},{tmplPath:"TilesRollupHotDeal",accessorName:"tilesRollupHotDealTemplate",isPath:!1,helpers:{resultHash:_.debounce(function(n){if(t==="")return(t=GolfNow.Web.UrlParams.GetUrlHash()||"",$(".special-rates").hasClass("promo-campaign-landing"))?t.replace("hotdealsonly=false","hotdealsonly=true"):t;var i="#hotdealsonly=true";return n&&_.isNumber(n)&&(i+="&daysout="+n),i},150,!0),isBestDealsPage:function(){return $(".special-rates").hasClass("best-tee-times-deals")},isPromotedCampaignLanding:function(){return $(".special-rates").hasClass("promo-campaign-landing")},units:GolfNow.Web.Utils.AppendRadiusUnits,daysout:GolfNow.Web.Date.DaysFromToday}},{tmplPath:"NextAvailableFacilitySummarySliderTile",accessorName:"nextAvailableFacilitySummaryTmpl",isPath:!1,helpers:{units:GolfNow.Web.Utils.AppendRadiusUnits,phoneNumber:function(){return""},resultHash:function(){return""}}},{tmplPath:"FavoritesRollupSinglePricing",accessorName:"rollupSingleFromPriceTmpl",isPath:!1,helpers:{istoday:GolfNow.Web.Date.IsToday,daysout:GolfNow.Web.Date.DaysFromToday}},{tmplPath:"FeaturedFacility2",accessorName:"featuredFacilityTemplate",isPath:!1,helpers:{resultHash:_.debounce(function(){return t===""&&(t=GolfNow.Web.UrlParams.GetUrlHash()||""),t},150,!0),useNoTeeTimesTopTierTemplate:function(){var n=["toff-featured-courses-in-city-state","toff-best-courses-in-destination","toff-9hole-courses-in-destination","toff-public-courses-in-destination"],t="",r;for(i=0;i<n.length;i++)if(r=$(document).find("body."+n[i]).length>0,r){t=n[i];break}return $("body").hasClass(t)}}},{tmplPath:"TopTierFacility",accessorName:"topTierFacilityTemplate",isPath:!1,helpers:{units:GolfNow.Web.Utils.AppendRadiusUnits}},{tmplPath:"TopTierFacilityTeeTimes",accessorName:"topTierFacilityTeeTimesTemplate",isPath:!1,helpers:{isPromotedCampaignLanding:function(){return $(".special-rates").hasClass("promo-campaign-landing")},isMobile:function(){return Foundation.utils.is_small_only()},tradeOnlyResultHash:_.debounce(function(){return t===""&&(t=GolfNow.Web.UrlParams.GetUrlHash()||""),t.replace("hotdealsonly=false","hotdealsonly=true")},150,!0),units:GolfNow.Web.Utils.AppendRadiusUnits,daysout:GolfNow.Web.Date.DaysFromToday}},{tmplPath:"Cube",accessorName:"cubeTemplate",isPath:!1},{tmplPath:"CubeGrouping",accessorName:"cubeGroupingTemplate",isPath:!1},{tmplPath:"CubeRollupNewCourse",accessorName:"cubeRollupNewCourseTemplate",isPath:!1,helpers:{resultHash:_.debounce(function(){return t===""&&(t=GolfNow.Web.UrlParams.GetUrlHash()||""),t},150,!0)}},{tmplPath:"CoursePriorityLabel",accessorName:"coursePriorityLabelTemplate",isPath:!1},{tmplPath:"CoursePriorityLabelGeo",accessorName:"coursePriorityLabelTemplateGeo",isPath:!1},{tmplPath:"StarRatings",accessorName:"starRatingsTemplate",isPath:!1},{tmplPath:"star",accessorName:"star",isPath:!1},{tmplPath:"PromoCampaigns",accessorName:"availablePromosTemplate",isPath:!1,helpers:{eligiblePromotedCampaigns:function(n){if(_.isNull(n)||_.isNull(n.teeTimes)||_.isUndefined(n.teetimes))return _.isNull(n)||_.isNull(n.promotedCampaignCollection)||_.isUndefined(n.promotedCampaignCollection)?!1:n.promotedCampaignCollection.length>0?!0:!1;var t=_.find(n.teeTimes,function(n){return n.promotedCampaignsWithLabel.length>0});return _.isUndefined(t)?!1:!0},formattedTime:function(t){n.CultureInfo.name=gnSiteLocale||"en-US";var i=n.parse(t);return i.toString(gnSiteLocale==="en-US"?"h tt":"HH")},formattedDaysOfWeek:function(t){if(_.isArray(t)){var i=n.CultureInfo.shortestDayNames,r=[];return _.forEach(_.sortBy(t),function(n){var t=isNaN(Number(n))?-1:Number(n),u=t>=0&&t<i.length?i[t]:"Su";r.push(u)}),r.join(", ")}return"Mo - Su"},formattedBlackoutDays:function(t){if(_.isArray(t)){var i=[];return _.forEach(t,function(t){var r=n.parse(t);i.push(r.toString("MMM dd, yyyy"))}),i.join(", ")}return"N/A"},getLocalizedCopy:function(){return et},showMoreExpand:function(n){var t=0,i=n.length;return i===1&&(t=_.reduce(n[0].promoCodes,function(n,t,i){return n+i},1)),i>1||t>1||Foundation.utils.is_small_only()?!0:!1},isPromotedCampaignLanding:function(){return $(".special-rates").hasClass("promo-campaign-landing")}}}]})}function st(n){_.isEmpty(n)||_.forEach(n,function(n){var f=$("div[data-facilityid='"+n.courseId+"']"),t=f.find("div .course-features"),e=Number($("div[data-facilityid='"+n.courseId+"']").data("averagerating")),o=$("div[data-facilityid='"+n.courseId+"']").data("ispremium"),l=$("div[data-facilityid='"+n.courseId+"']").data("isteeofftoptier"),s=Foundation.utils.is_medium_up()&&_.isNumber(e)&&e>4.5,h=Foundation.utils.is_medium_up()&&n.roundsBooked>=5,c=n.hasSmartPlayTag,a=$("<span>",{"class":"course-rating top-rated-tag",html:'<i class="gn-gn_thumbsUp font-18"><\/i> Top Rated Course'}),v=$("<span>",{"class":"course-rating booked-times-tag",html:'<i class="gn-gn_booked hide font-18"><\/i> Booked <strong> '+n.roundsBooked+"<\/strong> times today"}),y=$("<span>",{"class":"course-rating mobile-checkin-tag",html:'<i class="gn-smartplay font-18"><\/i> Mobile Check-In'}),u,i,r;t.length&&(u=t.data("split"),r=u?{"padding-right":"10px",color:"#666666"}:o?{}:{"border-top":"solid 1px #E0E0E0",color:"#666666",width:"100%"},i=u?t.siblings(".course-rating").addClass("columns large-6").css("width","55%").end():t.siblings(".course-rating").addClass("course-rating-nc").removeClass("course-rating").removeClass("large-7").addClass("large-6").empty().end(),c&&i.append(y.css(r)),s&&i.append(a.css(r)),h&&i.append(v.css(r)),l&&o&&s&&h&&c&&$(f.find(".course-features .booked-times-tag")).hide())})}function tr(n){var t=[],i=[],r=[],u=[],f,e;return $.each(n,function(n,f){f.timeHour>=1&&f.timeHour<=10?t.push(f):f.timeHour>=11&&f.timeHour<=13?i.push(f):f.timeHour>=14&&f.timeHour<=16?r.push(f):f.timeHour>=17&&f.timeHour<=24&&u.push(f)}),f={morning:t,midDay:i,afternoon:r,twilight:u},e=_.map(f,function(n,t){return{key:t,value:n}}),e}function ti(){var n=this.ctx.root[this.getIndex()],t,i;if(n)return t=n.sortDirection,i=function(){var u=n.view,r=n.sortBy,f=r!==null?GolfNow.Web.Utils.GetSearchSortRollupFromSort(r,t):null,i=u==="Course"||u==="Tile"?f:r;return i.toLowerCase().indexOf(".max")>-1||i.toLowerCase().indexOf(".min")>-1?i.split(".")[0]:i},i()}function ir(){return Foundation.utils.is_small_only()?3:Foundation.utils.is_medium_only()?4:(Foundation.utils.is_large_up(),5)}function ii(){var n=this.ctx.root[this.getIndex()];if(n)return n.view}function rr(){var n=this.ctx.root[this.getIndex()];if(n)return Boolean(n.hotDealsOnly)===!0}function ur(n){var t=null,i=this.ctx.root;return i&&i.length>1?t=this.ctx.root[this.getIndex()]:i&&i.length===1&&(t=this.ctx.root[0]),t&&n?t.isVipMember&&n.vipEligible:void 0}function fr(){return GolfNow.Web.Page.Pub("content_rendered",null),!0}function er(){return GolfNow.Web.Page.Pub("featured_rendered",null),g.hide(),!0}function ri(){return GolfNow.Web.Page.Pub("no_results_rendered",null),!0}function or(){var n=Number(searchController.SearchParameters.Get().Players)||"";return _.isNumber(n)&&n>0?n:""}function h(n,t){(t===undefined||t===null||t==="")&&(t="");var i=at,f=$("#map-wrapper"),r=tt,s=vt,h=ci,e=$("#pResultsOptions"),u=$("#sortingcontrols"),o=$("#pResultsPromotionsOptions");n===1?(i.show(),u.show(),l.hide(),c(n)):n===2?(t!==""?(e.hide(),r.html(t)):r.html(kt),l.show(),y.show(),GolfNow.Web.Widgets.RelatedCoursesTeeTimes.LoadData(),i.hide(),f.hide(),h.hide(),r.show(),s.hide(),u.hide(),o.hide(),c(n),ri(),ht(e)):n===3?(l.show(),i.hide(),v.hide().removeClass("hide-for-large-up"),f.hide(),h.hide(),r.hide(),u.show(),o.hide(),s.show(),c(n),ht(e)):n===4?(y.hide(),i.hide(),f.hide(),u.hide(),l.hide(),c(n)):n===5&&(l.show(),y.show(),i.hide(),v.hide().removeClass("hide-for-large-up"),f.hide(),r.hide(),h.show(),s.hide(),u.hide(),c(n),ri(),e.hide(),o.show(),ht(o))}function c(n){var i=searchController.SearchParameters.Get().View,t=".list-animation";switch(i){case"Grouping":t=".chip-animation";break;case"Tile":case"Tile-HD":case"Tile-PC":t=".tile-animation"}switch(n){case 1:case 2:case 3:case 5:nt.hide().find(".list-animation, .chip-animation, .tile-animation").hide();break;case 4:nt.show().find(t).show()}}function ht(n){var i=$(".try-options-message"),t;GolfNow.Web.Utils.GetSearchTypeName(searchController.SearchParameters.Get().SearchType)===searchType_Favorites&&(t=GolfNow.Web.Favorites.GetIds()!==null,t||(n.find("#checkNextDay").hide().end().find("#view-all-nearby-tee-times").hide().end(),GolfNow.Web.Localization.GetString("Widgets","favorite_spelling_capital").done(function(n){i.first().parent().html('<span class="try-options-message">It looks like you do not have any '+n+'s saved. Simply click the <i class="gn-heart-empty color-red"><\/i> on any of your '+n+" courses and they will be saved here for all future visits.<\/span>")})))}function sr(){n.today().compareTo(n.parse(searchController.SearchParameters.Get().Date))===0&&$(".button-prev-date").hide()}function hr(n){if(!rt){var t=d(n);t&&t.Sorts&&t.Sorts.length>0?$("#sort-listing-button").parent().removeClass("disabled"):$("#sort-listing-button").parent().addClass("disabled");rt=!0}}function d(n){var i=null,r=n||lr(),t=GolfNow.Web.Page.GetPageConfig();return _.isObject(t)&&_.isArray(t.Views)?i=_.find(t.Views,function(n){if(n.Name===r)return n})||[]:GolfNow.Web.Utils.ConsoleWarn("Unable to get page config in Search"),i}function cr(n,t){var i=d(t);if(i&&i.Sorts){var r=n.split("|"),u=r[0],f=Number(r[1])||0,e={Name:u,Direction:f};return!_.isEmpty(_.findWhere(i.Sorts,e))}return!1}function lr(){var i=searchController.SearchParameters.Get(),n=i.View||i.SearchType,t;if(typeof n=="number"){switch(n){case 0:t="Course";break;case 1:t="Tile";break;default:t="List"}n=t}return n}function ar(n,t){var f=$("meta[name='currency-code']").attr("content"),i,r,u;n.ttResults.facilities&&n.ttResults.facilities.length?(r=n.ttResults.facilities[0],u=_.findKey(n.ttResults.facilities[0],function(n,t){return t==="currencyCode"||t==="culture"}),i=r[u]):n.ttResults.teeTimes&&n.ttResults.teeTimes[0].teeTimeRates&&(i=n.ttResults.teeTimes[0].teeTimeRates[0].singlePlayerPrice.greensFees.currencyCode);f!==i&&($("meta[name='currency-code']").attr("content",i),GolfNow.Web.UrlParams.PopulateSearchHeadline(searchController,t))}function vr(n){n.total>0&&fi(n.ttResults.predicate.promotedCampaignsOnly,n.ttResults.predicate.view)&&(n.ttResults.facilities=_.filter(n.ttResults.facilities,function(n){if(n.promotedCampaignTeeTimes&&n.promotedCampaignTeeTimes.length>0)return n}),n.ttResults.featuredFacilities=_.filter(n.ttResults.featuredFacilities,function(n){if(n.promotedCampaignTeeTimes&&n.promotedCampaignTeeTimes.length>0)return n}),n.total=n.ttResults.facilities.length)}function yr(n,t){var r,u,f,i;GolfNow.Web.Utils.GetSearchTypeName(t)===searchType_GoPlay&&n.ttResults.promotedCampaignCollection&&n.ttResults.promotedCampaignCollection.length?(i=$.templates.availablePromosTemplate,r=n.ttResults.promotedCampaignCollection,v.show().addClass("hide-for-large-up"),ot("Shared","GenericDisplay_HotDeal").done(function(n){et=n}),a.on("click",".copy-promo-code",lt).slideDown(function(){var f=$(this),t,u;if(i.link("#"+f.attr("id"),n.ttResults),n.ttResults.validGolfPassOnlyProducts||(r=_.filter(n.ttResults.promotedCampaignCollection,function(n){if(!n.restrictions.golfPassOnly)return n})),$("#offers-available-count").html(r.length+" "),Foundation.utils.is_large_up()&&$("#filters-menu").append($("#available-promos-container")),v.length>0&&v.is(":visible")){$("#available-promos-container").appendTo($("#promoted-campaigns-modal"));$("#mobile-available-offers").on("click",function(){$("#promoted-campaigns-modal").foundation("reveal","open")})}t=$("[data-expandable]");u=$("[data-expand-button]");ui();ei(t);_.forEach(u,function(n){var t=$(n);t.on("click",oi);ct(t)})})):GolfNow.Web.Utils.GetSearchTypeName(t)===searchType_Facility&&n.ttResults.promotedCampaignCollection&&n.ttResults.promotedCampaignCollection.length?(u=$("#smartplay-perks-section-container"),f=$("#golfpass-perks-section-container"),ot("Shared","GenericDisplay_HotDeal").done(function(n){et=n}),i=$.templates.availablePromosTemplate,a.on("click",".copy-promo-code",lt).slideDown(function(){var u=$(this),t,r;i.link("#"+u.attr("id"),n.ttResults);t=$("[data-expandable]");r=$("[data-expand-button]");ui();ei(t);_.forEach(r,function(n){var t=$(n);t.on("click",oi);ct(t)})}),$("#smartplay-banner-container").hasClass("show-for-large-up")||$("#smartplay-banner-container").addClass("show-for-large-up"),$("#golfpass-perks-banner-container").hasClass("show-for-large-up")||$("#golfpass-perks-banner-container").addClass("show-for-large-up"),u.children().length===0&&u.append(yt),f.children().length===0&&f.append(pt)):si()}function ui(){var n=!1;_.forEach($(".promoted-campaign-description"),function(t){var i=$(t),r,u;i.length&&(r=i.prop("scrollWidth")>i.prop("clientWidth"),t.dataset.overflow=r,r&&(n=!0,u=i.parent(".promoted-campaign-header").find(".promoted-campaign-moreinfo"),u[0].dataset.overflow=r))});n&&$(document).foundation("tooltip","reflow")}function fi(n,t){return n=typeof n=="boolean"?n:n==="true",n&&(t==="Tile-PC"||t==="Course-Tile-PC")}function ei(n){_.forEach(n,function(n){var i=$(n),t,r;i.hasClass("expanded")||(t=i.find("[data-expand-text]"),t.length&&(r=t.prop("scrollHeight")>t.prop("clientHeight"),n.dataset.overflow=r))})}function oi(n){var t=$(n.currentTarget),i=t.closest("[data-expandable]");i.toggleClass("expanded");ct(t)}function ct(n){var t=n.closest("[data-expandable]"),i=t.hasClass("expanded");n.innerHTML=i?'<i class="gn-caret-up"><\/i>':'<i class="gn-caret-down"><\/i>'}function lt(n){var f,e,i,t,o,s,h;n.stopPropagation();n.preventDefault();var r=$(n.currentTarget),u=r.data("code")||"",c=$(".course-basic-info > section > h1").text();if(u!==""&&c!=="")return(TrackGoogleEvent("promoCodeCopy","Promo Code Copy","Click",u+" - "+c),f=2e3,e=function(){$(".promo-copy-elem").remove();$(".promo-copied-msg").fadeOut(500).remove()},navigator.clipboard)?(navigator.clipboard.writeText(u).then(function(){r.parent().append($("<div>",{"class":"promo-copied-msg color-green font-12",html:"<strong>Copied to clipboard!<\/strong>"}))}),_.delay(e,f),!1):(i=$("<span>",{"class":"hide promo-copy-elem",height:0,width:0}),t=$("<input>",{id:"txtPromoCode",type:"text",value:u}),i.append(t),r.parent().append(i),ai?(t.attr("readonly",!0).attr("contenteditable",!1),o=t[0],s=document.createRange(),s.selectNodeContents(o),h=window.getSelection(),h.removeAllRanges(),h.addRange(s),o.setSelectionRange(0,9999),$btn.addClass("disabled"),i.toggleClass("hide"),t.focus(),t.select(),i.toggleClass("hide"),r.parent.append($("<div>",{"class":"promo-copied-msg color-green font-12",html:"<strong>Unable to copy to clipboard. Please copy text manually.<\/strong>"}))):(i.toggleClass("hide"),t.focus(),t.select(),document.execCommand("copy"),i.toggleClass("hide"),r.parent().append($("<div>",{"class":"promo-copied-msg color-green font-12",html:"<strong>Copied to clipboard!<\/strong>"}))),_.delay(e,f),!1)}function f(n){var i=$("#teetimeslist, #search-results"),t=$("gn-search-filters > aside"),r=$("gn-search-results").find("#ttresults, #loading, #map-wrapper, #nextPageThrobber, .no-results.mulligan"),f=$("#facility-listing"),u=$("gn-search-result-actions > .search-results-heading > div");i.hasClass("row")&&i.removeClass("row");t.removeClass();r.removeClass("large-9");n>1?(i.addClass("row"),t.addClass("columns large-3"),GolfNow.Web.Utils.IsFacilityPageLeftSide()?r.addClass("columns large-8 right"):GolfNow.Web.Utils.GetSearchTypeName(viewOverrideParams.SearchType)!==searchType_Facility&&r.addClass("columns large-9"),t.show(),u.show()):n===1&&(t.addClass("left-off-canvas-menu"),_.delay(function(){$(document).foundation("offcanvas","reflow");t.show();u.show()},500))}function pr(n){var t=GolfNow.Web.Page.GetPageConfig();_.isObject(t)&&_.isObject(t.Views)?_.each(n,function(n){var i=$(n),u=i.data("view-criteria"),f={Name:u},r;_.findWhere(t.Views,f)?(r=i.parent(),r.hasClass("depricated")===!1&&r.show()):i.parent().hide()}):GolfNow.Web.Utils.ConsoleWarn("Unable to remove unsupported view options in Search.")}function wr(n){var t=d();_.isEmpty(t)?(GolfNow.Web.Utils.ConsoleWarn("Unable to remove unsupported sort options in Search."),Foundation.utils.is_small_only()?$("#sort-listing-button").attr("data-toggle","").attr("data-target","").addClass("disabled"):$("#sort-listing-button").parent().addClass("disabled")):($("#sort-listing-button").parent().removeClass("disabled"),_.each(n,function(n){var i=$(n),u=i.data("sort-criteria").split("|"),f=u[0],e=Number(u[1]),o={Name:f,Direction:e},r;_.findWhere(t.Sorts,o)?(r=i.parent(),r.hasClass("depricated")===!1&&r.show()):i.parent().hide()}))}function br(n){var t=!viewoverridesObj.IsTeeTimeSearchResultsPage&&!homepageSearch;location.hash&&/date|daysout/ig.test(location.hash)||t||(searchController.SetDate(n,!0),GolfNow.Web.Cache.SetActiveDate(GolfNow.Web.Utils.GetDateString(n)),searchController.SaveFederatedSearchParameters(searchController.SearchParameters.Get()))}function kr(n){return n.displayRate.isHotDeal}function si(){var n,t;typeof p!="undefined"&&p?(n=$(".inner-smart-play-banner"),$("#smartplay-banner-container").removeClass("show-for-large-up"),n.length>1&&n[1].remove()):typeof w!="undefined"&&w&&(t=$(".inner-golfpass-perks-banner"),$("#golfpass-perks-banner-container").removeClass("show-for-large-up"),t.length>1&&t[1].remove())}function dr(n,t){p=n;w=t;p&&(yt=$("#smartplay-perks-section-container").html());w&&(pt=$("#golfpass-perks-section-container").html())}var hi=GolfNow.Web.Utils,g=$("#nextPageThrobber"),nt=$("#loading"),at=$("#ttresults"),y=$("gn-related-courses-teetimes"),l=$("section.mulligan"),vt=$("#pResultsError"),tt=$("#pResultsNone"),ci=$("#pResultsPromotionsNone"),a=$("#available-promos-container"),v=$("#mobile-available-offers"),p=!1,yt=null,w=!1,pt=null,e=[],o=[],wt=[],b=[],it=0,bt=0,r={ttResults:null},u={featured:[]},rt=!1,k=$(window),li=$(document),t="",kt=tt.html(),gr=vt.html(),ut=!1,s=null,dt=!1,ft=new Map,ai=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform),et="Hot Deal",ot,hi=GolfNow.Web.Utils,vi=_.throttle(wi,500,{leading:!1});return ti.depends=["#index","~root"],ii.depends=["#index","~root"],{initializeSearch:nr,bindEventHandlers:ki,bindDatePicker:pi,handlePreviousDateLink:sr,handleSortState:hr,getAllowedPageSorts:d,isSortAllowed:cr,removeUnSupportedSortOptions:wr,removeUnSupportedViewOptions:pr,datePickerBound:function(){return ut},continueToBookRate:_.debounce(gi,150,!0),setSearchDate:br,toggleLoadingAnimation:c,setPerksSectionValues:dr,buildCourseFeatureTags:st}}(Date);;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Search.UseDateExclusions=!1;GolfNow.Web.Search.ExcludeDays=[];GolfNow.Web.Search.ExcludeDayIds=[];GolfNow.Web.Search.GetExludedDayIds=function(){return GolfNow.Web.Search.UseDateExclusions?GolfNow.Web.Search.ExcludeDayIds:null};GolfNow.Web.Search.DatePickerOnOpenHandler=null;GolfNow.Web.Search.DatePickerOnCloseHandler=function(){$(document.activeElement).blur()};GolfNow.Web.GoPlay=function(){function h(){var n=this.getAttribute("facility-id"),t=this.getAttribute("tee-time-id");window.location.href="/tee-times/facility/"+n+"/tee-time/"+t}function c(n){if($(n.target).hasClass("favorite-icon"))return!0}function l(n){var r=$(".hot-deal-tile-rollup"),i,t;n.requestStatus==="success"&&(i=null,t=n.result.facilityId||null,t!==null&&(i=$(r).find('i[data-facilityid="'+t+'"]').data("facilityname")||null),i!==null&&t!==null&&GolfNow.Web.Favorites.TrackAdd(t,i,"HotDeals Search"))}var r="",v=GolfNow.Web.LocationServices,t=null,n=null,u=0,f=!1,i=null,e={noResultsMessage:"No results found.  Please try another search."},o=function(i){i=typeof i=="undefined"?{}:i;$.extend(i,e);r=i.noResultsMessage;viewOverrideParams.View==="Tile-HD"?searchController.SearchParameters.Set({TeeTimeCount:3},!0):viewOverrideParams.View==="Tile-PC"&&searchController.SearchParameters.Set({TeeTimeCount:20},!0);var u=GolfNow.Web.Client.ChangeLocationSetup(r);n=u.$textbox;t=u.$resultsList;s();a()},s=function(){GolfNow.Web.Page.Sub("search_results_data_loaded",function(){var n=document.querySelector("gn-featured-courses");n&&n.setAttribute("show-featured",!1)});GolfNow.Web.Page.Sub("user-location-changed",function(){var n=new Date(searchController.SearchParameters.Get().Date)||null,t;searchController.SearchParameters.Set({Latitude:null,Longitude:null,PageNumber:0},!0);_.isNull(i)||_.isNull(n)||i.equals(n)||!Foundation.utils.is_small_only()?GolfNow.Web.UrlParams.HandleGoPlayUrlHash(searchController):(t=document.location.pathname,document.location.href=t+"#date="+encodeURIComponent(GolfNow.Web.Utils.GetDateString(n)).replace(/%20/g,"+"))});GolfNow.Web.Page.Sub("search_date_changed",function(n){i=n});$(document).on("opened.fndtn.reveal","#change-location-modal",function(n){if(n.namespace==="fndtn.reveal"){var t=$(this);f=!0;u=$(document).scrollTop();window.scrollTo(0,0);GolfNow.Web.Client.ForceFullPageHeight();t.css({top:0})}});$(document).on("close.fndtn.reveal","#change-location-modal",function(n){n.namespace==="fndtn.reveal"&&(f=!1)});$(document).on("closed.fndtn.reveal","#change-location-modal",function(i){i.namespace==="fndtn.reveal"&&($("#save-location-change-error").text(""),n.val(""),n.tooltipster("hide"),t.hide(),GolfNow.Web.Client.ForceDefaultPageHeight(),$(document).scrollTop(u))});n.on("keyup",_.partial(GolfNow.Web.Client.ChangeLocationSearch,n,t));n.on("focus",_.partial(GolfNow.Web.Client.ChangeLocationSearch,n,t));n.tooltipster({content:$('<p class="help-block"><strong class="required-text">Search Requirements<\/strong><br />Multiple Hyphens, Symbols, and Special Characters are not Allowed<br />'),trigger:"custom",position:"bottom-right"});$("body").on("click","#save-location-change",GolfNow.Web.Client.ChangeLocation_SaveClick).on("click","#cancel-location-change",GolfNow.Web.Client.ChangeLocation_CancelClick);var r=document.querySelector("gn-search-results");$(r).on("click",".favorite-course,i.favorite-icon",GolfNow.Web.Favorites.favoriteIconEventHandler).on("click",".tee-time-detail",h).on("click","div a:not('.favorite-course,i.favorite-icon,.geo-changelocation,.show-more,.geo-hotdeals'),span.button:not('.favorite-course,i.favorite-icon,.geo-changelocation,.show-more,.geo-hotdeals')",c);GolfNow.Web.Page.Sub("xhr_post_always_favorite-course-add",l)},a=function(){if($activeMessage=$("#active-period-message"),$inactiveMessage=$("#inactive-period-message"),$inactiveMessage.length&&$activeMessage.length){var i=new Date,t=null,n=null,r=$activeMessage[0].getAttribute("data-startdate"),u=$activeMessage[0].getAttribute("data-enddate");r!==null&&(t=new Date(r));u!==null&&(n=new Date(u));t!==null&&i.getTime()>=t.getTime()&&(n!==null&&i.getTime()<=n.getTime()||n===null)?($activeMessage.show(),$inactiveMessage.hide()):($activeMessage.hide(),$inactiveMessage.show())}};return{InitPage:o}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.RedeemRewards=GolfNow.Web.RedeemRewards||{};GolfNow.Web.RedeemRewards=function(){function gi(t,i,u,f,c,l,k,d){n=t;n.isDueOnlineZero=!1;n.allChecked=!1;n.allNotChecked=!1;n.selectedRewards=[];n.executeRewardOnChange=ou;_.map(n.eligibleCouponCodes,function(n){return n.name=n.id=n.code,n.isChecked=!1,n.isDisabled=!1,n});s=f;b=c;h=d;a=t.discountTotal;ki=t.giftCardFunds;ot=t.accountBalanceFunds;st=t.urlPostGetInvoiceDetails;ht=t.customeremail;at=t.teetimeid;vt=t.players;y=t.facilityId;yt=t.productPriceId;pt=t.productTypeId;p=t.isHotDeal;wt=t.canPurchaseSubscription;di=t.rewardsEligible;o=t.isLoyaltyPointsEnabled;r=et=t.dueOnline;ct=t.currencySymbol;w=t.grandTotal;e=t.promoCodeResults;var g=ri($("#hdfpromo").val());ui();$("#hdfpromo").val(g);$.when.apply(this,nr()).then(function(){$.templates.redeemRewardsModalTmpl.link("#redeem-rewards-tmpl-container",n)}).then(tr).done(function(){ti();bi();u&&($("#hdfpromo").val(""),v(i))});kt=l;lt=k}function nr(){for(var n,r,i=[],t=0;t<dt.length;t++)n=dt[t],r=n.isPath?n.tmplPath:"/Tmpls/_"+n.tmplPath+".tmpl.html",i.push(GolfNow.Web.Client.LoadTemplate(r,n.accessorName,n.helpers));return i}function tr(){$("#frmPromoCode").on("blur","input",function(){var n=$(this);$.trim(n.val())===""&&$("#btnPromoCode").addClass("disabled").removeClass("btn-green")}).on("keyup change paste","input",function(){var n=$(this);$.trim(n.val())!==""&&$("#btnPromoCode").addClass("btn-green").removeClass("disabled")}).on("click","#btnPromoCode:not(.disabled)",function(n){n.preventDefault();var t=$("#txtpromocode");$.trim(t.val())!==""&&(i=!0,pi(t.val(),n))}).on("keypress","input",function(n){if(n.keyCode===13){n.preventDefault();var t=$(this);$.trim(t.val())!==""&&(i=!0,pi(t.val(),n))}});$(document).on("click",".promo-used",function(n){n.preventDefault();i=!0;var t=$(this).data("promo");v(t)});$("#btnRemoveAllCodes").on("click",fr);$(document).foundation("reveal","reflow");$("#redeem-rewards-modal").on("open.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&(i=!1,c(),tt(""))});$("#redeem-rewards-modal").on("opened.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&lu()});$("#redeem-rewards-modal").on("close.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&gt()});or()&&$("#rewards-hd-apply-box").hide();GolfNow.Web.Page.Sub("enable-all-checkboxes",function(){var t=n.eligibleCouponCodes.slice();$.each(t,function(t){$.observable(n.eligibleCouponCodes[t]).setProperty({isDisabled:!1})})});GolfNow.Web.Page.Sub("disable-all-checkboxes",function(){var t=n.eligibleCouponCodes.slice();$.each(t,function(t){$.observable(n.eligibleCouponCodes[t]).setProperty({isDisabled:!0})})});(s||b||membershipNotEligibleErrMsgFound)&&ir()}function ir(){$(document).on("opened.fndtn.reveal","#msgModal",function(n){if(n.namespace==="fndtn.reveal"){var r=s?$("#hdffreetrialerrmsgfound"):h?$("#hdfmembershipnoteligibleerrmsgfound"):$("#hdfreservationrestrictederrmsgfound"),u=s?s:h?h:b,t=$("#msgModal #modalTitle"),f=t.text(),e=h?"Ineligible for GolfPass Member Rate":f,i=$("#msgModal #contenterror");i.html(i.text());t.text(e);r.val(u)}})}function rr(){var n=$("#redeem-rewards-modal .redeem-rewards-code-rows").find(":checkbox:disabled").length,t=$("#redeem-rewards-modal .redeem-rewards-code-rows").find(":checkbox").length;return n===t}function ur(){$.observable(n).setProperty("allChecked",n.selectedRewards.length===n.eligibleCouponCodes.length&&n.selectedRewards.length>0);$.observable(n).setProperty("allNotChecked",n.selectedRewards.length>0)}function gt(){var n=u();n.length?$("#applyRewardsBtn").find("span").text("Modify"):$("#applyRewardsBtn").find("span").text("Redeem")}function ni(n){$("#lblpromoerror").hide();var t=$.trim($("#txtpromocode").val())||n;t===""?$("#lblpromoerror").show():(rt("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo"),k(sr(t),function(n){var r,u;l("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo");r=hr(t,n);cr(t,r);i&&($("#txtpromocode").val("").focus(),u=_.isArray(n.promoCodeResults)&&n.promoCodeResults.length>0?n.promoCodeResults[0].isStackable:!0,t!==""&&typeof t!="undefined"&&eu(t,r,u));d(n);nt();c();it(r);GolfNow.Web.Page.Pub("checkPromoCodeComplete",n)},function(n){if(l("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo"),ci(replaceAll(unicodeParse(n.responseText),'"',""),"Invalid Promo Code"),ut(t),$("#frmPromoCode").show(),i&&($("#txtpromocode").val("").focus(),n.status===404)){var r=p?"Trade":"Course";TrackGoogleEvent("failedPromoCodeEntry","Failed Promo Codes","Failed Application",t+" | "+y+" | "+r,null)}}))}function v(n){n===""?$("#lblpromoerror").show():(rt("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details"),k(br(n),function(t){l("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details");lr(n);$("#txtpromocode").val("");i&&ut(n);d(t);c();it("",!0);t.hasDiscounts||$("#remove-promo .promo-code a").length===0&&($("#remove-promo").hide(),si());GolfNow.Web.Page.Pub("removePromoCodeComplete",t)},function(t){l("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details");ci(unicodeParse(t.responseText),"Checkout Promo code");ut(n)}))}function fr(){var t=u(),i;t.length&&!rr()&&(i=n.selectedRewards.slice(),$.each(i,function(){$.observable(n.selectedRewards).remove()}),v(t))}function k(n,i,r){var b=$("#UseGiftCardFunds").prop("checked"),k=$("#UseAccountBalance").prop("checked"),d=$("#PrimaryReservationId").val(),g=$("#hdfemailpromo").val(),nt=ft($("#hdfissitepromocodeinvalid").val()),tt=ft($("#hdffreetrialerrmsgfound").val()),it=ft($("#hdfmembershipnoteligibleerrmsgfound").val()),f=0,s=$("#btn-apply-loyalty-points").hasClass("applied"),h=o?GolfNow.Web.LoyaltyPoints.GetAllowedLoyaltyDiscountPoints():0,c=GolfNow.Web.LoyaltyPoints.IsGPPointsUpgradeFlow(),l=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true",u=!1,a,v,w;$("#AddVIP").length>0&&(u=$("#AddVIP").prop("checked"),vu(u));o&&c&&s?f=l?0:h:o&&!c&&(s||u)&&(f=l?0:h);a=GolfNow.Web.TeeTimeProtection.UpdateTeeTimeProtection();v=GolfNow.Web.WeatherProtection.UpdateWeatherProtection();hu();n=ri(n);w=GolfNow.Web.Request.Post("get-invoice-totals",st,JSON.stringify({promocode:n,charityamount:ei(),roundup:oi(),customeremail:ht,teetimeid:at,players:vt,facilityId:y,giftcardbalance:kr(),usegiftcardbalance:b,hasVIPPurchase:u,accountbalancebalance:ot,useaccountbalancebalance:k,primaryReservationId:d,emailOptInPromo:g,productPriceId:yt,productTypeId:pt,isHotDeal:p,canPurchaseSubscription:wt,isSitePromoCodeInvalid:nt,freeTrialErrMsgFound:tt,purchaseCancellationProtection:a,purchaseWeatherProtection:v,allowedLoyaltyDiscountPoints:f,memberPricingTier:lt,membershipNotEligibleErrMsgFound:it}));w.done(function(n){e=t=typeof n=="undefined"?null:n.promoCodeResults;ar();vr();yr();i(n);ui();wi();gt();ur();cu(n)}).fail(function(n,t,i){r(n,t,i);vi();wi()})}function d(n){var s=n.hasDiscounts,u=typeof n.discountList!="undefined"&&n.discountList!==null&&n.discountList!=="",f,t,r;if($("#grandtotal").html(n.grandTotal),nu(n.grandTotal),$("#duecourse").html(n.dueAtCourse),$(".due-online").html(n.dueOnline),$(".dueonline").html(n.dueOnline),$("#discount").html("- "+n.discountTotal),$("#taxesandfees").html(n.taxesAndFees),$("#salestax").html(n.salesTax),$("#donation-amount").html(n.charitableDonation),gr(n.charitableDonation),$("#giftdiscount").html("- "+n.giftCardAmount.formattedBalanceApplied),$("#accountbalancediscount").html("- "+n.accountBalanceAmount.formattedBalanceApplied),$("#account-balance-applied").html(n.accountBalanceAmount.formattedBalanceApplied),$("#giftfundstotal").html(n.giftCardAmount.formattedAvailableBalance),$("#giftfundsapplied").html(n.giftCardAmount.formattedBalanceApplied),$("#giftfundsremaining").html(n.giftCardAmount.formattedBalanceRemaining),$("#hdfgiftcredit").val(n.giftCardAmount.availableBalance),$("#hdfbalanceapplied").val(n.giftCardAmount.balanceApplied),$("#hdfbalanceremaining").val(n.giftCardAmount.balanceRemaining),$("#account-balance-funds-total").html(n.accountBalanceAmount.formattedAvailableBalance),$("#account-balance-applied").html(n.accountBalanceAmount.formattedBalanceApplied),$("#account-balance-remaining").html(n.accountBalanceAmount.formattedBalanceRemaining),$("#hdfaccountbalance").val(n.accountBalanceAmount.availableBalance),$("#hdfaccountbalanceapplied").val(n.accountBalanceAmount.balanceApplied),$("#hdfaccountbalanceremaining").val(n.accountBalanceAmount.balanceRemaining),GolfNow.Web.TeeTimeProtection.ShowHideCancellationProtectionLineItem(n.cancellationProtectionFee),GolfNow.Web.WeatherProtection.ShowHideWeatherProtectionLineItem(n.weatherProtectionFee),GolfNow.Web.WeatherProtection.ShowHideGolfPassDiscount(n),o&&GolfNow.Web.LoyaltyPoints.UpdateLoyaltyPointsBox(n),f=$vipCheckbox.is(":checked"),t=n.productInvoice||null,t!==null&&t.items!==null&&f&&iu(t),s||u?nt():si(),$("#transactiontotal").length){var h=n.showCurrencyCode,c=n.currencyCode,l=n.currencySymbol,i=0,e=0;t!==null&&(e=t.totalDue.value,i=t.totalDue.formattedValue2,t.totalDue.showCurrencyCode&&(i+=" "+productInoice.totalDue.currencyCode),$("#membership-trans-subtotal").html(i));r=l+(Number(e)+Number(n.dueOnlineTransactionTotal)).toFixed(2);h&&(r+=" "+c);$("#transactiontotal").html(r)}$("#discount-list").remove();$("#discount-list.tooltip").remove();u&&$("#discount-tooltip").before('<span id="discount-list" data-tooltip aria-haspopup="true" class="has-tip tip-bottom radius" title="'+n.discountList+'"><i class="gn-information"><\/i><\/span>');$(document).foundation("tooltip","reflow");ti(n);bi();er(n)}function er(n){var t=n.nonRefundableSubtotal,i=$("#non-refundable-subtotal-box"),r=$("#non-refundable-subtotal");Number(t.value)>0?(r.html(t.formattedValue2),i.show()):i.hide()}function ti(t){t!==null&&typeof t!="undefined"?(r=$("<div>"+t.dueOnline+"<\/div>").text(),t.discountTotal=$("<div>"+t.discountTotal+"<\/div>").text(),$.observable(n).setProperty({dueOnline:r,discountTotal:"- "+t.discountTotal})):(r=$("<div>"+r+"<\/div>").text(),a=$("<div>"+a+"<\/div>").text(),$.observable(n).setProperty({dueOnline:r,discountTotal:"- "+a}));vi()}function ii(){var n=r,t=Number(n.replace(/[^0-9\.]+/g,""));return t===0}function or(){var n=Number(et.replace(/[^0-9\.]+/g,""));return n===0}function sr(n){if(n=typeof n=="undefined"?null:n,!n)return li();var t=u();return t=ai(t,n),t.join("|")}function hr(n,t){var i="";return t.promoCodeResults!==null&&$.each(t.promoCodeResults,function(t,r){if(r.promoCode===n)return i=r.message,!1}),i}function cr(n,t){var r,f,i,e;(n=typeof n=="undefined"?null:n,t=typeof n=="undefined"?"":t,n)&&(r=u(),r=ai(r,n),$("#hdfpromo").val(r.join("|")),n!==""&&typeof n!="undefined"&&(f=$("<span />").addClass("codeused").text(n),i=$("<p />"),i.append($("<i />").addClass("gn-close")),t===null||typeof t=="undefined"||t.trim().length===0?i.append(document.createTextNode("Promo Code ")).append(f).append(document.createTextNode(" applied.")):i.append(f).append($("<div><\/div>").html(" &ndash; ").text()).append(document.createTextNode(t)),e=$("<a />").addClass("promo-used").attr("data-promo",n),e.append(i),$("#remove-promo .promo-code").append(e)))}function lr(n){var t,i,r;(n=typeof n=="undefined"?null:n,n)&&(t=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n],i=_.difference(u(),t),$("#hdfpromo").val(i.join("|")),r=$("#remove-promo .promo-code a"),$.each(r,function(n,i){_.contains(t,$(i).find(".codeused").text())&&$(i).remove()}))}function ar(){if(t){var i=_.isArray(t)?t:[],n=_.filter(i,function(n){return n.isSitePromoCode!==!0});t=n;n=_.map(n,function(n){return n.promoCode});$("#hdfpromo").val(n.join("|"))}}function vr(){if(t){var i=_.isArray(t)?t:[],n=_.filter(i,function(n){return n.isSideCartPromoCode!==!0});t=n;n=_.map(n,function(n){return n.promoCode});$("#hdfpromo").val(n.join("|"))}}function ri(n){if(n=typeof n=="undefined"?null:n,n){var t=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n],i=_.filter(t,function(n){return n!==g()}),r=_.difference(i,fi());return r.join("|")}}function yr(){if(t){var i=_.isArray(t)?t:[],n=_.filter(i,function(n){return n.isUniversalPromoCode!==!0});t=n;n=_.map(n,function(n){return n.promoCode});$("#hdfpromo").val(n.join("|"))}}function ui(){$("#remove-promo a").each(function(n,t){var r=$(t),u=r.data("promo"),f=g(),i=fi(),e=u===f||i!==null&&!_.isEmpty(i)&&i.indexOf(u)!==-1;e&&r.addClass("hide")});var n=$("#remove-promo :not(a.hide)[data-promo]").length;n===0?$("#remove-promo hr").hide():$("#remove-promo hr").show()}function g(){var n=_.findWhere(e,{isSitePromoCode:!0})||null;return n!==null?n.promoCode:""}function pr(){var n=_.findWhere(e,{isSideCartPromoCode:!0})||null;return n!==null?n.promoCode:""}function fi(){var n=_.filter(e,function(n){return n.isUniversalPromoCode==!0});return _.map(n,function(n){return n.promoCode})}function wr(n){var i=_.filter(e,function(n){return n.isUniversalPromoCode==!0}),t=_.findWhere(i,{promoCode:n})||null;return t!==null?t.promoCode:""}function br(n){if(n=typeof n=="undefined"?null:n,!n)return li();var t=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n],i=_.difference(u(),t);return i.join("|")}function kr(){return Number($("#hdfgiftcredit").val())}function ei(){var n=0;return $(".charity-amount").each(function(t,i){var r=$(i).val();r=parseFloat(r);isNaN(r)||(n+=r)}),n}function dr(){var n=$("#donation-amount").text();return parseFloat(n.replace(/[^0-9\.]+/g,""))}function gr(n){bt=parseFloat(n.replace(/[^0-9\.]+/g,""));var t=bt>0;t||GolfNow.Web.Page.Pub("removeRoundUpDonation")}function nu(n){w=n}function tu(){return parseFloat(w.replace(/[^0-9\.]+/g,""))}function oi(){var n=$("a.button.charity.selected"),t;return n.length&&(t=n.hasClass("roundup"),t)?!0:$(".roundup-donation").is(":checked")}function iu(n){var t=n.discountList||[],i;t.length?(i=_.reduce(t,function(n,t){return n+(", "+t)}),ru(i,n)):uu()}function ru(n,t){var r="- "+t.totalDiscountAmount.formattedValue2,i;t.totalDiscountAmount.showCurrencyCode&&(r+=" "+t.totalDiscountAmount.currencyCode);i=t.totalDue.formattedValue2;t.totalDue.showCurrencyCode&&(i+=" "+invoince.totalDue.currencyCode);$("#product-dueonline").html(i);$("#product-discount").html(r);$("#product-discount-list").html(n);$("#product-promocoderesult").removeClass("hide")}function uu(){$("#product-promocoderesult").addClass("hide");$("#product-discount-list").html("");$("#product-dueonline").html("");$("#product-discount").html("")}function c(){$("#remove-promo").show()}function nt(){$("#promocoderesult").show()}function si(){$("#promocoderesult").hide()}function hi(){$("#manual-redeem-code-message").hide()}function tt(n){n=ii()?n+'<div id="promo-no-longer-applied" class="rewards-modal-message italic">Promo codes can no longer be applied as your total due online has reached '+ct+"0. Please return to checkout to complete the reservation.<\/div>":n;f||(n='<span class="display-font">'+n+'<span><div class="rewards-modal-message italic">This promotion cannot be combined with any other offer.<\/div>');$("#manual-redeem-code-message").html(n);$("#manual-redeem-code-message").show()}function it(n,t){i&&n!==""&&(t||_.isUndefined(t))?showMessage('<span class="display-font font-18">'+n+"<\/span>"):(n!==""||n===""&&t)&&tt('<span class="display-font font-18">'+n+"<\/span>")}function ci(n,t){i?(showMessage(t,n),hi()):(tt('<span class="color-red display-font">'+t+"<br />"+n+"<\/span>"),c())}function li(n){n=typeof n=="undefined"?null:n;var t=u();return n&&t.push(n),t.join("|")}function u(){var n=$("#hdfpromo").val();return n===""?[]:n.split("|")}function ai(n,t){var i=_.isArray(t)?t:t.split("|");return _.union(n,i)}function rt(n,t){n=typeof n=="undefined"?null:n;t=typeof t=="undefined"?null:t;$(n).show();t&&$(t).hide();hi();GolfNow.Web.Page.Pub("disable-all-checkboxes",!0)}function l(n,t){n=typeof n=="undefined"?null:n;t=typeof t=="undefined"?null:t;$(n).hide();t&&$(t).show();GolfNow.Web.Page.Pub("enable-all-checkboxes",!1)}function vi(){var t=ii();$.observable(n).setProperty("isDueOnlineZero",t);var e=n.eligibleCouponCodes.slice(),u=!1,i=!1,r=n.selectedRewards.length===0;fu(e);$("#AddVIP").length>0&&(u=$("#AddVIP").prop("checked"));$("#UseAccountBalance").length>0&&(i=$("#UseAccountBalance").prop("checked"));$.each(e,function(e,o){$.observable(n.eligibleCouponCodes[e]).setProperty({isDisabled:r&&!u&&!i?!1:!_.contains(n.selectedRewards,o.code)&&t||!_.contains(n.selectedRewards,o.code)&&f&&!o.isStackable&&!r||!_.contains(n.selectedRewards,o.code)&&!f&&!r||u&&t||i&&t&&r||i&&t&&!_.contains(n.selectedRewards,o.code),isChecked:_.contains(n.selectedRewards,o.code)})})}function fu(t){var i=_.map(n.selectedRewards,function(n){return _.findWhere(t,{code:n})});f=_.some(i,{isStackable:!0});f=i.length<=0?!0:f}function eu(t,i,r){var f,u;t!==null&&t!==undefined&&(f=yi(t),f!==-1?$.observable(n.selectedRewards).insert(0,t):(i=i||"Promo Code",u={code:t,expirationDate:"",id:t,isChecked:!0,isDisabled:!1,name:t,shortDescription:i,isStackable:r},$.observable(n.selectedRewards).insert(0,u.code),$.observable(n.eligibleCouponCodes).insert(0,u)))}function ut(t){if(t!==null&&t!==undefined){var i=yi(t),r=su(t);i!==-1&&$.observable(n.selectedRewards).remove(r)}}function ou(n,t){var i=t.view.data;_.contains(this.selectedRewards,i.code)?v(i.code):($("#promo-code-toggle-wrapper").is(":hidden")&&$("#lnk-promo-code-toggle").trigger("click"),ni(i.code))}function yi(t){var i=n.eligibleCouponCodes.slice(),r=_.map(i,function(n){return n.code});return $.inArray(t,r)}function su(t){var i=n.selectedRewards.slice(),r=_.map(i,function(n){return n});return $.inArray(t,_.uniq(r))}function pi(t){var i=_.contains(n.selectedRewards,t),r=t===g(),u=t===pr(),f=t===wr(t);i||r||u||f?(it("This Promo Code is already applied"),$("#txtpromocode").val("").focus()):ni()}function hu(){$("#applyRewardsBtn").addClass("disabled").attr("disabled",!0).prepend('<i class="fa-solid fa-loader fa-spin"><\/i>')}function wi(){$("#applyRewardsBtn").removeClass("disabled").attr("disabled",!1).find(".fa-loader").remove()}function cu(n){var t=n.dueOnlineTransactionTotal,u=parseFloat(n.charitableDonation.replace("$",""))>0,r=parseInt((t-parseInt(t))*1e3)>0,i=$(".roundup-donation"),f=$("a.button.charity.selected");i.length&&_.each(i,function(n){var t=$(n),i=t.is(":checked");i||(r?t.removeAttr("disabled"):t.attr("disabled","disabled"))})}function lu(){var n=!1;_.forEach($(".redeem-rewards-label .round span"),function(t){var i=$(t),r,u,f,e;i.length&&(r=i.prop("scrollWidth")>i.prop("clientWidth"),r&&(n=!0,u=i.closest(".redeem-rewards-code-rows").data("short-description"),f=i.parents(".redeem-rewards-code-rows").find(".redeem-rewards-moreinfo").length>0,f||(e="<i class='gn-information redeem-rewards-moreinfo has-tip tip-right' data-tooltip aria-haspopup='true' title='"+u+"'><\/i>",i.closest(".redeem-rewards-label").after(e))))});n&&$(document).foundation("tooltip","reflow")}function au(){return $("#redeem-rewards-modal .redeem-rewards-code-rows").find(":checkbox:checked").length}function bi(){var t=Number(r.replace(/[^0-9\.]+/g,""));n.rewardsAvailable&&t>0&&$(".rewards-hd-apply-box").show()}function vu(n){n?($("#add-vip-button").css("background-color","transparent"),$("#add-vip-button").css("border-color","transparent"),$("#add-vip-button").css("padding","0px"),$("#add-vip-button label span").text("Remove")):($("#add-vip-button label span").text(kt),$("#add-vip-button").css("border-color","white"),$("#add-vip-button").css("padding","8px"))}function ft(n){var t=typeof n=="boolean",i=n!==null&&typeof n!="undefined"&&n!=="";return t?n:i?n.toLowerCase()==="true":!1}var f,a,r,et,ki,ot,st,ht,ct,lt,at,vt,y,yt,pt,p,wt,di,o,i=!1,n,bt,w,e,t,s=!1,h=!1,b=!1,kt,dt=[{tmplPath:"RedeemRewardsModal",accessorName:"redeemRewardsModalTmpl",isPath:!1}];return{initPage:gi,GetInvoiceTotals:k,UpdateInvoicePrice:d,showPromoCodeResult:nt,togglePromoCodeForm:c,hideThrobber:l,showThrobber:rt,GetDonationTotal:ei,IsRoundUpSelected:oi,RewardsViewModel:function(){return n},GetAppliedDonationAmount:dr,GetGrandTotal:tu,NumberOfSelectedCodes:au}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.StandAloneProductRewards=GolfNow.Web.StandAloneProductRewards||{};GolfNow.Web.StandAloneProductRewards=function(){function gt(t,i,f){n=t;n.isDueOnlineZero=!1;n.allChecked=!1;n.allNotChecked=!1;n.selectedRewards=[];n.executeRewardOnChange=ai;_.map(n.eligibleCouponCodes,function(n){return n.name=n.id=n.code,n.isChecked=!1,n.isDisabled=!1,n});o=t.discountTotal;tt=t.urlPostGetInvoiceDetails;it=t.productPriceId;r=nt=t.dueOnline;l=t.currencySymbol;a=t.productName;rt=totalDueAmount;s=t.isLoyaltyPointsEnabled;u=t.promoCodesApplied;$.when.apply(this,ni()).then(function(){$.templates.redeemRewardsModalTmpl.link("#redeem-rewards-tmpl-container",n)}).then(ti).done(function(){if(ct(u),st(),f){$("#hdfpromo").val("");c(u);var n=$("#hdfurlpromo").val();n!==""&&h(n)}})}function ni(){for(var n,r,i=[],t=0;t<ut.length;t++)n=ut[t],r=n.isPath?n.tmplPath:"/Tmpls/_"+n.tmplPath+".tmpl.html",i.push(GolfNow.Web.Client.LoadTemplate(r,n.accessorName,n.helpers));return i}function ti(){$("#frmPromoCode").on("blur","input",function(){var n=$(this);$.trim(n.val())===""&&$("#btnPromoCode").addClass("disabled").removeClass("btn-green")}).on("keyup change paste","input",function(){var n=$(this);$.trim(n.val())!==""&&$("#btnPromoCode").addClass("btn-green").removeClass("disabled")}).on("click","#btnPromoCode:not(.disabled)",function(n){n.preventDefault();var i=$("#txtpromocode");$.trim(i.val())!==""&&(t=!0,kt(i.val()))}).on("keypress","input",function(n){if(n.keyCode===13){n.preventDefault();var i=$(this);$.trim(i.val())!==""&&(t=!0,kt(i.val()))}});$(document).on("click",".promo-used",function(n){n.preventDefault();t=!0;var i=$(this).data("promo");c(i)});ri();et();ui();$("#btnRemoveAllCodes").on("click",ei);$("#btnSelectAllCodes").on("click",fi);$("#redeem-rewards-modal").on("open.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&(t=!1,f(),w(""))});$("#redeem-rewards-modal").on("close.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&ot()});oi()&&$("#rewards-hd-apply-box").hide();GolfNow.Web.Page.Sub("enable-all-checkboxes",function(){var t=n.eligibleCouponCodes.slice();$.each(t,function(t){$.observable(n.eligibleCouponCodes[t]).setProperty({isDisabled:!1})})});GolfNow.Web.Page.Sub("disable-all-checkboxes",function(){var t=n.eligibleCouponCodes.slice();$.each(t,function(t){$.observable(n.eligibleCouponCodes[t]).setProperty({isDisabled:!0})})})}function ii(){if(rewardsCodes.length){if(showRedirectFromTrialModal)return $("#rewards-promo-modal").foundation("reveal","open"),$("#apply-rewards-btn").attr("disabled",!1),!1;$("#redeem-rewards-modal").foundation("reveal","open");GolfNow.Web.Page.Sub("promo-code-addedToList",function(){t||TrackGoogleEvent("membershipRewardApply","Membership Promo Apply","Success",a)});GolfNow.Web.Page.Sub("check-promo-code-failed",function(){t||TrackGoogleEvent("membershipRewardApply","Membership Promo Apply","Failure",a)})}}function ft(){var n=$("#redeem-rewards-modal .redeem-rewards-code-rows").find(":checkbox:disabled").length,t=$("#redeem-rewards-modal .redeem-rewards-code-rows").find(":checkbox").length;return n===t}function ri(){$("#btnSelectAllCodes").show();$("#btnRemoveAllCodes").removeClass("left").addClass("right");$("#btnReturnToCheckout").removeClass("right").css("width","100%")}function ui(){var t=n.eligibleCouponCodes.slice();rewardsCodes.length&&$.each(t,function(t,i){$.observable(n.eligibleCouponCodes[t]).setProperty({shortDescription:l+i.value+" Loyalty Reward"})})}function et(){$.observable(n).setProperty("allChecked",n.selectedRewards.length===n.eligibleCouponCodes.length&&n.selectedRewards.length>0);$.observable(n).setProperty("allNotChecked",n.selectedRewards.length>0)}function ot(){var n=i();n.length?$("#applyRewardsBtn").find("span").text("Modify"):$("#applyRewardsBtn").find("span").text("Apply Rewards")}function h(n){$("#lblpromoerror").hide();var i=$.trim($("#txtpromocode").val())||n;i===""?$("#lblpromoerror").show():(g("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo"),v(si(i),function(n){e("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo");var u=!_.isNull(n)&&!_.isNull(n.discountList)&&!_.isEmpty(n.discountList)?n.discountList:[],r=hi(u,n);ct(u,r);t&&($("#txtpromocode").val("").focus(),_.contains(n.discountList,i)?pt(i,r):k("We're sorry, we couldn't find that promotion code. Please check the spelling (codes are case sensitive) and try again.","Invalid Promo Code"));y(n);p();f();b(r)},function(n){e("#throbber-container, #redeem-throbber-container",".promo-details, #remove-promo");k(replaceAll(unicodeParse(n.responseText),'"',"").replace(/[\{\}\:]|\message\b/g,""),"Invalid Promo Code");wt(i);$("#frmPromoCode").show();t&&$("#txtpromocode").val("").focus();GolfNow.Web.Page.Pub("check-promo-code-failed")}))}function c(n){n===""?$("#lblpromoerror").show():(g("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details"),v(li(n),function(i){e("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details");ci(n);$("#txtpromocode").val("");t&&wt(n);y(i);f();b("",!1);i.totalDiscountAmount.value<=0&&$("#remove-promo .promo-code a").length===0&&($("#remove-promo").hide(),lt())},function(t){e("#throbber-container, #redeem-throbber-container","#remove-promo, .promo-details");k(unicodeParse(t.responseText),"Checkout Promo code");GolfNow.Web.Page.Pub("remove-promo-code-failed");pt(n)}))}function fi(){var r=n.eligibleCouponCodes.slice(),t=_.map(r,function(n){return n.code}),i;t.length&&!ft()&&(i=_.difference(t,n.selectedRewards),$.each(i,function(t,i){$.observable(n.selectedRewards).insert(t,i)}),h(t))}function ei(){var t=i(),r;t.length&&!ft()&&(r=n.selectedRewards.slice(),$.each(r,function(){$.observable(n.selectedRewards).remove()}),c(t))}function v(n,t,i){var u=$("#UseGiftCardFunds").prop("checked"),f=$("#UseAccountBalance").prop("checked"),r=0,e=$("#btn-apply-loyalty-points").hasClass("applied"),o=s?GolfNow.Web.LoyaltyPointsVIP.GetAllowedLoyaltyDiscountPoints():0,h=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true";s&&e&&(r=h?0:o);pi();$.ajax({url:tt,type:"POST",datatype:"json",data:{promoCode:n,productPriceId:Number(it),giftcardbalance:GolfNow.Web.StandAloneGiftCardsCredits.GetGiftCardBalance(),usegiftcardbalance:u,accountbalancebalance:accountBalanceFunds,useaccountbalancebalance:f,allowedLoyaltyDiscountPoints:r},success:function(n){GolfNow.Web.StandAloneGiftCardsCredits.SetInvoiceAndGiftCardAccountBalanceObjects(n.invoice,n.accountBalanceAmount,n.giftCardAmount,n.totalDueAmount);t(GolfNow.Web.StandAloneGiftCardsCredits.GetProductInvoice());dt();ot();et()},error:function(n,t,r){i(n,t,r.message);yt();dt()}})}function y(n){var t=typeof n.discountList!="undefined"&&n.discountList!==null&&n.discountList!==""&&n.discountList.length>0;$.observable(invoiceModel).setProperty(n);n.totalDiscountAmount.value>0?p():lt();s&&GolfNow.Web.LoyaltyPointsVIP.UpdateLoyaltyPointsBox(n);$("#discount-list").remove();$("#discount-list.tooltip").remove();t&&$("#discount-tooltip").before('<span id="discount-list" data-tooltip aria-haspopup="true" class="has-tip tip-bottom radius" title="'+n.discountList+'"><i class="gn-information"><\/i><\/span>');$(document).foundation("tooltip","reflow");st(n);GolfNow.Web.StandAloneGiftCardsCredits.UpdateAccountBalanceGiftCard()}function st(t){t!==null&&typeof t!="undefined"?(r=$("<div>"+t.totalAmountDueFormatted+"<\/div>").text(),t.totalDiscountAmount.formattedValue=$("<div>"+t.totalDiscountAmount.formattedValue+"<\/div>").text(),$.observable(n).setProperty({dueOnline:r,discountTotal:"- "+t.totalDiscountAmount.formattedValue})):(r=$("<div>"+rt+"<\/div>").text(),o=$("<div>"+o+"<\/div>").text(),$.observable(n).setProperty({dueOnline:r,discountTotal:"- "+o}));yt()}function ht(){var n=r,t=Number(n.replace(/[^0-9\.]+/g,""));return t===0}function oi(){var n=Number(nt.replace(/[^0-9\.]+/g,""));return n===0}function si(n){if(n=typeof n=="undefined"?null:n,!n)return d();var t=i();return t=vt(t,n),t.join("|")}function hi(n,t){var i="";return t.promoCodeResults!==null&&$.each(t.promoCodeResults,function(t,r){if(r.promoCode===n)return i=r.message,!1}),i}function ct(n,t){if(n=typeof n=="undefined"?null:n,t=typeof n=="undefined"?"":t,n){var r=i(),u=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n];_.each(u,function(n){var u,i,f;_.contains(r,n,0)||(r=vt(r,n),$("#hdfpromo").val(r.join("|")),u=$("<span />").addClass("codeused").text(n),i=$("<p />"),i.append($("<i />").addClass("gn-close")),t===null||typeof t=="undefined"||t.trim().length===0?i.append(document.createTextNode("Promo Code ")).append(u).append(document.createTextNode(" applied.")):i.append(u).append($("<div><\/div>").html(" &ndash; ").text()).append(document.createTextNode(t)),f=$("<a />").addClass("promo-used").data("promo",n),f.append(i),$("#remove-promo .promo-code").append(f))});GolfNow.Web.Page.Pub("promo-code-addedToList")}}function ci(n){var t,r,u;(n=typeof n=="undefined"?null:n,n)&&(t=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n],r=_.difference(i(),t),$("#hdfpromo").val(r.join("|")),u=$("#remove-promo .promo-code a"),$.each(u,function(n,i){_.contains(t,$(i).find(".codeused").text())&&$(i).remove()}),GolfNow.Web.Page.Pub("promo-code-removedFromList"))}function li(n){if(n=typeof n=="undefined"?null:n,!n)return d();var t=_.isArray(n)?n:n.indexOf("|")!==-1?n.split("|"):[n],r=_.difference(i(),t);return r.join("|")}function f(){$("#remove-promo, .promo-code-toggle-wrapper").show()}function p(){$("#promocoderesult").show()}function lt(){$("#promocoderesult").hide()}function at(){$("#manual-redeem-code-message").hide()}function w(n){n=ht()?n+'<div id="promo-no-longer-applied">Promo codes can no longer be applied as your total due online has reached '+l+"0. Please return to checkout to complete the reservation.<\/div>":n;$("#manual-redeem-code-message").html(n);$("#manual-redeem-code-message").show()}function b(n,i){t&&(i||_.isUndefined(i))?n&&showMessage(n):w(n)}function k(n,i){t?(showMessage(i,n),at()):(w("<strong>"+i+"<\/strong><br />"+n),f())}function d(n){n=typeof n=="undefined"?null:n;var t=i();return n&&t.push(n),t.join("|")}function i(){var n=$("#hdfpromo").val();return n===""?[]:n.split("|")}function vt(n,t){var i=_.isArray(t)?t:t.split("|");return _.union(n,i)}function g(n,t){n=typeof n=="undefined"?null:n;t=typeof t=="undefined"?null:t;$(n).show();t&&$(t).hide();at();GolfNow.Web.Page.Pub("disable-all-checkboxes",!0)}function e(n,t){n=typeof n=="undefined"?null:n;t=typeof t=="undefined"?null:t;$(n).hide();t&&$(t).show();GolfNow.Web.Page.Pub("enable-all-checkboxes",!1)}function yt(){var i=ht(),r,t;$.observable(n).setProperty("isDueOnlineZero",i);r=n.eligibleCouponCodes.slice();t=!1;$("#AddVIP").length>0&&(t=$("#AddVIP").prop("checked"));$.each(r,function(r,u){$.observable(n.eligibleCouponCodes[r]).setProperty({isDisabled:n.selectedRewards.length===0&&!t?!1:!_.contains(n.selectedRewards,u.code)&&i||t&&i,isChecked:_.contains(n.selectedRewards,u.code)})})}function pt(t,i){var u,r;t!==null&&t!==undefined&&(u=bt(t),u!==-1?$.observable(n.selectedRewards).insert(0,t):(i=i||"Promo Code",r={code:t,expirationDate:"",id:t,isChecked:!0,isDisabled:!1,name:t,shortDescription:i},$.observable(n.selectedRewards).insert(0,r.code),$.observable(n.eligibleCouponCodes).insert(0,r)))}function wt(t){if(t!==null&&t!==undefined){var i=bt(t),r=vi(t);i!==-1&&$.observable(n.selectedRewards).remove(r)}}function ai(n,t){var i=t.view.data;_.contains(this.selectedRewards,i.code)?c(i.code):($("#promo-code-toggle-wrapper").is(":hidden")&&$("#lnk-promo-code-toggle").trigger("click"),h(i.code))}function bt(t){var i=n.eligibleCouponCodes.slice(),r=_.map(i,function(n){return n.code});return $.inArray(t,r)}function vi(t){var i=n.selectedRewards.slice(),r=_.map(i,function(n){return n});return $.inArray(t,_.uniq(r))}function kt(t){var i=_.contains(n.selectedRewards,t);i||yi(t)?(b("This Promo Code is already applied"),$("#txtpromocode").val("").focus()):h()}function yi(n){var t=u!==null&&typeof u!="undefined"?u.split("|"):"";return _.contains(t,n)}function pi(){$("#applyRewardsBtn").addClass("disabled").attr("disabled",!0).append('<i class="fa-solid fa-loader fa-spin" style="vertical-align: middle; margin-left: 10px;"><\/i>')}function dt(){$("#applyRewardsBtn").removeClass("disabled").attr("disabled",!1).find(".fa-loader").remove()}var o,r,nt,tt,l,a,it,t=!1,n,rt,s,u,ut=[{tmplPath:"RedeemRewardsModal",accessorName:"redeemRewardsModalTmpl",isPath:!1}];return{initPage:gt,GetInvoiceTotals:v,UpdateInvoicePrice:y,showPromoCodeResult:p,togglePromoCodeForm:f,getPromoCodesString:d,ApplyRewards:ii,hideThrobber:e,showThrobber:g,RewardsViewModel:function(){return n}}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.StandAloneGiftCardsCredits=GolfNow.Web.StandAloneGiftCardsCredits||{};GolfNow.Web.StandAloneGiftCardsCredits=function(){function s(n){h();u();f();_siteKey=n}function h(){$(".additional-payments-info-wrapper").on("click","#lnk-promo-code-toggle",function(n){var t=$(n.currentTarget);t.hide();$(".promo-code-toggle-wrapper").show()}).on("click","#lnk-account-balance-toggle",function(n){var t=$(n.currentTarget);t.hide();$(".credits").show()}).on("click","#lnk-gift-card-toggle",function(n){var t=$(n.currentTarget);t.hide();$(".gift-card-input").show()});showGiftCardBalance&&$("#lnk-gift-card-toggle").click();useAccountBalance&&$("#lnk-account-balance-toggle").click()}function u(){var n=$("#GiftCardPinNumber");$("#txtgiftcard").on("blur",function(){var t=$(this);(t.val().trim()===""||n.is(":visible")&&n.val()==="")&&$("#gift-card-apply-button").attr("disabled","disabled")}).on("keyup change paste",function(){var t=$(this);(t.val().trim()!==""&&!n.is(":visible")||n.is(":visible")&&n.val()!=="")&&$("#gift-card-apply-button").removeAttr("disabled")}).on("keypress",function(t){if(t.key==="Enter"){t.preventDefault();var i=$(this);i.val().trim()===""||n.is(":visible")&&n.val()===""?$("#gift-card-apply-button").attr("disabled","disabled"):r(t)}});n.on("blur",function(){var n=$(this);n.val().trim()===""&&$("#gift-card-apply-button").attr("disabled","disabled")}).on("keypress",function(n){if(n.key==="Enter"){n.preventDefault();var t=$(this);t.val().trim()===""?$("#gift-card-apply-button").attr("disabled","disabled"):r(n)}}).on("keyup change paste",function(){var n=$(this);n.val().trim()!==""&&$("#gift-card-apply-button").removeAttr("disabled")});$("#gift-card-apply-button:not(.disabled)").on("click",function(n){n.preventDefault();r()});$("#UseGiftCardFunds").on("click",function(){GolfNow.Web.StandAloneProductRewards.showThrobber(".giftCardThrobber","#gift-card-checkbox, #gift-card-form");var n=$("#hdfpromo").val();GolfNow.Web.StandAloneProductRewards.GetInvoiceTotals(n,function(n){GolfNow.Web.StandAloneProductRewards.UpdateInvoicePrice(n);GolfNow.Web.StandAloneProductRewards.hideThrobber(".giftCardThrobber","#gift-card-checkbox, #gift-card-form")},function(){showMessage("Error","An error occurred")})})}function f(){$("#UseAccountBalance").on("click",function(){GolfNow.Web.StandAloneProductRewards.showThrobber(".account-balance-throbber","#account-balance-checkbox");var n=$("#hdfpromo").val();GolfNow.Web.StandAloneProductRewards.GetInvoiceTotals(n,function(n){GolfNow.Web.StandAloneProductRewards.hideThrobber(".account-balance-throbber","#account-balance-checkbox");GolfNow.Web.StandAloneProductRewards.UpdateInvoicePrice(n)},function(){showMessage("Error","An error occurred")})});$(".credits").on("blur","input",function(){var n=$(this);n.val().trim()===""&&n.parents(".gift-card").find("span.button").addClass("disabled").removeClass("btn-green")}).on("keyup change paste","input",function(){var n=$(this);n.val().trim()!==""&&n.parents(".gift-card").find("span.button").addClass("btn-green").removeClass("disabled")})}function r(){grecaptcha.ready(function(){grecaptcha.execute(_siteKey,{action:o}).then(c)})}function c(n){var t=$("#txtgiftcard").val(),i=$("#GiftCardPinNumber"),f=e(),r,u;i.is(":visible")&&i.val()===""&&showMessage("Gift Card Error","Please enter a gift card PIN number.");t===""?showMessage("Gift Card Error","Please enter a gift card number."):$.inArray(t,f)!==-1?showMessage("Gift Cards","Gift card has been previously entered."):(r=$("#gift-card-checkbox").is(":visible"),GolfNow.Web.StandAloneProductRewards.showThrobber(".giftCardThrobber","#gift-card-form, #gift-card-checkbox"),u=GolfNow.Web.Request.Post("check-giftcard",apiCheckGiftCardUrl,JSON.stringify({captcha:n,giftcard:t,giftCardPinNumber:i.val()})),u.done(function(n){$("#UseGiftCardFunds").prop("checked",!0);$(this).parent().hide();$(".gf-options").removeClass("hide-gift-card-info");l(n);$("#txtgiftcard").val("");$("#GiftCardPinNumber").val("");$("#gift-card-form").removeClass("pin-box");GolfNow.Web.StandAloneProductRewards.hideThrobber(".giftCardThrobber","#gift-card-form, #gift-card-checkbox")}).fail(function(n){var t=n.responseJson?n.responsJson.message:n.responseText;showMessage("Gift Cards",replaceAll(unicodeParse(t),'"',""));GolfNow.Web.StandAloneProductRewards.hideThrobber(".giftCardThrobber","#gift-card-form");r&&$("#gift-card-checkbox").show()}))}function l(n){var r=$("#hdfpromo").val(),t=$("#txtgiftcard").val(),u=$("#hdfgiftcredit").val(),i=n.pinNumber;$("#hdfgiftcredit").val(Number(u)+Number(n.balance.value));GolfNow.Web.StandAloneProductRewards.GetInvoiceTotals(r,function(n){$("#UseGiftCardFunds").prop("checked",!0);GolfNow.Web.StandAloneProductRewards.UpdateInvoicePrice(n);var r=e();t=typeof i!="undefined"&&i!==null&&i!==""?t+"|"+i:t;r.push(t);$("#hdfgiftlistadded").val(JSON.stringify(r))},function(){showMessage("Error","An error occurred")})}function e(){var n=$("#hdfgiftlistadded").val();return n===""?[]:JSON.parse(n)}function a(r,u,f,e){n=u;t=f;i=r;i.totalAmountDueFormatted=e;i.accountBalanceAppliedValue=u.balanceApplied;i.accountBalanceAppliedFormatted=u.formattedBalanceApplied;i.accountCreditAppliedValue=f.balanceApplied;i.accountCreditAppliedFormatted=f.formattedBalanceApplied}function v(){return Number($("#hdfgiftcredit").val())}function y(){$("#giftdiscount").html("- "+t.formattedBalanceApplied);$("#accountbalancediscount").html("- "+n.formattedBalanceApplied);$("#account-balance-applied").html(n.formattedBalanceApplied);$("#giftfundstotal").html(t.formattedAvailableBalance);$("#giftfundsapplied").html(t.formattedBalanceApplied);$("#giftfundsremaining").html(t.formattedBalanceRemaining);$("#hdfgiftcredit").val(t.availableBalance);$("#hdfbalanceapplied").val(t.balanceApplied);$("#hdfbalanceremaining").val(t.balanceRemaining);$("#account-balance-funds-total").html(n.formattedAvailableBalance);$("#account-balance-applied").html(n.formattedBalanceApplied);$("#account-balance-remaining").html(n.formattedBalanceRemaining);$("#hdfaccountbalance").val(n.availableBalance);$("#hdfaccountbalanceapplied").val(n.balanceApplied);$("#hdfaccountbalanceremaining").val(n.balanceRemaining)}function p(){return i}var n,t,i,o="GiftCardCheckout";return{initPage:s,SetInvoiceAndGiftCardAccountBalanceObjects:a,UpdateAccountBalanceGiftCard:y,GetGiftCardBalance:v,BindAccountBalanceEvents:f,BindGiftCardEvents:u,GetProductInvoice:p}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.GiftCardsCheckBalance=GolfNow.Web.GiftCardsCheckBalance||{};GolfNow.Web.GiftCardsCheckBalance=function(){function i(){t()}function t(){var t=$("#GiftCardPinNumber");$("#txtgiftcard").on("blur",function(){var n=$(this);(n.val().trim()===""||t.is(":visible")&&t.val()==="")&&$("#gift-card-apply-button").attr("disabled","disabled")}).on("keyup change paste",function(){var n=$(this);(n.val().trim()!==""&&!t.is(":visible")||t.is(":visible")&&t.val()!=="")&&$("#gift-card-apply-button").removeAttr("disabled")}).on("keypress",function(i){if(i.key==="Enter"){i.preventDefault();var r=$(this);r.val().trim()===""||t.is(":visible")&&t.val()===""?$("#gift-card-apply-button").attr("disabled","disabled"):n()}});t.on("blur",function(){var n=$(this);n.val().trim()===""&&$("#gift-card-apply-button").attr("disabled","disabled")}).on("keypress",function(t){if(t.key==="Enter"){t.preventDefault();var i=$(this);i.val().trim()===""?$("#gift-card-apply-button").attr("disabled","disabled"):n()}}).on("keyup change paste",function(){var n=$(this);n.val().trim()!==""&&$("#gift-card-apply-button").removeAttr("disabled")});$("#gift-card-apply-button:not(.disabled)").on("click",function(t){t.preventDefault();n()})}function n(){grecaptcha.ready(function(){grecaptcha.execute(siteKey,{action:reCaptchaAction}).then(r)})}function r(n){var r=$("#txtgiftcard").val(),t=$("#GiftCardPinNumber"),i=$("#gift-card-balance-wrapper"),u;i.hide().find("span").html("");t.is(":visible")&&t.val()===""&&showMessage("Gift Card Error","Please enter a gift card PIN number.");r===""?showMessage("Gift Card Error","Please enter a gift card number."):(u=GolfNow.Web.Request.Post("check-giftcard",apiCheckGiftCardUrl,JSON.stringify({captcha:n,giftcard:r,giftCardPinNumber:t.val(),saveToCustomerAccount:!1})),u.done(function(n){$("#gift-card-pin-container").is(":visible")?TrackGoogleEvent("SVSGiftCards","Gift Card Landing Page","Click","PIN True"):TrackGoogleEvent("SVSGiftCards","Gift Card Landing Page","Click","PIN False");$("#txtgiftcard").val("");$("#GiftCardPinNumber").val("");$("#gift-card-apply-button").attr("disabled","disabled");i.show().find("span").html(n.balance.formattedValue)}).fail(function(n){i.hide();var t=n.responseJson?n.responsJson.message:n.responseText;showMessage("Gift Cards",replaceAll(unicodeParse(t),'"',""))}))}return{initPage:i,BindGiftCardEvents:t}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.TeeTimeProtection=GolfNow.Web.TeeTimeProtection||{};GolfNow.Web.TeeTimeProtection=function(){function y(i){n=i;e=n.currencySymbol;r=Number(n.cancellationProtectionCreditPrice.replace(/[^0-9\.]+/g,""));u=Number(n.worryFreeCreditsTotal);t=n.userIsGolfpassMember;o=Number(n.productPrice.replace(/[^0-9\.]+/g,""))>0;f=n.isHotDeal?"Trade":"Course";s=n.showCurrencyCode;h=s?n.currencyCode:"";c=n.siteName?n.siteName:"GolfNow";l=n.isSimulator;p();a();v();b()}function p(){var n=$("#hdfpurchasecancellationprotection").val().toLowerCase()==="true";n&&$('input[name="rdlTeeTimeProtection"]').filter("[data-value=addTeeTimeProtection]").trigger("click")}function w(n){var t=$(n),i=t.data("value")==="addTeeTimeProtection",r=$("#hdfpromo").val();$("#hdfpurchasecancellationprotection").val(i);GolfNow.Web.RedeemRewards.GetInvoiceTotals(r,function(n){GolfNow.Web.RedeemRewards.UpdateInvoicePrice(n);d(n.cancellationProtectionFee)},function(){showMessage("Error","An error occurred")})}function a(){var a=$('input[name="rdlTeeTimeProtection"]:checked').data("value"),r=a==="addTeeTimeProtection",v=l?"reservation":"tee time",n="The flexibility to cancel your "+v+" up to one (1) hour before your round and receive a refund to your "+c+" account.",f="You've run out of Tee Time Protection credits. Protect today's round to allow cancellations up to 1 hour before play.",e=!1;$("#AddVIP").length>0&&(e=$("#AddVIP").prop("checked"));i=!t&&e&&o||t&&u>0;var y=!r&&!t||!t&&!o,p=r&&!t,s=r&&t&&u<=0,h=!r&&t&&u<=0;return $("#tee-time-protection-box-replacement").hide(),$("#tee-time-protection-box").show(),i?(n=t?"As a GolfPass+ member, you're covered!":"Your new membership includes protection for up to 10 rounds. Cancel up to 1 hour before play and receive a full account credit refund.",$("#cancellation-protection-info-replacement").text(n),$('input[name="rdlTeeTimeProtection"]').filter("[data-value=removeTeeTimeProtection]").prop("checked",!0),$('input[name="rdlTeeTimeProtectionReplacement"]').filter("[data-value=addTeeTimeProtection]").prop("checked",!0),$('input[name="rdlTeeTimeProtectionReplacement"]').filter("[data-value=removeTeeTimeProtection]").attr("disabled",!0),$("#add-teetime-protection-price").css({"text-decoration":"line-through","text-decoration-color":"black"}),$("#tee-time-protection-box").hide(),$("#tee-time-protection-box-replacement").show(),$("#hdfpurchasecancellationprotection").val(!1)):y||h?n=h?f:n:(p||s)&&(n=s?f:n),$("#cancellation-protection-info").text(n),$('input[name="rdlTeeTimeProtection"]:checked').data("value")==="addTeeTimeProtection"}function v(n){if(displayTeeTimeProtection){var o=$('input[name="rdlTeeTimeProtection"]:checked').data("value"),u=o==="addTeeTimeProtection",t=i?r:n!==null&&typeof n!="undefined"?Number(n.replace(/[^0-9\.]+/g,"")):r,s=t>0&&u||t===0&&u||i,f=e+Number(t).toFixed(2)+" "+h;$("#cancellation-protection-fee").html(f);i?$("#cancellation-protection-fee").css({"text-decoration":"line-through","text-decoration-color":"black"}):$("#cancellation-protection-fee").css("text-decoration","none");$("#add-teetime-protection-price-main").html(f);s?$("#cancellation-protection-fee").parent(".reservation-details").show():$("#cancellation-protection-fee").parent(".reservation-details").hide()}}function b(){var t=$("#tee-time-protection-box").is(":visible"),n;t&&(n=e+Number(r).toFixed(2),TrackGoogleEvent("teeTimeProtection","Tee Time Protection","Impression",f+" | "+n,null))}function k(){var r=$('input[name="rdlTeeTimeProtection"]:checked').data("value"),u=r==="addTeeTimeProtection",n,i;u&&(n=t?"GolfPass Member":"Non-Member",i=$("#add-teetime-protection-price-main").text(),TrackGoogleEvent("teeTimeProtection","Tee Time Protection","Enable",n+" | "+f+" | "+i,null))}function d(n){var u=$('input[name="rdlTeeTimeProtection"]:checked').data("value"),e=u==="removeTeeTimeProtection",i,r;e&&(i=t?"GolfPass Member":"Non-Member",r=n,TrackGoogleEvent("teeTimeProtection","Tee Time Protection","Disable",i+" | "+f+" | "+r,null))}var n,e,r,u,t,o,f,s,h,c,l,i;return{initPage:y,TeeTimeProtectionOnChanged:w,UpdateTeeTimeProtection:a,ShowHideCancellationProtectionLineItem:v,LogTeeTimeProtectionAnalyticsOnMakeReservation:k}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.WeatherProtection=GolfNow.Web.WeatherProtection||{};GolfNow.Web.WeatherProtection=function(){function w(f){n=f;h=n.currencySymbol;c=Number(n.weatherProtectionCreditPrice.replace(/[^0-9\.]+/g,""));t=n.userIsGolfpassMember;l=n.showCurrencyCode;a=l?n.currencyCode:"";i=n.weatherProtectionProvider;r=n.facilityName;u=n.facilityId;e=n.hasSensibleWeatherDiscount;o=n.sidecartHasSensibleWeatherDiscountBenefit;b();v();p();setTimeout(nt,500)}function b(){var n=$("#hdfpurchaseweatherprotection").val().toLowerCase()==="true";n&&$('input[name="rdlWeatherProtection"]').trigger("click")}function v(n){n&&($(".sensible-weather-suggested-price").text(n.addOnSuggestedPrice),$(".sensible-weather-discounted-price").text(n.addOnDiscountedPrice));var i=$("#AddVIP").prop("checked"),t=e||i&&o,r=o&&!e;$(".sensible-weather-gp-join-text").toggle(r);$(".sensible-weather-gp-member-text").toggle(t);$(".sensible-weather-discounted-price").toggle(t);$(".sensible-weather-suggested-price").css("text-decoration",t?"line-through":"")}function k(){y(!0)}function d(){$("#rdlWeatherProtection").is(":checked")||($("#rdlWeatherProtection").prop("checked",!0),y(!1))}function y(n){var t=$("#rdlWeatherProtection").is(":checked"),i=$("#hdfpromo").val();$("#weatherProtectionPhoneNumber").toggle(t);$("#fmcheck").valid();t&&_.isFunction(window.ValidatePaymentMethod)&&ValidatePaymentMethod(!1);$("#hdfpurchaseweatherprotection").val(t);GolfNow.Web.RedeemRewards.GetInvoiceTotals(i,function(t){GolfNow.Web.RedeemRewards.UpdateInvoicePrice(t);it(n)},function(){showMessage("Error","An error occurred")})}function g(){return $('input[name="rdlWeatherProtection"]').is(":checked")}function p(n){if(displayWeatherProtection){var i=$('input[name="rdlWeatherProtection"]').is(":checked"),t=n!==null&&typeof n!="undefined"?Number(n.replace(/[^0-9\.]+/g,"")):c,r=t>0&&i||t===0&&i,u=h+Number(t).toFixed(2)+" "+a;$("#weather-protection-fee").html(u);$("#weather-protection-name").html(f());r?$("#weather-protection-fee").parent(".reservation-details").show():$("#weather-protection-fee").parent(".reservation-details").hide()}}function nt(){var e=$("#sensible-weather").is(":visible"),n,i;e&&(n=$("#AddVIP").prop("checked"),i=t||n?"GolfPass Member":"Non-Member",TrackGoogleEvent(s(),f(),"Impression",r+" | "+u+" | "+i,null))}function tt(n){var i=$("#AddVIP").prop("checked"),e=t||i?"GolfPass Member":"Non-Member";TrackGoogleEvent(s(),f(),"Click See Details",r+" | "+u+" | "+e,null);$("#"+n).foundation("reveal","open")}function it(n){var i=$("#rdlWeatherProtection").is(":checked");if(i){var e=$("#AddVIP").prop("checked"),o=t||e?"GolfPass Member":"Non-Member",h=n?"Opt In Primary":"Opt In Secondary";TrackGoogleEvent(s(),f(),h,r+" | "+u+" | "+o,null)}}function s(){return i.charAt(0).toLowerCase()+i.slice(1)}function f(){return i.replace(/([A-Z])/g," $1").trim()}var n,h,c,t,l,a,i,r,u,e,o;return{initPage:w,WeatherProtectionOnChanged:k,WeatherProtectionAddButtonOnClicked:d,UpdateWeatherProtection:g,ShowHideWeatherProtectionLineItem:p,WeatherProtectionDetailsOnClicked:tt,ShowHideGolfPassDiscount:v}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.LoyaltyPoints=GolfNow.Web.LoyaltyPoints||{};GolfNow.Web.LoyaltyPoints=function(){function s(u){i=t=Number($("#hdfAllowedLoyaltyDiscountPoints").val());n=u;$("#hdfAllowedLoyaltyDiscountPoints").val(0);r(n,"Impression");h();l()}function h(){f=Number($("#member-pricing-instant-savings").text().replace(/[^0-9\.]+/g,""))}function c(){return i}function l(){$("#btn-apply-loyalty-points").on("click",function(n){n.preventDefault();$("#btn-apply-loyalty-points").toggleClass("applied");v();a()})}function a(){var t=$("#hdfpromo").val(),n=$("#btn-apply-loyalty-points"),i=$("#allowed-loyalty-discount-amount");n.prop("disabled",!0);GolfNow.Web.RedeemRewards.GetInvoiceTotals(t,function(t){n.prop("disabled",!1);GolfNow.Web.RedeemRewards.UpdateInvoicePrice(t)},function(){showMessage("Error","An error occurred");$("#btn-apply-loyalty-points").toggleClass("applied");n.prop("disabled",!1);i.html(u)})}function v(){var n=$("#allowed-loyalty-discount-amount");u=n.html();e()?n.html('Applying <i class="fas fa-spinner fa-spin"><\/i>'):n.html('Removing <i class="fas fa-spinner fa-spin"><\/i>')}function e(){var n=$("#btn-apply-loyalty-points").hasClass("applied"),t=$("#AddVIP").length>0&&$("#AddVIP").prop("checked"),i=o()?n:n||t;return i?!0:!1}function o(){var n=$("#loyalty-points-box").length>0,t=$("#AddVIP").length>0;return n&&t}function y(u){var ut=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true",o=$("#btn-apply-loyalty-points"),ft=o.hasClass("applied"),y=u.loyaltyEligibility.allowedLoyaltyDiscountAmountFormatted,c=u.loyaltyEligibility.totalPointsAvailableFormatted,et=u.loyaltyEligibility.allowedLoyaltyDiscountPoints,ot=u.loyaltyEligibility.allowedLoyaltyDiscountPointsFormatted,p=u.loyaltyEligibility.totalBaseEarnablePoints,w=u.loyaltyEligibility.totalBaseEarnablePointsFormatted,b=u.loyaltyEligibility.totalPromotionalEarnablePoints,k=u.loyaltyEligibility.totalPromotionalEarnablePointsFormatted,d=$("#allowed-loyalty-discount-amount"),g=$("#allowed-loyalty-discount-points"),nt=$("#loyalty-total-points-available"),tt=$("#loyalty-small-points-available-copy"),s=$("#loyalty-earnable-points-info-copy"),h=$("#loyalty-promo-earnable-points-info-copy"),l=$("#loyalty-earnable-points-info-copy-small"),st=$("#AddVIP").length>0&&$("#AddVIP").prop("checked"),it=u.loyaltyRedemptionDetail.redemptionPointsAppliedFormatted,a=Number(u.loyaltyRedemptionDetail.redemptionAmountApplied),v=u.loyaltyRedemptionDetail.redemptionAmountAppliedFormatted,rt;n.allowedLoyaltyDiscountAmountFormatted=y;n.totalPointsAvailableFormatted=c;n.redemptionPointsAppliedFormatted=it;n.redemptionAmountAppliedFormatted=v;e()?(d.html("<u>Remove<\/u>"),o.css("background-color","transparent"),o.css("border-color","transparent"),g.html(it+" points applied"),nt.html(c),tt.html("points remaining"),a>0&&($("#loyalty-points-line-item").html("-"+v),$("#loyalty-points-line-item").parent(".reservation-details").show()),p===0&&b===0&&a!==0?(rt="<span>You're saving "+v+" on your tee time with GolfPass points<\/span>",s.html(rt),h.hide(),l.hide()):p===0&&b===0&&a===0?(s.hide(),h.html("+ 0"),l.hide()):(s.html("<strike>+ "+w+"<\/strike>").show(),h.html("+ "+k).show()),r(n,"Apply"),$("#member-pricing-instant-savings").text(u.currencySymbol+u.instantSavingsRounded.toFixed(2))):(d.html("Save "+y),o.css("border-color","white"),g.html("Apply "+ot+" pts"),nt.html(c),tt.html("points"),$("#loyalty-points-line-item").parent(".reservation-details").hide(),l.show(),s.html("<strike>+ "+w+"<\/strike>").show(),h.html("+ "+k).show(),r(n,"Removed"),$("#member-pricing-instant-savings").text(u.currencySymbol+f.toFixed(2)));!ut&&(ft||st)?(t=et,$("#hdfAllowedLoyaltyDiscountPoints").val(t)):(t=i,$("#hdfAllowedLoyaltyDiscountPoints").val(0))}function r(n,t){var r=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true",i="";switch(t){case"Impression":i=" | Points Available: "+n.totalLoyaltyPointsAvailable+" | Discount Amount: "+n.allowedLoyaltyDiscountAmount;break;case"Apply":i=" | Points Redeemed: "+n.redemptionPointsAppliedFormatted+" | Discount Amount: "+n.redemptionAmountAppliedFormatted;break;default:i=""}r&&t==="Impression"?TrackGoogleEvent("golfpassPoints","GolfPass Points",t,"Below Threshold"+i):n.userIsGolfpassMember&&n.canPurchaseSubscription&&n.hasUpgradeProductPriceId?TrackGoogleEvent("golfpassPoints","GolfPass Points",t,"Upgrade Sidecart"+i):n.canPurchaseSubscription?TrackGoogleEvent("golfpassPoints","GolfPass Points",t,"Sidecart"+i):n.userIsGolfpassMember&&TrackGoogleEvent("golfpassPoints","GolfPass Points",t,"Tee Time"+i)}var t=0,i=0,u="",n={},f=0;return{initPage:s,UpdateLoyaltyPointsBox:y,GetAllowedLoyaltyDiscountPoints:c,IsGPPointsUpgradeFlow:o}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.LoyaltyPointsVIP=GolfNow.Web.LoyaltyPointsVIP||{};GolfNow.Web.LoyaltyPointsVIP=function(){function e(u){n=u;r=t=Number($("#hdfAllowedLoyaltyDiscountPoints").val());f=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true";$("#hdfAllowedLoyaltyDiscountPoints").val(0);i(n,"Impression");s()}function o(){return t}function s(){$("#btn-apply-loyalty-points").on("click",function(n){n.preventDefault();$("#btn-apply-loyalty-points").toggleClass("applied");c();h()})}function h(){var t=$("#hdfpromo").val(),n=$("#btn-apply-loyalty-points"),i=$("#allowed-loyalty-discount-amount");n.prop("disabled",!0);GolfNow.Web.StandAloneProductRewards.GetInvoiceTotals(t,function(t){n.prop("disabled",!1);GolfNow.Web.StandAloneProductRewards.UpdateInvoicePrice(t)},function(){showMessage("Error","An error occurred");$("#btn-apply-loyalty-points").toggleClass("applied");n.prop("disabled",!1);i.html(_originalAllowedLoyaltyDiscountAmountHtml)})}function c(){var n=$("#allowed-loyalty-discount-amount");_originalAllowedLoyaltyDiscountAmountHtml=n.html();u()?n.html('Applying <i class="fas fa-spinner fa-spin"><\/i>'):n.html('Removing <i class="fas fa-spinner fa-spin"><\/i>')}function u(){var n=$("#btn-apply-loyalty-points").hasClass("applied");return n?!0:!1}function l(f){var y=$("#hdfIsLoyaltyDiscountAmountBelowThreshold").val()==="true",e=$("#btn-apply-loyalty-points"),p=e.hasClass("applied"),w=f.loyaltyEligibility.allowedLoyaltyDiscountAmountFormatted,o=f.loyaltyEligibility.totalPointsAvailableFormatted,b=f.loyaltyEligibility.allowedLoyaltyDiscountPoints,k=f.loyaltyEligibility.allowedLoyaltyDiscountPointsFormatted,s=$("#allowed-loyalty-discount-amount"),h=$("#allowed-loyalty-discount-points"),c=$("#loyalty-total-points-available"),l=$("#loyalty-small-points-available-copy"),a=f.loyaltyRedemptionDetail.redemptionPointsAppliedFormatted,d=Number(f.loyaltyRedemptionDetail.redemptionAmountApplied),v=f.loyaltyRedemptionDetail.redemptionAmountAppliedFormatted;n.redemptionPointsAppliedFormatted=a;n.redemptionAmountAppliedFormatted=v;u()?(s.html("<u>Remove<\/u>"),e.css("background-color","transparent"),e.css("border-color","transparent"),h.html(a+" points applied"),c.html(o),l.html("points remaining"),i(n,"Apply"),d>0&&($("#loyalty-points-line-item").html("-"+v),$("#loyalty-points-line-item").parent(".reservation-details").show())):(s.html("Save "+w),e.css("border-color","white"),h.html("Apply "+k+" pts"),c.html(o),l.html("points"),$("#loyalty-points-line-item").parent(".reservation-details").hide(),i(n,"Removed"));y||!p?(t=r,$("#hdfAllowedLoyaltyDiscountPoints").val(0)):(t=b,$("#hdfAllowedLoyaltyDiscountPoints").val(t))}function i(n,t){var i="";switch(t){case"Impression":i=" | Points Available: "+n.totalLoyaltyPointsAvailable+" | Discount Amount: "+n.allowedLoyaltyDiscountAmount;break;case"Apply":i=" | Points Redeemed: "+n.redemptionPointsAppliedFormatted+" | Discount Amount: "+n.redemptionAmountAppliedFormatted;break;default:i=""}TrackGoogleEvent("golfpassPoints","GolfPass Points",t,"Standalone"+i)}var t=0,r=0,f=!0,n={};return{initPage:e,UpdateLoyaltyPointsBox:l,GetAllowedLoyaltyDiscountPoints:o}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.SkipFreeTrialButton=GolfNow.Web.SkipFreeTrialButton||{};GolfNow.Web.SkipFreeTrialButton=function(){function t(t){n=t;i()}function i(){$("#golfpass-skip-freetrial-button").on("click",function(){window.location.href=n+window.location.search})}var n;return{initPage:t}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.CreateNewAccount=GolfNow.Web.CreateNewAccount||{};GolfNow.Web.CreateNewAccount=function(){function s(n,t,f){i=n;u=f;r=t||"/";GolfNow.Web.Login.KeepPurchaseFlowCookieOriginalValue();GolfNow.Web.Login.KeepPurchaseFlowCookieProductOriginalValue();h()}function h(){$("#btnCreateAccount").addClass("btn-green").prop("disabled",!0);$("#frmCreateNewAccount").foundation("tooltip","reflow");$("#frmCreateNewAccount").on("submit",function(n){t=$(this);n.preventDefault();e()});$("input.form-control").on("input",function(){$(this).attr("value",this.value);this.value.length>0?$(this).siblings(".continue-label").addClass("font-down"):$(this).siblings(".continue-label").removeClass("font-down")});f=$("#frmCreateNewAccount").validate({errorElement:"small",rules:{PasswordCreate:{gnPasswordValidate:"Password does not follow requirements.",minlength:10,messages:{required:"Password required",minlength:jQuery.validator.format("Password must be at least 10 characters long.")}}},onfocusout:function(n){var t=$(n);t.attr("value",t.val());t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error")},onkeyup:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error");f.valid()?$("#btnCreateAccount").addClass("btn-green").removeAttr("disabled"):$("#btnCreateAccount").addClass("btn-green").prop("disabled",!0)},errorPlacement:l,submitHandler:e});_.delay(c,150);$("#frmCreateNewAccount").on("click","#CombinedSubscribe",function(){var n=$(this).is(":checked");$("#GolfNowSubscribe").prop("checked",n);$("#EmailSubscribe").prop("checked",n)}).on("click",".toggle-password",a);$("#lnk-continue-as-guest-login").on("click",function(){var n=GolfNow.Web.Cache.GetValue("SavedUserEmail");$("#frmCreateNewAccount").hide();$("#frmGuestCreateNewAccount").show();$(".create-account-wrapper").show();$("#GuestUserName").val(n.customerEmail);$("#frmGuestCreateNewAccount").validate().form()?$("#frmGuestCreateNewAccount").find("button").removeAttr("disabled"):$("#frmGuestCreateNewAccount").find("button").prop("disabled",!0)});$(".lnk-back-to-create").on("click",function(){var n=GolfNow.Web.Cache.GetValue("SavedUserEmail");$("#fmlogin").hide();$("#frmGuestCreateNewAccount").hide();$("#frmCreateNewAccount").show();$(".create-account-wrapper").show();$("#btnsign").val("Login");$("#EmailAddress").val(n.customerEmail);$("#frmCreateNewAccount").validate().form()?$("#frmCreateNewAccount").find("button").removeAttr("disabled"):$("#frmCreateNewAccount").find("button").prop("disabled",!0);$("#frmCreateNewAccount").find("#PasswordCreate").trigger("focus")});$(".lnk-login").on("click",function(){var n=GolfNow.Web.Cache.GetValue("SavedUserEmail");$("#frmCreateNewAccount").hide();$("#frmGuestCreateNewAccount").hide();$(".create-account-wrapper").hide();$("#member-checkout").show();$("#fmlogin").show();$("#btnsign").text("Login");$("#UserName").val(n.customerEmail);$("#fmlogin").validate().form()?$("#fmlogin").find("button").removeAttr("disabled"):$("#fmlogin").find("button").prop("disabled",!0);$("#fmlogin").find("#Password").trigger("focus")});v();y()}function c(){$("#EmailAddress").rules("add",{remote:{url:"/account/check-email",type:"post",data:{email:function(){return $("#EmailAddress").val().toLowerCase()}}},messages:{remote:"Someone already has that email",email:u},gnEmailValidate:"The Email Address field is not a valid email address."});$("#PasswordCreate").rules("add",{gnPasswordValidate:"Password does not follow requirements.",minlength:10,messages:{required:"Password required",minlength:jQuery.validator.format("Password must be at least 10 characters long.")}})}function l(n,t){n.insertAfter(t)}function e(){return t.valid()&&!n&&(n=!0,GolfNow.Web.LocationServices.LocateMe(!1,o,o),$("#btnCreateAccount").prop("disabled",!0),$.post(i,t.serialize()).success(function(n){n.success&&n.error===""&&n.modelState.accountCreated&&(window.location.href=r)}).error(function(t){var i,f,r,u,e,o;if(n=!1,$("#btnCreateAccount").prop("disabled",!1),i=null,t&&t.responseJSON&&(i=t.responseJSON.modelState),i)if(i.unhandledExceptions)f=i.unhandledExceptions[0],showMessage("Create Account Error",f);else{r={};for(u in i)i.hasOwnProperty(u)&&(e=u.split(".")[1],o=i[u][0],r[e]=o);$.isEmptyObject(r)||validator.showErrors(r)}else showMessage("Create Account Error","There was an error submitting the form, please try again.")})),!1}function o(n){$(".account-signup-state").val(n.State);$(".account-signup-latitude").val(n.Latitude);$(".account-signup-longitude").val(n.Longitude)}function a(){var t=$(this),n;t.toggleClass("fa-eye fa-eye-slash");n=$(t.attr("toggle"));n.attr("type")==="password"?n.attr("type","text"):n.attr("type","password")}function v(){if(GolfNow.Web.Login.IsPurchaseFlowCookieFound()||GolfNow.Web.Login.IsPurchaseFlowCookieProductFound()){var n=GolfNow.Web.Login.IsVipSubscribeFlow()?GolfNow.Web.Login.GetPurchaseFlowCookieProductOriginalValue():GolfNow.Web.Login.GetPurchaseFlowCookieOriginalValue();TrackGoogleEvent("reservationFlowAuth","Purchase Flow Auth","Impression",n)}}function y(){if(GolfNow.Web.Login.IsPurchaseFlowCookieFound()||GolfNow.Web.Login.IsPurchaseFlowCookieProductFound())$("#btnCreateAccount, #btnguest, #btnsign").on("click",function(){var n="",t=GolfNow.Web.Login.IsVipSubscribeFlow()?GolfNow.Web.Login.GetPurchaseFlowCookieProductOriginalValue():GolfNow.Web.Login.GetPurchaseFlowCookieOriginalValue(),i=GolfNow.Web.Login.IsVipSubscribeFlow()?GolfNow.Web.Login.GetPurchaseFlowCookieProductKey():GolfNow.Web.Login.GetPurchaseFlowCookieKey();$(this).is("#btnguest")&&(n="Guest");$(this).is("#btnCreateAccount")&&(n="Create Account");$(this).is("#btnsign")&&(n="Log In");t=t+" | "+n;GolfNow.Web.Utils.SetCookie(i,t,1)})}var i,r,u,f,n=!1,t;return{initPage:s}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.Login=GolfNow.Web.Login||{};GolfNow.Web.Login=function(){function pt(n){p=n.isBookingProcess;w=n.hasSignInValue;_vipEnableRoutes=n.vipEnableRoutes;_vipProduct=n.vipProduct;c=n.isVipSubscribeFlow;b=n.locationCacheName;k=n.lastLocationCheck;t=n.purchaseFlowCookieKey;o=n.purchaseFlowCookieProductKey;s=n.purchaseFlowCookieFound;h=n.purchaseFlowCookieProductFound;i=n.invalidEmailAddressMsg;at=n.keepMeSignedInTitle;vt=n.keepMeSignedInInfo;yt=n.privacyPolicyLink;d=n.enhancedEcommerceInfoLoginUrl;it=n.fullCustomerGuestLoginError;g=n.teeTimeId;nt=n.facilityId;tt=n.players;ut=n.loginAjaxUrl;ft=n.isWhiteLabelSite;rt=n.forgotPasswordUrl;_optInSourceType=n.sourceType;_isLocalUrl=n.isLocalUrl;wt()}function wt(){$("#btncontinue").on("click",function(n){n.preventDefault();$("#frmContinueAccount").valid()&&$.ajax({url:"/account/check-email",type:"POST",data:{email:$("#ContinueEmail").val().toLowerCase()},success:function(n){var t=$("#ContinueEmail").val().toLowerCase(),i=$("#frmCreateNewAccount"),r=$("#frmContinueAccount"),u=$("#fmlogin");GolfNow.Web.Cache.SetLocalStorageValue("SavedUserEmail",{customerEmail:t},7776e6);n?(r.hide(),i.show(),$("#EmailAddress").val(t),i.validate().form(),$("#PasswordCreate").trigger("focus")):(r.hide(),u.show(),$("#UserName").val(t),u.validate().form(),$("#Password").trigger("focus"));$(".continue-label").addClass("font-down")}})});$("input.form-control").on("input",function(){$(this).attr("value",this.value);this.value.length>0?$(this).siblings(".continue-label").addClass("font-down"):$(this).siblings(".continue-label").removeClass("font-down")});if(e=$("#frmContinueAccount").validate({errorElement:"small",rules:{ContinueEmail:{gnEmailValidate:"The Email Address field is not a valid e-mail address."}},messages:{ContinueEmail:i},onfocusin:function(){e&&(e.resetForm(),$("#frmContinueAccount").find("input").each(function(n,t){$elem=$(t);$("label[for="+$elem.attr("id")+"]").removeClass("error").addClass("valid")}))},onkeyup:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error");e.valid()?$("#btncontinue").addClass("btn-green").removeAttr("disabled"):$("#btncontinue").addClass("btn-green").prop("disabled",!0)},onfocusout:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error")}}),u=$("#fmlogin").validate({errorElement:"small",rules:{UserName:{gnEmailValidate:"The Email Address field is not a valid e-mail address."},Password:{gnPasswordLoginValidate:"Password does not follow requirements."}},messages:{UserName:i},onfocusin:function(){u&&(u.resetForm(),$("#fmlogin").find("input").each(function(n,t){$elem=$(t);$("label[for="+$elem.attr("id")+"]").removeClass("error").addClass("valid")}))},onkeyup:function(n){var t=$(n);t.attr("value",t.val());t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error");u.valid()?$("#btnsign").addClass("btn-green").removeAttr("disabled"):$("#btnsign").addClass("btn-green").prop("disabled",!0)},onfocusout:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error")},submitHandler:function(n){var i,r,t;$(n).valid()&&($(n).find("button").prop("disabled",!0),$("#RememberMe").length>0&&$("#RememberMe").attr("checked",!0),$("#RememberMe").is(":checked")?(i=7776e6,GolfNow.Web.Cache.SetLocalStorageValue("rememberMeInfo",{username:$("#email").val()},i)):(r=GolfNow.Web.Cache.GetValue("rememberMeInfo")||null,r!==null&&GolfNow.Web.Cache.SetLocalStorageValue("rememberMeInfo",null)),et(!0),t={},$("#fmlogin").serializeArray().map(function(n){t[n.name]=DOMPurify.sanitize(n.value)}),GolfNow.Web.Request.Post("LoginAjax",ut,JSON.stringify(t),{dataType:"json",contentType:"application/json; charset=UTF-8"}).done(function(n){var i,t,r,u,f,e;if($("#fmlogin-submit-error").remove(),n.success&&n.error==="")if(i=$("#fmlogin").attr("action"),t=typeof i!="undefined",t&&(i=i.replace("login?returnUrl=","")),r=window.location.protocol+"//"+window.location.host,u=t?i:r+window.location.pathname+window.location.hash,loginModalReturnUrl=t?i:loginModalReturnUrl,f=t?r+loginModalReturnUrl:r+loginModalReturnUrl,e=u===f,loginModalReturnUrl&&(_isLocalUrl||ft))if(e)window.location.reload();else{var o=t?"":loginModalReturnUrl.indexOf("#")!==-1,s=t?"":u.indexOf("#")!==-1,h=!o&&s?loginModalReturnUrl+window.location.hash:decodeURIComponent(loginModalReturnUrl);window.location.href=h}else window.location.href="/"}).fail(function(n){var t=null,i;n&&n.responseJSON&&(t=n.responseJSON.modelState,t&&(i=t[""][0],$("#fmlogin-submit-error").remove(),$('<small id="fmlogin-submit-error" class="error margin-bottom-15">'+i+"<\/small>").insertBefore("#fmlogin .checkbox-label")))}))}}),p){f=$("#frmGuestCreateNewAccount").validate({errorElement:"small",rules:{GuestUserName:{gnEmailValidate:"The Email Address field is not a valid e-mail address."},Password:{gnPasswordValidate:"Password does not follow requirements."}},messages:{GuestUserName:i},onfocusin:function(){f&&(f.resetForm(),$("#frmGuestCreateNewAccount").find("input").each(function(n,t){$elem=$(t);$("label[for="+$elem.attr("id")+"]").removeClass("error").addClass("valid")}))},onkeyup:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error");f.valid()?$("#btnguest").addClass("btn-green").removeAttr("disabled"):$("#btnguest").addClass("btn-green").prop("disabled",!0)},onfocusout:function(n){var t=$(n);t.valid()?t.parent("label").removeClass("error").addClass("valid"):t.parent("label").removeClass("valid").addClass("error")},submitHandler:function(t){var i,u;ot();$(t).valid()?(TrackGoogleEvent("slideOutAuth","Slide Out Auth","Successful Submission",r+(n?" | "+n:"")),$(t).find("button").prop("disabled",!0),$("#RememberMe").is(":checked")?(i=7776e6,GolfNow.Web.Cache.SetLocalStorageValue("rememberMeInfo",{username:$("#email").val()},i)):(u=GolfNow.Web.Cache.GetValue("rememberMeInfo")||null,u!==null&&GolfNow.Web.Cache.SetLocalStorageValue("rememberMeInfo",null)),et(!0,t)):TrackGoogleEvent("slideOutAuth","Slide Out Auth","Failure",r+(n?" | "+n:""))}});_.delay(bt,150);$("#fmlogin").on("click","#CombinedSubscribe",function(){var n=$(this).is(":checked");$("#GolfNowSubscribe").prop("checked",n);$("#EmailSubscribe").prop("checked",n)}).on("click",".toggle-password",kt);GolfNow.Web.Analytics.Google.Ecommerce.GetLoginPageInformation(d,Number(nt),Number(g),Number(tt),function(n){n&&n.facilityAddress&&GolfNow.Web.Analytics.Google.Ecommerce.CheckoutStep2(n.facilityName,Number(n.facilityID),Number(n.perGolferPrice),Boolean(n.isHotDeal)?"Hot Deal":"Course",n.rateName,n.facilityAddress.city,n.facilityAddress.stateProvinceCode,n.facilityAddress.country,n.players)})}if(it){var t='<div class="content-login"><h3>Account Located<\/h3><\/ br><p>Good news, golfer! Looks like you have an account with us. Log in using your account to get all of your benefits.';t+="<\/p><\/div>";$("#member-checkout").prepend(t)}w&&$("article#member-checkout > a").trigger("click");GolfNow.Web.Utils.ClearAvailableCustomerRewards();GolfNow.Web.Utils.ClearPendingSocialRequests();_vipEnableRoutes&&c&&_vipProduct!=null&&GolfNow.Web.Analytics.Google.Ecommerce.VipCheckoutStep2(_vipProduct.productName,"VIP-"+_vipProduct.productId,Number(_vipProduct.productPrice),"VIP")}function bt(){$("#GuestUserName").rules("add",{remote:{url:"/account/check-email",type:"post",data:{email:function(){return $("#GuestUserName").val().toLowerCase()}}},gnEmailValidate:"The Email Address field is not a valid email address.",messages:{remote:"Someone already has that email.",GuestUserName:i}})}function kt(){var t=$(this),n;t.toggleClass("fa-eye fa-eye-slash");n=$(t.attr("toggle"));n.attr("type")==="password"?n.attr("type","text"):n.attr("type","password")}function dt(){var n=GolfNow.Web.Cache.GetValue("rememberMeInfo")||null;n!==null&&($("#email").val(n.username),$("#RememberMe").attr("checked",!0))}function et(n,t){n=n||!1;n&&(GolfNow.Web.Cache.SetValue(k,null,!1),GolfNow.Web.Cache.SetValue(b,null,!0));t&&t.submit()}function gt(){if(s){var n=GolfNow.Web.Utils.GetCookie(t),i=n.indexOf("Trade")!==-1;a=i?"Trade":"Course";GolfNow.Web.Utils.SetCookie(t,a,1)}}function ni(){h&&(v="Product",GolfNow.Web.Utils.SetCookie(o,v,1))}function y(n){var t=$("#login-form-title"),i=n==="createAccount"?"Create your GolfNow account":n==="signIn"||n==="guest"?"Enter your email to continue":"Create your GolfNow account";t.html(i)}function ti(){$("#golfid-oauth-frame-wrapper").hide();$("#frmCreateNewAccount").hide();$("#frmGuestCreateNewAccount").show();$(".create-account-wrapper").show();$(".lnk-back-to-create").off("click");$(".lnk-back-to-create").on("click",function(){y("createAccount");$("#frmCreateNewAccount").hide();$("#frmGuestCreateNewAccount").hide();$(".create-account-wrapper").hide();$("#golfid-oauth-frame-wrapper").show()});y("guest")}function ii(){golfIdEnabled&&($("#frmCreateNewAccount").hide(),$(".create-account-wrapper").hide());$("#frmGuestCreateNewAccount").hide()}function ri(){var t=$(".menuCloseBtn > a"),i=t.length>0;i&&t.trigger("click");ii();$("div#signIn").foundation("reveal","open");ot();TrackGoogleEvent("slideOutAuth","Slide Out Auth","Impression",r+(n?" | "+n:""))}function ot(){var i=c?o:t;r=GolfNow.Web.Utils.CategorizeURLPath();n=s||h?r==="Tee Time Details"?GolfNow.Web.Utils.GetCookie(i):null:null}function ui(){st()}function st(){var n=$("[data-open-login-modal-login]");n.on("click",function(n){var t;if(n.preventDefault(),t=$(document).find("[data-cms-custom-header]").length>0,GolfNow.Web.Utils.ConsoleLog("Open modal Login button event: "+t),Foundation.utils.is_medium_up()&&!t){var i=document.location.href,r=document.location.protocol+"//"+document.location.host,u=i.substring(r.length);loginModalReturnUrl=u;_isLocalUrl=!0;_openLoginModalOnClick=!0;lt()}ht(n,t)})}function ht(n,t){if(Foundation.utils.is_small_only()||t){var i=$(n.currentTarget),r=t&&window.loginUrlWprotocol?window.loginUrlWprotocol:"/customer/login?returnUrl="+encodeURIComponent(document.location.pathname+document.location.hash)||encodeURIComponent("/"),u=t&&window.createAccountUrlWprotocol?window.createAccountUrlWprotocol:"/account/create";typeof i.data("login-link-identifier")!="undefined"&&(window.location.href=r);typeof i.data("create-account-link-identifier")!="undefined"&&(window.location.href=u)}}function fi(){window.location.href=rt}function ei(n){$("#frmGuestCreateNewAccount #GuestUserName").val(n);$("#frmGuestCreateNewAccount").validate().form()?$("#frmGuestCreateNewAccount").find("button").removeAttr("disabled"):$("#frmGuestCreateNewAccount").find("button").prop("disabled",!0)}function oi(){try{GolfNow.Web.LocationServices.LocateMe(!1,ct,ct)}catch(n){GolfNow.Web.Utils.ConsoleError("GolfId Email OptIn Error: "+n.message)}}function ct(n){n.email=$("#hdfemailaddressoptin").val();n.sourceType=_optInSourceType;GolfNow.Web.Request.Post("Email_OptIn_Subscribe","/api/utilities/emailaccount-subscribe",JSON.stringify(n),{dataType:"json",contentType:"application/json; charset=UTF-8"}).done(function(){GolfNow.Web.Utils.ConsoleLog("Location Data Email Opt-In Done")}).fail(function(){GolfNow.Web.Utils.ConsoleLog("Location Data Email Opt-In Fail")}).always(function(){GolfNow.Web.Utils.ConsoleLog("Location Data Email Opt-In Always");$("#hdfcreateaccountemailoptin").val("false");$("#hdfemailaddressoptin").val("");GolfNow.Web.MemberLoginGolfId.SendMessage("auth success")})}function lt(){l||$.ajax({type:"GET","async":!0,url:"/account/loginpartial",data:{returnUrl:loginModalReturnUrl},beforeSend:function(){l=!0},success:function(n){$("#login-partial-container").html(n.html);golfIdEnabled&&(window.initObj.loginModalReturnUrl=loginModalReturnUrl,GolfNow.Web.MemberLoginGolfId.initPage(window.initObj));isAuthenticated?window.location.reload():si()},complete:function(){l=!1},error:function(){l=!1}})}function si(){(openLoginModalPopup||_openLoginModalOnClick)&&(ri(),openLoginModalPopup=!1,_openLoginModalOnClick=!1)}function hi(){return s}function ci(){return h}function li(){return o}function ai(){return t}function vi(){return c}function yi(){return v}function pi(){return a}function wi(){return _isLocalUrl}var p=0,w=!1,u,f,e,b,k,a,v,t,o,s,h,c,i,at,vt,yt,d,g,nt,tt,it,rt,ut,ft,l=!1,r,n;return{InitPage:pt,GetRememberMeInfo:dt,KeepPurchaseFlowCookieOriginalValue:gt,KeepPurchaseFlowCookieProductOriginalValue:ni,IsPurchaseFlowCookieFound:hi,IsPurchaseFlowCookieProductFound:ci,GetPurchaseFlowCookieProductKey:li,GetPurchaseFlowCookieKey:ai,GetPurchaseFlowCookieProductOriginalValue:yi,GetPurchaseFlowCookieOriginalValue:pi,IsVipSubscribeFlow:vi,UpdateLoginFormTitle:y,SwitchForm:ti,IsLocalUrl:wi,LoadLoginModal:lt,BindLoginModalEvents:ui,OpenModalLoginButtonEvent:st,ForgotPasswordLinkClicked:fi,SetHamburgerLinksRedirect:ht,CarryOverEmail:ei,GetLocationDataEmailOptin:oi}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.DisableAutoRenewModal=GolfNow.Web.DisableAutoRenewModal||{};GolfNow.Web.DisableAutoRenewModal=function(){function a(n,t){o=n;l=t;v()}function v(){$("#auto-renew-off-confirm-modal #confirmYesButton").on("click",function(){h()&&u===1?p():u===2&&s()});$("#auto-renew-off-confirm-modal #confirmNoButton").on("click",function(){u===1?$("#auto-renew-off-confirm-modal").foundation("reveal","close"):window.location.href=c});$("#auto-renew-off-confirm-modal").on("closed.fndtn.reveal",function(n){n.namespace==="fndtn.reveal"&&b()});$("#auto-renew-off-confirm-modal").on("open.fndtn.reveal",function(t){if(t.namespace==="fndtn.reveal"){var i=$(".membership-savings-box-wrapper");i.length>0&&($("#membership-savings-tmpl-container").show(),i.each(function(t,i){var r=$(i).data("subscriptionid");r!==Number(n.customerSubscriptionId)&&$(i).hide()}))}})}function y(u,s){if(u.preventDefault(),e=$(u.currentTarget),n=s.view.data,t=u.currentTarget.checked===!0?"on":"off",n.hasDefaultPayment&&t==="on"&&n.autoRenewEnabled==="off")$.post(o,{customerSubscriptionId:n.customerSubscriptionId,autoRenew:t},function(t){t.success?($.observable(n).setProperty({autoRenewEnabled:"on"}),e.prop("checked","checked")):showMessage("Auto Renewal Error",t.errorMessage)});else if(n.hasDefaultPayment&&t==="off"&&n.autoRenewEnabled==="on")i=$("#cancellation-reason"),r=$("#cancellation-reason-error"),f=Number(i.val()),h=function(){return f=Number(i.val()),f===0?(i.addClass("error"),r.show(),!1):!0},$("#auto-renew-off-confirm-modal").foundation("reveal","open");else{if(n.hasDefaultPayment&&t==="off"&&n.autoRenewEnabled==="off"||n.hasDefaultPayment&&t==="on"&&n.autoRenewEnabled==="on")return!1;n.hasDefaultPayment||showMessage("Add Card For Renewal","You currently have no cards on file. Please add a card to enable auto renewal.")}}function p(){if(l){var t="/api/product/discounted-product-offer/"+n.productId+"/"+n.productPriceId;gnRequest.Get("get-discounted-product-offer",t).done(function(n){c=n.productOfferUrl;u=2;w(n.descriptionFormatted)}).fail(function(){s()}).always(function(){i.removeClass("error");r.hide()})}else s()}function w(n){$("#auto-renew-off-confirm-modal #cancellation-reason").hide();$("#auto-renew-off-confirm-modal #discounted-offer-copy-container").show();$("#auto-renew-off-confirm-modal #discounted-offer-copy").html(n);$("#auto-renew-off-confirm-modal #confirmModalTitle").hide();$("#auto-renew-off-confirm-modal #confirmNoButton").html("Accept Offer");$("#auto-renew-off-confirm-modal #confirmContent").html("You will get to keep all these great benefits:")}function b(){$("#auto-renew-off-confirm-modal #cancellation-reason").show();$("#auto-renew-off-confirm-modal #discounted-offer-copy-container").hide();$("#auto-renew-off-confirm-modal #discounted-offer-copy").html("");$("#auto-renew-off-confirm-modal #confirmModalTitle").show();$("#auto-renew-off-confirm-modal #confirmNoButton").html("Keep Benefits");$("#auto-renew-off-confirm-modal #confirmContent").html("If you don't renew your membership, you will lose access to all these great benefits.");i.removeClass("error").val("0");r.hide();u=1;$("#membership-savings-tmpl-container").hide();$(".membership-savings-box-wrapper").show()}function s(){$.post(o,{customerSubscriptionId:n.customerSubscriptionId,autoRenew:t,cancellationReasonId:f},function(t){$("#auto-renew-off-confirm-modal").foundation("reveal","close");t.success?($.observable(n).setProperty({autoRenewEnabled:"off"}),e.prop("checked",!1)):showMessage("Auto Renewal Error",t.errorMessage)}).always(function(){i.removeClass("error").val("0");r.hide()})}var t,n,e,h,f,i,r,u=1,c,o,l;return{InitPage:a,ToggleAutoRenew:y}}();;
var GolfNow=GolfNow||{};GolfNow.Web=GolfNow.Web||{};GolfNow.Web.GuestCreateAccount=GolfNow.Web.GuestCreateAccount||{};GolfNow.Web.GuestCreateAccount=function(){function e(t,r){i=t;n=r;o()}function o(){$("#Password").focus();$("#btnGuestCreateAccount").addClass("btn-green").prop("disabled",!0);$("#guest-create-account-modal").on("keyup","input",l);$("#frmGuestCreateAccount").submit(function(n){t=$(this);n.preventDefault();h()});$("input.form-control").on("input",function(){$(this).attr("value",this.value);this.value.length>0?$(this).siblings(".continue-label").addClass("font-down"):$(this).siblings(".continue-label").removeClass("font-down")});$("#btnLogInNow").on("click",function(){window.location.href=n});$(".full-details").on("click",function(){u?$("#guest-login-now-modal").foundation("reveal","open"):$("#guest-create-account-modal").foundation("reveal","open")});$(document).on("closed.fndtn.reveal","#guest-login-now-modal",function(t){t.namespace==="fndtn.reveal"&&(window.location.href=n)});_.delay(s,150);$("#frmGuestCreateAccount").on("click","#CombinedSubscribe",function(){var n=$(this).is(":checked");$("#GolfNowSubscribe").prop("checked",n);$("#EmailSubscribe").prop("checked",n)}).on("click",".toggle-password",c)}function s(){$("#Password").rules("add",{gnPasswordValidate:"Password does not follow requirements.",minlength:10,messages:{required:"Password required",minlength:jQuery.validator.format("Password must be at least 10 characters long.")}})}function h(){return t.valid()&&!r&&(r=!0,GolfNow.Web.LocationServices.LocateMe(!1,f,f)),!1}function f(n){$(".guest-signup-state").val(n.State);$(".guest-signup-latitude").val(n.Latitude);$(".guest-signup-longitude").val(n.Longitude);$("#btnGuestCreateAccount").prop("disabled",!0);$.post(i,t.serialize()).success(function(n){n.success&&n.error===""&&n.modelState.accountCreated&&(u=!0,$("#guest-login-now-modal").foundation("reveal","open"))}).error(function(n){var t=null,u,i,r,f,e;if(n&&n.responseJSON&&(t=n.responseJSON.modelState),t)if(t.unhandledExceptions)u=t.unhandledExceptions[0],showMessage("Create Account Error",u);else{i={};for(r in t)t.hasOwnProperty(r)&&(f=r.split(".")[1],e=t[r][0],i[f]=e);$.isEmptyObject(i)||validator.showErrors(i)}else showMessage("Create Account Error","There was an error submitting the form, please try again.")})}function c(){var t=$(this),n;t.toggleClass("fa-eye fa-eye-slash");n=$(t.attr("toggle"));n.attr("type")=="password"?n.attr("type","text"):n.attr("type","password")}function l(){$("#frmGuestCreateAccount").valid()?$("#btnGuestCreateAccount").addClass("btn-green").removeAttr("disabled"):$("#btnGuestCreateAccount").addClass("btn-green").prop("disabled",!0)}var i,n,r=!1,u=!1,t;return{initPage:e}}();;
var GolfNow = GolfNow || {};
GolfNow.Web = GolfNow.Web || {};

GolfNow.Web.Localization = (function ($, _, gnUtils, gnCache, gnReq) {
	var _url = '/api/config/localization/',
		_resourcesKey = 'GolfNow.Web.Resources',
		_resources = {}, _resourceList = [],
		storeResource = function (key, obj) {
			// map array of key/value objects to a sinle object with key/value values flattened
			_resources[key] = _.object(_.map(obj, function (item) { return [item.key.toLowerCase(), item.value] }));
			// get all stored resources from session storage
			var storedResources = gnCache.GetValue(_resourcesKey) || {};
			// merge stored, if there are any, with incoming
			_resources = _.extend(_resources, storedResources);
			// store in session storage
			gnCache.SetSessionStorageValue(_resourcesKey, _resources, null);

			return _resources[key];
		},
		getResource = function (resource) {
			var that = this;
			var deferred = new $.Deferred();

			// get all stored resources from session storage
			var storedResources = gnCache.GetValue(_resourcesKey) || {};

			// check if requested resource is already stored
			var hasResource = (storedResources[resource] || null) !== null;

			if (_.isEmpty(storedResources) || !hasResource) {
				// make sure we don't issue another call for the same resource
				// while another call is already started
				if (_.contains(_resourceList, resource)) {
					return deferred.reject(null);
				}

				// log resource call
				_resourceList.push(resource);

				// make api request for requested resource, store then resolve promise with returned resource
				gnReq.Get('localization', _url + resource, true).done(function (data) {
					deferred.resolve(storeResource(resource, data));
				});
			} else {
				// resource already stored so just immediately resolve promise with requested resource
				deferred.resolve(storedResources[resource]);
			}

			return deferred.promise();
		},
		getString = function (resource, key) {
			var def = new $.Deferred();

			// make request to getResources and let it determine whether an api request is necessary or not
			// then query returned resource for requested key
			getResource(resource).done(function (data) {
				def.resolve(data[key.toLowerCase()]);
			});

			return def.promise();
		};

	return {
		GetResource: getResource,
		GetString: getString
	};
})(jQuery, _, GolfNow.Web.Utils, GolfNow.Web.Cache, GolfNow.Web.Request);;
var GolfNow = GolfNow || {},
	uid = uid || '';
GolfNow.Web = GolfNow.Web || {};

///****** Self-Initializing object ******///
GolfNow.Web.Favorites = (function ($, _, gnUtils, gnCache, gnReq) {
	var cacheKey = 'favorite-courses',
		favoritesClass = 'favorite-icon',
		favoritesSelected = 'heart-filled',
		favoritesUnselected = 'heart-outline',
		maxFavoritesLimit = 30,
		modalConfirmDef = null,
		processingReq = false,
		_startingTopPos = 0,
		localizedCopy = { favorite_spelling_capital: 'Favorite', favorite_spelling_lower: 'favorite' },
		authenticated = function () {
			return uid !== '' && utype !== 'guest';
		},
		urlPrefix = '',
		jsTemplates = [
			{ tmplPath: 'FavoritesModal', accessorName: 'favsMessageHandlerHelperTmpl', isPath: false },
			{ tmplPath: 'FavoritesAckModal', accessorName: 'favsAckMessageHandlerHelperTmpl', isPath: false }
		],
		getAll = function () {
			var url = '/api/favorites';

			//check session storage for favorite ids
			processingReq = true;
			return gnReq.Get('favorite-courses', url)
				.fail(function (failData) {
					if (failData.status !== 200) {
						analyzeFailure(failData);
					}
				})
				.always(alwaysHandler);
		},
		getAllIdsOnly = function (forceFetch) {
			forceFetch = forceFetch || false;
			var deferred = new $.Deferred();
			if (!authenticated()) {
				clearIds();
				return deferred.resolve(null);
			}

			var url = '/api/favorites/ids';
			var ids = gnCache.GetValue(cacheKey) || null;

			if ((ids === null || forceFetch) && authenticated()) {
				gnReq.Get('favorite-courses-ids', url)
					.done(function (data) {
						storeIds(data);
						deferred.resolve(data);
					})
					.fail(function (failData) {
						if (failData.status !== 200) {
							analyzeFailure(failData);
						}
						deferred.reject('Get all ids failed with status code ' + failData.status);
					})
					.always(alwaysHandler);
			} else if (authenticated()) {
				deferred.resolve(ids);
			} else {
				clearIds();
				deferred.resolve(null);
			}

			return deferred.promise();
		},
		getById = function (id) {
			var url = urlPrefix + '/api/favorites/' + id;
			processingReq = true;
			return gnReq.Get('favorite-courses', url).always(alwaysHandler);
		},
		getIds = function () {
			return gnCache.GetValue(cacheKey) || null;
		},
		add = function (id) {
			var that = this;
			var url = urlPrefix + '/api/favorite/add/' + id;
			return gnReq
				.Post('favorite-course-add', url)
				.done(function (successData) {
					// add id to session storage array
					var storedIds = getIds() || [];
					storedIds.push(id);
					storeIds(storedIds);
				});
		},
		remove = function (id) {
			var that = this;
			var url = urlPrefix + '/api/favorite/remove/' + id;
			var deferred = $.Deferred();

			var titleTmpl = _.template("Remove {{favorite_spelling_capital}}");
			var msgTmpl = _.template("Are you sure you want to remove this course from your {{favorite_spelling_lower}}s?");

			// show confirmation dialog message utilizing deferred to handle the responses
			showDialogMessage(titleTmpl(localizedCopy), msgTmpl(localizedCopy), 'Yes, remove')
				.done(function (answer) {
					if (answer === 'yes') {
						gnReq
							.Post('favorite-course-remove', url)
							.done(function (successData) {
								// remove id from session storage array
								var storedIds = getIds();
								if (storedIds !== null) {
									storeIds(_.without(storedIds, id));
								}
								deferred.resolve('success');
							})
							.fail(analyzeFailure);
					} else {
						alwaysHandler();
						deferred.resolve('fail');
					}
				});

			return deferred.promise();
		},
		storeIds = function (ids) {
			if (_.isObject(ids)) {
				var storedIds = getIds();
				if ((storedIds === null) || _.isArray(ids)) {
					if (ids.length === 0) ids = null;
					if (!_.isEqual(storedIds, ids))
						gnCache.SetLocalStorageValue(cacheKey, ids);
				}
			}
		},
		clearIds = function () {
			gnCache.SetLocalStorageValue(cacheKey, null);
		},
		containsId = function (id) {
			return _.contains(getIds() || [], id);
		},
		selectedClass = function () {
			return favoritesSelected;
		},
		unselectedClass = function () {
			return favoritesUnselected;
		},
		trackAdd = function (id, name, page) {
			if (typeof dataLayer === "undefined") return;

			if (name !== null && id !== null) {
				dataLayer.push({
					'event': 'addFavorites',
					'eventLabel': name + ' | ' + id,
					'eventCategory': 'Favorites',
					'eventAction': 'Add to Favorites - ' + page
				});
			}
		},
		isMaxFavoritesReached = function () {
			var deferred = new $.Deferred();

			getAllIdsOnly(true)
				.done(function (data) {
					if (data) {
						if (data.length >= maxFavoritesLimit)
							return deferred.resolve({ maxReached: 'yes', favCount: data.length });
						else
							return deferred.resolve({ maxReached: 'no', favCount: data.length });
					}
					showLoginNeededMsg();
					return deferred.reject('Failed to retrieve Ids.');
				})
				.fail(function (err) {
					return deferred.reject(err);
				});
			return deferred.promise();
		},
		iconEventHandler = function (evt) {
			evt.preventDefault();
			evt.stopPropagation();

			var $elem = $(this);
			var id = $elem.data('facilityid') || $elem.children().data('facilityid') || null;
			if (id === null) return;

			//disable click events on all icons
			if (processingReq) return;

			if ($elem.hasClass(favoritesSelected) || $elem.children().hasClass(favoritesSelected)) {
				processingReq = true;
				remove(id).done(function (data) {
					if (data === 'success') {
						var selector = 'i.favorite-icon.' + favoritesSelected;
						$elem.find(selector).removeClass(favoritesSelected).addClass(favoritesUnselected);

						// remove the icon from all other instances of the facility
						$(selector).each(function (idx) {
							var $this = $(this);
							if ($this.data('facilityid') === id) {
								$this.removeClass(favoritesSelected).addClass(favoritesUnselected);
								return;
							}
						});
					}
				})
				.fail(analyzeFailure)
				.always(alwaysHandler);
			} else {
				processingReq = true;

				isMaxFavoritesReached()
					.done(function (data) {
						if (data.maxReached === 'no') {
							add(id).done(function (data) {
								if (data.result === 'success') {
									var selector = 'i.favorite-icon.' + favoritesUnselected;
									$elem.find(selector).addClass(favoritesSelected).removeClass(favoritesUnselected);

									// add the icon to all other instances of the facility
									$(selector).each(function (idx) {
										var $this = $(this);
										if ($this.data('facilityid') === id) {
											$this.addClass(favoritesSelected).removeClass(favoritesUnselected);
											return;
										}
									});
								}
							})
							.fail(analyzeFailure)
							.always(alwaysHandler);
						}
						else if (data.maxReached === 'yes') {
							showMaxFavoritesReachedMsg((data.favCount - maxFavoritesLimit) + 1);
						}
					})
					.fail(function (err) {
						GolfNow.Web.Utils.ConsoleLog(err);
					})
					.always(alwaysHandler);
			}
		};

	function analyzeFailure(failData) {
		if (_.isObject(failData) && failData.status === 401) showLoginNeededMsg();
	}

	function alwaysHandler() {
		processingReq = false;
	}

	function showLoginNeededMsg() {
		var title = 'Login Required';
		var loginUrl = urlPrefix + '/customer/login?returnUrl=' + encodeURIComponent(document.location.pathname + document.location.hash) || encodeURIComponent('/');
		var msg = _.template('Please <a href="' + loginUrl + '">login</a> to view/manage your {{favorite_spelling_lower}}s.');
		var data = {
			modaltitle: title, contenterror: msg(localizedCopy)
		};
		var html = $.render.favsMessageHandlerHelperTmpl(data);
		$('#modal-container').append(html);
		$('#msgFavsModal').foundation('reveal', 'open');
	}

	function showMaxFavoritesReachedMsg(limitOverage) {
		var title = 'Maximum Favorites Reached';

		var msg = _.template("Sorry, you've reached the maximum limit of " + maxFavoritesLimit
			+ " {{favorite_spelling_lower}}s." + " Please remove " + limitOverage
			+ " of your {{favorite_spelling_lower}}s to add this course.");
		var data = {
			modaltitle: title, contenterror: msg(localizedCopy)
		};
		var html = $.render.favsMessageHandlerHelperTmpl(data);
		$('#modal-container').append(html);
		$('#msgFavsModal').foundation('reveal', 'open');
	}

	function showDialogMessage(title, msg, btnText) {
		modalConfirmDef = $.Deferred();

		var data = {
			modalacktitle: title, htmlcontent: msg, ackbuttontext: btnText
		};
		var html = $.render.favsAckMessageHandlerHelperTmpl(data);
		$('#modal-container').append(html);
		$('#msgFavsAckModal').foundation('reveal', 'open');

		return modalConfirmDef.promise();
	}
	function loadTemplates() {
		var loadCalls = [];
		for (var i = 0; i < jsTemplates.length; i++) {
			var currItem = jsTemplates[i];
			var path = currItem.isPath ? currItem.tmplPath : urlPrefix + '/Tmpls/_' + currItem.tmplPath + '.tmpl.html';
			loadCalls.push(GolfNow.Web.Client.LoadTemplate(path, currItem.accessorName, currItem.helpers));
		}
		return loadCalls;
	}

	function getLocalizedResource() {
		return GolfNow.Web.Localization.GetResource('Widgets');
	}

	function init() {
		var that = this;

		var host = GolfNow.Web.Domains.GetDomainHost();
		if (/promotions|blog|travel|tournaments|concierge|news|base|origin-base|memberships/.test(location.hostname)){
			return;
		}
		//else if (cdnUrl !== '') {
		//	urlPrefix = cdnUrl;
		//	urlPrefix = (urlPrefix.lastIndexOf('/') > -1) ? urlPrefix.substr(0, urlPrefix.length - 1) : urlPrefix;
		//}

		// set underscore templating to use mustache style tags
		_.templateSettings = {
			interpolate: /\{\{(.+?)\}\}/g
		};

		// issue multiple async ajax requests for templates and localization resource for Widgets
		$.when
			.apply(this, [loadTemplates(), getLocalizedResource(), getAllIdsOnly()])
			.done(function (d1, d2, d3) {
				if (!_.isEmpty(d2)) localizedCopy = d2;
				if (authenticated() && !_.isEmpty(d3)) storeIds(d3);
			});

		// setup event handlers
		$('body')
			.on('open.fndtn.reveal', '#msgFavsAckModal, #msgFavsModal', function (e) {
				if (e.namespace !== 'fndtn.reveal') return;

				var $modal = $(this);
				_startingTopPos = $(document).scrollTop();

				// force modal to the top of the page
				window.scrollTo(0, 0);

				// force full page height
				GolfNow.Web.Client.ForceFullPageHeight();

				$modal.css({
					top: 0
				});

			})
			.on('close.fndtn.reveal', '#msgFavsAckModal', function (e) {
				if (e.namespace !== 'fndtn.reveal') return;

				// handle close event
				if (modalConfirmDef !== null && modalConfirmDef.state() !== "resolved")
					modalConfirmDef.resolve('no');
			})
			.on('closed.fndtn.reveal', '#msgFavsAckModal, #msgFavsModal', function (e) {
				if (e.namespace !== 'fndtn.reveal') return;

				var $modal = $(this);

				if (modalConfirmDef !== null && modalConfirmDef.state() !== "resolved")
					modalConfirmDef.resolve('no');

				GolfNow.Web.Client.ForceDefaultPageHeight();

				// force modal to the top of the page
				$(document).scrollTop(_startingTopPos);

				// clean up template for reuse
				$modal.remove();
			})
			.on('click', '.favs-ack-cancel-btn', function () {
				modalConfirmDef.resolve('no');
				$('#msgFavsAckModal').foundation('reveal', 'close');
			})
			.on('click', '.favs-ack-confirm-btn', function () {
				modalConfirmDef.resolve('yes');
				$('#msgFavsAckModal').foundation('reveal', 'close');
			});

		// template helpers
		$.views.helpers({
			isFavorite: function (facilityId) {
				if (_.isNumber(facilityId) && GolfNow.Web.Favorites.Contains(facilityId))
					return favoritesSelected;

				return favoritesUnselected;
			},
			isFavoriteBool: function (facilityId) {
				return (_.isNumber(facilityId) && GolfNow.Web.Favorites.Contains(facilityId));
			},
			isFavoriteWithCopy: function (facilityId) {
				var is = _.template('<sup>{{favorite_spelling_capital}} Course</sup>');
				var not = _.template('<sup>Add to {{favorite_spelling_lower}}s</sup>');
				if (_.isNumber(facilityId) && GolfNow.Web.Favorites.Contains(facilityId)) {
					return is(localizedCopy);
				} else {
					return not(localizedCopy);
				}

			},
			favoriteFacilityImagePathDisplay: function (facility) {
				var imagePathUrl = facility.imagePathURL || facility.imagePathUrl;
				if (facility.favoriteImagePathURL && Foundation.utils.is_large_up())
					return $.views.helpers.imagePathDisplay(facility.favoriteImagePathURL);
				else if (imagePathUrl)
					return $.views.helpers.imagePathDisplay(imagePathUrl);
				else if (facility.imgPath)
					return $.views.helpers.imagePathDisplay(facility.imgPath);
				else if (facility.thumbnailImagePath)
					return $.views.helpers.imagePathDisplay(facility.thumbnailImagePath);

				return "/Content/images/general.jpg";
			}
		});
	}

	var favorites = {
			GetAll: getAll,
			Get: getById,
			GetIds: getIds,
			Add: add,
			Remove: remove,
			Store: storeIds,
			Contains: containsId,
			SelectedIconClass: selectedClass,
			UnselectedIconClass: unselectedClass,
			TrackAdd: trackAdd,
			favoriteIconEventHandler: iconEventHandler
	};

	init();
	return favorites;
})(jQuery, _, GolfNow.Web.Utils, GolfNow.Web.Cache, GolfNow.Web.Request);;
//Used for Areas to override any public GolfNow.Web javascript object method;
(function ($) {
	"use strict";
	$.views.converters("escapeApostrophes", function (val) {
		val = val || "";
		var re1 = /&#39;/g;
		var re2 = /'/g;
		return val.replace(re1, "'").replace(re2, "\\'");
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.converters("formatFacilityName", function (facilityName) {
		if (!_.isUndefined(facilityName) && !_.isNull(facilityName) && !_.isEmpty(facilityName))
			return decodeURIComponent(facilityName.replace(/\+/g, ' '));

		return '';
	});
})(this.jQuery);;
(function ($) {
	"use strict";

	$.views.helpers({
		golfpassPerksOnly: function () {
			var searchResultsElem = document.querySelector('gn-search-results');
			return !_.isNull(searchResultsElem) && !_.isUndefined(searchResultsElem) ? searchResultsElem.getAttribute('golf-pass-perks-only') === 'true' : false;
		},
		isTitleEmpty: function (title) {
			return _.isNull(title) || _.isUndefined(title);
		},
		getPageTitleForAanalytics: function (eventName, customSectionTitle) {
			//get only the last segment of the url (no params, no hash params)
			var title = '';
			var sectionTitleHasValue = typeof customSectionTitle !== 'undefined' && customSectionTitle !== null && customSectionTitle !== '';

			//add page title and page path for "Featured" events
			if (eventName === 'Featured') {
				var $masterPageTitle = $('#master-page-title');
				var masterPageTitleHasText = $masterPageTitle.length > 0 && $masterPageTitle.html().length > 0;
				var pipeFoundInTitle = masterPageTitleHasText && $masterPageTitle.html().indexOf('|') > 0;

				var masterPageTitle = pipeFoundInTitle ? $masterPageTitle.html().substring(0, $masterPageTitle.html().indexOf('|')).trim() : (masterPageTitleHasText ? $masterPageTitle.html() : '');
				//if custom section title exists use it, if not then use the page title that comes from the page config
				var pageTitle = sectionTitleHasValue ? customSectionTitle : masterPageTitle;

				title = ' | ' + pageTitle;
			}
			//non "Featured" event with a custom section title, we append the page path, title will be empty for a non "Featured" event with no custom section title 
			return title || (sectionTitleHasValue ? ' | ' + customSectionTitle : '');
		},
		priorityLabelsCount: function (facility, idx) {
			//labelCount set to 3 in order to display at least 2 priority badges, this is needed so we can include the GP Deal badge when available
			var labelCount = 3;

			// The Simulator label should use the SIM tag and not the isSimulator flag
			var labels = [
				{ name: "isPremium", value: facility.isPremium, priority: 1, facility: facility, labelCount: labelCount },
				{ name: "isFeatured", value: facility.isFeatured && !facility.isPremium, priority: 2, facility: facility, labelCount: labelCount },
				{ name: "isPrivate", value: facility.isPrivate && facility.isPrivateCourseLabelEnabled && !$.views.helpers.golfpassPerksOnly(), priority: 3, facility: facility, labelCount: labelCount },
				{ name: "isSimulator", value: facility.tags && facility.tags.includes('SIM'), priority: 4, facility: facility, labelCount: labelCount },
				{ name: "isTrackman", value: facility.isTrackman, priority: 5, facility: facility, labelCount: labelCount },
				{ name: "hasPromotedCampaigns", value: facility.promotedCampaigns?.length && facility.isPremium, priority: 6, facility: facility, labelCount: labelCount },
				{ name: "hasHotDeal", value: facility.hasHotDeal && facility.promotedCampaigns?.length == 0 && facility.isPremium, priority: 7, facility: facility, labelCount: labelCount },
				{ name: "isNewCourse", value: facility.isNewCourse && facility.isNewCourseLabelEnabled, priority: 8, facility: facility, labelCount: labelCount },
				{ name: "hasMemberPricing", value: facility.hasMemberPricing, priority: 9, facility: facility, labelCount: labelCount },
				{ name: "isSparkGolf", value: facility.isSparkGolf && facility.isSparkGolfEnabled, priority: 10, facility: facility, labelCount: labelCount },
				{ name: "hasPerks", value: facility.hasPerks && facility.showGolfpassBadge, priority: 11, facility: facility, labelCount: labelCount }
			];
			var labelObjArray = _.where(labels, { value: true });
			var labelObjArraySorted = _.sortBy(labelObjArray, 'priority')

			return labelObjArraySorted;
		},
		getGooglePriorityLabelImpressions: function (data, index, clickedElemObj, findFacilityFromElemObj) {
			//variable "executeAnalytics" is "true" only when calling "getGooglePriorityLabelImpressions" this way "$.views.helpers.getGooglePriorityLabelImpressions"
			var executeAnalytics = typeof findFacilityFromElemObj !== 'undefined' && findFacilityFromElemObj && typeof clickedElemObj !== 'undefined';
			var facility = null;
			var name = null;
			var value = null;
			var pageTitleAndLocation = '';

			if (executeAnalytics) {
				var $clickedElemObj = $(clickedElemObj);

				facility = {
					isPrivate: $clickedElemObj.data('isprivate'),
					isPrivateCourseLabelEnabled: $clickedElemObj.data('isprivatecourselabelenabled'),
					isFeatured: $clickedElemObj.data('isfeatured'),
					isNewCourse: $clickedElemObj.data('isnewcourse'),
					hasPerks: $clickedElemObj.data('hasperks'),
					facilityId: $clickedElemObj.data('facilityid'),
					facilityName: $clickedElemObj.data('facilityname'),
					label: $clickedElemObj.data('label'),
					facilityTag: $clickedElemObj.data('facilitytag')
				};
				name = $clickedElemObj.data('name');
				value = $clickedElemObj.data('value');
				index = $clickedElemObj.data('index');
			}
			else {
				facility = data.facility
				name = data.name;
				value = data.value;
			}

			var facilityId = $.views.helpers.findFacilityId(facility);
			var facilityName = $.views.helpers.findFacilityName(facility);
			var facilityTag = !_.isEmpty(facility.facilityTag) ? ' | ' + facility.facilityTag : '';
			var eventName = '';
			var eventValues = '';
			var impression = '';
			var track = '';

			//index < 2 in order to make sure that we only take in consideration the 2 highest priorities
			if (name === 'isPrivate' && value && index < 2) {
				eventName = 'Private';
			} else if (name === 'isFeatured' && value && index < 2) {
				eventName = 'Featured';
			} else if (name === 'isNewCourse' && value && index < 2) {
				eventName = 'New';
			} else if (name === 'hasPerks' && value && index < 2) {
				eventName = 'Perks';
			}
			else {
				return '';
			}

			pageTitleAndLocation = $.views.helpers.getTitleAndLocationForAnalytics(clickedElemObj, eventName);

			//used '^' delimiter in order to prevent the facility name to be splitted into a separate position if contains a comma
			eventValues = "'courseImpression'^ '" + eventName + " Course'^ 'impression'^ '" + $.views.converters.escapeApostrophes(facilityName) + " | " + facilityId + facilityTag + pageTitleAndLocation + "'^ 1.00";
			track = "TrackGoogleEvent(" + eventValues + ")";
			//replace '^' delimiter with a comma in order to maintain the string original state
			impression = '<img src="https://vs-y8x5j2b5.akamaized.net/Content/images/empty_pixel.gif?v=339922269" style="display: none;" onload="' + track.replaceAll('^',',') + '" />';

			if (executeAnalytics) {
				var eventValuesArr = $.views.helpers.removeQuotesFromEventValues(eventValues.split('^'));
				TrackGoogleEvent(eventValuesArr[0], eventValuesArr[1], eventValuesArr[2], eventValuesArr[3], eventValuesArr[4]);
			}

			return impression;
		},
		findFacilityProperty: function (facility, propertyName) {
			//array to make sure to loop only through the properties we need
			var facilityProperties = ['isPrivate', 'isPrivateCourseLabelEnabled', 'isFeatured', 'isNewCourse', 'hasPerks', 'facilityId', 'id', 'facilityName', 'name', 'label', 'tags']; 

			//return the value of the property "propertyName"
			for (var i = 0; i < facilityProperties.length; i++) {
				if (facilityProperties[i] === propertyName) {

					//this condition is done for the "tag" property since it's an array
					if (Array.isArray(facility[propertyName])) {

						var index1 = facility[propertyName].indexOf(siteConfigSettings.pmpTier1);
						var index2 = facility[propertyName].indexOf(siteConfigSettings.pmpTier2);

						var tierIndex = index1 !== -1 ? index1 : index2 !== -1 ? index2 : -1;

						if (tierIndex !== -1) {
							return facility[propertyName][tierIndex];
						}
						else {
							return '';
						}
					}

					return facility[propertyName];
				}
			}
		},
		getTitleAndLocationForAnalytics: function (elemObj, eventName) {
			var $elemObj = $(elemObj);
			var searchResultsTitle = $elemObj.parents('.featured-mini-analytics').length > 0 ? 'Featured Zone' : 'Search Results';
			var featuredCoursesDestinationTitle = $elemObj.parents('.featured-courses-destinations-analytics').length > 0 ? 'Destination Featured Courses' : 'Destination Other Sections';
			var title = '';
			var pagePath = window.location.pathname;
			//counter used for cases in which a page contains 2 css classes in its body but we need the first one that is found in the "cssAnalyticsClassArray"
			var elementIsFoundCounter = 0;

			//css class body pages array, these css classes need to be in this order in this array
			var cssAnalyticsClassArray = ['best-courses-nearme-analytics', 'deal-time-rates', 'special-rates', 'favorites', 'city-search-analytics', 'homepage', 'destination-city', 'featured-courses', 'tee-time-search', 'golfnow-reviews-courses-analytics'];
			var className = '';

			_.each(cssAnalyticsClassArray, function (cssClass) {
				var elementIsFound = $(document).find('body.' + cssClass).length > 0;

				if (elementIsFound && elementIsFoundCounter == 0) {
					className = cssClass;
					elementIsFoundCounter++;
				}
			});

			//switch for check page class, if page class exist check if a section has a class
			switch (className) {
				//GoPlay pages
				case 'best-courses-nearme-analytics':
				case 'deal-time-rates':
					var pagePageStartIndex = className === 'deal-time-rates' ? pagePath.indexOf('deal-times') : pagePath.indexOf('best-golf-courses-near-me');
					title = $.views.helpers.getPageTitleForAanalytics(eventName, searchResultsTitle) + ' - ' + pagePath.substring(pagePageStartIndex - 1, pagePath.lastIndexOf('/'));
					break;
				case 'special-rates':
				case 'favorites':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, searchResultsTitle) + ' - ' + pagePath.substring(pagePath.lastIndexOf('/'));
					break;
				case 'tee-time-search':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, searchResultsTitle) + ' - ' + pagePath.split('/').pop();
					break;
				case 'homepage':
					var widgetIdentifier = $elemObj.parents('.gn_widget').data('widgetidentifier') || '';

					title = $.views.helpers.getPageTitleForAanalytics(eventName, 'Homepage Widget') + ' - ' + widgetIdentifier;
					break;
				case 'destination-city':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, featuredCoursesDestinationTitle) + ' - ' + pagePath;
					break;
				case 'featured-courses':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, 'Featured Courses Landing Page') + ' - ' + pagePath;
					break;
				case 'city-search-analytics':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, searchResultsTitle) + ' - ' + pagePath.substring(pagePath.indexOf('city') - 1);
					break;
				case 'golfnow-reviews-courses-analytics':
					title = $.views.helpers.getPageTitleForAanalytics(eventName, 'GolfNow Reviews Courses') + ' - ' + pagePath;
					break;
				default:
					break;
			}
			return title;
		},
		getGoogleEventAndImpression: function (facility, eventType, clickedElemObj, findFacilityFromElemObj) {
			//variable "executeAnalytics" is "true" only when calling "getGoogleEventAndImpression" this way "$.views.helpers.getGoogleEventAndImpression"
			var executeAnalytics = typeof findFacilityFromElemObj !== 'undefined' && findFacilityFromElemObj && typeof clickedElemObj !== 'undefined';
			var pageTitleAndLocation = '';
			var eventValuesArr = [];

			if (executeAnalytics) {
				var $clickedElemObj = $(clickedElemObj);

				var facility = {
					isPrivate: $clickedElemObj.data('isprivate'),
					isPrivateCourseLabelEnabled: $clickedElemObj.data('isprivatecourselabelenabled'),
					isFeatured: $clickedElemObj.data('isfeatured'),
					isNewCourse: $clickedElemObj.data('isnewcourse'),
					hasPerks: $clickedElemObj.data('hasperks'),
					facilityId: $clickedElemObj.data('facilityid'),
					facilityName: $clickedElemObj.data('facilityname'),
					label: $clickedElemObj.data('label'),
					facilityTag: $clickedElemObj.data('facilitytag')
				};
			}

			var facilityId = $.views.helpers.findFacilityId(facility);
			var facilityName = $.views.helpers.findFacilityName(facility);
			var facilityTag = !_.isEmpty(facility.facilityTag) ? ' | ' + facility.facilityTag : '';
			var eventName = '';
			var eventValues = '';
			var impression = '';
			var track = '';

			if (facility.isPrivate && facility.isPrivateCourseLabelEnabled && !$.views.helpers.golfpassPerksOnly())
				eventName = 'Private';
			else if (facility.isFeatured)
				eventName = 'Featured';
			else if (facility.isNewCourse)
				eventName = 'New';
			else if (facility.hasPerks)
				eventName = 'Perks';
			else
				return '';

			pageTitleAndLocation = $.views.helpers.getTitleAndLocationForAnalytics(clickedElemObj, eventName);

			if (eventType === 'impression') {
				//used '^' delimiter in order to prevent the facility name to be splitted into a separate position if contains a comma
				eventValues = "'courseImpression'^ '" + eventName + " Course'^ 'impression'^ '" + $.views.converters.escapeApostrophes(facilityName) + " | " + facilityId + facilityTag + pageTitleAndLocation + "'^ 1.00";
				track = "TrackGoogleEvent(" + eventValues + ")";
				//replace '^' delimiter with a comma in order to maintain the string original state
				impression = '<img src="https://vs-y8x5j2b5.akamaized.net/Content/images/empty_pixel.gif?v=339922269" style="display: none;" onload="' + track.replaceAll('^',',') + '" />';

				if (executeAnalytics) {
					eventValuesArr = $.views.helpers.removeQuotesFromEventValues(eventValues.split('^'));
					TrackGoogleEvent(eventValuesArr[0], eventValuesArr[1], eventValuesArr[2], eventValuesArr[3], eventValuesArr[4]);
				}

				return impression;
			}
			else {
				//used '^' delimiter in order to prevent the facility name to be splitted into a separate position if contains a comma
				eventValues = "'courseClick'^ '" + eventName + " Course'^ 'click'^ '" + $.views.converters.escapeApostrophes(facilityName) + " | " + facilityId + facilityTag + pageTitleAndLocation + "'^ null";
				track = "TrackGoogleEvent(" + eventValues + ")";

				if (executeAnalytics) {
					//remove the beginning and the end  double quotes from string
					eventValuesArr = $.views.helpers.removeQuotesFromEventValues(eventValues.split('^'));
					TrackGoogleEvent(eventValuesArr[0], eventValuesArr[1], eventValuesArr[2], eventValuesArr[3], eventValuesArr[4]);
				}

				//replace '^' delimiter with a comma in order to maintain the string original state
				return track.replaceAll('^', ',');
			}
		},
		removeQuotesFromEventValues: function (eventValues) {
			var eventValuesTrimmed = [];

			_.each(eventValues, function (eventValue) {
				eventValuesTrimmed.push(eventValue.trim().replace(/^'+|'+$/g, ''));
			});

			return eventValuesTrimmed;
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		facilityImagePathDisplay: function (facility, overrideImageType) {
			var facilityImageCdn = 'https://exddilid.cdn.imgeng.in/app/ttf/image/';
			overrideImageType = overrideImageType || null;

			if (overrideImageType !== null) {
				var facilityId = facility.facilityId || facility.id;
				return $.views.helpers.imagePathDisplay(facilityImageCdn + overrideImageType + '/' + facilityId + '.jpg');
			}

			var imageUrl = facility.imagePathURL || facility.imagePathUrl;
			if (imageUrl) {
				return $.views.helpers.imagePathDisplay(imageUrl);
			} else if (facility.imgPath) {
				return $.views.helpers.imagePathDisplay(facility.imgPath);
			} else if (facility.thumbnailImagePath) {
				return $.views.helpers.imagePathDisplay(facility.thumbnailImagePath);
			}

			return "/Content/images/general.jpg";
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";

	$.views.helpers({
		isFacilityPageLeftSide: function () {
			return GolfNow.Web.Utils.IsFacilityPageLeftSide();
		}
	});

})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		facilitySearchSlug: function (facility) {
			var slug;
			var bestDealsPage = $('.special-rates').hasClass('best-tee-times-deals') || $('gn-best-deal-tiles-hpw').hasClass('best-tee-times-deals-widget');
			var url = bestDealsPage && facility.isPnas ? '/best-deals/facility/' : '/tee-times/facility/';
			if (facility.seoFriendlyName)
				slug = facility.seoFriendlyName;
			else if(facility.facilityId)
				slug = facility.facilityId;
			else if (facility.id)
				slug = facility.id;

			return url + slug + '/search';
		},
		courseDetailsSlug: function (facility) {
			var slug;
			if (facility.courseDetailSeoFriendlyName)
				slug = facility.courseDetailSeoFriendlyName;
			else if (facility.facilityId)
				slug = facility.facilityId;
			else if (facility.id)
				slug = facility.id;

			return '/courses/' + slug;
		},
		courseReviewDetailsSlug: function (facility) {
			var slug;
			var productReviewId;
			var friendlyName;

			if (facility.productReviewId) {
				productReviewId = facility.productReviewId;
			} else if (facility.reviewId) {
				productReviewId = facility.reviewId;
			}
			if (facility.seoFriendlyName) {
				friendlyName = facility.seoFriendlyName.substring(facility.seoFriendlyName.indexOf('-') + 1);
			}
			slug = '/courses/' + productReviewId + '-' + friendlyName + '-details#ratings-snapshot';

			return slug;
		},
		courseWriteReviewsSlug: function (facility) {
			var slug;
			var productReviewId;
			var facilityId = $.views.helpers.findFacilityId(facility) || null;

			if (facilityId !== null) {
				facilityId = facilityId;
			}
			if (facility.productReviewId) {
				productReviewId = facility.productReviewId;
			} else if (facility.reviewId) {
				productReviewId = facility.reviewId;
			}

			slug = '/courses/' + facilityId + '/write-review/' + productReviewId;

			return slug;
		},
		reservationDetailsSlug: function (reservation) {
			var reservationID = $.views.helpers.findReservationId(reservation) || null;
			var facilityId = $.views.helpers.findFacilityId(reservation.facility) || null;

			if (reservation.reservationCanCheckIn)
				return 'smart-play/pay-check-in/' + reservationID + '/' + facilityId;

			return '/account/booking-history/' + reservationID + '/details';
		},
		findFacilityId: function (facility) {
			if (facility.facilityId)
				return Number(facility.facilityId);
			else if (facility.id)
				return Number(facility.id);
		},
		findReservationId: function (reservation) {
			if (reservation.reservationID)
				return Number(reservation.reservationID);
			else if (reservation.id)
				return Number(reservation.id);
		},
		findFacilityName: function (facility) {
			if (facility.facilityName)
				return facility.facilityName;
			else if (facility.name)
				return facility.name;
			else if (facility.label)
				return facility.label;
		}
	});
})(this.jQuery);;
(function ($) {
    "use strict";
    $.views.helpers({
        filterTotalDisplay: function (filterTotalsObject, filterCategory, filterSubcategory) {
            filterCategory = filterCategory.toString().toLowerCase();
            filterSubcategory = filterSubcategory.toString().toLowerCase();

            if (typeof filterTotalsObject === "undefined") { return 0; }
            if (typeof filterTotalsObject[filterCategory] === "undefined") { return 0; }
            if (typeof filterTotalsObject[filterCategory][filterSubcategory] === "undefined") { return 0; }

            return filterTotalsObject[filterCategory][filterSubcategory];
        }
    });
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		holesDisplay: function (teeTimeRate) {
			if (teeTimeRate.isNine) {
				return '<strong>Holes:</strong> 9';
			} else if (teeTimeRate.isEightteen) {
				return '<strong>Holes:</strong> 18';
			} else {
				return '<strong>Holes:</strong> ' + teeTimeRate.holeCount;
			}
		},
		holesDisplay2: function (teeTimeRate) {
			if (teeTimeRate.isNine) {
				return '<span title="Holes" class="holes font-12"><i class="gn-icon gn-flag"></i> 9</span>';
			} else if (teeTimeRate.isEightteen) {
				return '<span title="Holes" class="holes font-12"><i class="gn-icon gn-flag"></i> 18</span>';
			} else {
				return '<span title="Holes" class="holes font-12"><i class="gn-icon gn-flag"></i> ' + teeTimeRate.holeCount + '</span>';
			}
		},
		holesDisplay3: function (multipleHolesRate, text) {
			//text is used for adding any words next to the hole count (e.g., 18/9 Holes)
			if (text) {
				text = ' ' + text;
			}
			else {
				text = '';
			}

			return '<span title="Holes" class="holes font-12"><i class="gn-icon gn-flag"></i>' + multipleHolesRate + text + '</span>';
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		isHomePage: function () {
			return GolfNow.Web.Utils.IsHomePageSearch();
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		iconSummaryDisplay: function (teeTimeRate) {
			var strReturn = '';

			if (teeTimeRate.isCartIncluded) {
				strReturn += ' <strong>Cart:</strong> Included';
			}

			if (teeTimeRate.isAdvisory) {
				strReturn += ' <strong>Advisory:</strong> <i class="fa-solid fa-triangle-exclamation"></i>';
			}

			return strReturn;
		},
		iconSummaryDisplay2: function (teeTimeRate) {
			var strReturn = '';

			if (teeTimeRate.isCartIncluded) {
				strReturn += '&nbsp;<span class="icon-break">/</span>&nbsp;<span title="Cart Included"><i class="gn-icon gn-golfcart"></i></span>';
			}

			return strReturn;
		},
		advisoryDisplay: function (teeTimeRate) {
			var strReturn = '';

			if (teeTimeRate.isAdvisory) {
				strReturn += '&nbsp;<span title="Advisory"><i class="fa-solid fa-triangle-exclamation"></i></span>';
			}

			return strReturn;
		}
	});
})(this.jQuery);;
(function ($) {
    "use strict";
    $.views.helpers({
        imagePathDisplay: function (url) {
            if (url !== '' && url.indexOf('http') === -1) {
                return document.location.protocol + '//' + url;
            }
            else if (url !== '') {
                return url;
            }
        }
    });
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		localizeCurrency: function (value, cultureCode, isoCurrencySymbol) {
			var _cultureCode = cultureCode || 'en-US';
			var _isoCurrencySymbol = isoCurrencySymbol || 'USD';
			var formatter = new Intl.NumberFormat(_cultureCode, {
				style: 'currency',
				currency: _isoCurrencySymbol,
			});
			return formatter.format(value);
		}
	});
})(this.jQuery);;
(function ($) {
    "use strict";
    $.views.helpers({
        wholeStar: function (value) {
            if (value < 0 || value > 5) { return 0; }
            return parseInt(value);
        }
    });

    $.views.helpers({
        partialStar: function (value, index) {
            var result = 0;
            if (value >= index - 1 && value <= index) {
                result = parseFloat(Math.round((value % 1) * 100) / 100).toFixed(1);
            }
            return result;
        }
    });
    $.views.helpers({
        generateStarId: function () {
            var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });

            return id;
        }
    });

    $.views.helpers({
		getRoundedRating: function (value) {
			var decimalPlace = (value % 1).toFixed(1);
			if (decimalPlace != 0.0) {
				return value.toFixed(1);
			}
			else {
				return Math.floor(value);
			}
        }
    });

    $.views.helpers({
        getStarRatingId: function (elem) {
            return $.view(this).closest("span").id();
        }
    });



})(this.jQuery);;
///
(function ($) {
	"use strict";
	$.views.helpers({
		playerRuleDisplay: function (rule) {
			switch (rule) {
				case 1:
					return '<strong>Golfers:</strong> 1';
				case 9:
					return '<strong>Golfers:</strong> 1, 4';
				case 15:
					return '<strong>Golfers:</strong> 1 - 4';
				case 8:
					return '<strong>Golfers:</strong> 4';
				case 5:
					return '<strong>Golfers:</strong> 1, 3';
				case 13:
					return '<strong>Golfers:</strong> 1, 3 - 4';
				case 3:
					return '<strong>Golfers:</strong> 1 - 2';
				case 11:
					return '<strong>Golfers:</strong> 1 - 2, 4';
				case 7:
					return '<strong>Golfers:</strong> 1 - 3';
				case 4:
					return '<strong>Golfers:</strong> 3';
				case 12:
					return '<strong>Golfers:</strong> 3 - 4';
				case 2:
					return '<strong>Golfers:</strong> 2';
				case 10:
					return '<strong>Golfers:</strong> 2, 4';
				case 6:
					return '<strong>Golfers:</strong> 2 - 3';
				case 14:
					return '<strong>Golfers:</strong> 2 - 4';
				default:
					return '<strong>Golfers:</strong> Unknown';
			}
		},
		playerRuleDisplay2: function (rule, singleLine) {
			singleLine = (singleLine === undefined || singleLine === null) ? false : singleLine;
			var multiLineHtml = '&nbsp;<span class="icon-break">/</span>&nbsp;';
			var html = '';
			switch (rule) {
				case 1:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1</span>';
					break;
				case 9:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1, 4</span>';
					break;
				case 15:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1-4</span>';
					break;
				case 8:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 4</span>';
					break;
				case 5:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1, 3</span>';
					break;
				case 13:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1, 3-4</span>';
					break;
				case 3:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1-2</span>';
					break;
				case 11:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1-2, 4</span>';
					break;
				case 7:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 1-3</span>';
					break;
				case 4:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 3</span>';
					break;
				case 12:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 3-4</span>';
					break;
				case 2:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 2</span>';
					break;
				case 10:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 2, 4</span>';
					break;
				case 6:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 2-3</span>';
					break;
				case 14:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> 2-4</span>';
					break;
				default:
					html = '<span class="golfers-available" title="Golfers"><i class="gn-icon gn-golfers"></i> Unknown</span>';
					break;
			}
			if (!singleLine)
				html = multiLineHtml + html;
			return html;
		},
		playerRuleMaxPlayers: function (rule) {
			switch (rule) {
				case 1:
					return 1;
				case 2:
				case 3:
					return 2;
				case 4:
				case 5:
				case 6:
				case 7:
					return 3;
				case 8:
				case 9:
				case 10:
				case 11:
				case 12:
				case 13:
				case 14:
				case 15:
					return 4;
				default:
					return 4;
			}
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		pointsFormatter: function (dashboardValue) {
			var removedDecimals = Math.trunc(dashboardValue); // remove decimals
			var addCommas = removedDecimals.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); // insert commas (thousands)

			return addCommas;
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		ifResultHash: function (useHashParam) {
			return !_.isUndefined(useHashParam) && !_.isNull(useHashParam) && useHashParam;
		},
		useHashParams: function (resultHashParams) {
			if (!_.isUndefined(resultHashParams) && !_.isNull(resultHashParams))
				return resultHashParams;
			else
				return '';
		}
	});
})(this.jQuery);;
(function ($, _, dateJs, gnDate) {
    "use strict";
    
    String.prototype.padLeft = function (char, length) {
        var str = this;
        if (!this instanceof String) { str = this.toString(); }
        while (str.length < length) {
            str = char + str;
        }

        return str;
    };

	Date.prototype.toShortDateString = dateJs.prototype.toShortDateString = function () {
        return (this.getMonth() + 1).toString().padLeft('0', 2) +
            "/" + this.getDate().toString().padLeft('0',2) +
            "/" + this.getFullYear();
    };

    $.views.helpers({
        shortDate: function (date) {
            if (!date) return '';
			if (date instanceof Date || date instanceof dateJs) {
				date = dateJs.parse(date.toShortDateString());
            } else {
                var dateStr = date;
                var pos = date.indexOf('.');
                if (pos > -1)
                    dateStr = date.substr(0, pos);

				date = dateJs.parse(dateStr);

				if (date === null) {
					date = new Date(dateStr);
				}
            }
            if (_.isDate(date)) { return date.toShortDateString(); }
			else { return new dateJs().toShortDateString(); }
        },
		formatDate: function (date, format, defaultValue) {
            if (!date) return defaultValue || '';
            if (format === undefined || format === null || format === '') format = 'dddd, MMM dd';
			if (date instanceof Date || date instanceof dateJs) {
				date = dateJs.parse(date);
            } else {
                var dateStr = date;
                var pos = date.indexOf('.');
                if (pos > -1)
                    dateStr = date.substr(0, pos);

				date = dateJs.parse(dateStr);

				if (date === null) {
					date = new Date(dateStr);
				}
			}

            if (_.isDate(date)) { return date.toString(format); }
			else if (defaultValue) { return defaultValue; }
			else { return new dateJs().toString(format); }
        },
        isAfterCurrentDate: function (date) {
            if (!date) return false;
			var currentDate = new dateJs();
			var parsedDate = dateJs.parse(date);
        	return (currentDate.compareTo(parsedDate) > 0);
		}
    });
})(this.jQuery, _, Date, GolfNow.Web.Date);;
(function ($) {
    "use strict";
    $.views.helpers({
        subratingDisplay: function (subratingObject) {
            if (typeof subratingObject === "undefined") { return "n/a"; }
            return subratingObject.ValueLabel;
        }
    });
})(this.jQuery);;
(function ($) {
	"use strict";
	$.views.helpers({
		minTeeTimeRate: function (teeTimes) {
			var lowest = Number.POSITIVE_INFINITY;
			var tmp;
			for (var i = teeTimes.length - 1; i >= 0; i--) {
				tmp = teeTimes[i].teeTimeRates[0].singlePlayerPrice.greensFees.value;
				if (tmp < lowest) lowest = tmp;
			}
			return "$" + parseFloat(lowest).toFixed(2);
		}
	});

	$.views.helpers({
		maxTeeTimeRate: function (teeTimes) {
			var highest = Number.NEGATIVE_INFINITY;
			var tmp;
			for (var i = teeTimes.length - 1; i >= 0; i--) {
				tmp = teeTimes[i].teeTimeRates[0].singlePlayerPrice.greensFees.value;
				if (tmp > highest) highest = tmp;
			}
			return "$" + parseFloat(highest).toFixed(2);
		}
	});

	$.views.helpers({
		minTeeTimeRateVal: function (teeTimes) {
			var lowest = Number.POSITIVE_INFINITY;
			var tmp;
			var currencySymbol;
			for (var i = teeTimes.length - 1; i >= 0; i--) {
				tmp = teeTimes[i].teeTimeRates[0].singlePlayerPrice.greensFees.value;
				currencySymbol = teeTimes[i].teeTimeRates[0].singlePlayerPrice.greensFees.currencySymbol;
				if (tmp < lowest) lowest = tmp;
			}
			return currencySymbol + parseFloat(lowest).toFixed(2);
		}
	});

	$.views.helpers({
		isTopGolf: function (teeTimes) {
			var isTopGolf = teeTimes[0].facility.isTopGolf;
			return isTopGolf;
		}
	});

	$.views.helpers({
		isSimulator: function (teeTimes) {
			var isSimulator = teeTimes[0].facility.isSimulator;
			return isSimulator;
		}
	});

})(this.jQuery);;
(function ($) {
    "use strict";

    function shortenLongText(reviewText, userName, reviewDate, length) {
        //need to create a unique id for each review since a userName may have multiple reviews for a single course
        //so the combination of the userName and reviewDate w/timestamp info should generate a unique identifier for each review
        var userId = userName + '_' + reviewDate;
        var displayText = reviewText.substr(0, length);
        var html = '';
        if (displayText !== '' && displayText.length < reviewText.length)
        {
            html = '<div><p id="Less' + userId + '">' + displayText + '...<a class="more" href="javascript:toggleReviewText(\'' + userId + '\');">Read More</a></p></div>';
            html += '<div><p id="More' + userId + '" style="display:none;">' + reviewText + ' <a class="more" href="javascript:toggleReviewText(\'' + userId + '\');">Read Less</a></p></div>';
        }else{
            html = '<div><p>' + displayText + '</p></div>';
        }
        return html;
    }

    $.views.tags({
        abbreviateText: {
            render: shortenLongText
        }
    });

})(this.jQuery);;
(function ($, _, Date) {
	"use strict";
	var _currentProfileId = '', _avatarRootUrl = '', _gaPhotoRootUrl = '';
	function buildActivityItems(item, currentProfileId, avatarRootUrl, gaPhotoRootUrl) {
		var $html = '';
		_currentProfileId = currentProfileId;
		_avatarRootUrl = avatarRootUrl;
		_gaPhotoRootUrl = gaPhotoRootUrl;

		var activityData = getDataLines(item);
		if (activityData === undefined) return undefined;

		$html = $('<div>', { 'class': 'collapse ' + activityData.className })
				.append($('<div>', {'class': 'columns small-2', 'html': activityData.avatar}))
					.append($('<div>', { 'class': 'columns small-10 collapse ' + activityData.className + '-sub' })
						.append($('<i>', { 'class': 'fa-solid fa-xmark', 'style': 'cursor: pointer;', 'data-link': activityData.dismiss }))
					.append($('<h3>', { 'html': activityData.title }))
					.append($('<p>', { 'class': 'right', 'html': activityData.date }))
					.append($('<p>', { 'class': 'small-9', 'html': activityData.subject })));


		if (activityData.cta !== '') $html.find('.' + activityData.className + '-sub').append($('<button>', { 'class': 'button btn btn-blue', 'data-link': activityData.cta, 'html': 'View' }));
		$html.append($('<hr>'));
		if (activityData.gtf !== '') $html.find('.' + activityData.className + '-sub').append($('<button>', { 'class': 'button btn btn-green', 'style': 'margin: 3px', 'data-link': activityData.gtf, 'html': 'Book Again' }));
		$html.append($('<hr>'));
		return $html[0].outerHTML;
	}

	function getDataLines(activityItem) {
		/// <summary>
		/// Gets the data lines.
		/// </summary>
		/// <param name="activityItem">The activity item.</param>
		/// <returns></returns>
		/// Objects:  Unknown, User, Facility, Reservation, Review, Scorecard, ReservationInvite, FriendRequest, Reward
		var title = '', action = '', subject = '',
			metadata, className,
			date = Date.parse(activityItem.time).toString('ddd, MMM dd'),
			dismiss = '{on "click" ~dismissActivity "' + activityItem.activityGuid + '"}',
			cta = '', activityText = '', avatar = '',
			gtf = '';

		switch (activityItem.activityType) {
			case 3:	//Reservation
				subject = activityItem.text;
				title = activityItem.headerText;
				className = 'friend-request';
				cta = '{on "click" ~gotoReservation "' + activityItem.activityId + '"}';
				gtf = '{on "click" ~gotoFacility "' + activityItem.facilityId + '"}';
				avatar = facilityAvatar(activityItem.activityId, activityItem.facilityId, activityItem.reviewId);
				break;
			case 6:	//ReservationInvite
				subject = activityItem.text;
				title = activityItem.headerText;
				className = 'friend-request';
				cta = activityItem.hasReservationGroup ? '' : '{on "click" ~lookupReservationInvite "' + activityItem.reservationId + '"}';
				avatar = facilityAvatar(activityItem.activityId, activityItem.facilityId, activityItem.reviewId);
				break;
			case 7:	//FriendRequest
				subject = activityItem.text;
				title = activityItem.headerText;
				className = 'friend-request';
				avatar = $.views.tags.avatarPic.render(activityItem.friendProfile.firstName, activityItem.friendProfile.lastName, _avatarRootUrl, activityItem.friendProfile.avatarUrl);
				break;
			case 1:	//User
			case 2:	//Facility
			case 4:	//Review
			case 5:	//Scorecard
			case 8:	//Reward
				subject = activityItem.text;
				title = activityItem.headerText;
				className = 'friend-request';
				avatar = '<div class="small-profile-pic" style="background-image: url(https://vs-y8x5j2b5.akamaized.net/Content/images/Rewards_Trophy.svg?v=339922269)"></div>';
				cta = '{on ~gotoRewards}'; 
				break;
			default:	//Unknown
				return undefined;
		}
		subject = replaceTokens(subject, activityItem);
		return { title: title, subject: subject, date: date, className: className, dismiss: dismiss, cta: cta, gtf: gtf, avatar: avatar };
	}

	function facilityAvatar(activityId, facilityId, reviewId) {
		var facilityImageUrl;
		if (_gaPhotoRootUrl && _gaPhotoRootUrl !== "" && facilityId !== 0) {
			facilityImageUrl = _gaPhotoRootUrl + facilityId;
		}
		if (facilityImageUrl && facilityImageUrl !== "") {
			return '<a href="/courses/' + reviewId + '"><div class="small-profile-pic" style="background-image: url(' + _gaPhotoRootUrl + facilityId + '.jpg)"></div></a>'
		}
		else {
		    return '<div class="small-profile-pic" style="background-image: url(https://vs-y8x5j2b5.akamaized.net/Content/images/social/profile-pic-default.png?v=339922269)"></div>';
		}
	}

	function replaceTokens(subject, activityItem) {
		if (subject && subject !== '') {
			if (activityItem.friendProfile) {
				var friendName = activityItem.friendProfile.name;
				var friendProfileId = activityItem.friendProfile.profileId;
				subject = subject.replace('{friendProfile.name}', '<a href="/golfer/' + friendProfileId + '">' + friendName + '</a>');
			}

			var facilityName = activityItem.facilityName;
			var reservationDate = activityItem.playDate;
			var reviewId = activityItem.reviewId; 

			subject = subject.replace('{facility.name}', '<a href="/courses/' + reviewId + '">' + facilityName + '</a>');
			subject = subject.replace('{reservationDateTime}', reservationDate);

			return subject;
		}
	}

	$.views.tags({
		activityFeedItems: {
			render: buildActivityItems,
			template: ''
		}
	});
})(this.jQuery, this._, Date);;
(function ($) {
	"use strict";

	function getPictureInitials(initials, avatarRootUrl, avatarFileName, className) {
		var avatarHtml = undefined;
		if (_.isEmpty(avatarFileName)) {
			if (initials !== '') {
				var $initialsElem = $('<div>', {
					'id': (className === 'profile-picture') ? 'profile-pic-uploader' : _.random(1, 1000),
					'class': className + ' initials',
					'html': $('<span>', {
						'html': initials.toUpperCase(),
						'id': 'initials-container'
					})
				});
				avatarHtml = $initialsElem[0].outerHTML;
			}
		} else {
			var avatarPath = avatarFileName;
			if ((avatarFileName.indexOf('/') === -1)) avatarPath = avatarRootUrl + avatarFileName;
			var $avatarElem = $('<div>', {
				'id': (className === 'profile-picture') ? 'profile-pic-uploader' : _.random(1, 1000),
				'class': className,
				'style': 'background-image: url(' + avatarPath + ')'
			});
			avatarHtml = $avatarElem[0].outerHTML;
		}
		return avatarHtml;
	}

	function getSmallPicture() {
		var ctx = null;
		if (_.isEmpty(this.tagCtx) && arguments.length > 0) {
			ctx = { args: arguments };
		} else {
			ctx = this.tagCtx;
		}
		var params = getInitials(ctx);
		return getPictureInitials(params.initials, params.urlRoot, params.fileName, 'small-profile-pic');
	}

	function getFullPicture() {
		var ctx = null;
		if (_.isEmpty(this.tagCtx) && arguments.length > 0) {
			ctx = { args: arguments };
		} else {
			ctx = this.tagCtx;
		}
		var params = getInitials(ctx);
		return getPictureInitials(params.initials, params.urlRoot, params.fileName, 'profile-picture');
	}

	function getInitials(tagCtx) {
		var initials = '', urlRoot = '', fileName = '', _firstName = '', _lastName = '';
		switch (tagCtx.args.length) {
			case 3:
				var nameParts = [];
				if (!_.isEmpty(tagCtx.args[0])) nameParts = tagCtx.args[0].split(' ');

				if (nameParts.length >= 1) _firstName = nameParts[0] || '';
				if (nameParts.length >= 2) _lastName = nameParts[1] || '';
				initials = _firstName.substr(0, 1) + _lastName.substr(0, 1);
				urlRoot = tagCtx.args[1];
				fileName = tagCtx.args[2];
				break;
			case 4:
				_firstName = tagCtx.args[0] || '';
				_lastName = tagCtx.args[1] || '';

				initials = _firstName.substr(0, 1) + _lastName.substr(0, 1);
				urlRoot = tagCtx.args[2];
				fileName = tagCtx.args[3];
				break;
			default:
				return '';
		}
		return { initials: initials, urlRoot: urlRoot, fileName: fileName };
	}

	$.views.tags({
		avatarPic: {
			render: getSmallPicture,
			template: '<div class="small-profile-pic" style="background-image: url(https://vs-y8x5j2b5.akamaized.net/Content/images/social/profile-pic-default.png?v=339922269)"></div>'
		},
		avatarPicFull: {
			render: getFullPicture,
			template: '<div id="profile-pic-uploader" class="profile-picture" data-link="css-background-image{:\'url(https://vs-y8x5j2b5.akamaized.net/Content/images/social/profile-pic-default.png?v=339922269)\'}"></div>'
		}
	});
})(this.jQuery);;
/**
 * Custom JsRender debug tag
 * Log a message and an object to the console.
 * Usage: {{debug #parent message='Inside the for loop'/}}
 **/
$.views.tags({
    debug: function (obj) {
        var props = this.tagCtx.props;
        // output a default message if the user didn't specify a message
        var msg = props.message || 'Debug:';
        console.log(msg, obj);
    }
});;
(function ($) {
    "use strict";

    function calcOccurance(array, ctx) {
        var d = $.Deferred();
        var featuredFacilitiesArray = array,
            startIndex = ctx.tagCtx.props.startIndex,
            currentIndex = ctx.tagCtx.props.currentIndex,
            date = ctx.tagCtx.props.date,
            frequency = ctx.tagCtx.props.frequency,
            totalRecords = ctx.tagCtx.props.totalRecords;

        if (((startIndex + currentIndex) % frequency) === 0) {
            var featuredFacilityIndex = (startIndex + currentIndex) / frequency;
            var totalFeaturedPerResultset = totalRecords / frequency;
            if (featuredFacilityIndex < featuredFacilitiesArray.length && featuredFacilityIndex < totalFeaturedPerResultset) {
                var facility = featuredFacilitiesArray[featuredFacilityIndex];
                if (facility && !facility.minPrice) {
                    var that = ctx;
                    var html = '';

                    return $.ajax({
                        type: 'POST',
                        async: true,
                        url: "/api/tee-times/featured-facility-result",
                        data: JSON.stringify({ 'facilityId': facility.facilityId, 'predicateDate': date }),
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8'
                    }).pipe(function (data) {
                        facility['minPrice'] = data.ffResult.minPrice;
                        facility['teeTimeCount'] = data.ffResult.teeTimeCount;

                        return { facility: facility, pos: currentIndex, startIndex: startIndex };
                    });
                } else {
                    d.reject();
                }
            } else {
                d.reject();
            }
        } else {
            d.reject();
        }
        return d.promise();
    }

    function getFacility(array) {
        var that = this;
        $.when(calcOccurance(array, that)).done(function (obj) {
            if (obj !== undefined){
                var html = that.tagCtx.content.render(obj.facility);
                var index = obj.startIndex + obj.pos;
                $('#results').children('.single-course-list').eq(index).before(html);
            } else {
                return undefined;
            }
        });
    }

    $.views.tags({
        featuredFacility: {
            render: getFacility,
            template: ''
        }
    });

})(this.jQuery);;
/*! Sample JsViews tag control: {{range}} control v0.9.90 (Beta)
see: http://www.jsviews.com/#download/sample-tagcontrols */
/*
 * Copyright 2017, Boris Moore
 * Released under the MIT License.
 */

(function ($) {
	"use strict";

	// An extended {{for}} tag: {{range}} inherits from {{for}}, and adds
	// support for iterating over a range (start to end) of items within an array,
	// or for iterating directly over integers from start integer to end integer

	$.views.tags({
		range: {
			boundProps: ["start", "end"],

			// Inherit from {{for}} tag
			baseTag: "for",

			// Don't default first arg to the current data
			argDefault: false,

			// Override the render method of {{for}}
			render: function (val) {
				var array = val,
				  tagCtx = this.tagCtx,
				  start = tagCtx.props.start || 0,
				  end = tagCtx.props.end,
				  props = tagCtx.params.props;

				if (start || end) {
					if (!tagCtx.args.length) { // No array argument passed from tag, so create
						// a computed array of integers from start to end

						array = [];
						end = end || 0;
						for (var i = start; i <= end; i++) {
							array.push(i);
						}
					} else if ($.isArray(array)) { // There is an array argument and start and end
						// properties,so render using the array truncated to the chosen range
						array = array.slice(start, end);
					}
				}

				// Call the {{for}} baseTag render method
				return arguments.length || props && (props.start || props.end)
				  ? this.base(array)
				  : this.base(); // Final {{else}} tag, so call base() without arguments, for
				// final {{else}} of base {{for}} tag
			},

			// override onArrayChange of the {{for}} tag implementation
			onArrayChange: function (ev, eventArgs) {
				this.refresh();
			}
		}
	});

})(this.jQuery);;
(function ($) {
    "use strict";

    function renderReviewClientResponse() {
        return this.tagCtx.content.render({ ClientResponse: this.tagCtx.props.ClientResponse, Product: this.tagCtx.props.Product });
    }

    $.views.tags({
        reviewClientResponse: {
            render: renderReviewClientResponse
        }
    });

})(this.jQuery);;
(function ($) {
    "use strict";

    function renderReviewComment() {
        return this.tagCtx.content.render({ Comment: this.tagCtx.props.Comment });
    }

    $.views.tags({
        reviewComment: {
            render: renderReviewComment
        }
    });

})(this.jQuery);;
(function ($) {
	"use strict";
	var spotlightArticleUrl = '/{{:~spotlightArticleUrl()}}/{{>slug}}';

	$.views.tags({
		spotlightArticlesLink: {
			template: '<a href="' + spotlightArticleUrl + '" title="{{>title}}" data-spotlightid="{{>id}}" data-spotlighttitle="{{>title}}"\
					  onclick="TrackGoogleEvent(\'spotlightHomepage\', \'Spotlight Homepage\', \'Click\', \'{{>title}}|' + spotlightArticleUrl + '\', null);">\
					  {{include tmpl=#content /}}</a> '
		}
	});
})(this.jQuery);;
(function ($) {
	"use strict";

	function renderRating() {
		return this.tagCtx.content.render({ averageRating: this.tagCtx.props.averageRating, reviewCount: this.tagCtx.props.reviewCount, distance: this.tagCtx.props.distance, isAdvisory: this.tagCtx.props.isAdvisory, includeContainer: this.tagCtx.props.includeContainer || 'true', facilityId: this.tagCtx.props.facilityId, productReviewId: this.tagCtx.props.productReviewId, starsOnly: this.tagCtx.props.starsOnly || 'false', starsAndReviewsOnly: this.tagCtx.props.starsAndReviewsOnly || 'false', readReviewPageUrl: this.tagCtx.props.readReviewPageUrl || '#', showZeroReviews: this.tagCtx.props.showZeroReviews || 'true' });
	}

	$.views.tags({
		starRating: {
			render: renderRating
		}
	});

})(this.jQuery);;
(function ($) {
    "use strict";

    function getTeeTime(teeTimeId) {
        var featuredFacilitiesArray = array,
            startIndex = this.tagCtx.props.startIndex,
            currentIndex = this.tagCtx.props.currentIndex,
            date = this.tagCtx.props.date,
            frequency = this.tagCtx.props.frequency;

        if (((startIndex + currentIndex) % frequency) === 0) {
            var featuredFacilityIndex = (startIndex + currentIndex) / frequency;
            var facility = featuredFacilitiesArray[featuredFacilityIndex];
            if (facility) {
                var that = this;
                var html = '';
                $.ajax({
                    type: 'POST',
                    async: false,
                    url: "/api/tee-times/featured-facility-result",
                    data: JSON.stringify({ 'facilityId': facility.facilityId, 'predicateDate': date }),
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8'
                }).done(function (data) {
                    facility['minPrice'] = data.ffResult.minPrice;
                    facility['teeTimeCount'] = data.ffResult.teeTimeCount;

                    html = that.tagCtx.content.render(facility);
                });
                return html;
            }
        }
        return '';
    }

    $.views.tags({
        teeTimeRate: {
            render: getTeeTime
        }
    });

})(this.jQuery);;
(function ($) {
	"use strict";

	$.views.tags({
		ttViewLink: {
			template: '{{if hasMoreRates}}<a href="{{:detailUrl}}/select-rate/players/{{:~playersFilterOption()}}" title="{{>~findFacilityName(#data)}} Tee Times">{{else}}<a href="{{:detailUrl}}" title="{{>~findFacilityName(#data)}} Tee Time"\
				onclick="var href=this.href;\
				{{:~getGoogleEventAndImpression(#data,\'click\')}};\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'{{:teeTimeRates[0].singlePlayerPrice.greensFees.formattedValue}}\',\'{{:teeTimeRates[0].isHotDeal}}\',\'\',\'\',\'\',\'\', href)">\
				{{/if}}\
				{{include tmpl=#content /}}</a>'
		},
		courseViewLink: {
			template: '<a href="{{:~facilitySearchSlug(#data)}}{{:~resultHash(daysOut)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-daysout="{{:daysOut}}" data-facilityname="{{>~findFacilityName(#data)}}" data-facilityid="{{:~findFacilityId(#data)}}" data-city="{{>address.city}}"\
				data-isprivate="{{:~findFacilityProperty(#data, \'isPrivate\')}}" data-isprivatecourselabelenabled="{{:~findFacilityProperty(#data, \'isPrivateCourseLabelEnabled\')}}" data-isfeatured="{{:~findFacilityProperty(#data, \'isFeatured\')}}" data-isnewcourse="{{:~findFacilityProperty(#data, \'isNewCourse\')}}"\
				data-hasperks="{{:~findFacilityProperty(#data, \'hasPerks\')}}" data-label="{{:~findFacilityProperty(#data, \'label\')}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}"\
				onclick="$.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'\',\'\',\'\',\'\',\'\',\'\', href)"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}">\
				{{include tmpl=#content /}}</a>'
		},
		tradeOnlyCourseViewLink: {
			template: '<a href="{{:~facilitySearchSlug(#data)}}{{:~tradeOnlyResultHash()}}" title="{{>~findFacilityName(#data)}} Tee Times" data-daysout="{{:daysOut}}" data-facilityname="{{>~findFacilityName(#data)}}" data-facilityid="{{:~findFacilityId(#data)}}" data-city="{{>address.city}}"\
				onclick="var href=this.href;\
				{{:~getGoogleEventAndImpression(#data,\'click\')}};\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'\',\'\',\'\',\'\',\'\',\'\', href)"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}">\
				{{include tmpl=#content /}}</a>'
		},
		reviewsCourseViewLink: {
			template: '<a href="{{:~courseReviewDetailsSlug(#data)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-daysout="{{:daysOut}}" data-facilityname="{{>~findFacilityName(#data)}}" data-facilityid="{{:~findFacilityId(#data)}}" data-city="{{>address.city}}"\
				onclick="var href=this.href; $.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);\
				{{:~getGoogleEventAndImpression(#data,\'click\')}};\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'\',\'\',\'\',\'\',\'\',\'\', href)"\
				data-state="{{:address.stateProvinceCode}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}" data-isfeatured="{{:~findFacilityProperty(#data, \'isFeatured\')}}" data-country="{{>address.country}}">\
				{{include tmpl=#content /}}</a>'
		},
		otherCoursesLink: {
			template: '<a href="{{:~facilitySearchSlug(#data)}}{{:~resultHash(daysOut)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-facilityid="{{:~findFacilityId(#data)}}" data-facilityname="{{>~findFacilityName(#data)}}" data-city="{{>address.city}}"\
				data-isprivate="{{:~findFacilityProperty(#data, \'isPrivate\')}}" data-isprivatecourselabelenabled="{{:~findFacilityProperty(#data, \'isPrivateCourseLabelEnabled\')}}" data-isfeatured="{{:~findFacilityProperty(#data, \'isFeatured\')}}" data-isnewcourse="{{:~findFacilityProperty(#data, \'isNewCourse\')}}"\
				data-hasperks="{{:~findFacilityProperty(#data, \'hasPerks\')}}" data-label="{{:~findFacilityProperty(#data, \'label\')}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}"\
				onclick="$.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}" data-daysout="{{:daysOut}}">\
				{{include tmpl=#content /}}</a>'
		},
		nineHoleCoursesLink: {
			template:
				'<a href="{{:~facilitySearchSlug(#data)}}{{:~resultHash(daysOut)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-facilityid="{{:~findFacilityId(#data)}}" data-facilityname="{{>~findFacilityName(#data)}}" data-city="{{>address.city}}" data-isfeatured="{{:~findFacilityProperty(#data, \'isFeatured\')}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}"\
				onclick="{{if !~findFacilityProperty(#data, \'isFeatured\')}}TrackGoogleEvent(\'9holeHomepageCallout\', \'9 Hole Homepage Callout\', \'Click\', \'{{>~findFacilityName(#data)}}\' + \'|\' + \'{{:~findFacilityId(#data)}}\' + \' | \' + \'Homepage Widget\' + \' - \' + \'Play Nine\', null);{{else}}$.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);{{/if}}"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}" data-daysout="{{:daysOut}}">\
				{{include tmpl=#content /}}</a>'
		},
		bestDealCoursesLink: {
			template:
				'<a href="{{:~facilitySearchSlug(#data)}}{{:~resultHash(daysOut)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-facilityid="{{:~findFacilityId(#data)}}" data-facilityname="{{>~findFacilityName(#data)}}" data-city="{{>address.city}}"\
				data-isprivate="{{:~findFacilityProperty(#data, \'isPrivate\')}}" data-isprivatecourselabelenabled="{{:~findFacilityProperty(#data, \'isPrivateCourseLabelEnabled\')}}" data-isfeatured="{{:~findFacilityProperty(#data, \'isFeatured\')}}" data-isnewcourse="{{:~findFacilityProperty(#data, \'isNewCourse\')}}"\
				data-hasperks="{{:~findFacilityProperty(#data, \'hasPerks\')}}" data-label="{{:~findFacilityProperty(#data, \'label\')}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}"\
				onclick="{{if !~findFacilityProperty(#data, \'isFeatured\')}}TrackGoogleEvent(\'BestDealsNearMeHomepage\', \'Best Deals Near Me Homepage\', \'Click\', \'{{>~findFacilityName(#data)}}\' + \'|\' + \'{{:~findFacilityId(#data)}}\', null);{{else}}$.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);{{/if}}"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}" data-daysout="{{:daysOut}}">\
				{{include tmpl=#content /}}</a>'
		},
		ttViewModalLink: {
			template: '{{if hasMoreRates}}<a class="select-rate-link tt-tile-link" href="#" title="{{>~findFacilityName(#data)}} Tee Times" data-detailurl="{{:detailUrl}}" data-players="{{:~playersFilterOption()}}" data-facilityid="{{:~findFacilityId(#data)}}" data-daysout="{{:daysOut}}">{{else}}<a class="select-rate-link"\'\
				href="{{:detailUrl}}" data-detailurl="{{:detailUrl}}" title="{{>~findFacilityName(#data)}} Tee Times"\
				onclick="var href=this.href;\
				{{:~getGoogleEventAndImpression(#data,\'click\')}};\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'{{:teeTimeRates[0].singlePlayerPrice.greensFees.formattedValue}}\',\'{{:teeTimeRates[0].isHotDeal}}\',\'\',\'\',\'\',\'\', href)">{{/if}}\
				{{include tmpl=#content /}}</a>'
		},
		courseWriteReviewLink: {
			template: '<a href="{{:~courseWriteReviewsSlug(#data)}}" title="{{>~findFacilityName(#data)}} Tee Times" data-daysout="{{:daysOut}}" data-facilityname="{{>~findFacilityName(#data)}}" data-facilityid="{{:~findFacilityId(#data)}}" data-city="{{>address.city}}"\
				onclick="var href=this.href;\
				{{:~getGoogleEventAndImpression(#data,\'click\')}};\
				GolfNow.Web.Analytics.Google.Ecommerce.ProductClick(\'{{>~findFacilityName(#data)}}\',\'{{:~findFacilityId(#data)}}\',\'\',\'\',\'\',\'\',\'\',\'\', href)"\
				data-state="{{:address.stateProvinceCode}}" data-country="{{>address.country}}">\
				{{include tmpl=#content /}}</a>'
		},
		reservationDetailsLink: {
			template: '<a href="{{:~reservationDetailsSlug(#data)}}" title="{{>~findFacilityName(facility)}} Upcoming Reservation" data-facilityid="{{:~findFacilityId(facility)}}" data-facilityname="{{>~findFacilityName(facility)}}" data-city="{{>facility.address.city}}"\
				data-isprivate="{{:~findFacilityProperty(facility, \'isPrivate\')}}" data-isprivatecourselabelenabled="{{:~findFacilityProperty(facility, \'isPrivateCourseLabelEnabled\')}}" data-isfeatured="{{:~findFacilityProperty(facility, \'isFeatured\')}}" data-isnewcourse="{{:~findFacilityProperty(facility, \'isNewCourse\')}}"\
				data-hasperks="{{:~findFacilityProperty(facility, \'hasPerks\')}}" data-label="{{:~findFacilityProperty(facility, \'label\')}}" data-facilitytag="{{:~findFacilityProperty(#data, \'tags\')}}"\
				onclick="$.views.helpers.getGoogleEventAndImpression(null,\'click\',this,true);"\
				data-state="{{:facility.address.stateProvinceCode}}" data-country="{{>facility.address.country}}">\
				{{include tmpl=#content /}}</a>'
		}
	});
})(this.jQuery);;
/*
 * Copyright 2012 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

if (typeof WeakMap === 'undefined') {
  (function() {
    var defineProperty = Object.defineProperty;
    var counter = Date.now() % 1e9;

    var WeakMap = function() {
      this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
    };

    WeakMap.prototype = {
      set: function(key, value) {
        var entry = key[this.name];
        if (entry && entry[0] === key)
          entry[1] = value;
        else
          defineProperty(key, this.name, {value: [key, value], writable: true});
        return this;
      },
      get: function(key) {
        var entry;
        return (entry = key[this.name]) && entry[0] === key ?
            entry[1] : undefined;
      },
      delete: function(key) {
        var entry = key[this.name];
        if (!entry) return false;
        var hasValue = entry[0] === key;
        entry[0] = entry[1] = undefined;
        return hasValue;
      },
      has: function(key) {
        var entry = key[this.name];
        if (!entry) return false;
        return entry[0] === key;
      }
    };

    window.WeakMap = WeakMap;
  })();
}
;
/*
 * Copyright 2012 The Polymer Authors. All rights reserved.
 * Use of this source code is goverened by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(global) {

  var registrationsTable = new WeakMap();

  // We use setImmediate or postMessage for our future callback.
  var setImmediate = window.msSetImmediate;

  // Use post message to emulate setImmediate.
  if (!setImmediate) {
    var setImmediateQueue = [];
    var sentinel = String(Math.random());
    window.addEventListener('message', function(e) {
      if (e.data === sentinel) {
        var queue = setImmediateQueue;
        setImmediateQueue = [];
        queue.forEach(function(func) {
          func();
        });
      }
    });
    setImmediate = function(func) {
      setImmediateQueue.push(func);
      window.postMessage(sentinel, '*');
    };
  }

  // This is used to ensure that we never schedule 2 callas to setImmediate
  var isScheduled = false;

  // Keep track of observers that needs to be notified next time.
  var scheduledObservers = [];

  /**
   * Schedules |dispatchCallback| to be called in the future.
   * @param {MutationObserver} observer
   */
  function scheduleCallback(observer) {
    scheduledObservers.push(observer);
    if (!isScheduled) {
      isScheduled = true;
      setImmediate(dispatchCallbacks);
    }
  }

  function wrapIfNeeded(node) {
    return window.ShadowDOMPolyfill &&
        window.ShadowDOMPolyfill.wrapIfNeeded(node) ||
        node;
  }

  function dispatchCallbacks() {
    // http://dom.spec.whatwg.org/#mutation-observers

    isScheduled = false; // Used to allow a new setImmediate call above.

    var observers = scheduledObservers;
    scheduledObservers = [];
    // Sort observers based on their creation UID (incremental).
    observers.sort(function(o1, o2) {
      return o1.uid_ - o2.uid_;
    });

    var anyNonEmpty = false;
    observers.forEach(function(observer) {

      // 2.1, 2.2
      var queue = observer.takeRecords();
      // 2.3. Remove all transient registered observers whose observer is mo.
      removeTransientObserversFor(observer);

      // 2.4
      if (queue.length) {
        observer.callback_(queue, observer);
        anyNonEmpty = true;
      }
    });

    // 3.
    if (anyNonEmpty)
      dispatchCallbacks();
  }

  function removeTransientObserversFor(observer) {
    observer.nodes_.forEach(function(node) {
      var registrations = registrationsTable.get(node);
      if (!registrations)
        return;
      registrations.forEach(function(registration) {
        if (registration.observer === observer)
          registration.removeTransientObservers();
      });
    });
  }

  /**
   * This function is used for the "For each registered observer observer (with
   * observer's options as options) in target's list of registered observers,
   * run these substeps:" and the "For each ancestor ancestor of target, and for
   * each registered observer observer (with options options) in ancestor's list
   * of registered observers, run these substeps:" part of the algorithms. The
   * |options.subtree| is checked to ensure that the callback is called
   * correctly.
   *
   * @param {Node} target
   * @param {function(MutationObserverInit):MutationRecord} callback
   */
  function forEachAncestorAndObserverEnqueueRecord(target, callback) {
    for (var node = target; node; node = node.parentNode) {
      var registrations = registrationsTable.get(node);

      if (registrations) {
        for (var j = 0; j < registrations.length; j++) {
          var registration = registrations[j];
          var options = registration.options;

          // Only target ignores subtree.
          if (node !== target && !options.subtree)
            continue;

          var record = callback(options);
          if (record)
            registration.enqueue(record);
        }
      }
    }
  }

  var uidCounter = 0;

  /**
   * The class that maps to the DOM MutationObserver interface.
   * @param {Function} callback.
   * @constructor
   */
  function JsMutationObserver(callback) {
    this.callback_ = callback;
    this.nodes_ = [];
    this.records_ = [];
    this.uid_ = ++uidCounter;
  }

  JsMutationObserver.prototype = {
    observe: function(target, options) {
      target = wrapIfNeeded(target);

      // 1.1
      if (!options.childList && !options.attributes && !options.characterData ||

          // 1.2
          options.attributeOldValue && !options.attributes ||

          // 1.3
          options.attributeFilter && options.attributeFilter.length &&
              !options.attributes ||

          // 1.4
          options.characterDataOldValue && !options.characterData) {

        throw new SyntaxError();
      }

      var registrations = registrationsTable.get(target);
      if (!registrations)
        registrationsTable.set(target, registrations = []);

      // 2
      // If target's list of registered observers already includes a registered
      // observer associated with the context object, replace that registered
      // observer's options with options.
      var registration;
      for (var i = 0; i < registrations.length; i++) {
        if (registrations[i].observer === this) {
          registration = registrations[i];
          registration.removeListeners();
          registration.options = options;
          break;
        }
      }

      // 3.
      // Otherwise, add a new registered observer to target's list of registered
      // observers with the context object as the observer and options as the
      // options, and add target to context object's list of nodes on which it
      // is registered.
      if (!registration) {
        registration = new Registration(this, target, options);
        registrations.push(registration);
        this.nodes_.push(target);
      }

      registration.addListeners();
    },

    disconnect: function() {
      this.nodes_.forEach(function(node) {
        var registrations = registrationsTable.get(node);
        for (var i = 0; i < registrations.length; i++) {
          var registration = registrations[i];
          if (registration.observer === this) {
            registration.removeListeners();
            registrations.splice(i, 1);
            // Each node can only have one registered observer associated with
            // this observer.
            break;
          }
        }
      }, this);
      this.records_ = [];
    },

    takeRecords: function() {
      var copyOfRecords = this.records_;
      this.records_ = [];
      return copyOfRecords;
    }
  };

  /**
   * @param {string} type
   * @param {Node} target
   * @constructor
   */
  function MutationRecord(type, target) {
    this.type = type;
    this.target = target;
    this.addedNodes = [];
    this.removedNodes = [];
    this.previousSibling = null;
    this.nextSibling = null;
    this.attributeName = null;
    this.attributeNamespace = null;
    this.oldValue = null;
  }

  function copyMutationRecord(original) {
    var record = new MutationRecord(original.type, original.target);
    record.addedNodes = original.addedNodes.slice();
    record.removedNodes = original.removedNodes.slice();
    record.previousSibling = original.previousSibling;
    record.nextSibling = original.nextSibling;
    record.attributeName = original.attributeName;
    record.attributeNamespace = original.attributeNamespace;
    record.oldValue = original.oldValue;
    return record;
  };

  // We keep track of the two (possibly one) records used in a single mutation.
  var currentRecord, recordWithOldValue;

  /**
   * Creates a record without |oldValue| and caches it as |currentRecord| for
   * later use.
   * @param {string} oldValue
   * @return {MutationRecord}
   */
  function getRecord(type, target) {
    return currentRecord = new MutationRecord(type, target);
  }

  /**
   * Gets or creates a record with |oldValue| based in the |currentRecord|
   * @param {string} oldValue
   * @return {MutationRecord}
   */
  function getRecordWithOldValue(oldValue) {
    if (recordWithOldValue)
      return recordWithOldValue;
    recordWithOldValue = copyMutationRecord(currentRecord);
    recordWithOldValue.oldValue = oldValue;
    return recordWithOldValue;
  }

  function clearRecords() {
    currentRecord = recordWithOldValue = undefined;
  }

  /**
   * @param {MutationRecord} record
   * @return {boolean} Whether the record represents a record from the current
   * mutation event.
   */
  function recordRepresentsCurrentMutation(record) {
    return record === recordWithOldValue || record === currentRecord;
  }

  /**
   * Selects which record, if any, to replace the last record in the queue.
   * This returns |null| if no record should be replaced.
   *
   * @param {MutationRecord} lastRecord
   * @param {MutationRecord} newRecord
   * @param {MutationRecord}
   */
  function selectRecord(lastRecord, newRecord) {
    if (lastRecord === newRecord)
      return lastRecord;

    // Check if the the record we are adding represents the same record. If
    // so, we keep the one with the oldValue in it.
    if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord))
      return recordWithOldValue;

    return null;
  }

  /**
   * Class used to represent a registered observer.
   * @param {MutationObserver} observer
   * @param {Node} target
   * @param {MutationObserverInit} options
   * @constructor
   */
  function Registration(observer, target, options) {
    this.observer = observer;
    this.target = target;
    this.options = options;
    this.transientObservedNodes = [];
  }

  Registration.prototype = {
    enqueue: function(record) {
      var records = this.observer.records_;
      var length = records.length;

      // There are cases where we replace the last record with the new record.
      // For example if the record represents the same mutation we need to use
      // the one with the oldValue. If we get same record (this can happen as we
      // walk up the tree) we ignore the new record.
      if (records.length > 0) {
        var lastRecord = records[length - 1];
        var recordToReplaceLast = selectRecord(lastRecord, record);
        if (recordToReplaceLast) {
          records[length - 1] = recordToReplaceLast;
          return;
        }
      } else {
        scheduleCallback(this.observer);
      }

      records[length] = record;
    },

    addListeners: function() {
      this.addListeners_(this.target);
    },

    addListeners_: function(node) {
      var options = this.options;
      if (options.attributes)
        node.addEventListener('DOMAttrModified', this, true);

      if (options.characterData)
        node.addEventListener('DOMCharacterDataModified', this, true);

      if (options.childList)
        node.addEventListener('DOMNodeInserted', this, true);

      if (options.childList || options.subtree)
        node.addEventListener('DOMNodeRemoved', this, true);
    },

    removeListeners: function() {
      this.removeListeners_(this.target);
    },

    removeListeners_: function(node) {
      var options = this.options;
      if (options.attributes)
        node.removeEventListener('DOMAttrModified', this, true);

      if (options.characterData)
        node.removeEventListener('DOMCharacterDataModified', this, true);

      if (options.childList)
        node.removeEventListener('DOMNodeInserted', this, true);

      if (options.childList || options.subtree)
        node.removeEventListener('DOMNodeRemoved', this, true);
    },

    /**
     * Adds a transient observer on node. The transient observer gets removed
     * next time we deliver the change records.
     * @param {Node} node
     */
    addTransientObserver: function(node) {
      // Don't add transient observers on the target itself. We already have all
      // the required listeners set up on the target.
      if (node === this.target)
        return;

      this.addListeners_(node);
      this.transientObservedNodes.push(node);
      var registrations = registrationsTable.get(node);
      if (!registrations)
        registrationsTable.set(node, registrations = []);

      // We know that registrations does not contain this because we already
      // checked if node === this.target.
      registrations.push(this);
    },

    removeTransientObservers: function() {
      var transientObservedNodes = this.transientObservedNodes;
      this.transientObservedNodes = [];

      transientObservedNodes.forEach(function(node) {
        // Transient observers are never added to the target.
        this.removeListeners_(node);

        var registrations = registrationsTable.get(node);
        for (var i = 0; i < registrations.length; i++) {
          if (registrations[i] === this) {
            registrations.splice(i, 1);
            // Each node can only have one registered observer associated with
            // this observer.
            break;
          }
        }
      }, this);
    },

    handleEvent: function(e) {
      // Stop propagation since we are managing the propagation manually.
      // This means that other mutation events on the page will not work
      // correctly but that is by design.
      e.stopImmediatePropagation();

      switch (e.type) {
        case 'DOMAttrModified':
          // http://dom.spec.whatwg.org/#concept-mo-queue-attributes

          var name = e.attrName;
          var namespace = e.relatedNode.namespaceURI;
          var target = e.target;

          // 1.
          var record = new getRecord('attributes', target);
          record.attributeName = name;
          record.attributeNamespace = namespace;

          // 2.
          var oldValue =
              e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;

          forEachAncestorAndObserverEnqueueRecord(target, function(options) {
            // 3.1, 4.2
            if (!options.attributes)
              return;

            // 3.2, 4.3
            if (options.attributeFilter && options.attributeFilter.length &&
                options.attributeFilter.indexOf(name) === -1 &&
                options.attributeFilter.indexOf(namespace) === -1) {
              return;
            }
            // 3.3, 4.4
            if (options.attributeOldValue)
              return getRecordWithOldValue(oldValue);

            // 3.4, 4.5
            return record;
          });

          break;

        case 'DOMCharacterDataModified':
          // http://dom.spec.whatwg.org/#concept-mo-queue-characterdata
          var target = e.target;

          // 1.
          var record = getRecord('characterData', target);

          // 2.
          var oldValue = e.prevValue;


          forEachAncestorAndObserverEnqueueRecord(target, function(options) {
            // 3.1, 4.2
            if (!options.characterData)
              return;

            // 3.2, 4.3
            if (options.characterDataOldValue)
              return getRecordWithOldValue(oldValue);

            // 3.3, 4.4
            return record;
          });

          break;

        case 'DOMNodeRemoved':
          this.addTransientObserver(e.target);
          // Fall through.
        case 'DOMNodeInserted':
          // http://dom.spec.whatwg.org/#concept-mo-queue-childlist
          var target = e.relatedNode;
          var changedNode = e.target;
          var addedNodes, removedNodes;
          if (e.type === 'DOMNodeInserted') {
            addedNodes = [changedNode];
            removedNodes = [];
          } else {

            addedNodes = [];
            removedNodes = [changedNode];
          }
          var previousSibling = changedNode.previousSibling;
          var nextSibling = changedNode.nextSibling;

          // 1.
          var record = getRecord('childList', target);
          record.addedNodes = addedNodes;
          record.removedNodes = removedNodes;
          record.previousSibling = previousSibling;
          record.nextSibling = nextSibling;

          forEachAncestorAndObserverEnqueueRecord(target, function(options) {
            // 2.1, 3.2
            if (!options.childList)
              return;

            // 2.2, 3.3
            return record;
          });

      }

      clearRecords();
    }
  };

  global.JsMutationObserver = JsMutationObserver;

  if (!global.MutationObserver)
    global.MutationObserver = JsMutationObserver;


})(this);
;
/**
 * @license
 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */
"undefined"==typeof WeakMap&&!function(){var a=Object.defineProperty,b=Date.now()%1e9,c=function(){this.name="__st"+(1e9*Math.random()>>>0)+(b++ +"__")};c.prototype={set:function(b,c){var d=b[this.name];return d&&d[0]===b?d[1]=c:a(b,this.name,{value:[b,c],writable:!0}),this},get:function(a){var b;return(b=a[this.name])&&b[0]===a?b[1]:void 0},"delete":function(a){var b=a[this.name];if(!b)return!1;var c=b[0]===a;return b[0]=b[1]=void 0,c},has:function(a){var b=a[this.name];return b?b[0]===a:!1}},window.WeakMap=c}(),function(a){function b(a){u.push(a),t||(t=!0,q(d))}function c(a){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(a)||a}function d(){t=!1;var a=u;u=[],a.sort(function(a,b){return a.uid_-b.uid_});var b=!1;a.forEach(function(a){var c=a.takeRecords();e(a),c.length&&(a.callback_(c,a),b=!0)}),b&&d()}function e(a){a.nodes_.forEach(function(b){var c=p.get(b);c&&c.forEach(function(b){b.observer===a&&b.removeTransientObservers()})})}function f(a,b){for(var c=a;c;c=c.parentNode){var d=p.get(c);if(d)for(var e=0;e<d.length;e++){var f=d[e],g=f.options;if(c===a||g.subtree){var h=b(g);h&&f.enqueue(h)}}}}function g(a){this.callback_=a,this.nodes_=[],this.records_=[],this.uid_=++v}function h(a,b){this.type=a,this.target=b,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function i(a){var b=new h(a.type,a.target);return b.addedNodes=a.addedNodes.slice(),b.removedNodes=a.removedNodes.slice(),b.previousSibling=a.previousSibling,b.nextSibling=a.nextSibling,b.attributeName=a.attributeName,b.attributeNamespace=a.attributeNamespace,b.oldValue=a.oldValue,b}function j(a,b){return w=new h(a,b)}function k(a){return x?x:(x=i(w),x.oldValue=a,x)}function l(){w=x=void 0}function m(a){return a===x||a===w}function n(a,b){return a===b?a:x&&m(a)?x:null}function o(a,b,c){this.observer=a,this.target=b,this.options=c,this.transientObservedNodes=[]}var p=new WeakMap,q=window.msSetImmediate;if(!q){var r=[],s=String(Math.random());window.addEventListener("message",function(a){if(a.data===s){var b=r;r=[],b.forEach(function(a){a()})}}),q=function(a){r.push(a),window.postMessage(s,"*")}}var t=!1,u=[],v=0;g.prototype={observe:function(a,b){if(a=c(a),!b.childList&&!b.attributes&&!b.characterData||b.attributeOldValue&&!b.attributes||b.attributeFilter&&b.attributeFilter.length&&!b.attributes||b.characterDataOldValue&&!b.characterData)throw new SyntaxError;var d=p.get(a);d||p.set(a,d=[]);for(var e,f=0;f<d.length;f++)if(d[f].observer===this){e=d[f],e.removeListeners(),e.options=b;break}e||(e=new o(this,a,b),d.push(e),this.nodes_.push(a)),e.addListeners()},disconnect:function(){this.nodes_.forEach(function(a){for(var b=p.get(a),c=0;c<b.length;c++){var d=b[c];if(d.observer===this){d.removeListeners(),b.splice(c,1);break}}},this),this.records_=[]},takeRecords:function(){var a=this.records_;return this.records_=[],a}};var w,x;o.prototype={enqueue:function(a){var c=this.observer.records_,d=c.length;if(c.length>0){var e=c[d-1],f=n(e,a);if(f)return void(c[d-1]=f)}else b(this.observer);c[d]=a},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(a){var b=this.options;b.attributes&&a.addEventListener("DOMAttrModified",this,!0),b.characterData&&a.addEventListener("DOMCharacterDataModified",this,!0),b.childList&&a.addEventListener("DOMNodeInserted",this,!0),(b.childList||b.subtree)&&a.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(a){var b=this.options;b.attributes&&a.removeEventListener("DOMAttrModified",this,!0),b.characterData&&a.removeEventListener("DOMCharacterDataModified",this,!0),b.childList&&a.removeEventListener("DOMNodeInserted",this,!0),(b.childList||b.subtree)&&a.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(a){if(a!==this.target){this.addListeners_(a),this.transientObservedNodes.push(a);var b=p.get(a);b||p.set(a,b=[]),b.push(this)}},removeTransientObservers:function(){var a=this.transientObservedNodes;this.transientObservedNodes=[],a.forEach(function(a){this.removeListeners_(a);for(var b=p.get(a),c=0;c<b.length;c++)if(b[c]===this){b.splice(c,1);break}},this)},handleEvent:function(a){switch(a.stopImmediatePropagation(),a.type){case"DOMAttrModified":var b=a.attrName,c=a.relatedNode.namespaceURI,d=a.target,e=new j("attributes",d);e.attributeName=b,e.attributeNamespace=c;var g=a.attrChange===MutationEvent.ADDITION?null:a.prevValue;f(d,function(a){return!a.attributes||a.attributeFilter&&a.attributeFilter.length&&-1===a.attributeFilter.indexOf(b)&&-1===a.attributeFilter.indexOf(c)?void 0:a.attributeOldValue?k(g):e});break;case"DOMCharacterDataModified":var d=a.target,e=j("characterData",d),g=a.prevValue;f(d,function(a){return a.characterData?a.characterDataOldValue?k(g):e:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(a.target);case"DOMNodeInserted":var h,i,d=a.relatedNode,m=a.target;"DOMNodeInserted"===a.type?(h=[m],i=[]):(h=[],i=[m]);var n=m.previousSibling,o=m.nextSibling,e=j("childList",d);e.addedNodes=h,e.removedNodes=i,e.previousSibling=n,e.nextSibling=o,f(d,function(a){return a.childList?e:void 0})}l()}},a.JsMutationObserver=g,a.MutationObserver||(a.MutationObserver=g)}(this),window.CustomElements=window.CustomElements||{flags:{}},function(a){var b=a.flags,c=[],d=function(a){c.push(a)},e=function(){c.forEach(function(b){b(a)})};a.addModule=d,a.initializeModules=e,a.hasNative=Boolean(document.registerElement),a.useNative=!b.register&&a.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(CustomElements),CustomElements.addModule(function(a){function b(a,b){c(a,function(a){return b(a)?!0:void d(a,b)}),d(a,b)}function c(a,b,d){var e=a.firstElementChild;if(!e)for(e=a.firstChild;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;for(;e;)b(e,d)!==!0&&c(e,b,d),e=e.nextElementSibling;return null}function d(a,c){for(var d=a.shadowRoot;d;)b(d,c),d=d.olderShadowRoot}function e(a,b){g=[],f(a,b),g=null}function f(a,b){if(a=wrap(a),!(g.indexOf(a)>=0)){g.push(a);for(var c,d=a.querySelectorAll("link[rel="+h+"]"),e=0,i=d.length;i>e&&(c=d[e]);e++)c["import"]&&f(c["import"],b);b(a)}}var g,h=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";a.forDocumentTree=e,a.forSubtree=b}),CustomElements.addModule(function(a){function b(a){return c(a)||d(a)}function c(b){return a.upgrade(b)?!0:void h(b)}function d(a){u(a,function(a){return c(a)?!0:void 0})}function e(a){h(a),m(a)&&u(a,function(a){h(a)})}function f(a){if(y.push(a),!x){x=!0;var b=window.Platform&&window.Platform.endOfMicrotask||setTimeout;b(g)}}function g(){x=!1;for(var a,b=y,c=0,d=b.length;d>c&&(a=b[c]);c++)a();y=[]}function h(a){w?f(function(){i(a)}):i(a)}function i(a){a.__upgraded__&&(a.attachedCallback||a.detachedCallback)&&!a.__attached&&m(a)&&(a.__attached=!0,a.attachedCallback&&a.attachedCallback())}function j(a){k(a),u(a,function(a){k(a)})}function k(a){w?f(function(){l(a)}):l(a)}function l(a){a.__upgraded__&&(a.attachedCallback||a.detachedCallback)&&a.__attached&&!m(a)&&(a.__attached=!1,a.detachedCallback&&a.detachedCallback())}function m(a){for(var b=a,c=wrap(document);b;){if(b==c)return!0;b=b.parentNode||b.host}}function n(a){if(a.shadowRoot&&!a.shadowRoot.__watched){t.dom&&console.log("watching shadow-root for: ",a.localName);for(var b=a.shadowRoot;b;)q(b),b=b.olderShadowRoot}}function o(a){if(t.dom){var c=a[0];if(c&&"childList"===c.type&&c.addedNodes&&c.addedNodes){for(var d=c.addedNodes[0];d&&d!==document&&!d.host;)d=d.parentNode;var e=d&&(d.URL||d._URL||d.host&&d.host.localName)||"";e=e.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",a.length,e||"")}a.forEach(function(a){"childList"===a.type&&(z(a.addedNodes,function(a){a.localName&&b(a)}),z(a.removedNodes,function(a){a.localName&&j(a)}))}),t.dom&&console.groupEnd()}function p(a){for(a=wrap(a),a||(a=wrap(document));a.parentNode;)a=a.parentNode;var b=a.__observer;b&&(o(b.takeRecords()),g())}function q(a){if(!a.__observer){var b=new MutationObserver(o);b.observe(a,{childList:!0,subtree:!0}),a.__observer=b}}function r(a){a=wrap(a),t.dom&&console.group("upgradeDocument: ",a.baseURI.split("/").pop()),b(a),q(a),t.dom&&console.groupEnd()}function s(a){v(a,r)}var t=a.flags,u=a.forSubtree,v=a.forDocumentTree,w=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;a.hasPolyfillMutations=w;var x=!1,y=[],z=Array.prototype.forEach.call.bind(Array.prototype.forEach),A=Element.prototype.createShadowRoot;Element.prototype.createShadowRoot=function(){var a=A.call(this);return CustomElements.watchShadow(this),a},a.watchShadow=n,a.upgradeDocumentTree=s,a.upgradeSubtree=d,a.upgradeAll=b,a.attachedNode=e,a.takeRecords=p}),CustomElements.addModule(function(a){function b(b){if(!b.__upgraded__&&b.nodeType===Node.ELEMENT_NODE){var d=b.getAttribute("is"),e=a.getRegisteredDefinition(d||b.localName);if(e){if(d&&e.tag==b.localName)return c(b,e);if(!d&&!e["extends"])return c(b,e)}}}function c(b,c){return g.upgrade&&console.group("upgrade:",b.localName),c.is&&b.setAttribute("is",c.is),d(b,c),b.__upgraded__=!0,f(b),a.attachedNode(b),a.upgradeSubtree(b),g.upgrade&&console.groupEnd(),b}function d(a,b){Object.__proto__?a.__proto__=b.prototype:(e(a,b.prototype,b["native"]),a.__proto__=b.prototype)}function e(a,b,c){for(var d={},e=b;e!==c&&e!==HTMLElement.prototype;){for(var f,g=Object.getOwnPropertyNames(e),h=0;f=g[h];h++)d[f]||(Object.defineProperty(a,f,Object.getOwnPropertyDescriptor(e,f)),d[f]=1);e=Object.getPrototypeOf(e)}}function f(a){a.createdCallback&&a.createdCallback()}var g=a.flags;a.upgrade=b,a.upgradeWithDefinition=c,a.implementPrototype=d}),CustomElements.addModule(function(a){function b(b,d){var i=d||{};if(!b)throw new Error("document.registerElement: first argument `name` must not be empty");if(b.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(b)+"'.");if(e(b))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(b)+"'. The type name is invalid.");if(j(b))throw new Error("DuplicateDefinitionError: a type with name '"+String(b)+"' is already registered");if(!i.prototype)throw new Error("Options missing required prototype property");return i.__name=b.toLowerCase(),i.lifecycle=i.lifecycle||{},i.ancestry=f(i["extends"]),g(i),h(i),c(i.prototype),k(i.__name,i),i.ctor=l(i),i.ctor.prototype=i.prototype,i.prototype.constructor=i.ctor,a.ready&&q(document),i.ctor}function c(a){if(!a.setAttribute._polyfilled){var b=a.setAttribute;a.setAttribute=function(a,c){d.call(this,a,c,b)};var c=a.removeAttribute;a.removeAttribute=function(a){d.call(this,a,null,c)},a.setAttribute._polyfilled=!0}}function d(a,b,c){a=a.toLowerCase();var d=this.getAttribute(a);c.apply(this,arguments);var e=this.getAttribute(a);this.attributeChangedCallback&&e!==d&&this.attributeChangedCallback(a,d,e)}function e(a){for(var b=0;b<v.length;b++)if(a===v[b])return!0}function f(a){var b=j(a);return b?f(b["extends"]).concat([b]):[]}function g(a){for(var b,c=a["extends"],d=0;b=a.ancestry[d];d++)c=b.is&&b.tag;a.tag=c||a.__name,c&&(a.is=a.__name)}function h(a){if(!Object.__proto__){var b=HTMLElement.prototype;if(a.is){var c=document.createElement(a.tag),d=Object.getPrototypeOf(c);d===a.prototype&&(b=d)}for(var e,f=a.prototype;f&&f!==b;)e=Object.getPrototypeOf(f),f.__proto__=e,f=e;a["native"]=b}}function i(a){return s(y(a.tag),a)}function j(a){return a?w[a.toLowerCase()]:void 0}function k(a,b){w[a]=b}function l(a){return function(){return i(a)}}function m(a,b,c){return a===x?n(b,c):z(a,b)}function n(a,b){var c=j(b||a);if(c){if(a==c.tag&&b==c.is)return new c.ctor;if(!b&&!c.is)return new c.ctor}var d;return b?(d=n(a),d.setAttribute("is",b),d):(d=y(a),a.indexOf("-")>=0&&t(d,HTMLElement),d)}function o(a){var b=A.call(this,a);return r(b),b}var p,q=a.upgradeDocumentTree,r=a.upgrade,s=a.upgradeWithDefinition,t=a.implementPrototype,u=a.useNative,v=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],w={},x="http://www.w3.org/1999/xhtml",y=document.createElement.bind(document),z=document.createElementNS.bind(document),A=Node.prototype.cloneNode;p=Object.__proto__||u?function(a,b){return a instanceof b}:function(a,b){for(var c=a;c;){if(c===b.prototype)return!0;c=c.__proto__}return!1},document.registerElement=b,document.createElement=n,document.createElementNS=m,Node.prototype.cloneNode=o,a.registry=w,a["instanceof"]=p,a.reservedTagList=v,a.getRegisteredDefinition=j,document.register=document.registerElement}),function(a){function b(){f(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(a){f(wrap(a["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var c=a.useNative,d=a.initializeModules;if(c){var e=function(){};a.watchShadow=e,a.upgradeAll=e,a.upgradeDocumentTree=e,a.takeRecords=e,a["instanceof"]=function(a,b){return a instanceof b}}else d();var f=a.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(a){return a}),"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(a,b){b=b||{};var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,Boolean(b.bubbles),Boolean(b.cancelable),b.detail),c},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||a.flags.eager)b();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var g=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(g,b)}else b()}(window.CustomElements);;
