/* Minification failed. Returning unminified contents.
(5056,9-10): run-time error JS1010: Expected identifier: .
(5056,9-10): run-time error JS1195: Expected expression: .
 */
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.6.0
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
/* global window, document, define, jQuery, setInterval, clearInterval */
(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function() {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                asNavFor: null,
                prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',
                nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',
                autoplay: false,
                autoplaySpeed: 3000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function(slider, i) {
                    return $('<button type="button" data-role="none" role="button" tabindex="0" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: true,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function() {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof(index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function(index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function() {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function(targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function(now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function() {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function() {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function() {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if ( asNavFor && asNavFor !== null ) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function(index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
            asNavFor.each(function() {
                var target = $(this).slick('getSlick');
                if(!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function(slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function() {

        var _ = this;

        _.autoPlayClear();

        if ( _.slideCount > _.options.slidesToShow ) {
            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
        }

    };

    Slick.prototype.autoPlayClear = function() {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function() {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if ( !_.paused && !_.interrupted && !_.focussed ) {

            if ( _.options.infinite === false ) {

                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
                    _.direction = 0;
                }

                else if ( _.direction === 0 ) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if ( _.currentSlide - 1 === 0 ) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler( slideTo );

        }

    };

    Slick.prototype.buildArrows = function() {

        var _ = this;

        if (_.options.arrows === true ) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if( _.slideCount > _.options.slidesToShow ) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add( _.$nextArrow )

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function() {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false');

        }

    };

    Slick.prototype.buildOut = function() {

        var _ = this;

        _.$slides =
            _.$slider
                .children( _.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function(index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div aria-live="polite" class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function() {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if(_.options.rows > 1) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for(a = 0; a < numOfSlides; a++){
                var slide = document.createElement('div');
                for(b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for(c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width':(100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function(initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if ( _.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if( !initial && triggerBreakpoint !== false ) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function(event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if(!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function(index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function() {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function() {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function() {

        var _ = this, originalSlides;

        if(_.options.rows > 1) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function(event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function(refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }


        if ( _.$prevArrow && _.$prevArrow.length ) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.prevArrow )) {
                _.$prevArrow.remove();
            }
        }

        if ( _.$nextArrow && _.$nextArrow.length ) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.nextArrow )) {
                _.$nextArrow.remove();
            }

        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function(){
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if(!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function(slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function(slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function() {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function(slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function() {

        var _ = this;

        _.$slider
            .off('focus.slick blur.slick')
            .on('focus.slick blur.slick',
                '*:not(.slick-arrow)', function(event) {

            event.stopImmediatePropagation();
            var $sf = $(this);

            setTimeout(function() {

                if( _.options.pauseOnFocus ) {
                    _.focussed = $sf.is(':focus');
                    _.autoPlay();
                }

            }, 0);

        });
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function() {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if(!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        }else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function(slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                verticalOffset = (verticalHeight * _.options.slidesToShow) * -1;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft =  0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft =  0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function() {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function() {

        return this;

    };

    Slick.prototype.getSlideCount = function() {

        var _ = this,
            slidesTraversed, swipedSlide, centerOffset;

        centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;

        if (_.options.swipeToSlide === true) {
            _.$slideTrack.find('.slick-slide').each(function(index, slide) {
                if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function(creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if ( _.options.autoplay ) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function() {
        var _ = this;
        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        _.$slideTrack.attr('role', 'listbox');

        _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
            $(this).attr({
                'role': 'option',
                'aria-describedby': 'slick-slide' + _.instanceUid + i + ''
            });
        });

        if (_.$dots !== null) {
            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
                $(this).attr({
                    'role': 'presentation',
                    'aria-selected': 'false',
                    'aria-controls': 'navigation' + _.instanceUid + i + '',
                    'id': 'slick-slide' + _.instanceUid + i + ''
                });
            })
                .first().attr('aria-selected', 'true').end()
                .find('button').attr('role', 'button').end()
                .closest('div').attr('role', 'toolbar');
        }
        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'previous'
               }, _.changeSlide);
            _.$nextArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'next'
               }, _.changeSlide);
        }

    };

    Slick.prototype.initDotEvents = function() {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);
        }

        if ( _.options.dots === true && _.options.pauseOnDotsHover === true ) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function() {

        var _ = this;

        if ( _.options.pauseOnHover ) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function() {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.initUI = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function(event) {

        var _ = this;
         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' :  'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function() {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function() {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function() {

                    image
                        .animate({ opacity: 0 }, 100, function() {
                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function() {
                                    image
                                        .removeAttr('data-lazy')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function() {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function() {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function() {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function() {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function() {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function(index) {

        var _ = this;

        if( !_.unslicked ) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            _.setPosition();

            _.swipeLeft = null;

            if ( _.options.autoplay ) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function(event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function( tryCount ) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
            image,
            imageSource,
            imageToLoad;

        if ( $imgsToLoad.length ) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function() {

                image
                    .attr( 'src', imageSource )
                    .removeAttr('data-lazy')
                    .removeClass('slick-loading');

                if ( _.options.adaptiveHeight === true ) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function() {

                if ( tryCount < 3 ) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout( function() {
                        _.progressiveLazyLoad( tryCount + 1 );
                    }, 500 );

                } else {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [ _ ]);

        }

    };

    Slick.prototype.refresh = function( initializing ) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if ( _.slideCount <= _.options.slidesToShow ) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if( !initializing ) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function() {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {

            _.respondTo = _.options.respondTo || 'window';

            for ( breakpoint in responsiveSettings ) {

                l = _.breakpoints.length-1;
                currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while( l >= 0 ) {
                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
                            _.breakpoints.splice(l,1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function(a, b) {
                return ( _.options.mobileFirst ) ? a-b : b-a;
            });

        }

    };

    Slick.prototype.reinit = function() {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function() {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function() {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if( !_.unslicked ) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function(position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function() {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function() {

        var _ = this,
            targetLeft;

        _.$slides.each(function(index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function() {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
    Slick.prototype.slickSetOption = function() {

        /**
         * accepts arguments in format of:
         *
         *  - for changing a single option's value:
         *     .slick("setOption", option, value, refresh )
         *
         *  - for changing a set of responsive options:
         *     .slick("setOption", 'responsive', [{}, ...], refresh )
         *
         *  - for updating multiple values at once (not responsive)
         *     .slick("setOption", { 'option': value, ... }, refresh )
         */

        var _ = this, l, item, option, value, refresh = false, type;

        if( $.type( arguments[0] ) === 'object' ) {

            option =  arguments[0];
            refresh = arguments[1];
            type = 'multiple';

        } else if ( $.type( arguments[0] ) === 'string' ) {

            option =  arguments[0];
            value = arguments[1];
            refresh = arguments[2];

            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {

                type = 'responsive';

            } else if ( typeof arguments[1] !== 'undefined' ) {

                type = 'single';

            }

        }

        if ( type === 'single' ) {

            _.options[option] = value;


        } else if ( type === 'multiple' ) {

            $.each( option , function( opt, val ) {

                _.options[opt] = val;

            });


        } else if ( type === 'responsive' ) {

            for ( item in value ) {

                if( $.type( _.options.responsive ) !== 'array' ) {

                    _.options.responsive = [ value[item] ];

                } else {

                    l = _.options.responsive.length-1;

                    // loop through the responsive object and splice out duplicates.
                    while( l >= 0 ) {

                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {

                            _.options.responsive.splice(l,1);

                        }

                        l--;

                    }

                    _.options.responsive.push( value[item] );

                }

            }

        }

        if ( refresh ) {

            _.unload();
            _.reinit();

        }

    };

    Slick.prototype.setPosition = function() {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function() {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if ( _.options.fade ) {
            if ( typeof _.options.zIndex === 'number' ) {
                if( _.options.zIndex < 3 ) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    Slick.prototype.setSlideClasses = function(index) {

        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (_.options.centerMode === true) {

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {

                    _.$slides
                        .slice(index - centerOffset, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq(allSlides.length - 1 - _.options.slidesToShow)
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand') {
            _.lazyLoad();
        }

    };

    Slick.prototype.setupInfinite = function() {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                        infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function( toggle ) {

        var _ = this;

        if( !toggle ) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function(event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.setSlideClasses(index);
            _.asNavFor(index);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            return;
        }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if ( _.options.autoplay ) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;

        _.setSlideClasses(_.currentSlide);

        if ( _.options.asNavFor ) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function() {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true) {
            _.animateSlide(targetLeft, function() {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function() {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function(event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.interrupted = false;
        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;

        if ( _.touchObject.curX === undefined ) {
            return false;
        }

        if ( _.touchObject.edgeHit === true ) {
            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
        }

        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {

            direction = _.swipeDirection();

            switch ( direction ) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if( direction != 'vertical' ) {

                _.slideHandler( slideCount );
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction ]);

            }

        } else {

            if ( _.touchObject.startX !== _.touchObject.curX ) {

                _.slideHandler( _.currentSlide );
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function(event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function(event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = Math.round(Math.sqrt(
                Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
        }

        swipeDirection = _.swipeDirection();

        if (swipeDirection === 'vertical') {
            return;
        }

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function(event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function() {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function(fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function() {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if ( _.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite ) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function() {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                .removeClass('slick-active')
                .attr('aria-hidden', 'true');

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active')
                .attr('aria-hidden', 'false');

        }

    };

    Slick.prototype.visibility = function() {

        var _ = this;

        if ( _.options.autoplay ) {

            if ( document[_.hidden] ) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function() {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));
;
/*
 * jNice
 * version: 1.0 (11.26.08)
 * by Sean Mooney (sean@whitespace-creative.com) 
 * Examples at: http://www.whitespace-creative.com/jquery/jnice/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * To Use: place in the head 
 *  <link href="inc/style/jNice.css" rel="stylesheet" type="text/css" />
 *  <script type="text/javascript" src="inc/js/jquery.jNice.js"></script>
 *
 * And apply the jNice class to the form you want to style
 *
 * To Do: Add textareas, Add File upload
 *
 ******************************************** */
  var selectIndex = 0;
(function($){
	$.fn.jNice = function(options)
	{
		var self = this;
		var safari = false; //$.browser.safari; /* We need to check for safari to fix the input:text problem */
		/* Apply document listener */
		//$(document).mousedown(checkExternalClick);
		/* each form */
		return this.each(function(){
			$('input:submit, input:reset, input:button', this).each(ButtonAdd);
			$('button').focus(function(){ $(this).addClass('jNiceFocus')}).blur(function(){ $(this).removeClass('jNiceFocus')});
			//$('input:text:visible, input:password', this).each(TextAdd);
			/* If this is safari we need to add an extra class */
			//if (safari){$('.jNiceInputWrapper').each(function(){$(this).addClass('jNiceSafari').find('input').css('width', $(this).width()+11);});}
			$('input:checkbox', this).each(CheckAdd);
			$('input:radio', this).each(RadioAdd);
			if(!(navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1))
				$('select', this).each(function(index){ SelectAdd(this, index); });
			else
				$('select').css('visibility', 'visible');
				
			/* Add a new handler for the reset action */
			$(this).bind('reset',function(){var action = function(){ Reset(this); }; window.setTimeout(action, 10); });
			$('.jNiceHidden').css({opacity:0});
		});		
	};/* End the Plugin */

	var Reset = function(form){
		var sel;
		$('.jNiceSelectWrapper select', form).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
		$('a.jNiceCheckbox, a.jNiceRadio', form).removeClass('jNiceChecked');
		$('input:checkbox, input:radio', form).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jNiceChecked');}});
	};

	var RadioAdd = function(){
		if($(this).parent().hasClass("jRadioWrapper")) return;
		var $input = $(this).addClass('jNiceHidden').wrap('<span class="jRadioWrapper jNiceWrapper"></span>');
		var $wrapper = $input.parent();
		var $a = $('<span class="jNiceRadio"></span>');
		$wrapper.prepend($a);
		//if($.browser.safari)  $('p.text_radio').css("margin-left", "5px");
		
		/* Click Handler */
		$a.click(function(){
			var $input = $(this).addClass('jNiceChecked').siblings('input').prop('checked',true);
			/* uncheck all others of same name */
			$('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
				$(this).prop('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
			});
			// return false;
		});
		$input.click(function()
		{
			if(this.checked)
			{
				var $input = $(this).siblings('.jNiceRadio').addClass('jNiceChecked').end();
				/* uncheck all others of same name */
				$('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
					$(this).prop('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
				});
			}
		}).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });

		/* set the default state */
		if (this.checked){ $a.addClass('jNiceChecked'); }
	};

	var CheckAdd = function(){
		if($(this).parent().hasClass("jNiceWrapper")) return;
		var $input = $(this).addClass('jNiceHidden').wrap('<span class="jNiceWrapper"></span>');
		var $wrapper = $input.parent().append('<span class="jNiceCheckbox"></span>');
		/* Click Handler */
		var $a = $wrapper.find('.jNiceCheckbox').click(function(){
				var $a = $(this);
				var input = $a.siblings('input')[0];
				if (input.checked===true){
					input.checked = false;
					$a.removeClass('jNiceChecked');
				}
				else {
					input.checked = true;
					$a.addClass('jNiceChecked');
				}
				// return false;
		});
		$input.click(function(){
			if(this.checked){ $a.addClass('jNiceChecked'); 	}
			else { $a.removeClass('jNiceChecked'); }
		}).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });
		
		/* set the default state */
		if (this.checked){$('.jNiceCheckbox', $wrapper).addClass('jNiceChecked');}
	};

	var TextAdd = function()
	{
		var $input = $(this).addClass('jNiceInput').wrap('<div class="jNiceInputWrapper"><div class="jNiceInputInner"></div></div>');
		var $wrapper = $input.parents('.jNiceInputWrapper');
		$input.focus(function(){ 
			$wrapper.addClass('jNiceInputWrapper_hover');
		}).blur(function(){
			$wrapper.removeClass('jNiceInputWrapper_hover');
		});
	};

	var ButtonAdd = function(){
		var value = $(this).attr('value');
		$(this).replaceWith('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +'" value="'+ value +'"><span><span>'+ value +'</span></span>');
	};

	/* Hide all open selects */
	var SelectHide = function()
	{
		if(navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1) return;
		$('.jNiceSelectWrapper ul:visible').hide();
	};

	/* Check for an external click */
	var checkExternalClick = function(event) {
		if ($(event.target).parents('.jNiceSelectWrapper').length === 0) { SelectHide(); }
	};

	var SelectAdd = function(element, index)
	{
		if(navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1) return;

		var $select = $(element);

		index = index || $select.css('zIndex')*1;
		index = (index) ? index : 0;
		/* First thing we do is Wrap it */
		$select.wrap($('<div class="jNiceWrapper"></div>').css({zIndex: 100-selectIndex}));
		selectIndex = selectIndex + 1;
		
		var width = $select.width();
		if(width == 0) width = parseInt($select.css('width'), 10);
		if($select.parents(".fascia_registrazione_content_row_select").length > 0)
			width = $select.parents(".fascia_registrazione_content_row_select").width();
		if($select.parents(".login_alert_column_row_select").length > 0)
			width = $select.parents(".login_alert_column_row_select").width();
			
		$select.addClass('jNiceHidden').after('<div class="jNiceSelectWrapper"><div><span class="jNiceSelectText"></span><span class="jNiceSelectOpen"></span></div><ul></ul></div>');
		var $wrapper = $(element).siblings('.jNiceSelectWrapper').css({width: width +'px'});
		
		var openWidth = $('.jNiceSelectOpen', $wrapper).width();
		if(openWidth == 0)
			openWidth = parseInt($('.jNiceSelectOpen', $wrapper).css('width'), 10);
		
		/*if(!jQuery.browser.opera) 
		{
			$('.jNiceSelectText', $wrapper).width( width - openWidth);
			var border = 0;
			if($select.attr('border') != null && $select.attr('border') != "undefined")
				border = parseInt($select.attr('border'), 10);
			$('.jNiceSelectWrapper ul', $wrapper).width( width - border );
		}*/
		/* IF IE 6 */
		/*if ($.browser.msie && jQuery.browser.version < 7) {
			$select.after($('<iframe src="javascript:\'\';" style="visibility:hidden" marginwidth="0" marginheight="0" align="bottom" scrolling="no" tabIndex="-1" frameborder="0"></iframe>').css({ height: $select.height()+ 6 +'px' }).css({width: $select.width() + 5 + 'px' }));
		}
		
		if ($.browser.msie && jQuery.browser.version < 7) { $select.hide(); }*/
	
		
		/* Now we add the options */
		SelectUpdate(element);
		/* Apply the click handler to the Open */
		$('div', $wrapper).click(function()
		{
			if($(this).parent().hasClass("selected"))
				$(this).parent().removeClass("selected");
			else
				$(this).parent().addClass("selected");
			
			var $ul = $(this).siblings('ul');
			if ($ul.css('display')=='none'){ SelectHide(); } /* Check if box is already open to still allow toggle, but close all other selects */
			$ul.toggle();
			var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
			$ul.animate({scrollTop: offSet});
			return false;
		});
		/* Add the key listener */
		$select.keydown(function(e){
			var selectedIndex = this.selectedIndex;
			switch(e.keyCode){
				case 40: /* Down */
					if (selectedIndex < this.options.length - 1){ selectedIndex+=1; }
					break;
				case 38: /* Up */
					if (selectedIndex > 0){ selectedIndex-=1; }
					break;
				default:
					return;
					break;
			}
			$('ul a', $wrapper).removeClass('selected').eq(selectedIndex).addClass('selected');
			$('span:eq(0)', $wrapper).html($('option:eq('+ selectedIndex +')', $select).attr('selected', 'selected').text());
			return false;
		}).focus(function(){ $wrapper.addClass('jNiceFocus'); }).blur(function(){ $wrapper.removeClass('jNiceFocus'); });
	};

	var SelectUpdate = function(element)
	{
		if(navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1) return;
		var $select = $(element);
		var $wrapper = $select.siblings('.jNiceSelectWrapper');
		var $ul = $wrapper.find('ul').find('li').remove().end().hide();
		$('option', $select).each(function(i)
		{
			if(jQuery(this).attr('escludi') == null || jQuery(this).attr('escludi') == "undefined")
				$ul.append('<li><a href="#" index="'+ i +'">'+ this.text +'</a></li>');
			else
				$ul.append('<li style="display:none"><a href="#" index="'+ i +'">'+ this.text +'</a></li>');
		});
		/* Add click handler to the a */
		$ul.find('a').bind("click", function()
		{
			$('a.selected', $wrapper).removeClass('selected');
			$(this).addClass('selected');	
			/* Fire the onchange event */
			if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) 
			{ 
				$select[0].selectedIndex = $(this).attr('index'); 
				$select[0].onchange(); 
			}
			$select[0].selectedIndex = $(this).attr('index');
			$('span:eq(0)', $wrapper).html($(this).html());
			$ul.hide();
			return false;
		});
		/* Set the defalut */
		$('a:eq('+ $select[0].selectedIndex +')', $ul).click();
	};

	var SelectRemove = function(element)
	{
		if(navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1) return;
		var zIndex = $(element).siblings('.jNiceSelectWrapper').css('zIndex');
		$(element).css({zIndex: zIndex}).removeClass('jNiceHidden');
		$(element).siblings('.jNiceSelectWrapper').remove();
	};

	/* Utilities */
	$.jNice = {
			SelectAdd : function(element, index){ 	SelectAdd(element, index); },
			SelectRemove : function(element){ SelectRemove(element); },
			SelectUpdate : function(element){ SelectUpdate(element); }
	};/* End Utilities */

	/* Automatically apply to any forms with class jNice */
	$(function()
	{ 
	});
})(jQuery);;
(function(e,t,n,r){function o(t,n){this.$element=e(t);this.settings=e.extend({},s,n);this.init()}var i="floatlabel",s={slideInput:true,labelStartTop:"0px",labelEndTop:"0px",paddingOffset:"12px",transitionDuration:.1,transitionEasing:"ease-in-out",labelClass:"",typeMatches:/text|password|email|number|search|url|tel/};o.prototype={init:function(){var e=this,n=this.settings,r=n.transitionDuration,i=n.transitionEasing,s=this.$element;var o={"-webkit-transition":"all "+r+"s "+i,"-moz-transition":"all "+r+"s "+i,"-o-transition":"all "+r+"s "+i,"-ms-transition":"all "+r+"s "+i,transition:"all "+r+"s "+i};if(s.prop("tagName").toUpperCase()!=="INPUT"){return}if(!n.typeMatches.test(s.attr("type"))){return}var u=s.attr("id");if(!u){u=Math.floor(Math.random()*100)+1;s.attr("id",u)}var a=s.attr("placeholder");var f=s.data("label");var l=s.data("class");if(!l){l=""}if(!a||a===""){a="You forgot to add placeholder attribute!"}if(!f||f===""){f=a}this.inputPaddingTop=parseFloat(s.css("padding-top"))+parseFloat(n.paddingOffset);s.wrap('<div class="floatlabel-wrapper" style="position:relative"></div>');s.before('<label for="'+u+'" class="label-floatlabel '+n.labelClass+" "+l+'">'+f+"</label>");this.$label=s.prev("label");this.$label.css({position:"absolute",top:n.labelStartTop,left:"8px",display:"none","-moz-opacity":"0","-khtml-opacity":"0","-webkit-opacity":"0",opacity:"0","font-size":"11px","font-weight":"bold",color:"#838780"});if(!n.slideInput){s.css({"padding-top":this.inputPaddingTop})}s.on("keyup blur change",function(t){e.checkValue(t)});s.on("blur",function(){s.prev("label").css({color:"#838780"})});s.on("focus",function(){s.prev("label").css({color:"#2996cc"})});t.setTimeout(function(){e.$label.css(o);e.$element.css(o)},100);this.checkValue()},checkValue:function(e){if(e){var t=e.keyCode||e.which;if(t===9){return}}var n=this.$element,r=n.data("flout");if(n.val()!==""){n.data("flout","1")}if(n.val()===""){n.data("flout","0")}if(n.data("flout")==="1"&&r!=="1"){this.showLabel()}if(n.data("flout")==="0"&&r!=="0"){this.hideLabel()}},showLabel:function(){var e=this;e.$label.css({display:"block"});t.setTimeout(function(){e.$label.css({top:e.settings.labelEndTop,"-moz-opacity":"1","-khtml-opacity":"1","-webkit-opacity":"1",opacity:"1"});if(e.settings.slideInput){e.$element.css({"padding-top":e.inputPaddingTop})}e.$element.addClass("active-floatlabel")},50)},hideLabel:function(){var e=this;e.$label.css({top:e.settings.labelStartTop,"-moz-opacity":"0","-khtml-opacity":"0","-webkit-opacity":"0",opacity:"0"});if(e.settings.slideInput){e.$element.css({"padding-top":parseFloat(e.inputPaddingTop)-parseFloat(this.settings.paddingOffset)})}e.$element.removeClass("active-floatlabel");t.setTimeout(function(){e.$label.css({display:"none"})},e.settings.transitionDuration*1e3)}};e.fn[i]=function(t){return this.each(function(){if(!e.data(this,"plugin_"+i)){e.data(this,"plugin_"+i,new o(this,t))}})}})(jQuery,window,document)
;
var Global = (function () {

	function salvaImmobileClickHandler(savedClass, nonSavedClass) {
		
		return function (ev) {

			if (!ev) return false;
			ev.stopPropagation();
			ev.preventDefault();
			var target = ev.target;
			salvaImmobile(target);
		}
	}


	function salvaImmobile(target) {
		var parent = $(target).parent();
		if ($(target).parent()[0] && $(target).parent()[0].className.indexOf("save-to-immobile-salvato-lista") >= 0)
			target = $(target).parent()[0];

		var idImmobile = $(target).attr('data-val');
		if (idImmobile == null || idImmobile < 1) {
			idImmobile = $(target).attr('data-id');
		}
		if (idImmobile == null || idImmobile < 1) {
			$.notify(NonSalvato + ":" + idImmobile, 'error');
		}

		var payload = {
			ID: idImmobile,
			Tipo: 1
		};


		if ($(target).html().indexOf(Salvato) > -1) {
			$.ajax({
				type: 'DELETE',
				url: '/api/dashboard/immobiliSalvati',
				contentType: 'application/json',
				data: JSON.stringify(payload)
			})
				.done(function (r) {
					//  $(target).attr('class', nonSavedClass);
				   // $(target).html("<i class='fa fa-heart-o'></i><span class='hidden-xs'>" + Salva + "</span>");
					$(target).html("<i class='fa fa-heart-o'></i><span class=''>" + Salva + "</span>");
					//  $.notify("L\'immobile è stato rimosso con successo", 'info');
					// showCallToAction("Immobile");

				})
				.fail(function (err) {
					$.notify(NonSalvato, 'error');
				});
		}
		else {
			$.ajax({
				type: 'POST',
				url: '/api/dashboard/immobiliSalvati',
				contentType: 'application/json',
				data: JSON.stringify(payload),
			})
				.done(function (r) {
					//  $(target).attr('class', savedClass);
					//test fuzzy  $.notify(ImmobileSalvato, 'info');
					//$(target).html("<i class='fa fa-heart'></i><span class='hidden-xs'>" + Salvato +"</span>");
					$(target).html("<i class='fa fa-heart'></i><span class=''>" + Salvato + "</span>");
					showCallToAction("Immobile");

						fbq('track', 'AddToCart', { 'content_ids': '[' + idImmobile + ']' });        
				})
				.fail(function (err) {
					$.notify(NonSalvato, 'error');
				});
		}
}
	
	function redirectToPageMantainState(page) {
		var returnUrl = getQueryVariable('ReturnUrl');

		if (window.location.href.indexOf('ReturnUrl') >= 0) {
			if (window.location.href.indexOf('fromRicerca') >= 0) {
				if (window.location.href.indexOf('dontSave') >= 0) {
					window.location.href = '/' + page + '?fromRicerca&dontSave&ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?", "#"));
				}
				else {
					window.location.href = '/' + page + '?fromRicerca&ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?", "#"));
				}
			}
			else {
				window.location.href = '/' + page + '?ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?", "#"));
			}
		}
		else {
			window.location.href = "/" + page;
		}
	}

   


	//mostra calto action solo ogni 5 volte
	function showCallToAction(tipo) {
		//mostro solo se non sei già registrato
		if (user_state == 'register')
			return;
		var numTime = Cookies.get('callToActionRegistratiShowed');
		var show = true;
		//if (!numTime) {
		//    show = true;
		//    numTime = 0;
		//}
		//else {
		//    if ((numTime % 5) == 0)
		//        show = true;
		//    numTime++;
		//}

		$("#emailCall").val(user_info.email);
		//Cookies.set('callToActionRegistratiShowed', numTime)

		if (show) {
			if (tipo == "Immobile") {
				$("#callToActionRegistrati .modal-title").html("Immobile salvato con successo :)");
			}
			else {
				$("#callToActionRegistrati .modal-title").html("Ricerca salvata con successo :)");
			}
			$('#tienimiInformato2').modal('hide');
			setTimeout(function () { $("#callToActionRegistrati").modal("show") },300);
			
		}


	};
	return {
		salvaImmobileClickHandler: salvaImmobileClickHandler,
		redirectToPageMantainState: redirectToPageMantainState,
		showCallToAction: showCallToAction,
		salvaImmobile: salvaImmobile
	};
}());
function getUrlParameter(name) {
	name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
	var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
	var results = regex.exec(location.search);
	return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

function setUrlParameter(param, value) {
	var url = window.location.href;
	var hash = location.hash;
	url = url.replace(hash, '');
	if (url.indexOf(param + "=") >= 0) {
		var prefix = url.substring(0, url.indexOf(param));
		var suffix = url.substring(url.indexOf(param));
		suffix = suffix.substring(suffix.indexOf("=") + 1);
		suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
		url = prefix + param + "=" + value + suffix;
	}
	else {
		if (url.indexOf("?") < 0)
			url += "?" + param + "=" + value;
		else
			url += "&" + param + "=" + value;
	}
	window.history.pushState(null, null, url + hash);
}
;
var utenteRegistrato = false;
var emailRegistrazione = null;
var emailLogin = null;
function toggleMenuButton() {
	var width = $(window).width();
	var height = $(window).height();
	//menu classic, menu sidemenu, menu basic
	$('#sidemenu').addClass('sidemenu open');
	$('#menu-responsive-sidemenu').toggleClass('open');
	if ($('#sidemenu').hasClass("slideInRight")) {
		$('#sidemenu').removeClass('animated slideInRight');
		$('#sidemenu').addClass('animated slideOutRight');
		setTimeout(function () {
			$('#sidemenu').toggleClass('sidemenu open');
			$('#sidemenu').removeClass('animated slideOutRight');
		}, 1000);
	} else {
		$('#sidemenu').addClass('animated slideInRight');
	}
	if (width < 991) {
		$('body').toggleClass('no-scroll');
		$('.overlay-mobile').toggleClass('active');
	}
}
$(function () {

	var width = $(window).width();
	var height = $(window).height();

	var is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

	utenteRegistrato = Cookies.get("utenteRegistrato") ? Cookies.get("utenteRegistrato") == true : false;
	emailRegistrazione = Cookies.get("emailRegistrazione") ? Cookies.get("emailRegistrazione") : null;
	emailLogin = Cookies.get("emailLogin") ? Cookies.get("emailLogin") : null;

	//$('[data-toggle="tooltip"]').tooltip();

	switch (user_state) {
		case 'none':
			$('.logged').addClass('hidden'); $('.loggedAnonymouse').addClass('hidden'); $('.anonymouse').removeClass('hidden');

			if (!is_mobile) {
				$('.register-btn1').tooltip('show');
				setTimeout(function () {
					$('.register-btn1').tooltip('hide');
				}, 10000);
			}
			else {
				$('.register-btn1b').tooltip('show');
				setTimeout(function () {
					$('.register-btn1b').tooltip('hide');
				}, 10000);
			}
			break;
		case 'anonymous':
			$('.logged').addClass('hidden'); $('.loggedAnonymouse').removeClass('hidden');
			$('#header-tooltip-trigger i').removeClass("grey");
			$('#header-tooltip-trigger i').addClass("color");
			$('.register-btn').tooltip('show');
			setTimeout(function () {
				$('.register-btn').tooltip('hide');
			}, 5000);
			break;
		case 'register':
			$('.anonymouse').addClass('hidden'); $('.logged').removeClass('hidden');
			$('#header-tooltip-trigger i').removeClass("grey");
			$('#header-tooltip-trigger i').addClass("color");

			if (getParameterByName("gaSocial")) {

				$('#register-form-modal .form-success  div.static').html($('#register-form-modal .form-success div.static').html().replace("{0}",
					(user_info.nome + " " + user_info.cognome)));

				$('#register-success-was_social-wrapper').show();
				$('#register-success-must-confirm-email').hide();

				$('#register-success-was_something_else-wrapper').hide();
				$('#register-success-was_dettaglio_immobile-wrapper').hide();
				$('#register-success-was_search-wrapper').hide();

				$("#register-form-modal").modal("show");

			}

			break;



		default:
	}

	if (is_mobile && Cookies.get('dash_mobile_training') == null && (user_state == "anonymous" || user_state == 'register')) {

		Cookies.set('dash_mobile_training', true);
		//setTimeout(function () {
		//    toggleMenuButton();
		//    setTimeout(function () {
		//        $(".mobile-show").click();
		//        setTimeout(function () { toggleMenuButton();}, 1500);
		//    }, 2000);
		//}, 1000);

	}

	if (getParameterByName("gaSocial")) {
		ga('send', 'event', 'Compro', 'Registrati', 'Social');
		if (location.href.indexOf("?gaSocial") > -1)
			history.pushState('', document.title, window.location.pathname);
		else
			history.pushState('', document.title, location.href.replace("&gaSocial=" + getParameterByName("gaSocial"), ""));
	}

	if (getParameterByName("callToActionRegister")) {
		Global.showCallToAction(getParameterByName("callToActionRegister"));
		if (location.href.indexOf("?callToActionRegister") > -1)
			history.pushState('', document.title, window.location.pathname);
		else
			history.pushState('', document.title, location.href.replace("&callToActionRegister=" + getParameterByName("callToActionRegister"), ""));
	}
	/*-------------------------------------------------*/
	/* =  Header
	/*-------------------------------------------------*/

	$('.menu-button').on("click", function (e) {
		if (e) e.preventDefault();
		toggleMenuButton();
	});

	$('.overlay-mobile').on("click", function (e) {

		if (e) e.preventDefault();
		toggleMenuButton();
		return false;
	});

	$(document).on("click", function (e) {
		var container = $("#sidemenu");
		var containerButton = $("#menu-responsive-sidemenu");
		if (container.hasClass("slideInRight")) {
			if (!container.is(e.target)
				&& container.has(e.target).length === 0 && !containerButton.is(e.target) && containerButton.has(e.target).length === 0) {
				container.removeClass('animated slideInRight');
				container.addClass('animated slideOutRight');
				containerButton.removeClass('open');
				setTimeout(function () {
					container.toggleClass('sidemenu open');
					container.removeClass('animated slideOutRight');
				}, 1000);

				if (width < 991) {
					$('body').toggleClass('no-scroll');
				}
			}
		}
	});
	if (width < 991) {
		$(".secondary-menu ul#nav > li").on("click", function () {
			//$('body').addClass('no-scroll');
			//$(".secondary-menu li.submenu").removeClass('open');
			$('body').addClass('no-scroll');
			$(".secondary-menu ul#nav > li").removeAttr('class');
			$(this).addClass("open");
		});
		$(".secondary-menu .close-btn").on("click", function (e) {
			$(this).parent().parent().removeClass('open');
			$('body').removeAttr('class');
			e.stopPropagation();
			//$(this).parent().addClass('sub-menu');
		});
	}
	if (width < 991) {
		$(".menu-holder ul > li.submenu").on("click", function (e) {
			$(".menu-holder > ul").children('li').toggleClass('hidden');
			$(this).toggleClass('active');

			var submenu = $(this).find('.sub-menu');

			if (submenu.hasClass('active')) {
				submenu.toggleClass("active");
			} else {
				setTimeout(function () {
					submenu.toggleClass("active");
				}, 200);
			}
		});
	}

	/*-------------------------------------------------*/
	/* =  Home
	/*-------------------------------------------------*/

	$('#open-city-category').on("click", function () {
		$('.city-hidden').toggleClass('visible');
	});


	//if (width > 767)
	{

		$('.showcase-nav .first-box.arrow-left').on("click", function () {
			$('.first-box').slick('slickPrev');
		});
		$('.showcase-nav .first-box.arrow-right').on("click", function () {
			$('.first-box').slick('slickNext');
		});
		$('.showcase-nav .second-box.arrow-left').on("click", function () {
			$('.second-box').slick('slickPrev');
		});
		$('.showcase-nav .second-box.arrow-right').on("click", function () {
			$('.second-box').slick('slickNext');
		});
		$('.showcase-nav .third-box.arrow-left').on("click", function () {
			$('.third-box').slick('slickPrev');
		});
		$('.showcase-nav .third-box.arrow-right').on("click", function () {
			$('.third-box').slick('slickNext');
		});

	}

	/*else {
		$('.showcase-nav-mobile .first-box.arrow-left').on("click", function () {
			$('.first-box').slick('slickPrev');
		});
		$('.showcase-nav-mobile .first-box.arrow-right').on("click", function () {
			$('.first-box').slick('slickNext');
		});
		$('.showcase-nav-mobile .second-box.arrow-left').on("click", function () {
			$('.second-box').slick('slickPrev');
		});
		$('.showcase-nav-mobile .second-box.arrow-right').on("click", function () {
			$('.second-box').slick('slickNext');
		});
		$('.showcase-nav-mobile .third-box.arrow-left').on("click", function () {
			$('.third-box').slick('slickPrev');
		});
		$('.showcase-nav-mobile .third-box.arrow-right').on("click", function () {
			$('.third-box').slick('slickNext');
		});
	}
	if (width < 481) {
		$('.showcase-tabs img').remove();
	}*/


	$('.showcase-tab ul li').on("click", function () {

		var attr = $(this).attr('idshowcasetab'),
			attClass = '.' + attr,
			number = attr.split("-"),
			index = number[0],
			linkClass = '.' + index + '.' + 'main-link',
			linkNav = '.' + index;

		console.log(attClass);

		$(".showcase.home .main-link").hide();
		$(".showcase.home").find(linkClass).show();

		$(".showcase.home .showcase-nav-mobile .slick-slider").removeClass('active');
		$(".showcase.home .showcase-nav-mobile").find(attClass).addClass('active');

		$(".showcase-nav a").removeClass('active');
		$(".showcase-tab ul li").removeClass('active');
		$(this).addClass('active');
		$(".showcase-tabs").find('.active').removeClass('active');
		$(".showcase-nav").find(attClass).addClass('active');

		var attId = '#' + attr;
		$(attId).addClass("active");

		//update lazy
		$(window).trigger("updateLazy");

	});

	$('#select-home-place-list').on('change', function () {
		$('#tab-place .tab-content-inside-place .tab-inside').removeClass('open');
		$('#tab-place .tab-content-inside-place .' + $(this).val()).addClass('open');
	});
	$('#select-home-place-map').on('change', function () {
		$('#tab-place .tab-content-inside-map .tab-inside').removeClass('open');
		$('#tab-place .tab-content-inside-map .' + $(this).val()).addClass('open');
	});

	//tab lista/mappa ricerca per luogo
	$('#tab-place #filters-place li a.list').on('click touchstart', function () {
		$('#tab-place #filters-place li a').removeClass('active');
		$('#tab-place .tab-content-inside-place').addClass('open');
		$('#tab-place .tab-content-inside-map').removeClass('open');
		$(this).addClass('active');
	});
	$('#tab-place #filters-place li a.map').on('click touchstart', function () {
		$('#tab-place #filters-place li a').removeClass('active');
		$('#tab-place .tab-content-inside-map').addClass('open');
		$('#tab-place .tab-content-inside-place').removeClass('open');
		$(this).addClass('active');
	});

	//select residenziale/commerciale ricerca per agenzia
	$('#select-home-agency-list').on('change', function () {
		$('#tab-agency .tab-content-inside-place .tab-inside').removeClass('open');
		$('#tab-agency .tab-content-inside-place .' + $(this).val()).addClass('open');
	});
	$('#select-home-agency-map').on('change', function () {
		$('#tab-agency .tab-content-inside-map .tab-inside').removeClass('open');
		$('#tab-agency .tab-content-inside-map .' + $(this).val()).addClass('open');
	});

	//tab lista/mappa ricerca per agenzia
	$('#tab-agency #filters-place li a.list').on('click touchstart', function () {
		$('#tab-agency #filters-place li a').removeClass('active');
		$('#tab-agency .tab-content-inside-place').addClass('open');
		$('#tab-agency .tab-content-inside-map').removeClass('open');
		$(this).addClass('active');
	});
	$('#tab-agency #filters-place li a.map').on('click touchstart', function () {
		$('#tab-agency #filters-place li a').removeClass('active');
		$('#tab-agency .tab-content-inside-map').addClass('open');
		$('#tab-agency .tab-content-inside-place').removeClass('open');
		$(this).addClass('active');
	});

	$('#home-sell-btn').on("click", function () {
		$('#content-slider .home-search').removeClass('open');
		$('#content-slider .form-sell').addClass('open');
	});
	$('#content-slider .form-sell .closed a').on("click", function () {
		$('#content-slider .home-search').addClass('open');
		$('#content-slider .form-sell').removeClass('open');
	});
	$('#menu-responsive-sidemenu a.user').on("click", function () {
		$('#menu-responsive-sidemenu .user-mobile-info').toggleClass('visible');
	});

	/*-------------------------------------------------*/
	/* =  TTabs Home
	/*-------------------------------------------------*/
	$('.ttabs').on("click", " .ttab", function () {
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		var tabID = $(this).attr('data-ttab');

		var tabSelected = $(this).closest('.ttabs-wrap').find("[data-ttab='" + tabID + "']");
		tabSelected.siblings().removeClass('active');
		tabSelected.addClass('active');

	});

	/*-------------------------------------------------*/
	/* =  Search Home
	/*-------------------------------------------------*/
	$('.search-ttabs').on("click", " .search-ttab", function () {
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		var tabID = $(this).attr('data-search-ttab');

		var tabSelected = $(this).closest('.search-ttabs-wrap').find("[data-search-ttab='" + tabID + "']");
		tabSelected.siblings().removeClass('active');
		tabSelected.addClass('active');

	});

	/*-------------------------------------------------*/
	/* =  Footer
	/*-------------------------------------------------*/
	$('footer a#mobile-footer').on("click", function () {
		$('footer').toggleClass('closed');
		$('footer').toggleClass('open');
	});
	$(window).on('scroll', function () {

		var scroll = $(window).scrollTop();
		var backTop = $('#back-to-top');

		if (scroll >= 800) {
			backTop.addClass("visible");
			$("#header-tooltip-trigger").tooltip("hide");
		} else {
			backTop.removeClass("visible");
		}



	});
	$('#header-tooltip-trigger').on("click", function (ev) {
		ev.stopPropagation();
		if ($("#header-tooltip-content").is(":hidden")) $("#header-tooltip-content").show();
		$("#header-tooltip-trigger").tooltip("toggle");
	});

	$('#header-tooltip-trigger1').on("click", function (ev) {
		ev.stopPropagation();
		if (user_state == "register")
			ga('send', 'event', 'Compro', 'Accesso', 'Registrato');
		else
			ga('send', 'event', 'Compro', 'Accesso', 'NonRegistrato');

		ev.preventDefault();
		redirectToAuthPage('account/immobiliSalvati');
	});
	$(document).on('change', '#header-tooltip-show-auto', function () {
		if ($(this).is(':checked')) {
			$("#header-tooltip-trigger").tooltip("hide");
			Cookies.set('dash_tool_tip_close', true);
		}
		else {
			Cookies.remove('dash_tool_tip_close');
			sessionStorage.removeItem('session_dash_tool_tip_close');
		}
	});

	$(document).on('click touchstart', '.dashboard-button', function (e) {
		//  $('.dashboard-button').on("click touchstart", function (e) {

		var redirectPage = 'account/immobiliSalvati';
		var QS = "";

		if (user_state == "register") {
			ga('send', 'event', 'Compro', 'Accesso', 'Registrato');
		}

		else {
			ga('send', 'event', 'Compro', 'Accesso', 'NonRegistrato');

			if (location.search.indexOf("openCA") == -1) {
				QS = "openCA=1";
			}
			
		}

		e.preventDefault();

		redirectToAuthPage(redirectPage, QS);
	});

	$(document).on('click touchstart', '.register-btn,.register-btn1,.register-btn1b ', function (e) {
		// $('.register-btn').on("click touchstart", function (e) {    
		e.preventDefault();
		redirectToAuthPage('register');
	});

	$(document).on('click touchstart', '.login-btn', function (e) {
		// $('.register-btn').on("click touchstart", function (e) {    
		e.preventDefault();
		redirectToAuthPage('login');
	});
	$(document).on('click touchstart', '.logout-btn', function (e) {
		//$('.logout-btn').on("click touchstart", function () {
		$.ajax({
			type: 'POST',
			url: '/api/account/logout',
		})
			.always(function (response) {
				document.location.href = '/';
			});
	});

	/*-------------------------------------------------*/
	/* =  Mobile
	/*-------------------------------------------------*/
	if (is_mobile) {
		//$('.banner.home.app').hide();
		$('.info-section.home').addClass('mobile');
		$('.city-list.home').addClass('light-background');
		if ($("#home-slider")[0]) {
			$('footer .pre-footer').addClass('light-background');
		};
		var divapp = $("<div class='container'><div class='row'><div class='col-xs-1 padding-left-null'><img src='/img/icon_vuoi_vendere_btn.png' alt='App Toscano'></div><div class='col-xs-7 padding-leftright-null'><h6>Scarica l'app <br><span class='android'>Android</span><span class='ios'>iOS</span></h6></div></div><a id='btn-divapp' data-ios='https://itunes.apple.com/it/app/gruppo-toscano/id595595604' data-android='https://play.google.com/store/apps/details?id=air.it.gruppotoscano' href='void' class='btn-alt xs'>Installa</a><a class='close-banner-app'><i class='icon ion-android-close'></i></a></div>");

		var is_Android = /Android/i.test(navigator.userAgent);
		var is_iOS = /webOS|iPhone|iPad|iPod/i.test(navigator.userAgent);

		$(".app-mobile").append(divapp);


		if (is_Android) {
			var url = $('#btn-divapp').attr('data-android');
			$('#btn-divapp').attr('href', url);
			$('.app-mobile span.android').addClass('visible');
		}
		if (is_iOS) {
			//            if ($("#home-slider")[0]) {
			//                $(".app-mobile").addClass('hidden');
			//            }
			var url = $('#btn-divapp').attr('data-ios');
			$('#btn-divapp').attr('href', url);
			$('.app-mobile span.ios').addClass('visible');
		}
		//$(".app-mobile").show();
		$(".close-banner-app").on('click touchstart', function () {
			$(".app-mobile").hide();
		});

		if (width < 768) {
			if ($(".cta-mobile")[0]) {
				$("#main-wrap").addClass('cta');
			}
		}
		$(window).resize(function () {
			var widthresize = $(window).width();
			if (widthresize < 768) {
				if ($(".cta-mobile")[0]) {
					$("#main-wrap").addClass('cta');
				}
			}
		});
	};

	$('input.floatlabel').floatlabel({
		transitionDuration: 0.4
	});


	if ($("#page-content.color-prefooter ")[0]) {
		$('.pre-footer').addClass('light-background');
	}
	/*-------------------------------------------------*/
	/* =  Text Responsive
	/*-------------------------------------------------*/
	var ctaWrap = $('.cta-responsive[data-responsive-text]');
	var selectorText = 'data-responsive-text';

	if (width <= 480 || is_mobile) {
		ctaWrap.each(function (index) {
			var dataText = $(this).attr(selectorText);

			if (typeof dataText !== typeof undefined && dataText !== false) {

				$(this).text(dataText);
			}
		});
	}
});

var llinstance;
$(document).ready(function () {

	var width = $(window).width();
	var height = $(window).height();
	var is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
	if (width < 768) {
		$(".second-content").remove();
		$(".first-box ul li:nth-of-type(n+3)").hide();
		$(".second-box ul li:nth-of-type(n+3)").hide();
		$(".third-box ul li:nth-of-type(n+3)").hide();
	}
	//if (width >= 650)
	{
		$('.first-box').slick({
			arrows: false,
			lazyLoad: 'ondemand',
			infinite: false

		})
		$('.second-box').slick({
			arrows: false,
			lazyLoad: 'ondemand',
			infinite: false
		});
		$('.third-box').slick({
			arrows: false,
			lazyLoad: 'ondemand',
			infinite: false
		});
	}
	$(window).resize(function () {
		var width = $(window).width();

		if (width < 768) {
			$(".second-content").remove();
			$(".first-box ul li:nth-of-type(n+3)").hide();
			$(".second-box ul li:nth-of-type(n+3)").hide();
			$(".third-box ul li:nth-of-type(n+3)").hide();
		}
		$('.first-box').on('init', function (event, slick) {

			//if (width >= 650)
			{
				$('.first-box').slick({
					arrows: false,
					lazyLoad: 'ondemand',
					infinite: false
				})
				$('.second-box').slick({
					arrows: false,
					lazyLoad: 'ondemand',
					infinite: false
				});
				$('.third-box').slick({
					arrows: false,
					lazyLoad: 'ondemand',
					infinite: false
				});
			}
		});
	});

	if (width > 768) {
		// $("#header-tooltip-content").show();
		$("#header-tooltip-trigger").tooltip({
			trigger: "manual",
			html: true,
			template: '<div class="tooltip header-tooltip-canvas" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
			title: $("#header-tooltip-content"),
		});

		$("#header-tooltip-content").hide();

		if (user_state != 'none' && Cookies.get('dash_tool_tip_close') == null && !(window.location.href.indexOf("account") > -1) && sessionStorage.getItem('session_dash_tool_tip_close') == null) {
			$("#header-tooltip-content").show();
			$("#header-tooltip-trigger").tooltip("show");
		}
		else {
			$("#header-tooltip-trigger").tooltip("hide");
			$("#header-tooltip-show-auto").prop('checked', true);
		}

		if (window.location.href.indexOf("account") > -1)
			sessionStorage.setItem('session_dash_tool_tip_close', 'true');
	}
	else {
		$("#header-tooltip-content").hide();



	}



	//$("body").bind("click mousedown", function (e) {
	//    console.log(e);
	//});
	$('html').on('click', function (e) {
		$('[role="tooltip"]').each(function () {
			//the 'is' for buttons that trigger popups
			//the 'has' for icons within a button that triggers a popup
			if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.tootltip').has(e.target).length === 0) {
				$(this).tooltip('hide');
			}
		});
	});
	//    if (width < 768 && width >= 650) {
	//        //first-box home
	//        $('.first-box').slick('unslick');


	//        var firstBoxrow1 = $('.first-box .first-content .row ul.items-wrap').contents();
	//        $('.first-box .first-content').replaceWith(firstBoxrow1);
	//        var firstBoxrow2 = $('.first-box .second-content .row ul.items-wrap').contents();
	//        $('.first-box .second-content').replaceWith(firstBoxrow2);

	//        $('.first-box li.single-item').wrap('<div class="single-item"/>').contents().unwrap();

	//        $('.first-box').slick({
	//            arrows: false,
	//            slidesToShow: 2,
	//            lazyLoad: 'ondemand',
	//            prevArrow: '<button type="button" class="slick-prev">Precedente</button>',
	//            nextArrow: '<button type="button" class="slick-next">Successivo</button>',
	//            responsive: [
	//                {
	//                    breakpoint: 480,
	//                    settings: {
	//                        slidesToShow: 1
	//                    }
	//                }
	//            ]
	//        });
	//        //second-box home
	//        $('.second-box').slick('unslick');
	//        /*var secondBoxrow1 = $('.second-box .first-content .first-row').contents();
	//        $('.second-box .first-content .first-row').replaceWith(secondBoxrow1);
	//        var secondBoxrow2 = $('.second-box .first-content .second-row').contents();
	//        $('.second-box .first-content .second-row').replaceWith(secondBoxrow2);
	//        var secondBoxctn1 = $('.second-box .first-content').contents();
	//        $('.second-box .first-content').replaceWith(secondBoxctn1);

	//        var secondBoxrow3 = $('.second-box .second-content .first-row').contents();
	//        $('.second-box .second-content .first-row').replaceWith(secondBoxrow3);
	//        var secondBoxrow4 = $('.second-box .second-content .second-row').contents();
	//        $('.second-box .second-content .second-row').replaceWith(secondBoxrow4);
	//        var secondBoxctn2 = $('.second-box .second-content').contents();
	//        $('.second-box .second-content').replaceWith(secondBoxctn2);*/

	//        var secondBoxrow1 = $('.second-box .first-content .row ul.items-wrap').contents();
	//        $('.second-box .first-content').replaceWith(secondBoxrow1);
	//        var secondBoxrow2 = $('.second-box .second-content .row ul.items-wrap').contents();
	//        $('.second-box .second-content').replaceWith(secondBoxrow2);

	//        $('.second-box li.single-item').wrap('<div class="single-item"/>').contents().unwrap();

	//        $('.second-box').slick({
	//            arrows: false,
	//            slidesToShow: 2,
	//            lazyLoad: 'ondemand',
	//            prevArrow: '<button type="button" class="slick-prev">Precedente</button>',
	//            nextArrow: '<button type="button" class="slick-next">Successivo</button>',
	//            responsive: [
	//                {
	//                    breakpoint: 480,
	//                    settings: {
	//                        slidesToShow: 1
	//                    }
	//                }
	//            ]
	//        });

	//        //third-box home
	//        $('.third-box').slick('unslick');
	//        /*var thirdBoxrow1 = $('.third-box .first-content .first-row').contents();
	//        $('.third-box .first-content .first-row').replaceWith(thirdBoxrow1);
	//        var thirdBoxrow2 = $('.third-box .first-content .second-row').contents();
	//        $('.third-box .first-content .second-row').replaceWith(thirdBoxrow2);
	//        var thirdBoxctn1 = $('.third-box .first-content').contents();
	//        $('.third-box .first-content').replaceWith(thirdBoxctn1);

	//        var thirdBoxrow3 = $('.third-box .second-content .first-row').contents();
	//        $('.third-box .second-content .first-row').replaceWith(thirdBoxrow3);
	//        var thirdBoxrow4 = $('.third-box .second-content .second-row').contents();
	//        $('.third-box .second-content .second-row').replaceWith(thirdBoxrow4);
	//        var thirdBoxctn2 = $('.third-box .second-content').contents();
	//        $('.third-box .second-content').replaceWith(thirdBoxctn2);*/

	//        var thirdBoxrow1 = $('.third-box .first-content .row ul.items-wrap').contents();
	//        $('.third-box .first-content').replaceWith(thirdBoxrow1);
	//        var thirdBoxrow2 = $('.third-box .second-content .row ul.items-wrap').contents();
	//        $('.third-box .second-content').replaceWith(thirdBoxrow2);

	//        $('.third-box li.single-item').wrap('<div class="single-item"/>').contents().unwrap();

	//        $('.third-box').slick({
	//            arrows: false,
	//            slidesToShow: 2,
	//            lazyLoad: 'ondemand',
	//            prevArrow: '<button type="button" class="slick-prev">Precedente</button>',
	//            nextArrow: '<button type="button" class="slick-next">Successivo</button>',
	//            responsive: [
	//                {
	//                    breakpoint: 480,
	//                    settings: {
	//                        slidesToShow: 1
	//                    }
	//                }
	//            ]
	//        });

	////        var singleitemWidth = $('.showcase.home .single-item').width();

	////        $('.showcase.home .single-item').css({
	// //           'height': singleitemWidth / 1.3 + 'px'
	// //       });
	// //       $(window).resize(function () {
	// //           var singleitemWidth = $('.showcase.home .single-item').width();

	// //           $('.showcase.home .single-item').css({
	// //               'height': singleitemWidth / 1.3 + 'px'
	// //           });
	// //       });
	//   };


	$(window).resize(function () {
		var resizeWidth = $(window).width();
		var isresize_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

		if ($("#home-slider")[0]) {
			if (resizeWidth < 768 && isresize_mobile == false) {
				location.reload();
			}
		}

		$("#header-tooltip-trigger").tooltip("hide");
	});



	$('.results').on('click touchstart', '.chiamaeventdom', function (ev) { // per gestire il dom creato post doc.ready per lista sulla sx della mappa
		$(this).unbind("click touchstart");

		var href = $(this).attr('href');
		var dataTel = $(this).attr('data-tel');
		var idImmo = $(this).data('id-immobile');

		var payload = {
			ID: idImmo
		};
		if (is_mobile) {
			if (href.indexOf("tel") == -1) {
				$(this).attr("href", dataTel);
			}
			ga('send', 'event', 'Compro', 'Immobile', 'Telefono');
		}
		else
			if (href.indexOf("tel") == -1) {
				ev.preventDefault();
				$(this).find('.hover').show();
				$(this).find('.desktop').hide();
				$(this).find('i').hide();
				$(this).attr("href", dataTel);
				if (idImmo != undefined) {
					ga('send', 'event', 'Compro', 'Immobile', 'Telefono');
					$.ajax({
						method: 'POST',
						url: '/api/Util/PostPropertyNumberCalled',
						contentType: 'application/json',
						data: JSON.stringify(payload)
					});
				}
			}
	});

	$('.chiamaevent').on('click touchstart', function (ev) {
		//   $(this).unbind("click touchstart");

		var href = $(this).attr('href');
		var dataTel = $(this).attr('data-tel');
		var idImmo = $(this).data('id-immobile');

		var payload = {
			ID: idImmo
		};
		if (is_mobile) {
			if (href.indexOf("tel") == -1) {
				$(this).attr("href", dataTel);
				$(this).click();
			}
			else
				ga('send', 'event', 'Compro', 'Immobile', 'Telefono');
		}
		else
			if (href.indexOf("tel") == -1) {
				ev.preventDefault();
				$(this).find('.hover').show();
				$(this).find('.desktop').hide();
				$(this).find('i').hide();
				$(this).attr("href", dataTel);
				if (idImmo != undefined) {
					ga('send', 'event', 'Compro', 'Immobile', 'Telefono');
					$.ajax({
						method: 'POST',
						url: '/api/Util/PostPropertyNumberCalled',
						contentType: 'application/json',
						data: JSON.stringify(payload)
					});
				}
			}
	});

	$('.results').on('click touchstart', '.segui-btn', function (ev) {
		ev.preventDefault();
		//ev.stopPropagation();

		var id = $(ev.target).data('id');
		var prezzo = $(ev.target).data('prezzo');
		var rif = $(ev.target).data('rif');

		$('#sendTienimiInformato').data('id', id);
		$('#sendTienimiInformato').data('prezzo', prezzo);
		$('#sendTienimiInformato').data('rif', rif);


		if (user_state == 'register') {// se � registrato non faccio il tienimi informato
			$('#tienimiInformato2').modal('hide');
			primoSalvaNew();
		}
		else
			$('#tienimiInformato2').modal('show');

	});

	$('#tienimiInformato2').on('shown.bs.modal', function (e) {
		if (Cookies.get("email_saved") != null)
			$("#email_tienimiInformato").val(Cookies.get("email_saved"));
	});
	$('#callToActionRegistrati').on('shown.bs.modal', function (e) {
		if (Cookies.get("email_saved") != null)
			$("#email-call").val(Cookies.get("email_saved"));
	});


	$('#tienimiInformato2').on('hidden.bs.modal', function (e) {
		e.preventDefault();
		primoSalvaNew();
	});

	$('.salva-btn').on("click touchstart", function (ev) {
		ev.preventDefault();
		//ev.stopPropagation();

		var id = $(ev.target).data('id');
		var prezzo = $(ev.target).data('prezzo');
		var rif = $(ev.target).data('rif');

		$('#sendTienimiInformato').data('id', id);
		$('#sendTienimiInformato').data('prezzo', prezzo);
		$('#sendTienimiInformato').data('rif', rif);
		//  $('#tienimiInformato2').modal('show');

		//primoSalvaNew();
	});




	$('.segui-btn').on("click touchstart", function (ev) {
		ev.preventDefault();
		//ev.stopPropagation();
		var target = $(ev.target);

		if (typeof $(ev.target).data('id') === 'undefined')
			target = $(ev.target).parent();
		var id = target.data('id');
		var prezzo = target.data('prezzo');
		var rif = target.data('rif');

		$('#sendTienimiInformato').data('id', id);
		$('#sendTienimiInformato').data('prezzo', prezzo);
		$('#sendTienimiInformato').data('rif', rif);
		if (user_state == 'register') {// se � registrato non faccio il tienimi informato
			$('#tienimiInformato2').modal('hide');
			primoSalvaNew();
		}
		else
			$('#tienimiInformato2').modal('show');
	});
	/*-------------------------------------------------*/
	/* =  Anchor
	/*-------------------------------------------------*/
	var $root = $('html, body');

	$("a.anchor[href*='#']").on("click", function (event) {
		event.preventDefault();

		var offset = -70;

		$root.animate({
			scrollTop: $($.attr(this, 'href')).offset().top + offset
		}, 500);
	});


	function checkFormTienimiInformato() {
		count_error = 0;
		checkStepEmail('email_tienimiInformato', jQuery("#email_tienimiInformato").attr('value'));
		if (!($('#checkbox_form_2').is(":checked"))) {
			$('#modal-lblPrivacy').parent().addClass('error');
		}

		if (jQuery("#checkbox_form_2:checked").length == 0) {
			//errore privacy
			count_error = count_error + 1;

		}

		if (count_error == 0) {
			$('.basic-form div').removeClass('error');
			return true;
			//submit del form o chiamata ajax	
		} else {
			return false;
		}
	}


	function checkFormPrimoSalva() {
		count_error = 0;
		checkStepEmail('email_primoSalva', jQuery("#email_primoSalva").attr('value'));
		if (!($('#checkbox_form_3').is(":checked"))) {
			$('#modal-lblPrivacy1').parent().addClass('error');
		}

		if (jQuery("#checkbox_form_3:checked").length == 0) {
			//errore privacy
			count_error = count_error + 1;

		}

		if (count_error == 0) {
			$('.basic-form div').removeClass('error');
			return true;
			//submit del form o chiamata ajax	
		} else {
			return false;
		}
	}

	//$("#sendTienimiInformato").on("click touchstart", function (ev) {

	function primoSalvaNew() {

		var id = $('#sendTienimiInformato').data('id');
		if (user_state != 'none') {

			var target = $("a[data-id='" + id + "']")[0];




			if (id == null || id < 1) {
				$.notify(NonSalvato + ":" + idImmobile, 'error');
			}

			var payload = {
				ID: id,
				Tipo: 1
			};

			if ($(target).html().indexOf(Salvato) > -1) {
				$.ajax({
					type: 'DELETE',
					url: '/api/dashboard/immobiliSalvati',
					contentType: 'application/json',
					data: JSON.stringify(payload)
				})
					.done(function (r) {
						//  $(target).attr('class', nonSavedClass);
						$(target).html("<i class='fa fa-heart-o'></i>" + Salva);

						//  $.notify("L\'immobile � stato rimosso con successo", 'info');
						// showCallToAction("Immobile");

					})
					.fail(function (err) {
						$.notify(NonSalvato, 'error');
					});
			}
			else {
				$.ajax({
					type: 'POST',
					url: '/api/dashboard/immobiliSalvati',
					contentType: 'application/json',
					data: JSON.stringify(payload),
				})
					.done(function (r) {
						//  $(target).attr('class', savedClass);
						//test fuzzy  $.notify(ImmobileSalvato, 'info');
						$(target).html("<i class='fa fa-heart'></i>" + Salvato);
						$(target).attr("class", "save-to-immobile-salvato-lista btn-simple xs");
						$(target).off("click touchstart");
						$(target).on("click touchstart",
							Global.salvaImmobileClickHandler(
								'save-to-immobile-salvato-lista btn-simple xs',
								'save-to-immobile-salvato-lista btn-simple xs'));

						Global.showCallToAction("Immobile");
					})
					.fail(function (err) {
						$.notify(NonSalvato, 'error');
					});
			}


			return;
		}

		var prezzo = $('#sendTienimiInformato').data('prezzo');
		var rif = $('#sendTienimiInformato').data('rif');

		var tee = function (msg) { console.log(msg); };
		var dati = {
			Id_Immobile: id,
			Email: $("#email_tienimiInformato").val(),
			Prezzo: prezzo,
			Rif: rif,
			utm_source: Cookies.get('utm_source'),
			utm_medium: Cookies.get('utm_medium'),
			utm_campaign: Cookies.get('utm_campaign'),
			utm_term: Cookies.get('utm_term'),
			utm_content: Cookies.get('utm_content'),
			utenteRegistrato: utenteRegistrato,
			emailRegistrazione: emailRegistrazione,
			emailLogin: emailLogin,

		};
		if (id == null) return false;
		//if (!checkFormTienimiInformato()) return false;

		//  $.notify.defaults({ autoHide: false, clickToHide: true });

		//$.ajax(
		//    {
		//        url: "/api/Home/KeepUpdated",
		//        type: "POST",
		//        contentType: "application/json",
		//        data: JSON.stringify(dati),
		//        success: function (result) {
		//            ga('send', 'event', 'Compro', 'Immobile', 'TienimiInformato');
		//            // Trovit pixel
		//            ta('send', 'lead');

		//            //FB pixel
		//            //fbq('track', 'Lead');
		//            fbq('track', 'AddToCart', { 'content_ids': '[' + dati.Id_Immobile + ']' });

		//            $.notify(InformationSent, "success");
		//            $('#tienimiInformato2').modal('hide');
		//        },
		//        error: function (result) {

		//            $.notify(ErrorMessage, "error");
		//        }
		//    });



		//faccio anche il login anonimo
		var model = {
			//Email: dati.Email         
			Email: "anonymous@toscano.it"
		};

		$.ajax({
			type: 'POST',
			url: '/api/account/RegisterAnonymous',
			contentType: 'application/json',
			dataType: 'json',
			data: JSON.stringify(model),
		})
			.done(function (response) {
				if (!response.HasSucceded) {
					for (var i in response.Messages) {
						$.notify(response.Messages[i], 'info');

					}
				}
				else {
					//  $.notify("Account salvato", "info");

					if (dati.Id_Immobile == null || dati.Id_Immobile < 1) {
						$.notify(NonSalvato + ":" + dati.Id_Immobile, 'error');
						setTimeout(function () { location.href = location.href + (location.href.indexOf("?") == -1 ? "?" : "&") + "callToActionRegister=Immobile" }, 100);
					}
					//salvo anche l'immobile
					var payload = {
						ID: dati.Id_Immobile,
						Tipo: 1
					};
					$.ajax({
						type: 'POST',
						url: '/api/dashboard/immobiliSalvati',
						contentType: 'application/json',
						data: JSON.stringify(payload),
					})
						.done(function (r) {
							//test fuzzy  $.notify("Immobile salvato", "info");

							ga('send', 'event', 'Compro', 'Immobile', 'SalvaImmobile');
							// Trovit pixel
							ta('send', 'lead');

							//FB pixel
							//fbq('track', 'Lead');

							//  $('#tienimiInformato2').modal('hide');

							setTimeout(function () {
								location.href = location.href + (location.href.indexOf("?") == -1 ? "?" : "&") + "callToActionRegister=Immobile";
								location.reload(true);
							}, 100);

							fbq('track', 'InitiateCheckout', { 'content_ids': '[' + dati.Id_Immobile + ']', 'content_type': 'home_listing' })


						})
						.fail(function (err) {
							$.notify("Errore nel salva immobile", 'error');
							setTimeout(function () { location.href = location.href + (location.href.indexOf("?") == -1 ? "?" : "&") + "callToActionRegister=Immobile" }, 100);
						});


				}
			})
			.fail(function (_) { });

		return false;
	}
	//);
	// DF: nel caso si debba lavoroare sul popup di registrazione, lascio la riga commentata "for future purposes" ;)
	//$("#callToActionRegistrati").modal("show");

	$("#sendTienimiInformato").on("click touchstart", function (ev) {



		var id = $(ev.target).data('id');
		var prezzo = $(ev.target).data('prezzo');
		var rif = $(ev.target).data('rif');


		var tee = function (msg) { console.log(msg); };
		var dati = {
			Id_Immobile: id,
			Email: $("#email_tienimiInformato").val(),
			Prezzo: prezzo,
			Rif: rif,
			utm_source: Cookies.get('utm_source'),
			utm_medium: Cookies.get('utm_medium'),
			utm_campaign: Cookies.get('utm_campaign'),
			utm_term: Cookies.get('utm_term'),
			utm_content: Cookies.get('utm_content'),
			utenteRegistrato: utenteRegistrato,
			emailRegistrazione: emailRegistrazione,
			emailLogin: emailLogin,

		};
		if (id == null) return false;
		if (!checkFormTienimiInformato()) return false;

		//$.notify.defaults({ autoHide: false, clickToHide: true });

		$.ajax(
			{
				url: "/api/Home/KeepUpdated",
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(dati),
				success: function (result) {
					ga('send', 'event', 'Compro', 'Immobile', 'TienimiInformato');
					// Trovit pixel
					ta('send', 'lead');

					//FB pixel
					//fbq('track', 'Lead');
					fbq('track', 'InitiateCheckout', { 'content_ids': '[' + dati.Id_Immobile + ']', 'content_type': 'home_listing' })
					Cookies.set('email_saved', $("#email_tienimiInformato").val());
					$.notify(InformationSent, "success");
					$('#tienimiInformato2').modal('hide');
					//primoSalvaNew(); 
				},
				error: function (result) {

					$.notify(ErrorMessage, "error");
				}
			});
		return false;
	});

	$("#sendTienimiInformatoNO").on("click touchstart", function () {
		$('#tienimiInformato2').modal('hide');
		//primoSalvaNew();
	});

	//posso instanziare il lazyload
	llinstance = $('.lazy').Lazy({
		chainable: false,
		scrollDirection: 'vertical',
		effect: 'fadeIn',
		visibleOnly: true,
		beforeLoad: function (element) {
			$(element).addClass("loaded");

		},
		onError: function (element) {
			console.log('error loading ' + element.data('src'));
		}
	});

	$(window).on("updateLazy", function (e) {
		llinstance.update();
	});

});

function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null) {
		return "";
	}
	else {
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}

$(function () {
	$('.save-to-immobile-salvato-lista').on("click touchstart",
		Global.salvaImmobileClickHandler(
			'save-to-immobile-salvato-lista btn-simple xs',
			'save-to-immobile-salvato-lista btn-simple xs'));
});

function constructPropertyDetail(item) {
	var immobiliSalvatiElement = '';

	if (!IsAuthenticated) {
		immobiliSalvatiElement = '<li><a data-toggle="modal"' +
			'data-rif="' + item.Rif + '"' +
			'data-target="#tienimiInformato2"' +
			'data-id="' + item.Id + '"' +
			'data-prezzo="' + item.Prezzo + '"' +
			'href=""' +
			'class="follow-btn btn-simple xs icon-heart segui-btn">' +
			Segui + '</a></li>';
	}
	else if (IsAuthenticated) {
		if (item.Salvato) {
			immobiliSalvatiElement = '<li><a  style="margin:0;padding:0;"  data-val="' + item.Id + '" href="javascript:void(0)" class="save-to-immobile-salvato-lista btn-simple xs"><i class="fa fa-heart"></i>' + Salvato + '</a></li>';
		}
		else if (!item.Salvato) {
			immobiliSalvatiElement = '<li><a style="margin:0;padding:0;"   data-val="' + item.Id + '" href="javascript:void(0)" class="save-to-immobile-salvato-lista btn-simple xs"><i class="fa fa-heart-o"></i>' + Salva + '</a></li>';
		}
	}

	var element =
		"<div class='item' itemid='" + item.Id + "'>" +
		"    <div class='box-info'>" +
		"	<div class='col-xs-4 image padding-leftright-null'>" +
		"	    <div class='realty-map-carousel'>" +
		"           <img src='" + ((item.ImmagineUrl || '').length > 0 ? (immobileBaseUrl + item.ImmagineUrl) : "/img/no_photo.png") + "' />" +
		"	    </div>" +
		"	</div>" +
		"	<div class='col-xs-8 description'>" +
		"	    <a href=\"" + item.Url + "\" ><h2>" + item.Titolo + "</h2></a>" +
		"	    <div class='row'>" +
		"		<div class='col-lg-12 padding-leftright-null address'>" +
		"		    <h4>" + item.Indirizzo + "</h4>" +
		"		</div>" +
		"		<div class='col-lg-12 padding-leftright-null text-right place'>" +
		"		    <h4>" + item.Descrizione + "</h4>" +
		"		</div>" +
		"		<div class='col-lg-12 padding-leftright-null room'>" +
		(!!item.NumeroLocali ? "<h4>" + item.NumeroLocali + " Locali</h4>" : '<h4></h4>') +
		"		</div>" +
		"	    </div>" +
		"	    <div class='col-lg-12 padding-leftright-null  call-to-action'>" +
		"		<ul>" +
		'		    <li><a data-id-immobile="' + item.Id + '" href="javascipt:void(0)" data-tel="tel:' + item.AgenziaTelefono + '" class="btn-simple xs icon-tel chiamaeventdom hover-light" rel="nofollow"><em class="desktop">Chiama</em><em class="hover">' + (item.AgenziaTelefono || 'No Tel') + '</em></a></li>' +
		"		    <li><a href=\"" + item.Url + "#contact-us\" class='btn-simple xs icon-mail'>Email</a></li>" +
		immobiliSalvatiElement +
		"		</ul>" +
		"       <div class='col-lg-12 padding-leftright-null'" +
		"       </div>" +
		"	    </div>" +
		"	</div>" +
		"    </div>" +
		"</div>";

	return element;
}




window.$zopim || (function (d, s) {
	var z = $zopim = function (c) { z._.push(c) }, $ = z.s =
		d.createElement(s), e = d.getElementsByTagName(s)[0]; z.set = function (o) {
			z.set.
				_.push(o)
		}; z._ = []; z.set._ = []; $.async = !0; $.setAttribute("charset", "utf-8");
	$.src = "https://v2.zopim.com/?63CecbegS8tvmFGquyLsbP3DGxNY4S5e"; z.t = +new Date; $.
		type = "text/javascript"; e.parentNode.insertBefore($, e);
	$zopim(function () {
		$zopim.livechat.cookieLaw.comply();
	});
	$zopim(function () {
		$zopim.livechat.hideAll();
	});
})
	(document, "script");


/****************************************************************
 * FORM POPUPS SITE MASTER
 * **************************************************************/
//Contact us modal immobile*/
$(function () {


	$(".sendemail").click(function () {
		var $this = $(this);

		if ($this.data("videocall")) {

			$(".noVideoCallModal").hide();
			$(".videoCallModal").show();

			//testo note
			$("#messaggio_contatto_modal").val($("#messaggio_contatto_modal").attr("data-videoCallMode"));

			//motivo: video call
			$("#motivo_contatto_modal").val(4);

			$("#contact-us-modal-send").attr("data-videocalltype", $this.data("videocalltype"));
			/*
			 Nel form scheda dettaglio: Categoria: Compro - Azione: Immobile - Etichetta: Immobile
			Nei Risultati di Ricerca (per comune o agenzia): Categoria: Compro - Azione: Immobile - Etichetta: RicercaVideo
			Nella Gallery fotografica: Categoria: Compro - Azione: Immobile - Etichetta: GalleryVideo
			*/




		} else {

			$(".noVideoCallModal").show();
			$(".videoCallModal").hide();

			//testo note
			$("#messaggio_contatto_modal").val($("#messaggio_contatto_modal").attr("data-callMode"));

			//motivo: nessuno
			$("#motivo_contatto_modal").val("");

		}

		$("#contact-us-modal-send").attr("data-id", $this.data("immobileid"));
		$("#agenziaFoto").attr("src", $this.attr("data-fotoagenzia"));
		$("#agenziaUrl").attr("href", $this.attr("data-agenziaurl"));
		$("#agenziaUrl2").attr("href", $this.attr("data-agenziaurl"));
		$("#agenziaUrl2 h5").text($this.attr("data-agenzianome"));
		$("#agenziaIndirizzo").text($this.attr("data-agenziaindirizzo"));
		$("#agenziaNome").text($this.attr("data-agenziaragsoc"));
		$("#agenziaChiama").attr("data-id-immobile", $this.attr("data-immobileid"));
		$("#agenziaChiama").attr("data-tel", "tel:" + $this.attr("data-agenziatelefono"));

		if ($this.attr("data-agenziacell")) {
			$("#agenziaWA").removeClass("hidden");
			$("#agenziaWA").attr("data-id-immobile", $this.attr("data-immobileid"));
			$("#agenziaWA").attr("data-indirizzo", $this.attr("data-indirizzo"));
			$("#agenziaWA").attr("data-tel", $this.attr("data-agenziacell"));
		}
		else
			$("#agenziaWA").addClass("hidden");
		$("#agenziaChiama .hover").text($this.attr("data-agenziatelefono"));
		if ($this.attr("data-agenziatipo") == "D") {
			$(".hidden-tipo-1").hide();
		}



	});

	$("#contact-us-modal-send").on("click touchstart", function () {
		contactUsModalSend($(this).attr("data-id") ? true : false, $(this).attr("data-id"), $(this).attr("data-prezzo"), $(this).attr("data-idagenzia"), $(this).attr("data-videocalltype"));
		return false;
	});

	$("#contact-us-modal").on('hidden.bs.modal', function (e) {
		$("#contact-us-modal-send").show();
		$('#agency-form-modal').show();
		$('.contact-form-agency .form-success').hide();
	});

	$(".sendwa").click(function () {
		var indirizzo = $(this).data('indirizzo');
		var tel = $(this).data('tel');
		var idImmo = $(this).data('id-immobile');
		var testo = "";
		if (indirizzo)
			testo = "Vorrei maggiori informazioni per l'immobile in " + indirizzo;
		else
			testo = "Vorrei mettermi in contatto con voi";
		publicWhatsappShow.createWaLinkOnTheFly(tel, testo, true);
		if (RegioneAgenzia)
			ga('send', 'event', 'Compro', 'Immobile', 'chat-whatsapp', {
				'dimension1': RegioneAgenzia,
				'dimension2': DescrizioneTipoAgenzia,
				'dimension3': NomeAgenzia
				, 'dimension7': user_state
			});
		else
			ga('send', 'event', 'Compro', 'Agenzia', 'chat-whatsapp');
	});
});

function contactUsModalSend(isImmobile, idImmobile, prezzo, idAgenzia, videocalltype = null) {
	if (isImmobile) {

		var dati = {
			IdImmobile: idImmobile,
			Nome: $('#nome_contatto_modal').val(),
			Cognome: $('#cognome_contatto_modal').val(),
			Email: $('#email_contatto_modal').val(),
			Telefono: $('#telefono_contatto_modal').val(),
			Messaggio: $('#messaggio_contatto_modal').val(),
			VendereCasa: $('#vendere_casa_modal').is(":checked"),
			utm_source: Cookies.get('utm_source'),
			utm_medium: Cookies.get('utm_medium'),
			utm_campaign: Cookies.get('utm_campaign'),
			utm_term: Cookies.get('utm_term'),
			utm_content: Cookies.get('utm_content'),
			lang: $('meta[property=og\\:locale]').attr("content"),
			Newsletter: $('#privacy_newsletter_modal')[0].checked,
			gaid: gaclientId,
			TipoForm: videocalltype != null ? 1 : null
		};

		var RegioneAgenzia = "";
		var DescrizioneTipoAgenzia = "";
		var NomeAgenzia = "";

		if (!checkFormContattaModal()) {
			$(".obbligatorio > input").on("keydown", function (e) {
				$(this).parent().removeClass("obbligatorio");
			})
			return false;
		}

		$(".contact-form-agency .loader").show();
		$(".modal-footer").hide();

		$.ajax({
			url: "/api/Home/SendContattaAgenziaPerImmobile",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify(dati),
			success: function (result) {
				// Trovit pixel
				ta('send', 'lead');

				//FB pixel
				//fbq('track', 'Lead');
				fbq('track', 'Purchase', { 'value': prezzo, 'currency': 'EUR', 'content_ids': '[' + dati.IdImmobile + ']', 'content_type': 'home_listing' })

				ga('send', 'event', 'Compro', 'Immobile', 'Ricerca', {
					'dimension1': RegioneAgenzia,
					'dimension2': DescrizioneTipoAgenzia,
					'dimension3': NomeAgenzia
					, 'dimension7': user_state
				});
				if (dati.VendereCasa) ga('send', 'event', 'Vendo', 'Immobile', 'Checkbox', {
					'dimension1': RegioneAgenzia,
					'dimension2': DescrizioneTipoAgenzia,
					'dimension3': NomeAgenzia
					, 'dimension7': user_state
				});

				switch (videocalltype) {
					case "Immobile":
						ga('send', 'event', 'Compro', 'Immobile', 'ImmobileVideo', {
							'dimension1': RegioneAgenzia,
							'dimension2': DescrizioneTipoAgenzia,
							'dimension3': NomeAgenzia
							, 'dimension7': user_state
						});
						break;
					case "Ricerca":
						ga('send', 'event', 'Compro', 'Immobile', 'RicercaVideo', {
							'dimension1': RegioneAgenzia,
							'dimension2': DescrizioneTipoAgenzia,
							'dimension3': NomeAgenzia
							, 'dimension7': user_state
						});
						break;
					case "Gallery":
						ga('send', 'event', 'Compro', 'Immobile', 'GalleryVideo', {
							'dimension1': RegioneAgenzia,
							'dimension2': DescrizioneTipoAgenzia,
							'dimension3': NomeAgenzia
							, 'dimension7': user_state
						});
						break;
					default:
				}

				$(".contact-form-agency .loader").hide();
				$('#agency-form-modal').hide();
				$('.contact-form-agency .form-success  div.success').html($('.contact-form-agency .form-success div.static').html().replace("{0}", dati.Cognome));
				$('.contact-form-agency .form-success  div.static').hide();
				$('.contact-form-agency .form-success').show();

				$(".modal-footer").show();
				$("#contact-us-modal-send").hide();
			},
			error: function (result) {
				$(".contact-form-agency .loader").hide();
				$.notify(ErrorMessage, "error");
			}
		});
	}
	else {//  agenzia
		if (!checkFormContattaAgenziaModal()) {
			$(".obbligatorio > input").on("keydown", function (e) {
				$(this).parent().removeClass("obbligatorio");
			})
			return false;
		}
		$(".contact-form-agency .loader").show();
		$(".modal-footer").hide();

		var dati = {
			Nome: $('#nome_contatto_modal').val(),
			Cognome: $('#cognome_contatto_modal').val(),
			Email: $('#email_contatto_modal').val(),
			Telefono: $('#telefono_contatto_modal').val(),
			Messaggio: $('#messaggio_contatto_modal').val(),
			Motivo: $('#motivo_contatto_modal').val(),
			IdAgenzia: idAgenzia,
			utm_source: Cookies.get('utm_source'),
			utm_medium: Cookies.get('utm_medium'),
			utm_campaign: Cookies.get('utm_campaign'),
			utm_term: Cookies.get('utm_term'),
			utm_content: Cookies.get('utm_content'),
			lang: $('meta[property=og\\:locale]').attr("content"),
			Newsletter: $('#privacy_newsletter_modal')[0].checked,
			gaid: gaclientId
		};

		$.ajax(
			{
				url: "/api/Home/SendContattaAgenzia",
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(dati),
				success: function (result) {
					// Trovit pixel
					ta('send', 'lead');

					//FB pixel
					fbq('track', 'Lead');

					if (dati.Motivo == "1") ga('send', 'event', 'Vendo', 'Agenzia', 'Form', {
						'dimension1': RegioneAgenzia,
						'dimension2': DescrizioneTipoAgenzia,
						'dimension3': NomeAgenzia
						, 'dimension7': user_state
					});
					if (dati.Motivo == "2") ga('send', 'event', 'Compro', 'Agenzia', 'Form', {
						'dimension1': RegioneAgenzia,
						'dimension2': DescrizioneTipoAgenzia,
						'dimension3': NomeAgenzia
						, 'dimension7': user_state
					});
					if (dati.Motivo == "3") ga('send', 'event', 'Informazioni', 'Agenzia', 'Form', {
						'dimension1': RegioneAgenzia,
						'dimension2': DescrizioneTipoAgenzia,
						'dimension3': NomeAgenzia
						, 'dimension7': user_state
					});
					$(".contact-form-agency .loader").hide();
					$('#agency-form-modal').hide();
					$('.contact-form-agency .form-success  div.success').html($('.contact-form-agency .form-success div.static').html().replace("{0}", dati.Cognome));
					$('.contact-form-agency .form-success  div.static').hide();
					$('.contact-form-agency .form-success').show();

					$(".modal-footer").show();
					$("#contact-us-modal-send").hide();
				},
				error: function (result) {
					$(".contact-form-agency .loader").hide();
					$.notify(ErrorMessage, "error");
				}
			});
	}
}

$("#cognome_contatto_modal").change(function () {
	console.log($("#cognome_contatto_modal").val())

});
function motivoModalChangeEvent(value) {
	if (value == "1") {
		$(".newsLetterModal").removeClass("hidden");
	}
	else {
		$(".newsLetterModal").addClass("hidden");
	}
}

function checkFormContattaModal() {
	console.log($("#cognome_contatto_modal").val())


	checkStepText('cognome_contatto_modal', jQuery('#cognome_contatto_modal').attr('value'), 0);
	checkStepEmail('email_contatto_modal', jQuery('#email_contatto_modal').attr('value'));
	checkStepPhoneDatiPersonali('telefono_contatto_modal', jQuery("#telefono_contatto_modal").attr('value'), true);
	if (!($('#checkbox_form_modal').is(":checked"))) {
		$("#divprivacy_modal").addClass('error');
	}
	else $("#divprivacy_modal").removeClass('error');

	return ($("#contact-us-modal .error").length == 0)
}

function checkFormContattaAgenziaModal() {


	count_error = 0;
	checkStepText('cognome_contatto_modal', jQuery("#cognome_contatto_modal").attr('value'), 0);
	checkStepEmail('email_contatto_modal', jQuery("#email_contatto_modal").attr('value'), FormatoEmailSbagliato); // 3 arg is a resource
	checkStepPhoneDatiPersonali('telefono_contatto_modal', jQuery("#telefono_contatto_modal").attr('value'), true);

	//if (checkStepText('messaggio_contatto', jQuery("#messaggio_contatto").attr('value'), jQuery("#messaggio_contatto").attr('maxlength')) == "errorObbligatorio")
	//    jQuery("#messaggio_contatto").parent("div").addClass('obbligatorioTextbox');

	if ($('#motivo_contatto_modal').length == 1) {
		if ($('#motivo_contatto_modal').val() == "") {
			$('#motivo_contatto_modal').parent().addClass("obbligatorioSelect")
			$('#motivo_contatto_modal').css("border", "1px solid rgb(255, 0, 0)");
			count_error = count_error + 1;
		}
		else {
			$('#motivo_contatto_modal').css("border", "");
			$('#motivo_contatto_modal').parent().removeClass("obbligatorioSelect")
		}
	}
	if (!($('#checkbox_form_modal').is(":checked"))) {
		$("#divprivacy_modal").addClass('error');
	}
	else $("#divprivacy_modal").removeClass('error');

	return ($("#contact-us-modal .error").length == 0);
}


;
/*!
 * JavaScript Cookie v2.1.0
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		var _OldCookies = window.Cookies;
		var api = window.Cookies = factory();
		api.noConflict = function () {
			window.Cookies = _OldCookies;
			return api;
		};
	}
}(function () {
	function extend() {
		var i = 0;
		var result = {};
		for (; i < arguments.length; i++) {
			var attributes = arguments[i];
			for (var key in attributes) {
				result[key] = attributes[key];
			}
		}
		return result;
	}

	function init(converter) {
		function api(key, value, attributes) {
			var result;

			// Write

			if (arguments.length > 1) {
				attributes = extend({
					path: '/'
				}, api.defaults, attributes);

				if (typeof attributes.expires === 'number') {
					var expires = new Date();
					expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
					attributes.expires = expires;
				}

				try {
					result = JSON.stringify(value);
					if (/^[\{\[]/.test(result)) {
						value = result;
					}
				} catch (e) { }

				if (!converter.write) {
					value = encodeURIComponent(String(value))
						.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
				} else {
					value = converter.write(value, key);
				}

				key = encodeURIComponent(String(key));
				key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
				key = key.replace(/[\(\)]/g, escape);

				return (document.cookie = [
					key, '=', value,
					attributes.expires && '; expires=' + attributes.expires.toUTCString(), // use expires attribute, max-age is not supported by IE
					attributes.path && '; path=' + attributes.path,
					attributes.domain && '; domain=' + attributes.domain,
					attributes.secure ? '; secure' : ''
				].join(''));
			}

			// Read

			if (!key) {
				result = {};
			}

			// To prevent the for loop in the first place assign an empty array
			// in case there are no cookies at all. Also prevents odd result when
			// calling "get()"
			var cookies = document.cookie ? document.cookie.split('; ') : [];
			var rdecode = /(%[0-9A-Z]{2})+/g;
			var i = 0;

			for (; i < cookies.length; i++) {
				var parts = cookies[i].split('=');
				var name = parts[0].replace(rdecode, decodeURIComponent);
				var cookie = parts.slice(1).join('=');

				if (cookie.charAt(0) === '"') {
					cookie = cookie.slice(1, -1);
				}

				try {
					cookie = converter.read ?
						converter.read(cookie, name) : converter(cookie, name) ||
						cookie.replace(rdecode, decodeURIComponent);

					if (this.json) {
						try {
							cookie = JSON.parse(cookie);
						} catch (e) { }
					}

					if (key === name) {
						result = cookie;
						break;
					}

					if (!key) {
						result[name] = cookie;
					}
				} catch (e) { }
			}

			return result;
		}

		api.get = api.set = api;
		api.getJSON = function () {
			return api.apply({
				json: true
			}, [].slice.call(arguments));
		};
		api.defaults = {};

		api.remove = function (key, attributes) {
			api(key, '', extend(attributes, {
				expires: -1
			}));
		};

		api.withConverter = init;

		return api;
	}

	return init(function () { });
}));;
(function () {
    // Priorità ai ttm_
    var source = getParameterByName('ttm_source');
    var medium = getParameterByName('ttm_medium');
    var campaign = getParameterByName('ttm_campaign');
    var term = getParameterByName('ttm_term');
    var content = getParameterByName('ttm_content');

    if ((source + medium + campaign + term + content).length == 0) {
        // Se tutti i ttm_ son vuoti prende gli utm_
        source = getParameterByName('utm_source');
        medium = getParameterByName('utm_medium');
        campaign = getParameterByName('utm_campaign');
        term = getParameterByName('utm_term');
        content = getParameterByName('utm_content');
    }

    if ((source + medium + campaign + term + content).length > 0) {
        // Se nei ttm_ o nei utm_ c'era qualcosa scrive nei cookies
        Cookies.set('utm_source', source);
        Cookies.set('utm_medium', medium);
        Cookies.set('utm_campaign', campaign);
        Cookies.set('utm_term', term);
        Cookies.set('utm_content', content);
    }
})();

var gaclientId;
ga(function (tracker) {
    gaclientId = tracker.get('clientId');
});

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        return "";
    }
    else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}

function redirectToAuthPage(page, QS) {

    //var returnUrl = window.location.href;
    var pathName = window.location.pathname;
    var redirectDest = "";

    if (pathName === '/') {
        redirectDest = '/' + page;
    } else if (pathName.indexOf(page) >= 0) {

        //redirect alla stessa pagina
        redirectDest = '/' + page + location.search;
    }
    else {
        if (typeof __isRicerca !== 'undefined' && __isRicerca) {
            redirectDest = '/' + page + '?fromRicerca&dontSave&ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?","#"));
        }
        else if (typeof __isDettaglioImmobile !== 'undefined' && __isDettaglioImmobile) {
            redirectDest = '/' + page + '?fromDettaglioImmobile&dontSave&ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?", "#"));
        }
        else {
            redirectDest = '/' + page + '?ReturnUrl=' + encodeURIComponent(pathName + location.search.replace("?", "#"));
        }
    }

    if (QS) {

        redirectDest += (redirectDest.indexOf("?") == -1 ? "?" : "&") + QS;

    }

    window.location.href = redirectDest;


}

$('ul.anonymouse .login-btn').on("click touchstart",function (e) {
    e.preventDefault();
    redirectToAuthPage('login');
});


$('ul.anonymouse .register-btn').on("click touchstart",function (e) {
    e.preventDefault();
    redirectToAuthPage('register');
});


$('.complete-btn').on("click touchstart", function (e) {
    e.preventDefault();
    redirectToAuthPage('register');
});


$('ul.logged .logout-btn').on("click touchstart",function () {
    $.ajax({
        type: 'POST',
        url: '/api/account/logout',
    })
        .always(function (response) {
            document.location.href = '/';
        });
});


;
$(document).ready(function () {
    //setUpFloatForForm();

    if (user_state == 'anonymous') 
    {
        $("#email-call").val(user_info.email);
    }


    
    $(".register").keydown(function (e)           /* or keyup  */ {
        if (e.keyCode == 13) // 27=esc
        {
            e.preventDefault();
            $("#btn-register-call").click();
        }
    });

});



//$('#fb_register_auth_call, #goog_register_auth_call').on("click touchstart", function (ev) {
//    $('#register-privacy-call').parent().parent().removeClass('error');
//    if (!($('#register-privacy-call').is(":checked"))) {
//        $('#register-privacy-call').parent().parent().addClass('error');
//        $.notify("Privacy obbligatoria", 'info');
//        ev.preventDefault();
//        return false;
//    }
//});

$('#btn-register-call').on("click touchstart",function () {
    $.notify.defaults({ autoHide: true, clickToHide: true });
    $('#register-privacy-call').parent().parent().removeClass('error');
        if (!($('#register-privacy-call').is(":checked"))) {
            $('#register-privacy-call').parent().parent().addClass('error');
            $.notify("Privacy obbligatoria", 'info');
            return;
        }
    $(".register-form .loader").show();
    var nome = $('#nome-call').val();
    var cognome = $('#cognome-call').val();
    var telefono = $('#telefono-call').val()
    var email = $('#email-call').val();
    var pwd = $('#password-call').val();
    var ripetiPassword = $('#ripetiPassword-call').val();
    var newsletter = $('#register-call-newsletter').is(":checked")

    var model = {
        Nome: nome,
        Cognome: cognome,
        Email: email,
        Telefono: telefono,
        Password: pwd,
        RipetiPassword: ripetiPassword,
        Newsletter: newsletter
    };

    $.ajax({
        type: 'POST',
        url: '/api/account/Register',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(model),
    })
        .done(function (response) {
            if (!response.HasSucceded) {
                for (var i in response.Messages) {
                    $.notify(response.Messages[i], 'info');
                    $(".register-form .loader").hide();
                }
            }
            else {
          
                ga('send', 'event', 'Compro', 'Registrati', 'PreConfirm');
                $(".register-form .loader").hide();
                //$('#register-form').hide();
                $('#success-register-call  div.static').html($('#success-register-call  div.static').html().replace("{0}", ($('#nome-call').val() + " " + $('#cognome-call').val())));
                //$('#register-form-modal .form-success  div.static').hide();
                $("#success-register-call").show();
                $(".registerCall").hide();
                
             
            }
        })
        .fail(function (_) { });
});







function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
}








;
